@cursor/sdk 1.0.34 → 1.0.36

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.
Files changed (43) hide show
  1. package/dist/bundled/index.js +275 -274
  2. package/dist/bundled/sqlite.js +20 -20
  3. package/dist/cjs/{458.js → 478.js} +3 -3
  4. package/dist/cjs/856.js +1 -1
  5. package/dist/cjs/867.js +1 -0
  6. package/dist/cjs/agent/options.d.ts +6 -0
  7. package/dist/cjs/agent/options.d.ts.map +1 -1
  8. package/dist/cjs/agent/store/sdk-state-root.d.ts +3 -1
  9. package/dist/cjs/agent/store/sdk-state-root.d.ts.map +1 -1
  10. package/dist/cjs/custom-tools.d.ts +1 -1
  11. package/dist/cjs/custom-tools.d.ts.map +1 -1
  12. package/dist/cjs/executor-common.d.ts.map +1 -1
  13. package/dist/cjs/index.js +1 -1
  14. package/dist/cjs/local-executor.d.ts.map +1 -1
  15. package/dist/cjs/options.d.ts +6 -0
  16. package/dist/cjs/options.d.ts.map +1 -1
  17. package/dist/cjs/platform.d.ts.map +1 -1
  18. package/dist/cjs/sqlite.js +1 -1
  19. package/dist/cjs/store/sdk-state-root.d.ts +3 -1
  20. package/dist/cjs/store/sdk-state-root.d.ts.map +1 -1
  21. package/dist/esm/{458.js → 478.js} +3 -3
  22. package/dist/esm/856.js +1 -1
  23. package/dist/esm/867.js +1 -0
  24. package/dist/esm/agent/options.d.ts +6 -0
  25. package/dist/esm/agent/options.d.ts.map +1 -1
  26. package/dist/esm/agent/store/sdk-state-root.d.ts +3 -1
  27. package/dist/esm/agent/store/sdk-state-root.d.ts.map +1 -1
  28. package/dist/esm/custom-tools.d.ts +1 -1
  29. package/dist/esm/custom-tools.d.ts.map +1 -1
  30. package/dist/esm/executor-common.d.ts.map +1 -1
  31. package/dist/esm/index.js +1 -1
  32. package/dist/esm/local-executor.d.ts.map +1 -1
  33. package/dist/esm/options.d.ts +6 -0
  34. package/dist/esm/options.d.ts.map +1 -1
  35. package/dist/esm/platform.d.ts.map +1 -1
  36. package/dist/esm/sqlite.js +1 -1
  37. package/dist/esm/store/sdk-state-root.d.ts +3 -1
  38. package/dist/esm/store/sdk-state-root.d.ts.map +1 -1
  39. package/package.json +53 -54
  40. package/dist/cjs/479.js +0 -1
  41. package/dist/esm/479.js +0 -1
  42. /package/dist/cjs/{458.js.LICENSE.txt → 478.js.LICENSE.txt} +0 -0
  43. /package/dist/esm/{458.js.LICENSE.txt → 478.js.LICENSE.txt} +0 -0
package/dist/cjs/479.js DELETED
@@ -1 +0,0 @@
1
- exports.id=479,exports.ids=[479],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>o_});var o=r("node:buffer"),s=r("node:crypto"),n=r("node:os"),i=r("node:path"),a=r.t(i,2),c=r("../context/dist/otel.js"),l=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class u{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.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{l(e)}}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),o=t.search(/[?#]/),s=-1===o?t:t.slice(0,o),n=s.indexOf("//")+2,i=s.slice(n).search(/[/?#]/),a=-1===i?s.length:n+i,c=s.lastIndexOf("@",a-1);return c<n?s+r:s.slice(0,n)+s.slice(c+1)+r}const y=/ \[git: ([^\]]*)\]/;function v(e,t,r){if("object"!=typeof t||null===t)return e;if(y.test(e))return e;const o=t,s=[];if("string"==typeof o.gitErrorCode&&o.gitErrorCode.length>0&&s.push(`gitErrorCode=${o.gitErrorCode}`),"number"==typeof o.exitCode&&Number.isFinite(o.exitCode)&&s.push(`exitCode=${o.exitCode}`),0===s.length)return e;let n=`${e} [git: ${s.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof o.stderr&&o.stderr.length>0&&(n+=`\n--- git stderr ---\n${a=o.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),n}const b=(0,d.h)("SimpleControlledExecManager"),S=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),C={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 x extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function _(e){return e instanceof x?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class P{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:s}=r;return async function*(r){const n=performance.now(),i=[],a=await r.exec.execute(e,s,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts}),c=r.serializeResult(o,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-n)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class R{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:s}=r;return async function*(r){const n=performance.now(),i=[],a=r.exec.execute(e,s,{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()-n)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:o,hookAdditionalContexts:e}))}}(this)}}class I{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 s=t.message.case??"unknown";for(const e of this.handlers){const n=e.handle(r,t);if(void 0===n)continue;const i=n,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now();return(async()=>{try{for await(const e of i)await a.write(e);await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),k.increment(r,1,{exec_case:s})}catch(e){if(e instanceof f.W2)return;E.increment(r,1,{exec_case:s}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:_(e)})}}))}finally{const e=performance.now()-u;S.histogram(r,e,{exec_case:s}),clearTimeout(c),a.close(),this.runningExecs.delete(t.id),o()}})(),a}this.runningExecs.delete(t.id),o();const n=t.message.case,i=(void 0===n?void 0:C[n])??`No handler found for server message of type ${n}`;return b.error(e,i,{messageCase:n}),E.increment(e,1,{exec_case:s}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new I(t);for(const[t,o]of e.entries())t.registerControlledImplementation(o,r);return r}}async function T(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 A=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},M=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 D=(0,d.h)("ExecutorResource"),O=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class N{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 s=A(o,(0,c.VI)(e.withName("ExecutorResource.execute")),!1),n=s.ctx;void 0!==r?.execId&&s.span.setAttribute("exec.id",r.execId);const i=(0,c.mJ)(n),a=i?new p.Kg(i):void 0,l=this.execManager.createExecInstance(n,(e=>{const o=this.serializeArgs(e,t);return new p.Ye({id:o.id,message:o.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector})})),u=await T(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const f=e=>{if(void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)O.increment(n,1,{hook_event_name:t.hookEventName})}};f(d);let m=this.deserializeResult(d);for(;void 0===m;){const e=await T(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,f(d),m=this.deserializeResult(d)}return(async()=>{try{for await(const e of h)f(e)}catch(e){D.info(n,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){o.error=e,o.hasError=!0}finally{M(o)}}}class j{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 s=A(o,(0,c.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,n=(0,c.mJ)(s),i=n?new p.Kg(n):void 0,a=this.execManager.createExecInstance(s,(e=>{const o=this.serializeArgs(e,t);return new p.Ye({id:o.id,message:o.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})}));for await(const e of a){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{M(o)}}}function $(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function F(e,t,r){return{name:e,symbol:$(e),remoteImplementation:t,registerControlledImplementation:r}}class L{constructor(e,t){this.resource=e,this.value=t}}class U{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new L(e,t))}get(e){return this.resources.get(e.symbol)?.value}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class B{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?t.implementation:this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function z(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function W(e){return t=>{if(t.message.case===e)return t.message.value}}function H(e){return function(t,r){const o={case:e,value:r};return new p.yT({id:t,message:o})}}function q(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const G=F("agent-store-conflict-executor",(e=>new N(e,z("agentStoreConflictArgs"),W("agentStoreConflictResult"))),((e,t)=>{t.register(new P(e,q("agentStoreConflictArgs"),H("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]);class V{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"}}}F("agent-store-conflict-notice-executor",(e=>new V),((e,t)=>{}));const J=F("background-shell-executor",(e=>new N(e,z("backgroundShellSpawnArgs"),W("backgroundShellSpawnResult"))),((e,t)=>{t.register(new P(e,q("backgroundShellSpawnArgs"),H("backgroundShellSpawnResult")))})),K=F("write-background-shell-input-executor",(e=>new N(e,z("writeShellStdinArgs"),W("writeShellStdinResult"))),((e,t)=>{t.register(new P(e,q("writeShellStdinArgs"),H("writeShellStdinResult")))}));function Z(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 Q="local",X=F("canvas-diagnostics-executor",(e=>new N(e,z("canvasDiagnosticsArgs"),W("canvasDiagnosticsResult"))),((e,t)=>{t.register(new P(e,q("canvasDiagnosticsArgs"),H("canvasDiagnosticsResult")))}));Error;const Y=F("computer-use-executor",(e=>new N(e,z("computerUseArgs"),W("computerUseResult"))),((e,t)=>{t.register(new P(e,q("computerUseArgs"),H("computerUseResult")))})),ee=(F("conversation-search-executor",(e=>new N(e,z("conversationSearchArgs"),W("conversationSearchResult"))),((e,t)=>{t.register(new P(e,q("conversationSearchArgs"),H("conversationSearchResult")))})),F("delete-executor",(e=>new N(e,z("deleteArgs"),W("deleteResult"))),((e,t)=>{t.register(new P(e,q("deleteArgs"),H("deleteResult")))}))),te=F("diagnostics-executor",(e=>new N(e,z("diagnosticsArgs"),W("diagnosticsResult"))),((e,t)=>{t.register(new P(e,q("diagnosticsArgs"),H("diagnosticsResult")))}));var re=r("../context/dist/core.js");(0,re.cF)(Symbol("execConversationId"),void 0),(0,re.cF)(Symbol("execRequestId"),void 0),(0,re.cF)(Symbol("execBrowserOperationSource"),void 0);const oe=F("fetch-executor",(e=>new N(e,z("fetchArgs"),W("fetchResult"))),((e,t)=>{t.register(new P(e,q("fetchArgs"),H("fetchResult")))})),se=F("git-diff-executor",(e=>new N(e,z("gitDiffRequest"),W("gitDiffResponse"))),((e,t)=>{t.register(new P(e,q("gitDiffRequest"),H("gitDiffResponse")))})),ne=F("grep-executor",(e=>new N(e,z("grepArgs"),W("grepResult"))),((e,t)=>{t.register(new P(e,q("grepArgs"),H("grepResult")))})),ie={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"},ae={PreToolUse:ie.preToolUse,PermissionRequest:null,PostToolUse:ie.postToolUse,UserPromptSubmit:ie.beforeSubmitPrompt,Stop:ie.stop,SubagentStop:ie.subagentStop,SessionStart:ie.sessionStart,SessionEnd:ie.sessionEnd,PreCompact:ie.preCompact,Notification:null},ce=Object.fromEntries(Object.entries(ae).filter((e=>null!==e[1])).map((([e,t])=>[t,e]))),le={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},ue=["Glob"],de=["Notification","PermissionRequest"],he={warn:()=>{},info:()=>{}};function pe(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 fe(e,t,r=he){const o=[];let s;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=he){if(!e||"*"===e)return"*";const r=e.split("|"),o=[],s=[];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=le[t];null!==r?void 0!==r?o.includes(r)||o.push(r):o.push(t):ue.includes(t)&&s.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of s)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`),[];s="*"===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`),s=void 0):s=void 0;for(const t of e.hooks){const e=pe(t,s);e&&o.push(e)}return o}function me(e,t=he){const r={};for(const[o,s]of Object.entries(e)){const e=o;if(de.includes(e)){t.warn(`Claude Code event "${e}" is not supported in Cursor and will be ignored`);continue}const n=ae[e];if(!n){t.warn(`Unknown Claude Code event "${e}", skipping`);continue}const i=[];if(Array.isArray(s))for(const r of s){const o=fe(r,e,t);i.push(...o)}else void 0!==s&&t.warn(`Claude Code event "${e}" has invalid value (expected array), skipping`);if(i.length>0){const e=r[n]||[];r[n]=[...e,...i]}}return{version:1,hooks:r}}function ge(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 we=e=>"string"==typeof e,ye=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),ve=(e,t=[])=>({isValid:e,errors:t});function be(e,t,r){void 0===e||we(e)||r.push(`${t} must be a string if provided`)}const Se=e=>{const t=[];return ye(e)?ve(!0):(t.push("Expected an object"),ve(!1,t))},ke=e=>{const t=[],r=Se(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"),ve(0===t.length,t)};function Ee(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 Ce=new Set([ie.sessionStart,ie.beforeSubmitPrompt,ie.preToolUse,ie.postToolUse,ie.postToolUseFailure]);function xe(e){return"prompt"===e.type}function _e(e){return"command"===e.type||void 0===e.type}const Pe={[ie.beforeShellExecution]:ke,[ie.beforeMCPExecution]:ke,[ie.afterShellExecution]:e=>{const t=Se(e);return t.isValid,t},[ie.afterMCPExecution]:e=>{const t=Se(e);return t.isValid,t},[ie.beforeReadFile]:e=>{const t=[],r=Se(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"),ve(0===t.length,t)},[ie.afterFileEdit]:e=>{const t=Se(e);return t.isValid,t},[ie.beforeTabFileRead]:e=>{const t=[],r=Se(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"),ve(0===t.length,t)},[ie.afterTabFileEdit]:e=>Se(e),[ie.beforeSubmitPrompt]:e=>{const t=Se(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||we(e.additional_context)||r.push("additional_context must be a string if provided"),ve(0===r.length,r)},[ie.stop]:e=>{const t=Se(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"),ve(0===r.length,r)},[ie.afterAgentResponse]:e=>{const t=Se(e);return t.isValid,t},[ie.afterAgentThought]:e=>{const t=Se(e);return t.isValid,t},[ie.sessionStart]:e=>{const t=Se(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(ye(e.env))for(const[t,o]of Object.entries(e.env))we(t)||r.push(`env key "${t}" must be a string`),we(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||we(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||we(e.user_message)||r.push("user_message must be a string if provided"),ve(0===r.length,r)},[ie.sessionEnd]:e=>{const t=Se(e);return t.isValid?ve(!0,[]):t},[ie.preCompact]:e=>{const t=Se(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return ve(!0,[]);const r=[];if(!ye(e))return r.push("PreCompact response must be an object"),ve(!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"),ve(0===r.length,r)},[ie.subagentStart]:e=>{const t=Se(e);if(!t.isValid)return t;const r=[],o=e;if(void 0!==o.permission){const e=["allow","deny","ask"];e.includes(o.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===o.user_message||we(o.user_message)||r.push("user_message must be a string if provided"),ve(0===r.length,r)},[ie.subagentStop]:e=>{const t=Se(e);if(!t.isValid)return t;const r=[];return void 0!==e&&"object"==typeof e&&null!==e&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),ve(0===r.length,r)},[ie.preToolUse]:e=>{const t=[],r=Se(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"),be(e.additional_context,"additional_context",t),ve(0===t.length,t)},[ie.postToolUse]:e=>{const t=[],r=Se(e);return r.isValid?(be(e.additional_context,"additional_context",t),ve(0===t.length,t)):r},[ie.postToolUseFailure]:e=>{const t=Se(e);if(!t.isValid)return t;const r=[];return be(e.additional_context,"additional_context",r),ve(0===r.length,r)},[ie.workspaceOpen]:e=>{const t=Se(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{we(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")),ve(0===r.length,r)}},Re=(e,t,r)=>{const o=function(e,t,r){let o;return o=e===ie.preToolUse?function(e,t){if(!Fe(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(!$e(t))return r;const o=Le(e);if(!Ue(o,"PreToolUse"))return r;const s={...r};let n=!1;return void 0!==o.permissionDecision&&(s.permission=o.permissionDecision,n=!0),"string"==typeof o.permissionDecisionReason&&(s.user_message=o.permissionDecisionReason,n=!0),Fe(o.updatedInput)&&(s.updated_input=o.updatedInput,n=!0),n?s:r}(t,r):e===ie.stop?Be(t,r,"Stop"):e===ie.subagentStop?Be(t,r,"SubagentStop"):t,function(e,t,r,o){if(!Ce.has(e)||!Fe(r)||void 0!==r.additional_context)return r;const s=Fe(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!$e(r))return;const o=ce[e];if(void 0===o)return;const s=Le(t);return Ue(s,o)&&"string"==typeof s.additionalContext?s.additionalContext:void 0}(e,t,o):void 0;return void 0===s?r:{...r,additional_context:s}}(e,t,o,r)}(e,t,r),s=(0,Pe[e])(o);return s.isValid?{success:!0,data:o}:{success:!1,errors:s.errors}},Ie=[ie.beforeShellExecution,ie.beforeMCPExecution,ie.beforeReadFile,ie.beforeTabFileRead,ie.subagentStart,ie.preToolUse],Te=[ie.workspaceOpen];function Ae(e,t){const r=[];return e?.trim()&&r.push(e.trim()),t?.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function Me(e,t){if(e||t)return{...e||{},...t||{}}}function De(e){return Ie.includes(e)}function Oe({step:e,command:t,failClosed:r,kind:o}){const s=De(e);if(!r&&!s)return{shouldNotifyUser:!1};const n=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:Ne(e,n),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:n,shouldNotifyUser:s&&!r}}function Ne(e,t){return De(e)?{permission:"deny",user_message:t}:e===ie.beforeSubmitPrompt||e===ie.sessionStart?{continue:!1,user_message:t}:e===ie.stop?{}:void 0}function je(e){try{return{value:JSON.parse(e)}}catch{return}}function $e(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function Fe(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Le(e){if(!Fe(e))return;const t=e.hookSpecificOutput;return Fe(t)?t:void 0}function Ue(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function Be(e,t,r){if(!Fe(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(!$e(t))return o;const s=Le(e),n=Ue(s,r)?s:void 0,i=void 0!==n?{...o,...n}:o;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:o}const ze=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"],We=[".ps1",".exe",".bat",".cmd"];function He(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 qe=e=>{const t=[];if(!ye(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)"),ve(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{we(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&&(we(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)=>{we(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(we(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),ve(0===t.length,t)},Ge=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),ve(!1,r);for(let o=0;o<e.length;o++){const s=qe(e[o]);s.isValid||r.push(`${t}[${o}]: ${s.errors.join(", ")}`)}return ve(0===r.length,r)},Ve=e=>{const t=[];if(!ye(e))return t.push("Hooks config must be an object"),ve(!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"),!ye(e.hooks))return t.push("Config hooks must be an object"),ve(!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(ie),o=e.hooks;for(const[e,s]of Object.entries(o))if(r.includes(e)){if(void 0!==s){const r=Ge(s,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return ve(0===t.length,t)};var Je=r("../proto/dist/generated/agent/v1/hooks_pb.js");const Ke=F("hook-executor",(e=>new N(e,z("executeHookArgs"),W("executeHookResult"))),((e,t)=>{t.register(new P(e,q("executeHookArgs"),H("executeHookResult")))}));class Ze{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(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(ie.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new Je.$_({userMessage:o?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(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(ie.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new Je.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??"",...Ee(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:e.status,duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},o=await this.hookExecutor.executeHookForStep(ie.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new Je.AH({followupMessage:o?.followup_message,additionalContext:o?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ie.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(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 p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new Je.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ie.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new Je.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ie.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new Je.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ie.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(e),status:e.status,loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new Je.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{const e=r.request.value,t=e.toolInput?e.toolInput.toJson():{},o={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(e),...e.parentToolCallId?{parent_tool_call_id:e.parentToolCallId}:{},tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd},s=await this.hookExecutor.executeHookForStep(ie.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new Je.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{const e=r.request.value,t=e.toolInput?e.toolInput.toJson():{},o={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(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},s=await this.hookExecutor.executeHookForStep(ie.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new Je.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{const e=r.request.value,t=e.toolInput?e.toolInput.toJson():{},o={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ee(e),...e.parentToolCallId?{parent_tool_call_id:e.parentToolCallId}:{},tool_name:e.toolName,tool_input:t,error_message:e.errorMessage,failure_type:e.failureType,duration:Number(e.durationMs),tool_use_id:e.toolUseId,is_interrupt:e.isInterrupt},s=await this.hookExecutor.executeHookForStep(ie.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new Je.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var o}}(0,re.cF)(Symbol("execHookConversationId"),void 0),(0,re.cF)(Symbol("execHookGenerationId"),void 0),(0,re.cF)(Symbol("execHookModel"),void 0);const Qe=(0,re.cF)(Symbol("execHookWorkspaceRoots"),void 0),Xe=F("ls-executor",(e=>new N(e,z("lsArgs"),W("lsResult"))),((e,t)=>{t.register(new P(e,q("lsArgs"),H("lsResult")))})),Ye="cursor-ide-browser",et="cursor-dev-control",tt="custom-user-tools",rt=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Ye,et,tt,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function ot(e){return!rt.has(e)}const st=new Set([et,Ye]);function nt(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 at(e){return void 0===e||void 0===e.serverIdentifiers}function ct(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}!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 lt=F("mcp-executor",(e=>new N(e,z("mcpArgs"),W("mcpResult"))),((e,t)=>{t.register(new P(e,q("mcpArgs"),H("mcpResult")))})),ut=F("list-mcp-resources-executor",(e=>new N(e,z("listMcpResourcesExecArgs"),W("listMcpResourcesExecResult"))),((e,t)=>{t.register(new P(e,q("listMcpResourcesExecArgs"),H("listMcpResourcesExecResult")))})),dt=F("read-mcp-resource-executor",(e=>new N(e,z("readMcpResourceExecArgs"),W("readMcpResourceExecResult"))),((e,t)=>{t.register(new P(e,q("readMcpResourceExecArgs"),H("readMcpResourceExecResult")))})),ht=F("mcp-state-executor",(e=>new N(e,z("mcpStateExecArgs"),W("mcpStateExecResult"))),((e,t)=>{t.register(new P(e,q("mcpStateExecArgs"),H("mcpStateExecResult")))})),pt=F("mcp-allowlist-precheck-executor",(e=>new N(e,z("mcpAllowlistPrecheckArgs"),W("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new P(e,q("mcpAllowlistPrecheckArgs"),H("mcpAllowlistPrecheckResult")))})),ft=8388608;var mt=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),gt=r("../proto/dist/generated/agent/v1/read_exec_pb.js");function wt(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 yt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var vt=r("../utils/dist/promise-extras.js"),bt=r("@bufbuild/protobuf");const St=new TextEncoder;async function kt(e){const t=St.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 Et{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const o=new gt.a2({...t,digestOnly:void 0});return 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 kt(t.output.value);return new gt.sV({result:{case:"success",value:new gt.mE({...t,output:{case:void 0},outputBlobId:void 0,sha256:r,sizeBytes:BigInt(o)})}})}(await this.inner.execute(e,o,r))}}const Ct=F("read-executor",(e=>new N(e,z("readArgs"),W("readResult"))),((e,t)=>{t.register(new P(e,q("readArgs"),H("readResult")))})),xt=F("redacted-read-executor",(e=>new N(e,z("redactedReadArgs"),W("redactedReadResult"))),((e,t)=>{t.register(new P(e,q("redactedReadArgs"),H("redactedReadResult")))})),_t="$file:";const Pt=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary",labelNames:["route","outcome"]}),Rt=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),It=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),Tt=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function At(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${_t}${t}": ${r} A string argument of the form "${_t}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}class Mt extends Error{constructor(e){super(e.message),this.failure=e}}async function Dt(e,t,{route:r,getReadExecutor:o,...s}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const n=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...n.keys()],a=t=>(Pt.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new mt.iz({result:{case:"error",value:new mt.Nh({error:t.message})}})});let c;try{c=await async function(e,t,r,o,s,{maxFileBytes:n=8388608,maxTotalBytes:i=16777216}){if(t.length>4)throw new Mt(At("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 Mt(At("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const c=await(0,vt.xb)(t,(t=>async function(e,t,r,o,s,n){const i=await t.execute(e,new gt.a2({path:r,toolCallId:o,...n?{digestOnly:!0}:{}}));switch(i.result.case){case"success":{const t=i.result.value,o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new Mt(At("not_text",r,"the file is not a text file."));if(n&&(It.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o))throw new Mt(At("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 kt(a??"");if(t.truncated||l>s)throw new Mt(At("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${s} 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 Mt(At("not_found",r,"the file does not exist."));case"permissionDenied":throw new Mt(At("permission_denied",r,"reading it was not permitted."));case"rejected":throw new Mt(At("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 Mt(At("not_text",r,"the file cannot be read as text."));case"error":throw new Mt(At("read_error",r,i.result.value.error));default:throw new Mt(At("read_error",r,"the read returned no result."))}}(e,a,t,o,n,s)),{max:4});let l=0;for(const[e,r]of c)if(l+=r.bytes,l>i)throw new Mt(At("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,s)}catch(e){return a(function(e,t){return e instanceof Mt?e.failure:At("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=n.get(e);if(r?.sha256!==t.sha256)return a(At("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(_t))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==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,bt.Value.fromJson(t)]))),h.symbolicPathArguments=[],Pt.increment(e,1,{route:r,outcome:"expanded"}),Rt.record(e,l,{route:r}),Tt.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const Ot=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function Nt(e,t,r,o){return Ot.test(t)?(Pt.increment(e,1,{route:o,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${_t}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function jt(e){return e.files.map((e=>`"${_t}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class $t{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 Dt(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 s;try{s=await this.inner.execute(e,o.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=Nt(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 mt._Z({content:{case:"text",value:new mt.zN({text:jt(r)})}})):"error"===o.result.case&&(o.result.value.error=Nt(e,o.result.value.error,r,"local")),o}(e,s,o.expansion)}}const Ft=F("mini-swe-agent-bash-executor",(e=>new N(e,z("miniSweAgentBashArgs"),W("miniSweAgentBashResult"))),((e,t)=>{t.register(new P(e,q("miniSweAgentBashArgs"),H("miniSweAgentBashResult")))})),Lt=F("pi-bash-executor",(e=>new N(e,z("piBashArgs"),W("piBashResult"))),((e,t)=>{t.register(new P(e,q("piBashArgs"),H("piBashResult")))})),Ut=F("pi-edit-executor",(e=>new N(e,z("piEditArgs"),W("piEditResult"))),((e,t)=>{t.register(new P(e,q("piEditArgs"),H("piEditResult")))})),Bt=F("pi-find-executor",(e=>new N(e,z("piFindArgs"),W("piFindResult"))),((e,t)=>{t.register(new P(e,q("piFindArgs"),H("piFindResult")))})),zt=F("pi-grep-executor",(e=>new N(e,z("piGrepArgs"),W("piGrepResult"))),((e,t)=>{t.register(new P(e,q("piGrepArgs"),H("piGrepResult")))})),Wt=F("pi-ls-executor",(e=>new N(e,z("piLsArgs"),W("piLsResult"))),((e,t)=>{t.register(new P(e,q("piLsArgs"),H("piLsResult")))})),Ht=F("pi-read-executor",(e=>new N(e,z("piReadArgs"),W("piReadResult"))),((e,t)=>{t.register(new P(e,q("piReadArgs"),H("piReadResult")))})),qt=F("pi-write-executor",(e=>new N(e,z("piWriteArgs"),W("piWriteResult"))),((e,t)=>{t.register(new P(e,q("piWriteArgs"),H("piWriteResult")))}));var Gt=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Vt=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),Jt=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Kt=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Zt=F("shell-executor",(e=>new N(e,z("shellArgs"),W("shellResult"))),((e,t)=>{t.register(new P(e,q("shellArgs"),H("shellResult")))})),Qt=F("shell-stream-executor",(e=>new j(e,z("shellStreamArgs"),W("shellStream"))),((e,t)=>{t.register(new R(e,q("shellStreamArgs"),H("shellStream")))})),Xt=F("write-executor",(e=>new N(e,z("writeArgs"),W("writeResult"))),((e,t)=>{t.register(new P(e,q("writeArgs"),H("writeResult")))}));function Yt(e,t){return new Jt.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function er(e){return{execute:async(t,r)=>new Jt.W4({result:{case:"permissionDenied",value:Yt(e,r)}})}}function tr(e){return{async*execute(t,r){yield new Jt.FI({event:{case:"permissionDenied",value:Yt(e,r)}})}}}function rr(e){return{execute:async(t,r)=>new Gt.Lt({result:{case:"permissionDenied",value:Yt(e,r)}})}}function or(e){return{execute:async(t,r)=>new Kt.v3({result:{case:"permissionDenied",value:new Kt.U7({path:r.path,error:e,isReadonly:!0})}})}}function sr(e){return{execute:async(t,r)=>new Vt.Pi({result:{case:"permissionDenied",value:new Vt.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function nr(e){return{execute:async(t,r)=>new mt.iz({result:{case:"permissionDenied",value:new mt.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}function ir(e){return{execute:async(t,r)=>new Gt.nt({result:{case:"error",value:new Gt.Gv({error:e})}})}}const ar=F("record-screen-executor",(e=>new N(e,z("recordScreenArgs"),W("recordScreenResult"))),((e,t)=>{t.register(new P(e,q("recordScreenArgs"),H("recordScreenResult")))})),cr=F("request-context-executor",(e=>new N(e,z("requestContextArgs"),W("requestContextResult"))),((e,t)=>{t.register(new P(e,q("requestContextArgs"),H("requestContextResult")))}));var lr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const ur=F("shell-allowlist-precheck-executor",(e=>new N(e,z("shellAllowlistPrecheckArgs"),W("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new P(e,q("shellAllowlistPrecheckArgs"),H("shellAllowlistPrecheckResult")))})),dr=F("force-background-shell-executor",(e=>new N(e,z("forceBackgroundShellArgs"),W("forceBackgroundShellResult"))),((e,t)=>{t.register(new P(e,q("forceBackgroundShellArgs"),H("forceBackgroundShellResult")))}));function hr(e,t){e.hookApprovalRequirement=void 0!==t?new Jt.In(t):void 0}function pr(e){return e.hookApprovalRequirement}function fr(e){return e?.kind===Jt.b.FORCE_PROMPT}F("smart-mode-classifier-executor",(e=>new N(e,z("smartModeClassifierArgs"),W("smartModeClassifierResult"))),((e,t)=>{t.register(new P(e,q("smartModeClassifierArgs"),H("smartModeClassifierResult")))}));var mr=r("../proto/dist/generated/agent/v1/agent_pb.js"),gr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),wr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),yr=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),vr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),br=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Sr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),kr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class Er 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 Cr=e=>new mr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new kr.lI({result:{case:"approved",value:new kr.XJ}})}}),xr=(e,t)=>new mr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new kr.lI({result:{case:"rejected",value:new kr.yc({reason:t??""})}})}}),_r=e=>new mr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Sr.fS({result:{case:"approved",value:new Sr.Hs}})}}),Pr=(e,t)=>new mr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Sr.fS({result:{case:"rejected",value:new Sr.m$({reason:t??""})}})}}),Rr=(e,t)=>new mr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new mr.zT({result:t})}}),Ir=e=>new mr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new br.w$({result:{case:"approved",value:new br.q5}})}}),Tr=(e,t)=>new mr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new br.w$({result:{case:"rejected",value:new br.rA({reason:t??""})}})}}),Ar=(e,t)=>new mr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new wr.gz({result:t})}}),Mr=(e,t)=>new mr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Dr=(e,t)=>new mr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),Or=(e,t)=>new mr.Y5({id:e,result:{case:"prManagementResult",value:t}}),Nr=(e,t)=>new mr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new vr.h({result:{case:"rejected",value:new vr.OI({reason:t??"Authentication was rejected"})}})}}),jr=(e,t)=>new mr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new gr.qG({result:{case:"rejected",value:new gr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),$r=(e,t)=>new mr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new yr.vW({result:{case:"approved",value:new yr.l3({description:t??""})}})}}),Fr=(e,t)=>new mr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new yr.vW({result:{case:"rejected",value:new yr.Uq({reason:t??""})}})}});var Lr=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),Ur=r("../proto/dist/generated/agent/v1/subagents_pb.js");(0,re.cF)(Symbol("pendingSubagentReplay"),void 0);class Br extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const zr=F("subagent-executor",(e=>new N(e,z("subagentArgs"),W("subagentResult"))),((e,t)=>{t.register(new P(e,q("subagentArgs"),H("subagentResult")))})),Wr=F("subagent-await-executor",(e=>new N(e,z("subagentAwaitArgs"),W("subagentAwaitResult"))),((e,t)=>{t.register(new P(e,q("subagentAwaitArgs"),H("subagentAwaitResult")))})),Hr=F("force-background-subagent-executor",(e=>new N(e,z("forceBackgroundSubagentArgs"),W("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new P(e,q("forceBackgroundSubagentArgs"),H("forceBackgroundSubagentResult")))}));class qr{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:s}=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 s)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 n=this.getState(e);"release"===t.type&&"idle"!==n.status&&this.releaseRequestedBySession.add(e),"idle"!==n.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function Gr(e){return"string"==typeof e&&e.trim().length>0}const Vr=F("web-fetch-allowlist-precheck-executor",(e=>new N(e,z("webFetchAllowlistPrecheckArgs"),W("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new P(e,q("webFetchAllowlistPrecheckArgs"),H("webFetchAllowlistPrecheckResult")))})),Jr=e=>String(e).replace(/[\r\n]/g,"");function Kr(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":Jr(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":Jr(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":Jr(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Zr="x-inference-authentication-jwt";function Qr(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Zr]:t}}const Xr=e=>new mr.Uq({message:{case:"shellOutputDelta",value:new mr.Nn_({event:e})}});var Yr=r("../agent-kv/dist/index.js");function eo(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 to=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),ro=r("../proto/dist/generated/agent/v1/mcp_pb.js"),oo=r("@connectrpc/connect"),so=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),no=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),io=r("zod");const ao="relayedAttemptFailure",co=io.z.object({transport:io.z.boolean(),stallAborted:io.z.boolean(),errorName:io.z.string(),connectCode:io.z.number().optional(),connectCodeName:io.z.string().optional(),connectCause:io.z.object({code:io.z.union([io.z.string(),io.z.number()]).optional(),name:io.z.string().optional()}).optional(),transportFailureKind:io.z.string().optional(),loop:io.z.string().optional(),transportMode:io.z.string().optional()});function lo(e){const t=e?.details?.additionalInfo[ao];if(void 0!==t)try{const e=co.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class uo 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 ho extends uo{get kind(){return"RetriableError"}}class po extends uo{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class fo extends uo{get kind(){return"NonRetriableError"}}class mo extends fo{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 go extends uo{get kind(){return"CancelledError"}}const wo=new Set([no.yM.NOT_LOGGED_IN,no.yM.AGENT_REQUIRES_LOGIN,no.yM.AUTH_TOKEN_NOT_FOUND,no.yM.AUTH_TOKEN_EXPIRED,no.yM.INVALID_AUTH_ID,no.yM.UNAUTHORIZED,no.yM.GITHUB_NO_USER_CREDENTIALS,no.yM.GITHUB_USER_NO_ACCESS]),yo=new Set([no.yM.FREE_USER_USAGE_LIMIT,no.yM.FREE_USER_RATE_LIMIT_EXCEEDED,no.yM.PRO_USER_ONLY,no.yM.PRO_USER_USAGE_LIMIT,no.yM.PRO_USER_RATE_LIMIT_EXCEEDED,no.yM.RATE_LIMITED,no.yM.RATE_LIMITED_CHANGEABLE,no.yM.GENERIC_RATE_LIMIT_EXCEEDED]),vo=new Set([no.yM.USAGE_PRICING_REQUIRED,no.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),bo=new Set([no.yM.BAD_API_KEY,no.yM.BAD_USER_API_KEY,no.yM.OUTDATED_CLIENT]),So=new Set([no.yM.USER_ABORTED_REQUEST,no.yM.DEBOUNCED]),ko=new Set([no.yM.CUSTOM_MESSAGE]),Eo=new Map([[oo.Code.PermissionDenied,"Permission Denied"]]),Co=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted"],xo=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH"]),_o=new RegExp(`\\b(${[...xo].join("|")})\\b`),Po=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],Ro="x-cursor-inference-request-error-type";function Io(e,t={}){const{requestId:r}=t;if(e instanceof uo)return e;if(To(e))return function(e,t){const r=Ao(e),o=r.code,s=Mo(e),n=void 0===s?void 0:function(e){if(void 0===e.details?.additionalInfo[ao])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[ao],t.details.equals(new no.ej)&&(t.details=void 0)),t}(s),i={title:n?.details?.title,detail:n?.details?.detail,isRetryable:n?.details?.isRetryable,connectCode:o,errorCode:n?.error,inferenceRequestErrorType:Do(r,Ro)??Do(e,Ro),errorDetails:n},a={cause:e,requestId:t,displayInfo:i,...!0===lo(s)?.transport?{isTransport:!0}:{}};if(o===oo.Code.Canceled||o===oo.Code.Aborted)return Fo(e)?new ho(e.message,a):new go(e.message,a);if(void 0!==n?.error){const t=n.error;if(So.has(t))return new go(jo(e,n),a);const r=n.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new po(jo(e,n),r,a);if(wo.has(t))return new po(jo(e,n),"login",a);if(yo.has(t))return new po(jo(e,n),"upgrade",a);if(vo.has(t))return new po(jo(e,n),"payment",a);if(bo.has(t))return new po(jo(e,n),"config",a);if(ko.has(t)&&!0!==n.details?.isRetryable)return new fo(jo(e,n),a);if(!1===n.details?.isRetryable)return new fo(jo(e,n),a)}if(o===oo.Code.Unauthenticated)return new po(e.message,"login",a);const c=Eo.get(o);return void 0===c||!0===n?.details?.isRetryable||Fo(e)?new ho(e.message,a):new fo(jo(e,n),{...a,displayInfo:{...i,title:i.title||c,detail:i.detail||No(r),isRetryable:!1}})}(e,r);const o=(0,Yr.y_)(e);if(void 0!==o)return new fo(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:o.message,isRetryable:!1}});const s=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===$o)return r;t.add(r),r=r.cause}}(e);if(void 0!==s)return new fo(s.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:s.message,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new go(e.message,{cause:e,requestId:r});if("AgentWebSocketDeliveryAmbiguousError"===e.name)return new ho(e.message,{cause:e,requestId:r,isTransport:!0});if(Fo(e))return new ho(e.message,{cause:e,requestId:r})}const n=e instanceof Error?e.message:String(e);return new ho(n,{cause:e instanceof Error?e:void 0,requestId:r})}function To(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function Ao(e){let t=e;for(let e=0;e<10&&t.code===oo.Code.Unknown;e++){const e=t.cause;if(!To(e))break;t=e}return t}function Mo(e){let t=e;for(let e=0;e<10&&To(t);e++){try{const e=t.findDetails?.(no.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function Do(e,t){const r=e.metadata;if(null!==r&&"object"==typeof r&&"function"==typeof r.get)return r.get(t)??void 0}function Oo(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(To(t))return t;t="cause"in t?t.cause:void 0}}function No(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function jo(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 $o="SummaryPlaceholderRejectedError";function Fo(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(Co.some((t=>e.includes(t)))||_o.test(e))return!0;const o=r.code;if("string"==typeof o&&(Co.some((e=>o.includes(e)))||xo.has(o)))return!0;r=r.cause}return!1}function Lo(e){return!0===e.isTransport||(e.cause instanceof Error?Fo(e.cause):Co.some((t=>e.message.includes(t)))||_o.test(e.message))}function Uo(e){return void 0!==e&&e>0}function Bo(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function zo(e){const{cause:t,requestId:r,transportErrorRetries:o,connectCode:s}=e;return Uo(o)?Bo(new ho("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${o} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:s}})):Bo(new ho("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:s}}))}function Wo(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(To(t)&&(t.code===oo.Code.Canceled||t.code===oo.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}var Ho=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},qo=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Go extends Error{constructor(e){super(e),this.name="LostConnection"}}class Vo{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{Ho(t,(0,c.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if((0,bt.isMessage)(t,p.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const o=(async()=>{const r={stack:[],error:void 0,hasError:!1};try{let o,s;if(t.spanContext){const r=t.spanContext;o=(0,c.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),s=(0,c.fU)(o)}else o=e;Ho(r,s?new c.r2(o,s):void 0,!1);const n=this.controlledExecManager.handle(o,t);for await(const e of n)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{qo(r)}})();r.push(o)}await Promise.all(r)}catch(e){if(e instanceof oo.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Go(e.message);if(e instanceof oo.ConnectError&&e.code===oo.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 Go(e.message)}else{if(e instanceof f.W2)throw new Go(e.message);if(e instanceof oo.ConnectError&&e.code===oo.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Go(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{qo(t)}}}var Jo=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Ko=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Zo=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),Qo=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class Xo extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Xo.telemetryName="InteractionListenerStreamClosedError";var Yo=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 es=(0,d.h)("ClientInteractionController"),ts=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class rs{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let o,s=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);s=s.then(r).catch((r=>{es.error(e,"Error handling interaction message",r,{messageCase:t.case}),o??=r}))}if(await s,void 0!==o)throw o}catch(e){t.error=e,t.hasError=!0}finally{Yo(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&ts.has(t.query.case);let o=!1;const s=()=>{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 xr(e.id,t);case"webFetchRequestQuery":return Pr(e.id,t);case"askQuestionInteractionQuery":return Rr(e.id,new Jo.tz({result:{case:"rejected",value:new Jo.ox({reason:t})}}));case"switchModeRequestQuery":return Tr(e.id,t);case"createPlanRequestQuery":return Ar(e.id,new wr.bK({result:{case:"error",value:new wr.iY({error:t})}}));case"setupVmEnvironmentArgs":return Mr(e.id,new Qo.r$({result:{case:"success",value:new Qo.JH({})}}));case"replaceEnvArgs":return Dr(e.id,new Zo.dV({result:{case:"failure",value:new Zo.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return Or(e.id,new Ko.HL({result:{case:"error",value:new Ko.K$({error:t})}}));case"mcpAuthRequestQuery":return Nr(e.id,t);case"connectScmRequestQuery":return jr(e.id,t);case"generateImageRequestQuery":return Fr(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 mr.Y5))throw r;return es.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),o})).then((e=>(s(),this.queryResponseStream.write(e)))).catch((t=>{es.error(e,"Error handling interaction query",t)})).finally(s)}}async function os(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new go("User aborted request");throw new fo("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new fo("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new fo("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new mr.Ibo({bearerToken:r.bearerToken})}const ss=15728640,ns=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),is=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),as=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});class cs{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,Yr.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,Yr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Yr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Yr.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,Yr.nj)(t),o=this.transientBlobs.get(r);void 0===o||this.persistedBlobIds.has(r)||(await(0,vt.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 ls({ctx:e,action:t,resources:r,blobStore:o,mode:s,maxBlobBytes:n,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"===s)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,n=e.length>0&&o.hasAll(e);if(r||n){const e=t.requestContextParts;return"ref_only"===s&&r&&n&&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(cr),s=await o.execute(e,new lr._K({notesSessionId:r})),n="success"===s.result.case?s.result.value.requestContext:void 0;if(void 0===n)throw new Error(`Failed to compute request context: ${s.result.case}`);return n}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,n),ss),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:o}){const s=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 lr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new lr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new lr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new lr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e);if("ref_only"===t&&s.dynamicContext.toBinary().byteLength>o)return;const n=s.rules.toBinary(),i=s.skills.toBinary(),a=s.subagents.toBinary(),c=s.mcps.toBinary(),l=n.byteLength+i.byteLength+a.byteLength+c.byteLength;if(l>r)return;const[u,d,h,p]=await Promise.all([(0,Yr.Bk)(n),(0,Yr.Bk)(i),(0,Yr.Bk)(a),(0,Yr.Bk)(c)]),f=[{blobId:u,blobData:n},{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c}],m=new lr.sG({rulesBlobId:u,rulesByteLength:n.byteLength,skillsBlobId:d,skillsByteLength:i.byteLength,subagentsBlobId:h,subagentsByteLength:a.byteLength,mcpsBlobId:p,mcpsByteLength:c.byteLength,dynamicContext:"ref_only"===t?s.dynamicContext:void 0});return"dual"===t?{kind:"dual",inlineContext:e,byteLength:l,parts:m}:{kind:"ref_only",stagedBlobs:f,byteLength:l,parts:m}}({requestContext:h,mode:s,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,ns.increment(e,1,{mode:s,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!o.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,ns.increment(e,1,{mode:s,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 ns.increment(e,1,{mode:s,outcome:d?"hydrated":"inline"}),is.histogram(e,m,{mode:s}),as.histogram(e,performance.now()-c,{mode:s}),{kind:"prepared",byteLength:m,hydrated:d}}const us=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","idle_deadline","stall","other"],ds=/\bHTTP (\d{3})\b/;function hs(e){const t=e.message;return"string"==typeof t?t:""}function ps(e){return e instanceof Error&&"AbortError"===e.name||!0===e.isTransport}const fs={serverCap:3,transportCap:10};function ms(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gs(e,t,r){const o=r.attemptRequestId,s=!0===t.endless,n=r.retriesEnabled||s;let i=e instanceof uo?e:Io(e,{requestId:o});const a=i instanceof go&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&So.has(t)}(i)),c="stall_detector"===r.abortOrigin&&!a&&(i instanceof go||i instanceof ho),l="owner"===r.abortOrigin&&i instanceof ho&&Wo(i),u=function(e,t){return t.stalled?"stall":t.userStop?"other":function(e){const t=function(e){const t=[];let r=e;for(;"object"==typeof r&&null!==r&&!t.includes(r)&&t.length<10;)t.push(r),r="cause"in r?r.cause:void 0;return t}(e);if(t.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const r=t.map(hs);if(r.some((e=>e.includes("ALPN protocol failed to negotiate"))))return"alpn_failure";if(r.some((e=>e.includes("Unexpected seqno"))))return"poll_seqno_gap";const o=r.map((e=>ds.exec(e)?.[1])).find((e=>void 0!==e));if("464"===o)return"http_464";const s=function(e){const t=Oo(e);return void 0===t?void 0:Ao(t).code}(e);return"404"===o||s===oo.Code.Unimplemented?"http_404_unimplemented":s===oo.Code.DeadlineExceeded?"idle_deadline":s===oo.Code.Canceled||s===oo.Code.Aborted||function(e){return e instanceof Error&&Fo(e)}(e)||t.some(ps)?"socket_reset":"other"}(e)}(e,{stalled:c,userStop:a||l}),d=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:u}),h=(e,o)=>n?!s&&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(n&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return d(zo(p()),{countAsTransportError:!0});const e=h((()=>zo(p())),(()=>zo({...p(),transportErrorRetries:void 0})));return"retry"===e.action?{...e,stall:!0}:e}return i instanceof go&&!a&&Wo(i)&&(i=new ho(i.message,{cause:i.cause,requestId:o,displayInfo:i.displayInfo,isTransport:!0})),l?d(new go(i.message,{cause:i.cause,requestId:o,displayInfo:i.displayInfo})):!0===t.retryAllInference&&(i instanceof po||i instanceof fo)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!Po.some((e=>e===t))}(i)?!s&&r.serverErrorRetries>=t.serverCap?d(i):ms(u):i instanceof go||i instanceof po||i instanceof fo?d(i):i instanceof ho&&(Lo(i)||"owner"!==r.abortOrigin&&Wo(i))?h((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:o,connectCode:s}=e;return Uo(o)?new ho("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`The connection failed ${o} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:s}}):new ho("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:s}})}(p())),(()=>i)):n?!s&&r.serverErrorRetries>=t.serverCap?d(i):ms(u):d(i)}function ws(e){const t=(r=e.tokenDetails,void 0===r?.promptContextUsageTree?r:new mr.VNy({...r,promptContextUsageTree:void 0}));var r;const o=t!==e.tokenDetails;let s=!1,n=e.subagentStates;for(const[t,r]of Object.entries(e.subagentStates)){const o=r.conversationState;if(void 0===o)continue;const i=ws(o);i!==o&&(s||(n={...e.subagentStates},s=!0),n[t]=new mr.aK_({...r,conversationState:i}))}return o||s?new mr.Y9z({...e,tokenDetails:t,subagentStates:n}):e}const ys=(0,d.h)("@anysphere/agent-client:stall-detector"),vs=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,bs={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ss=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop"]}),ks=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop"]}),Es=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop"]}),Cs=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop"]});class xs{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 _s{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=bs[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),Cs.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(Ms),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 s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=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"});ys.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,s=this.lastOutboundMessage,n=this.ctx.get(Ms);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(ys.warn(this.ctx,a,i),Ss.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:s?.messageType,requestId:n?.requestId,modelName:n?.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});ys.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"),ks.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 Ps=(0,d.h)("@anysphere/agent-client:turn-runner"),Rs=1e3;async function Is(e){const{ctx:t,checkpointHandler:r,runOptions:o,requestId:s,hooks:n,cancellation:i}=e,a=e.originalRequestId??s;let c=Rs;const l=async(r,s,n,i)=>{if(n||(c=Rs),void 0!==e.backoff)return void await e.backoff(r,s);const a=n?function(e,t){const r=Math.min(3e5,3*e);return t??Rs+(r-Rs)*Math.random()}(c,o.fixedRetryDelayMs):function(e,t,r){const o=t?100:Rs,s=r??Math.min(o*2**e,6e4);return s+(void 0===r?.2*s*Math.random():0)}(r,o.isRunningInTest,o.fixedRetryDelayMs);n&&(c=a,e.logging&&Ps.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:a,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:n})),await async function(e,t){await new Promise(((r,o)=>{if(t?.aborted)return void o(new go("Cancelled during backoff"));const s=setTimeout((()=>{t?.removeEventListener("abort",n),r()}),e);function n(){clearTimeout(s),o(new go("Cancelled during backoff"))}t?.addEventListener("abort",n,{once:!0})}))}(a,s)};let u,d,h,p=e.state,f=e.action,m=0,g=s,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,s)=>{e===m&&(S=!0),await r.handleCheckpoint(t,o,s),e===m&&(u=o,d=s?.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,n.beginAttempt?.({attempt:m,originalRequestId:a}),m>0?(g=crypto.randomUUID(),await(o.onRetryStarting?.(m,{actionCase:f.action.case,conversationState:p,isResume:"resumeAction"===f.action.case,attemptRequestId:g})),e.logging&&Ps.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&&Ps.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:m,reason:"resume_action"}))):(e.logging&&Ps.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&&Ps.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:m,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,g);try{return await n.runAttempt({state:p,action:f,checkpointHandler:C(m),attempt:m,attemptRequestId:g,notifyConnected:k,notifyApplicationProgress:E}),k(),void(e.logging&&Ps.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 s=!0===o.endlessRetries?.(),c=e.nowMs?.()??Date.now(),k=void 0===h?void 0:c-h;let E=n.classify(r,{attempt:m,attemptRequestId:g,originalRequestId:a,serverErrorRetries:w,transportErrorRetries:y,stallRetryElapsedMs:k,endlessRetries:s});"retry"===E.action&&(void 0!==u?b=0:"resumeAction"===f.action.case&&S&&(b++,b>=2&&(e.logging&&Ps.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}),E={action:"throw",error:new ho("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:E.transportFailureKind})));const C={...void 0===E.transportFailureKind?{}:{transportFailureKind:E.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}};if(e.logging){const n="retry"===E.action?`RETRY (countAsServerError=${E.countAsServerError}, countAsTransportError=${E.countAsTransportError})`:`THROW ${E.error.kind}`;Ps.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${g} originalRequestId=${a} decision=${n}`,{decision:n,willRetry:"retry"===E.action,enableAgentRetries:o.enableAgentRetries??!1,endlessRetries:s,isRunningInTest:o.isRunningInTest??!1,serverErrorRetries:w,transportErrorRetries:y,attempt:m,requestId:g,originalRequestId:a,...C,...e.logging.diagnostics?.(r)})}if("throw"===E.action){if(0===m){const r={attempt:0,actionCase:f.action.case,error:E.error,requestId:g,originalRequestId:a,enableAgentRetries:!0===o.enableAgentRetries,endlessRetries:s,stallAborted:!1,abortSources:[]};try{await(o.onErrorNotRetried?.(n.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Ps.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:g,originalRequestId:a})}}throw e.logging&&Ps.warn(t,`[${e.logging.tag}] Error not retryable`,{attempt:m,actionCase:f.action.case,...!0===e.logging.includeErrorObjects?{error:E.error}:{errorName:E.error.name},serverErrorRetries:w,transportErrorRetries:y}),E.error}const x=m+1;if("ineligible_terminal_turn"===d)return void(e.logging&&Ps.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)}));o.onConnectionStateChange?.({state:"reconnecting",attempt:x,trigger:{...C,...n.reconnectTrigger?.(r,E,{originalRequestId:a,failedAttemptRequestId:g,nextAttempt:x})??{originatingRequestId:a,attemptRequestId:g}}}),v=!0,E.countAsServerError&&w++,E.countAsTransportError&&y++,!0===E.stall?h??=c:h=void 0,m=x,void 0!==u&&(p=u,f=new mr.QFf({action:{case:"resumeAction",value:new mr.qKo}})),n.onRetryCommitted?.(),await l(m,t.signal,s,E)}}}var Ts=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},As=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Ms=(0,re.cF)(Symbol("agentStreamMetadata"),void 0),Ds=(0,d.h)("@anysphere/agent-client:abort"),Os=(0,d.h)("@anysphere/agent-client:retry"),Ns=(0,d.h)("@anysphere/agent-client:request-context-blob");async function js({ctx:e,action:t,resources:r,blobStore:o,options:s,source:n,transportMode:i}){try{await ls({ctx:e,action:t,resources:r,blobStore:o,mode:i??s.requestContextBlobTransportMode??"legacy",maxBlobBytes:s.requestContextBlobMaxBytes??ss,maxInlineDynamicBytes:s.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:s.conversationId})}catch(r){t.requestContextParts=void 0,Ns.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:n})}}const $s=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 Fs(e,t,r){for await(const o of t)switch(o.event.case){case"stdout":await r.sendUpdate(e,Xr({case:"stdout",value:new Jt.o0({data:o.event.value.data})}));break;case"stderr":await r.sendUpdate(e,Xr({case:"stderr",value:new Jt.Db({data:o.event.value.data})}));break;case"exit":await r.sendUpdate(e,Xr({case:"exit",value:new Jt.vb({code:o.event.value.code,aborted:o.event.value.aborted})}))}}function Ls(e){return e instanceof Error?e.name:void 0}class Us{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,o,s,n,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new mo(d.maxSteps);const p=new cs(i),f=d.generationUUID??crypto.randomUUID(),m={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},g=e=>{const t=function(e){const t=Oo(e);return void 0===t?void 0:lo(Mo(t))}(e),r=m.sources.includes("stall_detector")||!0===t?.stallAborted,o=(s=m.sources).some((e=>"stall_detector"!==e))?"owner":s.includes("stall_detector")?"stall_detector":"none";var s;const n=function(e){const t={errorName:Ls(e)},r=Oo(e);if(void 0===r)return t;const o=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),s=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),n=Ls(o);return{...t,underlyingConnectError:{code:r.code,codeName:oo.Code[r.code],cause:void 0!==s||void 0!==n?{code:s,name:n}:void 0}}}(e),i=n.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===o&&r?"stall_detector":o,reading:void 0===t?{errorName:n.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...m.sources],abortReasonName:m.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 w=0,y=0;try{d.onNetworkPhaseStart?.()}catch(t){Os.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const v=Ts(h,(0,c.VI)(e.withName("networkPhase")),!1);e=v.ctx,await(0,c.MG)(v.span,(()=>Is({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:f,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}=g(e);return{stallAborted:t,abortOrigin:r,...o}}},cancellation:{toCancelledError:()=>new go("Request cancelled")},hooks:{beginAttempt:()=>{m.sources=[],m.abortReasonName=void 0,m.abortReasonMessage=void 0,y=++w},runAttempt:async({state:t,action:r,checkpointHandler:i,attempt:c,attemptRequestId:l,notifyConnected:h,notifyApplicationProgress:g})=>{const v=function(e,t,r){return{sendUpdate:async(o,s)=>{if(t===r())return e.sendUpdate(o,s);"toolCallCompleted"===s.message?.case&&Os.warn(o,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(o,s)=>{if(t!==r())throw new go("Stale query from previous attempt");return e.query(o,s)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(s,y,(()=>w));await this.runInternal(e,t,r,o,v,n,p,a,i,u,d,l,f,m,h,g,c)},classify:(e,t)=>{const{abortOrigin:r,relayed:o}=g(e),s=gs(e,function(e,t,r=fs){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}),n=o?.transportFailureKind;return"string"==typeof(i=n)&&us.includes(i)?{...s,transportFailureKind:n}:s;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:g(e.error).stallAborted,abortSources:[...m.sources],abortReasonName:m.abortReasonName,abortReasonMessage:m.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:o,stallAborted:s,reading:n}=g(e),i=e instanceof uo?e:Io(e,{requestId:r.failedAttemptRequestId});return{errorClass:o?.errorName??i.name,connectCode:n.connectCode,connectCodeName:n.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:s,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===n.transportMode?{}:{transportMode:n.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{As(h)}}async runInternal(e,t,r,o,s,n,i,a,l,d,h,m,g,w,y,v,b,S="agent.request.attempt"){const k={stack:[],error:void 0,hasError:!1};try{const E=e;e=this.options.prepareAttemptContext?.(e,{attempt:b,attemptRequestId:m,originalRequestId:g,runOptions:h})??e;const C=Ts(k,(0,c.VI)(e.withName(S)),!1);C.span.setAttribute("agent.attempt",b),C.span.setAttribute("agent.request_id",m),C.span.setAttribute("agent.original_request_id",g),e=C.ctx,e=(0,c.Mf)(e,"agent.request_id",m),e=(e=(0,c.Mf)(e,"agent.original_request_id",g)).with(Ms,{requestId:m,rootParentRequestId:h.rootParentRequestId,modelDetails:o});const x=new Set(w.sources);let _=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const P=(t,r)=>{if(x.has(t))return;x.add(t),w.sources=[...x];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);_||void 0===o||(_=!0,w.abortReasonName=o.abortReasonName,w.abortReasonMessage=o.abortReasonMessage),Ds.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:m,conversationId:h.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;P("ctx_signal_abort",eo(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;P("ctx_signal_abort",eo(t))}),{once:!0});const[R,T]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;P("conversation_action_abort",eo(e)),T()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;P("conversation_action_abort",eo(e)),T()}),{once:!0});if(e.canceled||R.canceled){const t={ctxCanceled:e.canceled,softCancel:R.canceled};throw P("pre_run_cancel",t),new go("User aborted request")}const A=(0,c.VI)(e.withName("createControlledExecManager")),M=I.fromResources(n);A[Symbol.dispose]();const[D,O]=e.withCancel(),N=new xs,{failThresholdMs:j,advisoryThresholdMs:$}=function(e,t){const r=vs(e?.failTimeoutMs)??3e4,o=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,s=vs(e?.advisoryTimeoutMs);return{failThresholdMs:o,advisoryThresholdMs:void 0!==s&&s>0&&(o<=0||s<o)?s:void 0}}(h.stallDetectorConfig,{isRunningInTest:h.isRunningInTest}),F=Ts(k,new _s(D,{thresholdMs:j,advisoryThresholdMs:$,loop:this.options.loop,onStall:()=>{P("stall_detector",{thresholdMs:j,advisoryThresholdMs:$}),O()},onStallCallback:h.onStall,handlerTracker:N}),!1);let L,U;const B=(0,so.Jt)(),z=new f.F8(B,(e=>(F.reset("outbound_write",$s(e)),e))),W=Ts(k,(0,c.VI)(e.withName("writeInitialRequest")),!1);let H;const q=d.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?bt.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0}))),G=h.requestContextBlobTransportMode??"legacy",V=0===b&&"userMessageAction"===r.action.case&&0===t.turns.length,J="ref_only"===G&&V?"dual":G,[,K]=await Promise.all([js({ctx:e,action:r,resources:n,blobStore:i,options:h,source:"run_request",transportMode:J}),void 0===h.mintLlmGatewayCredential?Promise.resolve(void 0):os(h.mintLlmGatewayCredential,{signal:R.signal,isCanceled:()=>R.canceled,requestId:m})]),Z={action:r,headers:h.headers??{}},Q=this.options.decorateAttempt?.(Z,h)??Z,X=new mr.Mpn({conversationState:ws(t),action:Q.action,modelDetails:o,requestedModel:h.requestedModel,clientLlmGatewayCredential:K,mcpTools:new ro.Or({mcpTools:q}),conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,systemPromptSpec:h.systemPromptSpec,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,suggestNextPrompt:h.suggestNextPrompt,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,clientSupportsPromptContextUsageRpc:h.clientSupportsPromptContextUsageRpc,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,runId:g});if(H=z.write(new to.KS({message:{case:"runRequest",value:X}})),R.canceled){const t={ctxCanceled:e.canceled,softCancel:R.canceled};throw P("post_write_cancel",t),W[Symbol.dispose](),new go("User aborted request")}const Y={...Q.headers,"x-request-id":m,"x-original-request-id":g,...Kr(h),...Qr()};L=(0,c.VI)(e.withName("handshakeEstablishment")),L.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ee=this.client.run(L.ctx,B,{signal:D.signal,headers:Y,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===U&&(U=performance.now())}}),te=performance.now(),re=e=>{L&&(L.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==U&&L.span.setAttribute("handshake.preNetworkMs",U-te),L[Symbol.dispose](),L=void 0),y();const t=performance.now();h.onFirstMessage?.(t-te),void 0!==U&&h.onFirstMessageNetwork?.(t-U)},oe=()=>{v(),h.onFirstNonHeartbeatResponse?.(performance.now()-te,b)},se=h.onTtftBreakdown?e=>{h.onTtftBreakdown(e,b)}:void 0,{interactionStream:ne,execStream:ie,checkpointStream:ae,kvStream:ce,done:le}=function(e,t,r,o,s,n,i,a){const c=(0,so.Jt)(),l=(0,so.Jt)(),u=(0,so.Jt)(),d=(0,so.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 s of t){if(void 0!==s.ttftBreakdown){const t=s.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs})}catch(t){Os.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===s.message.case&&"heartbeat"===s.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){Os.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",$s(s))}if("interactionUpdate"===s.message.case&&"turnEnded"===s.message.value.message.case&&(g=!0),"interactionUpdate"!==s.message.case&&"interactionQuery"!==s.message.case||await c.write(s.message).catch((()=>{})),"execServerMessage"!==s.message.case&&"execServerControlMessage"!==s.message.case||await l.write(s.message.value),"conversationCheckpointUpdate"===s.message.case){const e=g?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(w=!0),await u.write({checkpoint:s.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===s.message.case&&await d.write(s.message.value)}r.onStreamEnded()}catch(e){f=e}finally{if(m=f,g&&w&&void 0!==f&&!s?.aborted&&!n?.aborted&&function(e){const t=e instanceof uo?e:Io(e);return t instanceof ho&&Lo(t)}(f)&&(Os.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||s?.aborted||n?.aborted){if(!g&&!s?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${s?.aborted}, parentSignal.aborted=${n?.aborted}; firstMessageFired=${h}`;Os.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===f?(Os.warn(e,t),m=new ho(t,{isTransport:!0})):f instanceof Error&&"[aborted] aborted"===f.message?(Os.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new ho(t,{cause:f,isTransport:!0})):Os.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,ee,F,re,R.signal,e.signal,oe,se);let ue;const de={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),ue=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};W[Symbol.dispose]();const he=5e3;let pe;const fe=()=>{pe=setTimeout((()=>{z.write(new to.KS({message:{case:"clientHeartbeat",value:new to.kA}})).then((()=>F.onClientSentHeartbeat()),(()=>{})),fe()}),he)},me=()=>{void 0!==pe&&(clearTimeout(pe),pe=void 0)};fe();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const o=r.action.value,i=new Jt.a({command:o.shellCommand?.command||"",parsingResult:new Jt.HO,skipApproval:!0}),a=n.get(Qt).execute(e,i,{execId:o.execId}),c=new rs(ne,s,new f.F8(z,(e=>new to.KS({message:{case:"interactionResponse",value:e}}))),F);t={run:async e=>{await Promise.all([N.track("handleShellStream",Fs(e,a,s)),N.track("interactionController",c.run(e))])}}}else{const e=new rs(ne,s,new f.F8(z,(e=>new to.KS({message:{case:"interactionResponse",value:e}}))),F);t={run:async t=>{await N.track("interactionController",e.run(t))}}}void 0!==H&&await Promise.race([H,le.catch((()=>{}))]);const c=new f.F8(z,(e=>{if((0,bt.isMessage)(e,p.yT))return new to.KS({message:{case:"execClientMessage",value:e}});if((0,bt.isMessage)(e,p.$Y))return new to.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,bt.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Vo(ie,c,M),b=new Yr.hC(ce,new f.F8(z,(e=>new to.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),S=new u(ae,de,e);let k,C;const x={promise:new Promise(((e,t)=>{k=e,C=t})),resolve:k,reject:C};R.canceled?(x.resolve(),ne.close()):R.signal.addEventListener("abort",(()=>{x.resolve(),ne.close()}),{once:!0}),l.run(R).then(x.resolve).catch(x.reject);const _=Promise.allSettled([N.track("streamSplitter",le.finally((()=>{me(),a.close(),c.close()}))),N.track("execHandler",x.promise),t.run(e),N.track("checkpointController",S.run()),N.track("kvHandler",b.run(e)),N.track("conversationActionManager",a.run(e,{write:async t=>{await js({ctx:e,action:t,resources:n,blobStore:i,options:h,source:"queued_action"}),await z.write(new to.KS({message:{case:"conversationAction",value:t}}))}}))]);let P,I;const T={promise:new Promise(((e,t)=>{P=e,I=t})),resolve:P,reject:I};_.then(T.resolve).catch(T.reject),e.canceled?T.reject(new go("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new go("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?O():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let o=!1;const s=e=>{o||(o=!0,clearTimeout(n),r(e))},n=setTimeout((()=>s("linger_timed_out")),t);e.done.then((()=>s("stream_ended")),(()=>s("stream_ended")))}))}({done:le,lingerMs:h.softCancelLingerMs}).then((t=>{Os.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:m}),O()}))};R.canceled?(A(),T.reject(new go("User aborted request"))):R.signal.addEventListener("abort",(()=>{A(),T.reject(new go("User aborted request"))}),{once:!0});const D=await T.promise,j=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 fo("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:m,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const B="ineligible_terminal_turn"===ue;if(B){const t={..."rejected"===j.status?{streamSplitter:U(j)}:{},..."rejected"===$.status?{execHandler:U($)}:{}};Object.keys(t).length>0&&Os.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===j.status&&!B)throw j.reason;if("rejected"===$.status&&!B)throw $.reason;R.canceled||await this.processUnprocessedMessages(E,a,de,o,s,n,i,d,h,m,g,w,F,y,v)}finally{me(),L&&(L[Symbol.dispose](),L=void 0)}}catch(e){k.error=e,k.hasError=!0}finally{As(k)}}async processUnprocessedMessages(e,t,r,o,s,n,i,a,c,l,u,d,h,p,f){if(!t.hasUnprocessedMessages())return;const m=t.getUnprocessedUserMessages(),g=r.getLatestCheckpoint();if(!g||0===m.length)return;const w=m[0];t.markMessageAsProcessed(w),t.resetStream(),h[Symbol.dispose]();const y=r.getLatestCheckpoint();try{await this.runInternal(e,g,new mr.QFf({action:{case:"userMessageAction",value:new mr.Vtf({userMessage:w})}}),o,s,n,i,t,r,a,c,l,u,d,p,f,0,"agent.request.queuedMessage")}catch(e){throw y===r.getLatestCheckpoint()&&t.requeueMessage(w),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 Bs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),zs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const Ws=(0,oo.createContextKey)(void 0,{description:"anysphere.callerContext"});function Hs(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function qs(e,t,r){return{[Symbol.asyncIterator](){const o=e[Symbol.asyncIterator]();let s=!1;const n=e=>{s||(s=!0,e?(t?.recordException(e instanceof Error?e:new Error(String(e))),t?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:Bs.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await o.next();return e.done&&n(),e}catch(e){throw n(e),e}},return:async e=>(n(),o.return?o.return(e):{done:!0,value:void 0}),async throw(e){if(n(e),o.throw)return o.throw(e);throw e}}}}}function Gs(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r.forEach(((e,r)=>{t.set(r,e)})):Object.entries(r).forEach((([e,r])=>{t.set(e,r)})));return t}function Vs(e,t){const{injectTraceHeaders:r=!0,extractHeaders:o}=t;return new Proxy(e,{get(e,s){const n=e[s];return"function"!=typeof n?n:(i,a,l={})=>{const u=(0,c.fR)(i.withName(`rpc.${String(s)}`),{kind:zs.v.CLIENT,attributes:{"rpc.method":String(s),"rpc.system":"connect"}}),d=(0,c.fU)(u);let h;try{let s;if(r&&(s=function(e){const t=new Headers;try{const r=(0,c.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")}`;if(t.set("traceparent",r),t.set("backend-traceparent",r),o.traceState){const e="function"==typeof o.traceState.serialize?o.traceState.serialize():String(o.traceState);t.set("tracestate",e)}}}catch{}return t}(u)),o){const e=o(u);e&&(s=Gs(s,e))}const i=Gs(l.headers,s),{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)},s=()=>{r.abort(t.reason)};e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",s,{once:!0}),e.aborted?o():t.aborted&&s();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)}}}(u.signal,l.signal):{signal:l.signal,cleanup:void 0};h=m;const g=(l.contextValues??(0,oo.createContextValues)()).set(Ws,u),w={...l,headers:i,signal:f,contextValues:g},y=n.call(e,a,w);return Hs(y)?qs(y,d,h):null!==(p=y)&&"object"==typeof p&&"then"in p&&"function"==typeof p.then?y.then((e=>Hs(e)?qs(e,d,h):(d?.setStatus({code:Bs.s.OK}),d?.end(),h?.(),e))).catch((e=>{throw d?.recordException(e instanceof Error?e:new Error(String(e))),d?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e})):(d?.setStatus({code:Bs.s.OK}),d?.end(),h?.(),y)}catch(e){throw d?.recordException(e instanceof Error?e:new Error(String(e))),d?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e}var p}}})}var Js=r("../utils/dist/workspace-paths.js");function Ks(){return(0,i.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,i.join)((0,n.homedir)(),".cursor")}(),"projects")}function Zs(e){return(0,i.join)(Ks(),(0,Js.r_)(e))}var Qs=r("node:fs/promises"),Xs=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ys=r("node:fs"),en=r("../shell-exec/dist/index.js"),tn=r("./src/agent/native/tree-sitter.webpack.cjs"),rn=r("./src/agent/native/tree-sitter-bash.webpack.cjs");let on;const sn=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),nn=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function an(e){const t=function(){if(void 0!==on)return on;try{const e=new tn;e.setLanguage(rn),on=e}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;on=null,console.warn("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return on}();if(null===t)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=t.parse(e),o=new WeakSet;let s=!1,n=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{s=!0,a.hasRedirects=!0,n=n&&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=>nn.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:s}=r,n=((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("")}}})(s),c={operator:o,destinationFds:n,targetNodeType:s?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===o){const e=l(s),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 n)t.fdTargets.set(e,"unsafe");return!1}for(const e of n)t.fdTargets.set(e,r);return!0}if("<&"===o){const e=l(s),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of n)t.fdTargets.set(e,"unsafe");return!1}for(const e of n)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})(s)){for(const e of n)t.fdTargets.set(e,"unsafe");return!1}for(const e of n)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)sn.has(r.type)&&h(r,t)})(t),sn.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),s&&(a.allRedirectsAreDevNull=n),{legacy:i,structured:a}}var cn=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),ln=r("../utils/dist/path-utils.js");const un=async e=>{const t=(0,ln.o1)(e);try{return await(0,Qs.realpath)(t)}catch{return t}},dn="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",hn="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",pn=/\$\(|`|<\(|>\(/,fn=/[;&|]/;let mn,gn,wn,yn;function vn(){if(void 0===mn){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();mn=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return mn}function bn(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 Sn(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function kn(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 En(){if(void 0===yn){const e=(process.env[dn]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${dn} (expected "allow" or "deny"); using "deny".`);const r=Sn("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),o=(process.env[hn]??"").trim();let s=r;"none"===o.toLowerCase()?s=[]:""!==o&&(s=Sn(hn)),yn={networkDefault:t,denyDomains:r,dependencyDenyDomains:s,allowDomains:Sn("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:kn("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return yn}function Cn(e,t,r={}){const o=[bn(e),bn(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===o.length)return null;const s=o.join("|"),n=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${s})`:s;return new RegExp(n,"i")}function xn(e,t){const r=function(){const e=En();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===gn&&(gn=Cn("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),gn);if(null===o)return r;const s=t?.executableCommands??[];if(t?.parsingFailed||0===s.length)return r;if(pn.test(e))return r;const n=(void 0===wn&&(wn=Cn("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),wn);for(const e of s){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||n?.test(t)||fn.test(t))return r}return s.every((e=>o.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=En();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}var _n=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Pn(e){if(!e)return;let t;return"allow"===e.default?t=_n.h1.ALLOW:"deny"===e.default&&(t=_n.h1.DENY),new _n.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new _n.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function Rn(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 _n.h1.ALLOW:t.default="allow";break;case _n.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,en.T6)():(0,en.Po)())}function In(e){switch(e){case"system":return _n.Sz.SYSTEM;case"workspace":return _n.Sz.WORKSPACE;default:return _n.Sz.UNSPECIFIED}}function Tn(e){const t=function(e){switch(e){case _n.Sz.SYSTEM:return"system";case _n.Sz.WORKSPACE:return"workspace";case _n.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function An(e){if(!e)return{type:"insecure_none"};switch(e.type){case _n.vc.INSECURE_NONE:case _n.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case _n.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:Rn(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,...Tn(e)};case _n.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Rn(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...Tn(e)};default:return{type:"insecure_none"}}}function Mn(e){if(e)return"insecure_none"===e.type?new _n.Mw({type:_n.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new _n.Mw({type:_n.vc.WORKSPACE_READWRITE,networkAccess:(0,en.$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:Pn(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:In(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new _n.Mw({type:_n.vc.WORKSPACE_READONLY,networkAccess:(0,en.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Pn(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:In(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new _n.Mw({type:_n.vc.INSECURE_NONE})}function Dn(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function On(e){let t="",r=!1;for(const o of e)Dn(o)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=o);return t}function Nn(e){return e.length>0&&[...e].every((e=>"*"===e))}function jn(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 $n(e,t){const r=e.trim(),o=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(r),s=`^${o.replace(/\\\*/g,".*")}$`;try{return new RegExp(s).test(t)}catch{return r===t}}function Fn({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const Ln={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function Un(e){let t="",r="plain",o=0;for(;o<e.length;){const s=e[o];if("plain"===r){"$"===s&&"'"===e[o+1]?(r="ansi",o+=2):"$"===s&&'"'===e[o+1]?(r="double",o+=2):"'"===s?(r="single",o++):'"'===s?(r="double",o++):"\\"===s&&o+1<e.length?("\n"!==e[o+1]&&(t+=e[o+1]),o+=2):(t+=s,o++);continue}if("single"===r){"'"===s?r="plain":t+=s,o++;continue}if("double"===r){if('"'===s){r="plain",o++;continue}if("\\"===s&&o+1<e.length){const r=e[o+1];if("$"===r||"`"===r||'"'===r||"\\"===r||"\n"===r){"\n"!==r&&(t+=r),o+=2;continue}}t+=s,o++;continue}if("'"===s){r="plain",o++;continue}if("\\"!==s||o+1>=e.length){t+=s,o++;continue}const n=e[o+1],i=Ln[n];if(void 0!==i){t+=i,o+=2;continue}const a="x"===n?e.slice(o+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===n?e.slice(o+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===n?e.slice(o+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(o+1).match(/^[0-7]{1,3}/)?.[0],c="u"===n||"U"===n,l="x"===n||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+=n,o+=2}return On(t)}function Bn({rule:e,command:t}){const r=On(e).trim();return 0!==r.length&&(null!==function(e){const t=On(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Nn(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=jn(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Nn(e)&&(0===t.length||Nn(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),On(t).trim(),Un(t).trim()].some((e=>function(e,t){const r=jn(e);if(void 0!==r){const{executablePattern:e,argsPattern:o}=r,s=t.indexOf(" "),n=-1===s?t:t.slice(0,s),i=-1===s?"":t.slice(s+1).trim();if($n(e,n)&&$n(o,i))return!0}return e.includes("*")?$n(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function zn({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)),s=o.length>0?o:[""];for(const e of r)if(s.some((t=>Bn({rule:e,command:t}))))return e}function Wn(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 Hn({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=zn({matchForms:Fn({command:e,parsingResult:t}),blockedCommands:r});return void 0===o?void 0:Wn(o)}var qn=r("../utils/dist/lru-cache.js"),Gn=r("node:util"),Vn=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Jn=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");const Kn="utf8",Zn="utf8bom",Qn="latin1",Xn={"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 Yn(e){const t=e.toLowerCase();return"latin-1"===t?Qn:"utf-8"===t?Kn:"utf-8-bom"===t||"utf-8 bom"===t?Zn:t}var ei;!function(e){e.CRLF="CRLF",e.LF="LF"}(ei||(ei={}));const ti=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],ri=new Set(ti),oi=new Gn.TextDecoder("utf-8",{fatal:!0}),si=new Gn.TextDecoder("latin1"),ni=Buffer.from([239,187,191]),ii=new Map,ai=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...ti]),ci=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i;function li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ui(e){const t=li(e);return ri.has(t)}function di(e){const t=li(e);return{encoding:"binary",lineEnding:ei.LF,isBinaryFile:!0,isImageFile:ci.test(t),isVideoFile:ri.has(t)}}async function hi(e,t){const r=await(0,Qs.readFile)(e),o=gi(r);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ii.get(e);let n;n=t||s||o.encoding;const{text:i,encoding:a}=function(e,t){const r=Yn(t);if(r===Kn||r===Zn||"ascii"===r){const t=ki(e);return r===Zn&&t.encoding===Kn?{text:t.text,encoding:Zn}:t}if(r===Qn)return{text:si.decode(e),encoding:Qn};try{const t=function(e){return Xn[e]||e}(r);if(Vn.encodingExists(t))return{text:Vn.decode(e,t),encoding:r}}catch{}return ki(e)}(r,n),c=function(e){return e.startsWith("\ufeff")?e.slice(1):e}(i);return Si(e,a===Kn&&Ei(r)?Zn:a),o.lineEnding===ei.CRLF?c.replaceAll("\r\n","\n"):c}async function pi(e,t,r,o){let s;try{s=r?await async function(e,t){try{return await fi(e)}catch{}const r=li(e);if(ai.has(r))return di(e);try{return await async function(e){const t=new Map;let r=0;for await(const o of vi(e)){if(r>=100)break;try{const e=await fi(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:bi()}(t)}catch{return bi()}}(e,r):await fi(e)}catch{const t=li(e);s=ai.has(t)?di(e):bi()}const n=ii.get(e);if(!s.isBinaryFile){let t;t=Yn(o||n||s.encoding);const r=t===Zn||t===Kn&&!o&&await async function(e){try{return Ei(await yi(e))}catch{return!1}}(e);s={...s,encoding:r?Zn:t},Si(e,s.encoding)}const i=mi(t);if(s.lineEnding===ei.CRLF&&(t=t.replaceAll("\n","\r\n")),"binary"===s.encoding){const e=function(e){const t=e.trim().replace(/\s/g,"");if(t.length>50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:i,buffer:e,format:s}}return{lines:i,buffer:s.encoding===Zn?Buffer.concat([ni,Vn.encode(t,Kn,{defaultEncoding:Kn})]):Vn.encode(t,s.encoding,{defaultEncoding:Kn}),format:s}}async function fi(e){const t=gi(await yi(e));return t.isBinaryFile?{...t,isVideoFile:ui(e)}:{...t,isVideoFile:!1}}function mi(e){if(""===e)return 1;let t=1;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}function gi(e){if(0===e.length)return bi();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 s=0;s<2*o&&!(s+1>=e.length);s+=2){if(0===e[s+1]){const r=e[s];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[s]){const t=e[s+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);if(t)return{encoding:t,lineEnding:wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const r=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 s=0;s<4*o&&!(s+3>=e.length);s+=4){if(0===e[s]&&0===e[s+1]&&0===e[s+2]){const r=e[s+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[s+1]&&0===e[s+2]&&0===e[s+3]){const t=e[s];(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(r)return{encoding:r,lineEnding:wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(4096,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:ei.LF,isBinaryFile:!0,isImageFile:(s=e,!(s.length<4)&&(s.length>=8&&137===s[0]&&80===s[1]&&78===s[2]&&71===s[3]&&13===s[4]&&10===s[5]&&26===s[6]&&10===s[7]||255===s[0]&&216===s[1]&&255===s[2]||s.length>=12&&82===s[0]&&73===s[1]&&70===s[2]&&70===s[3]&&87===s[8]&&69===s[9]&&66===s[10]&&80===s[11]||s.length>=6&&71===s[0]&&73===s[1]&&70===s[2]&&56===s[3]&&(55===s[4]||57===s[4])&&97===s[5])),isVideoFile:!1};var s;if((0,o.isUtf8)(e)&&!e.includes(27))return{encoding:"UTF-8",lineEnding:wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const n=Jn.detect(e);let i=n.confidence>.7?n.encoding:"utf-8";return"ascii"===i&&(i="utf-8"),{encoding:i??"utf-8",lineEnding:wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function wi(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 0===t&&0===r?ei.LF:t/(t+r)*100>=5?ei.CRLF:ei.LF}async function yi(e){const t=await(0,Qs.open)(e,"r");try{const e=Buffer.allocUnsafe(8192),{bytesRead:r}=await t.read(e,0,8192,0);return e.subarray(0,r)}finally{await t.close()}}async function*vi(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,Qs.readdir)(e,{withFileTypes:!0});for(const o of r){if(o.name.startsWith(".")&&".gitignore"!==o.name)continue;const r=(0,i.join)(e,o.name);o.isDirectory()?t.has(o.name)||(yield*vi(r)):o.isFile()&&(yield r)}}catch(e){return}}function bi(){return{encoding:Kn,lineEnding:"win32"===process.platform?ei.CRLF:ei.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Si(e,t){if(ii.has(e)&&ii.delete(e),ii.set(e,t),ii.size<=100)return;const r=ii.keys().next().value;void 0!==r&&ii.delete(r)}function ki(e){try{return{text:oi.decode(e),encoding:Kn}}catch{return{text:si.decode(e),encoding:Qn}}}function Ei(e){return e.length>=ni.length&&e[0]===ni[0]&&e[1]===ni[1]&&e[2]===ni[2]}var Ci=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),xi=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class _i{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.ttlMs="function"==typeof e?e:_i.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 Pi=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Ri(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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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 s=(0,en.spawnInSandbox)((0,en.Ko)(),t,{cwd:r},o),n=[];s.stderr?.on("data",(e=>{n.push(e)}));const i=new Promise(((e,t)=>{s.on("error",t),s.on("close",(t=>e(t??0)))}));if(!s.stdout)throw new Error("No stdout from ripgrep process");const a=new Promise((t=>{e.signal.aborted?t("aborted"):e.signal.addEventListener("abort",(()=>t("aborted")),{once:!0})}));return{stdout:s.stdout,processExit:i,stderr:()=>Buffer.concat(n).toString(),aborted:a,[Symbol.dispose](){s.kill()}}}(e,h,t,c),!1);let s=0;const n=async function*(e){let t="";for await(const r of e){t+=r.toString();const e=t.split("\n");t=e.pop()??"",yield*e}t&&(yield t)}(o.stdout)[Symbol.asyncIterator]();for(;;){const e=await Promise.race([n.next(),o.aborted]);if("aborted"===e){m=!0,f(!0);break}if(e.done)break;s++,yield e.value}if(s>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{Pi(r)}}(),didTimeout:g}}let Ii;function Ti({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:o=[],caseSensitive:s=!1,cursorIgnoreFiles:n=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:o,caseSensitive:s,cursorIgnoreFiles:n,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Ai{constructor(e=()=>function(e=process.env){if(void 0!==Ii)return Ii;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 _i({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(Ti(e))}walk(e,t){const r=Ti(t);let o,s=!1,n=!1;const i=new Promise((e=>{o=e})),a=e=>{n||(n=!0,o(e))},c=(l=e.signal,new Promise((e=>{l.aborted?e("aborted"):l.addEventListener("abort",(()=>e("aborted")),{once:!0})})));var l;return{lines:async function*(){const o=this.cache.get(r);if(void 0!==o){const e=await Promise.race([o.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),c.then((()=>({type:"aborted"})))]);if("aborted"===e.type)return s=!0,void a(!0);if("lines"===e.type)return a(!1),void(yield*e.lines);this.cache.get(r)===o&&this.cache.delete(r)}let n,i;const l={linesPromise:new Promise(((e,t)=>{n=e,i=t}))};l.linesPromise.catch((()=>{})),this.cache.set(r,l);const u=[];let d,h=!1;try{const r=Ri(e,t);for await(const e of r.lines)u.push(e),yield e;if(await r.didTimeout)return s=!0,d=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);h=!0}catch(e){throw d=e,e}finally{h?n?.(u):(this.cache.get(r)===l&&this.cache.delete(r),i?.(d??new Error("Ripwalk terminated before cacheable result was available"))),s||a(!1)}}.bind(this)(),didTimeout:i}}}async function Mi(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}async function Di(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Oi(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return e.username="",e.password="",e.toString()}catch{return t}}function Ni(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}const ji=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],$i=[".gitignore",".cursorignore"];async function Fi(e){if(!(0,i.isAbsolute)(e))return null;const t=await(0,ln.DN)(e);return null===t?null:t}async function Li(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}class Ui{constructor(e,t,r){this.ignoreServicePromise=zi.init((0,re.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e){return this.ignoreServicePromise.then((t=>t.isCursorIgnored(e)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}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)))}}const Bi=Math.min(8,Math.max(1,Math.floor(n.availableParallelism()/2)));class zi{constructor(e,t,r,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=o,this.rootDirectories=s,this.gitIgnoreCache=new qn.q({max:2e3}),this.cursorIgnoreCache=new qn.q({max:2e3}),this.gitRootCache=new qn.q({max:1e3}),this.gitRemoteUrlCache=new qn.q({max:200}),this.hasGitDirCache=new qn.q({max:1e3}),this.gitParsedIgnoreCache=new Map,this.cursorParsedIgnoreCache=new Map}static getRipwalkCache(){return zi.ripwalkCache??=new Ai,zi.ripwalkCache}getIgnoreInstance(e,t,r){let o=r.get(e);return o||(o=Ci().add(t),r.set(e,o)),o}hasNoWorkspaceFolders(){return 0===Object.keys(this.gitIgnoreMapping).length&&0===Object.keys(this.cursorIgnoreMapping).length}async resolveLookupRoot(e){return await(0,ln.DN)(e)??(0,ln.o1)(e)}static async init(e,t,r,o){const s=await(0,vt.PH)(r,(async e=>{const t=await(0,ln.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),n={},i={},a=(await(0,vt.PH)(s,(r=>Mi(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([zi.initializeIgnoreMapping(a,".gitignore",n),zi.initializeIgnoreMapping(s,".cursorignore",i)]),new zi(t,n,i,o,s)}static async preloadHierarchy(e,t,r,o){let s=(0,ln.o1)(e);const n=(0,i.parse)(s).root;for(;s!==n;){if(o?.has(s)){const e=(0,i.dirname)(s);if(e===s)break;s=e;continue}void 0===r[s]&&await zi.handleHierarchyIgnore(s,t,r),o?.add(s);const e=(0,i.dirname)(s);if(e===s)break;s=e}}static async handleHierarchyIgnore(e,t,r){const o=(0,i.join)(e,t);try{await(0,Qs.access)(o,Qs.constants.F_OK);const t=await hi(o),s=zi.parseIgnoreRules(t);r[e]=s}catch(s){"ENOENT"===s.code||console.error(`Error reading ${t} file at ${o}:`,s),r[e]=[]}}static async initializeIgnoreMapping(e,t,r){try{const o=zi.deduplicateRootDirectories(e),s=await zi.promiseQueue.enqueueList(o,(e=>zi.findFilesWithRipgrep(e,t))),n=Array.from(s.values()).flat();await Promise.all(n.map((async e=>{try{const t=await hi(e),o=zi.parseIgnoreRules(t),s=(0,i.dirname)(e);r[s]=o}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const a=new Set;for(const e of o)await zi.preloadHierarchy(e,t,r,a)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t){const r=(0,re.q6)(),o=[],s={root:e,includeGlobs:$i.map((e=>`**/${e}`)),excludeGlobs:ji,source:"ignore_scan"},n=zi.getRipwalkCache().walk(r,s);for await(const r of n.lines)(0,i.basename)(r)===t&&o.push((0,i.join)(e,r));return o}async handleManualLookupWhenNoWorkspaceDirs(e,t){const r={};let o=(0,i.dirname)(e);const s=(0,i.parse)(o).root;for(;;){const e=(0,i.join)(o,t);try{const t=await hi(e),s=zi.parseIgnoreRules(t);s.length>0&&(r[o]=s)}catch{}if(o===s)break;o=(0,i.dirname)(o)}return this.testIgnored(e,r,((e,t)=>Ci().add(t)))}async isIgnoredByAny(e){const[t,r,o]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||o}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e){return this.checkCursorIgnored(e)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore");const t=this.cursorIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const r=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let o=(0,i.dirname)((0,ln.o1)(e));const s=[],n=(0,i.parse)(o).root;for(;o!==n;){if(this.rootDirectories.some((e=>(0,ln.ZU)({basePath:e,targetPath:o})))){o=(0,i.dirname)(o);continue}if(void 0!==r[o])break;s.push(o);const e=(0,i.dirname)(o);if(e===o)break;o=e}s.length>0&&(await zi.promiseQueue.enqueueList(s,(e=>zi.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[o,s]of Object.entries(t)){if(0===s.length)continue;if(!(0,ln.ZU)({basePath:o,targetPath:e}))continue;const t=(0,i.relative)(o,e);if(""===t)continue;const n=r(o,s),a=(0,ln.oL)(t),c=n.test(a);if(c.ignored&&!c.unignored)return!0;const l=n.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>this.getIgnoreInstance(e,t,r)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,o]of Object.entries(this.cursorIgnoreMapping)){if(0===o.length)continue;if(!(0,ln.ZU)({basePath:t,targetPath:e}))continue;const s=(0,i.join)(e,".cursorignore");try{await(0,Qs.access)(s),r.push(s)}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,ln.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear()}async handleCursorIgnoreCreated(e){const t=(0,i.dirname)(e),r=await hi(e),o=zi.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=o,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,i.dirname)(e),r=await hi(e),o=zi.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=o,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,i.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ln.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const o=[],s=[],n=[];let a=t;const c=(0,i.parse)(a).root;for(;a!==c;){s.push(a),void 0===this.hasGitDirCache.get(a)&&n.push(a);const e=(0,i.dirname)(a);if(e===a)break;a=e}if(n.length>0){const e=n.map((e=>(0,Qs.access)((0,i.join)(e,".git"),Qs.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 s)!0===this.hasGitDirCache.get(e)&&o.push(e);return this.gitRootCache.set(t,o),o}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=await this.findGitRootsForFile(e),r=await(this.teamSettingsService?.getTeamRepos());if(!r)return!1;const o=r.repos??[],s=r.disableLocalExecAllowlistEnforcement?[]:r.allowedRepos??[];if(0===o.length&&0===s.length)return!1;if(0===t.length)return this.checkNonRepoPathBlockedByAllowlist(e,s);let n=0===s.length,a=!1;for(const r of t){let t;if(this.gitRemoteUrlCache.has(r)?t=this.gitRemoteUrlCache.get(r):(t=await Di((0,re.q6)(),this.gitExecutor,r),void 0!==t&&this.gitRemoteUrlCache.set(r,t)),void 0===t)continue;const c=t,l=(0,i.relative)(r,e)||".";for(const e of o)if(this.doesRepoUrlMatch(e.url,c))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,l))return!0;s.length>0&&!a&&(a=!0,n=s.some((e=>this.doesRepoUrlMatch(e.url,c)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,l))))))}return!n}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,ln.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,ln.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ln.oL)((0,i.relative)(t,e)):(0,ln.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,i.join)(n.homedir(),".cursor");return await(0,ln.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){if(e.trim().toLowerCase().replace(/\.git$/i,""),e.includes("*")){if("*"===e.trim())return!0;const r=Ni(e).toLowerCase(),o=Ni(t).toLowerCase();return this.matchRepoUrlGlob(r,o)}return Ni(e).toLowerCase()===Ni(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return xi(r,{dot:!0})(t)}catch{return r===t}}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),o=await this.getGitRepoMapping();if(0===o.size)return[];const s=[];for(const[e,n]of o){if(void 0===n)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,i.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>this.doesRepoUrlMatch(e.url,n)));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,i.join)(l,e).replace(/\\/g,"/"):e,s.push(r),r.endsWith("/**")||s.push(`${r}/**`)}}return s}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,re.q6)();for(const e of this.rootDirectories){const s=(0,ln.o1)(e);try{await(0,Qs.access)((0,i.join)(s,".git"),Qs.constants.F_OK),t.includes(s)||t.push(s)}catch{}let n=(0,i.dirname)(s);const a=(0,i.parse)(n).root;for(;n!==a&&""!==n;){try{await(0,Qs.access)((0,i.join)(n,".git"),Qs.constants.F_OK),t.includes(n)||t.push(n)}catch{}const e=(0,i.dirname)(n);if(e===n)break;n=e}try{const e={root:s,includeGlobs:["**/.git/config"],excludeGlobs:r,noIgnoreVcs:!0,source:"ignore_scan"},n=zi.getRipwalkCache().walk(o,e);for await(const e of n.lines){const r=(0,i.join)(s,e),o=(0,i.dirname)(r),n=(0,i.dirname)(o);t.includes(n)||t.push(n)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Di(o,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}async function Wi(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(Wn(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Hi(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Wn(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 qi(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new Jt.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new Jt.pZ({command:e,workingDirectory:t,reason:Hi(r)})}}zi.promiseQueue=new vt.TJ({max:Bi});var Gi=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Vi=(0,d.h)("local-exec:background-shell");function Ji(e,t,r){return new Gt.Lt({result:qi(e,t,r)})}class Ki{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 Zi(e,t){let r;try{for(let o=await t.next();!o.done;o=await t.next())"stdin_ready"===o.value.type?(e.stdin=o.value.stdin,e.pid=o.value.pid):"exit"===o.value.type&&(r={code:o.value.code,aborted:o.value.aborted,outputPath:o.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function Qi(e){e().catch((()=>{}))}const Xi=65536;class Yi{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=cn.L3.compile(e.config.pattern,cn.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>Xi){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=Xi)this.observe(e.slice(t,t+Xi));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}.`:"",s=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}`,n=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:n,source:"shell",payload:{taskId:n,...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:s,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&&Vi.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 ea{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,s){if(!this.backgroundWorkRegistry||!s)return;if(0===s.pattern.trim().length)return;const n=i.join(this.projectDir,"terminals",`${t}.txt`);try{return new Yi({shellId:t,outputPath:n,config:s,conversationId:r??Q,toolCallId:o,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&Vi.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 s of r(e,o))"stdout"===s.type||"stderr"===s.type?t.observe(s.data):"exit"===s.type&&t.finish(),yield s}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 ta{async spawn(e,t){const r=new AbortController,o=new Ki(e.shellId,r),s=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 s.next();!e.done;e=await s.next())if("stdin_ready"===e.value.type){o.stdin=e.value.stdin,o.pid=e.value.pid;break}}catch(e){if(e instanceof en.SandboxUnsupportedError)throw e}return Qi((()=>Zi(o,s))),o}async adopt(e){const t=new Ki(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,Qi((()=>Zi(t,e.eventIterator))),t}}function ra(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function oa(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: ${ra(e.cwd)}\n`,o+=`command: ${ra(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(o+=`title: ${ra(e.title)}\n`),o+=`status: ${r}\n`,o+=`started_at: ${e.startedAt}\n`,o+=`running_for_ms: ${t}\n`,o+="---\n",o}class sa{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=i.join(this.projectDir,"terminals");await(0,Qs.mkdir)(r,{recursive:!0});const o=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,o)}createLoggingExecutor(e,t,r){const s=e.execute.bind(e);return{...e,execute:async function*(e,n){let a,c,l,u=!1,d=!1;const h=Date.now(),p=new Date(h).toISOString();let f,m="running",g=!1,w=Promise.resolve();const y=async e=>{if(c)try{await c.write(e)}catch(e){}},v=t.shellId,b=i.join(r,`${v}.txt`),S=async()=>{if(!a)return;const e=Date.now()-h,r=oa({pid:f,cwd:t.workingDirectory,command:t.command,title:t.description,status:m,startedAt:p,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},k=()=>(w=w.then(S).catch((()=>{})),w),E=()=>{void 0!==l&&(clearInterval(l),l=void 0)},C=async e=>{if(d)return;d=!0,f=e;const r=Date.now()-h,o=oa({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:m,startedAt:p,runningForMs:r});await(0,Qs.writeFile)(b,o,"utf8"),l=setInterval((()=>{k()}),5e3)},x=async()=>{a||(a=await Ys.promises.open(b,"r+")),c||(c=await Ys.promises.open(b,"a"))},_=async(e,t)=>{if(!g){if(g=!0,E(),d||await C(),await x(),void 0!==t){const e=Date.now()-h,r=`\n---\n${t}\n`+(n.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await y(r)}m=e,await k()}};try{for await(const r of s(e,n)){if("stdout"===r.type)d||(await C(),await x()),await y(r.data);else if("stderr"===r.type)d||(await C(),await x()),await y(r.data);else if("stdin_ready"!==r.type||u)"exit"===r.type&&await _(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,d||(await C(r.pid),await x());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`;y(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,o,s)=>(t(e),r(e,o,s)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,o,s)=>(void 0!==e&&t(e),r(e,o,s))}}}yield r}if(!g){const e=n.signal?.aborted??!1;await _(e?"aborted":"failed")}}catch(e){const t=n.signal?.aborted??!1,r=ra(e instanceof Error?e.message:"Unknown error");if(await _(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(E(),await w,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=i.join(this.projectDir,"terminals");await(0,Qs.mkdir)(t,{recursive:!0});const r=i.join(t,`${e.shellId}.txt`),o=e.startTime,s=new Date(o).toISOString();let n="running";const a=Date.now()-o,c=oa({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:n,startedAt:s,runningForMs:a})+(e.initialOutput??"");await(0,Qs.writeFile)(r,c,"utf8");const l=await Ys.promises.open(r,"r+");let u;try{u=await Ys.promises.open(r,"a")}catch(e){throw await l.close(),e}let d=!1,h=!1,p=Promise.resolve();const f=async()=>{const t=Date.now()-o,r=oa({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:n,startedAt:s,runningForMs:t});try{await l.write(r,0,"utf8")}catch{}},m=()=>(p=p.then(f).catch((()=>{})),p);let g=setInterval((()=>{m()}),5e3);const w=()=>{void 0!==g&&(clearInterval(g),g=void 0)},y=async()=>{if(!d){d=!0,w(),await p;try{await l.close()}catch{}try{await u.close()}catch{}}},v=async e=>{try{await u.write(e)}catch(e){}},b=async(t,r)=>{if(!h){if(h=!0,w(),void 0!==r){const t=Date.now()-o,s=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await v(s)}n=t,await m()}},S={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await b(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await v(e.data):"exit"===e.type&&(await b(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await y())}return t.done&&await y(),t}catch(t){const r=e.abortController.signal.aborted;throw await b(r?"aborted":"failed"),await y(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await b(t?"aborted":"failed")}return await y(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:S})}}class na{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:Z(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,s){if(!this.backgroundWorkRegistry)return;const n=s.aborted?"aborted":0===s.code?"success":"error",i=s.aborted||null===s.code||0===s.code?void 0:`exit_code=${s.code}`,a=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Q,id:a,source:"shell",payload:{taskId:a,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:n,title:o,...i?{detail:i}:{},...s.outputPath?{outputPath:s.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)})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,e.description||e.command,r),this.cleanupShell(t.id)})),{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(""),s=-1!==o?o:t.indexOf("\\u0004");if(-1!==s){const e=t.substring(0,s);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 ia{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 aa{constructor(e,t,r,o,s,n,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=n&&void 0!==i?new ia(n,i):n,c=s??function(e){const t=new ta;return new sa(t,e)}(o),l=new ea(c,o,a);this.backgroundShellManager=new na(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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const o=t.command,s=t.sandboxPolicy?An(t.sandboxPolicy):void 0,n=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ln.o1)(n),a=new Jt.HO(an(o).structured),l=Hn({command:o,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==l)return new Gt.Lt({result:{case:"rejected",value:new Jt.pZ({command:o,workingDirectory:i,reason:l})}});let u=s;if(Vi.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:s?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:a,toolCallId:t.toolCallId},s);if("block"===r.kind)return Vi.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),Ji(o,i,r.reason);Vi.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:pr(t)},s);if("block"===r.kind)return Vi.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),Ji(o,i,r.reason);u=r.policy,Vi.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(vn()&&(u=xn(o,a),"insecure_none"!==u.type)){const e=await Li(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),s=u?{perRepo:u}:void 0,n={ctx:e,command:o,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:s,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(n,this.coreExecutor);return new Gt.Lt({result:{case:"success",value:new Gt.Po({shellId:r,command:o,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof en.SandboxUnsupportedError){const s=u?.type??"unknown";return Vi.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:s,reason:r.reason}),new Gt.Lt({result:{case:"sandboxUnsupported",value:new Jt.rI({command:o,workingDirectory:i,sandboxPolicyType:s,reason:r.reason??r.message,isReadonly:"workspace_readonly"===s})}})}return new Gt.Lt({result:{case:"error",value:new Gt.Of({command:o,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Gi(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var ca=r("node:async_hooks"),la=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");const ua={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},da=io.z.object({command:io.z.string().optional(),args:io.z.array(io.z.string()).optional(),env:io.z.record(io.z.string(),io.z.string()).optional(),url:io.z.string().optional(),headers:io.z.record(io.z.string(),io.z.string()).optional(),cwd:io.z.string().optional(),envFile:io.z.string().optional(),auth:io.z.object({CLIENT_ID:io.z.string(),CLIENT_SECRET:io.z.string().optional(),scopes:io.z.array(io.z.string()).optional()}).optional(),enabledTools:io.z.array(io.z.string()).optional(),placement:io.z.enum(["server","client"]).optional(),tls:io.z.object({caBundle:io.z.string().trim().min(1).max(131072)}).optional()}),ha=io.z.object({mcpServers:io.z.record(io.z.string(),da).optional()}),pa=io.z.enum(["canvas"]),fa=io.z.array(pa).transform((e=>[...new Set(e)].sort()));class ma extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function ga(e){const t=e.trim();if(!t)throw new ma("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,o=t.indexOf("@");if(o!==t.lastIndexOf("@"))throw new ma("Plugin identifier cannot contain multiple @ symbols",e);if(-1===o){if(!r.test(t))throw new ma("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new ma("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const s=t.slice(0,o).trim(),n=t.slice(o+1).trim();if(!s)throw new ma("Missing plugin name before @",e);if(!n)throw new ma("Missing source after @",e);if(!r.test(s))throw new ma("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(s.length>100)throw new ma("Plugin name must be 100 characters or less",e);if(n.startsWith("github:")){const t=n.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new ma("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:s,sourceType:"github",githubRepo:t,raw:e}}if(n.startsWith("local:")){const t=n.slice(6).trim();if(!t)throw new ma("Missing path after 'local:'",e);return{name:s,sourceType:"local",localPath:t,raw:e}}if(n.startsWith("url:")){const t=n.slice(4).trim();if(!t)throw new ma("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new ma("Invalid Git URL format",e)}return{name:s,sourceType:"url",gitUrl:t,raw:e}}const i=n.indexOf("#");let a,c;if(-1!==i?(a=n.slice(0,i).trim(),c=n.slice(i+1).trim()):a=n,!a)throw new ma("Missing marketplace name",e);if(!r.test(a))throw new ma("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:s,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function wa(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 ya(e){return e.sourceInfo.name}function va(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ba(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function Sa(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const ka=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Ea(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=>ka.has(e)))}const Ca=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,xa=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),_a=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Pa(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return _a.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Ra(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Ra(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Ra(r,t)}else for(const[,r,o,s]of e.matchAll(Ca)){const e=r??o;if(void 0===e||xa.has(e)||t.has(e))continue;const n=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:n,defaultValue:s})}}function Ia(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Ra(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const{reference:o,defaultValue:s}=t.get(e);r[e]={type:"string",title:Pa(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Ea(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}var Ta=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const Aa=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Ma=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Da(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 Oa(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Ma.exec(e);if(null!==t)return t[1]}}function Na(e){return void 0===e?{kind:"absent"}:Aa.has(e)?{kind:"supported",id:e,version:Oa(e)??e}:{kind:"unsupported",id:e}}const ja=10485760,$a=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Fa=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],La=[".cursor-plugin",".claude-plugin"],Ua=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Ba=io.z.object({source:io.z.literal("github"),repo:io.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:io.z.string().optional(),sha:io.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),za=io.z.object({source:io.z.literal("url"),url:io.z.string().url().endsWith(".git","URL must end with .git"),ref:io.z.string().optional(),sha:io.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Wa=io.z.object({source:io.z.literal("git-subdir"),url:io.z.string().url().endsWith(".git","URL must end with .git"),path:io.z.string().min(1),ref:io.z.string().optional(),sha:io.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Ha=io.z.union([io.z.string(),Ba,za,Wa]),qa=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Ga='Must be a semver version (X.Y.Z) or "never"',Va=io.z.object({cursor:io.z.string().regex(qa,Ga).optional(),sand:io.z.string().regex(qa,Ga).optional()}),Ja=io.z.object({name:io.z.string().min(1,"Author name is required"),email:io.z.string().email().optional()}),Ka=io.z.enum(["string","number","integer","boolean","object","array","null"]),Za=io.z.union([Ka,io.z.array(Ka).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:io.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function Qa(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:io.z.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:io.z.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:io.z.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:io.z.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:io.z.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:io.z.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:io.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const Xa=io.z.lazy((()=>io.z.object({type:Za.optional(),title:io.z.string().optional(),description:io.z.string().optional(),format:io.z.string().optional(),writeOnly:io.z.boolean().optional(),default:io.z.unknown().optional(),enum:io.z.array(io.z.any()).nonempty().optional(),const:io.z.unknown().optional(),properties:io.z.record(io.z.string(),Xa).optional(),required:io.z.array(io.z.string()).optional(),additionalProperties:io.z.union([io.z.boolean(),Xa]).optional(),items:io.z.union([Xa,io.z.array(Xa)]).optional(),minLength:io.z.number().int().nonnegative().optional(),maxLength:io.z.number().int().nonnegative().optional(),minimum:io.z.number().optional(),maximum:io.z.number().optional(),exclusiveMinimum:io.z.number().optional(),exclusiveMaximum:io.z.number().optional(),multipleOf:io.z.number().positive().optional(),minItems:io.z.number().int().nonnegative().optional(),maxItems:io.z.number().int().nonnegative().optional(),uniqueItems:io.z.boolean().optional(),minProperties:io.z.number().int().nonnegative().optional(),maxProperties:io.z.number().int().nonnegative().optional()}).strict().superRefine(Qa)));function Ya(e){const t=Xa.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:io.z.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?{success:!0,data:t.data}:t}const ec=io.z.unknown().superRefine(((e,t)=>{const r=Ya(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),tc=(io.z.object({name:io.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>$a.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:io.z.string().optional(),source:Ha,description:io.z.string().optional(),version:io.z.string().optional(),author:Ja.optional(),publisher:io.z.string().min(1).optional(),homepage:io.z.string().url().optional(),repository:io.z.string().url().optional(),license:io.z.string().optional(),keywords:io.z.array(io.z.string()).optional(),capabilities:fa.optional(),logo:io.z.string().optional(),category:io.z.string().optional(),tags:io.z.array(io.z.string()).optional(),minClientVersions:Va.optional(),strict:io.z.boolean().default(!0),commands:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),agents:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),skills:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),rules:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),hooks:io.z.union([io.z.string(),io.z.record(io.z.unknown())]).optional(),variables:ec.optional(),mcpServers:io.z.union([io.z.string(),io.z.record(io.z.unknown()),io.z.array(io.z.union([io.z.string(),io.z.record(io.z.unknown())]))]).optional()}),io.z.object({description:io.z.string().optional(),version:io.z.string().optional(),pluginRoot:io.z.string().optional()}),io.z.object({name:io.z.string().min(1).regex($a,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:io.z.string().optional(),description:io.z.string().optional(),version:io.z.string().optional(),author:Ja.optional(),publisher:io.z.string().min(1).optional(),homepage:io.z.string().url().optional(),repository:io.z.string().url().optional(),license:io.z.string().optional(),logo:io.z.string().optional(),keywords:io.z.array(io.z.string()).optional(),capabilities:fa.optional(),minClientVersions:Va.optional(),commands:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),agents:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),skills:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),rules:io.z.union([io.z.string(),io.z.array(io.z.string())]).optional(),hooks:io.z.union([io.z.string(),io.z.record(io.z.unknown())]).optional(),variables:ec.optional(),mcpServers:io.z.union([io.z.string(),io.z.record(io.z.unknown()),io.z.array(io.z.union([io.z.string(),io.z.record(io.z.unknown())]))]).optional()}));function rc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oc(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function sc(e,t){if(rc(e)&&"string"==typeof e.name){const t=oc(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?oc(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,s.randomUUID)()}`}(t)}function nc(e){if(rc(e)&&rc(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 ic(e){return"string"==typeof e?e:void 0}function ac(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function cc(e){return"string"==typeof e?e:ac(e)}function lc(e){if(!rc(e)||!rc(e.metadata))return;const t={description:ic(e.metadata.description),version:ic(e.metadata.version),pluginRoot:ic(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function uc(e){if(!rc(e))return;const t=ic(e.name);if(void 0===t||0===t.length)return;const r=ic(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function dc(e){if("string"==typeof e||rc(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||rc(e)));return t.length>0?t:void 0}}function hc(e){if("string"==typeof e||rc(e))return e}function pc(e){if(void 0===e)return;const t=Ya(e);return t.success?t.data:void 0}function fc(e,t={}){if(e.length>ja)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(!rc(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const o=[],s=[],n=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!rc(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(o=e.source)?o:rc(o)?"github"===o.source&&"string"==typeof o.repo&&o.repo.length>0?{source:"github",repo:o.repo,ref:ic(o.ref),sha:ic(o.sha)}:("url"===o.source||void 0===o.source)&&"string"==typeof o.url&&o.url.length>0?{source:"url",url:o.url,ref:ic(o.ref),sha:ic(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:ic(o.ref),sha:ic(o.sha)}:"string"==typeof o.repo&&o.repo.length>0?{source:"github",repo:o.repo,ref:ic(o.ref),sha:ic(o.sha)}:void 0:void 0;var o;if(void 0===r){const r=ic(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 s=("string"==typeof e.name?oc(e.name):"")||function(e){if("string"==typeof e){const t=oc((0,i.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=oc(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=oc((0,i.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=oc((0,i.basename)(t));return r.length>0?r:void 0}(r);if(void 0===s)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const n=fa.safeParse(e.capabilities);if(void 0!==e.capabilities&&!n.success)return{skippedEntry:{index:t,name:s,error:`Plugin entry at index ${t} has invalid capabilities: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=n.success?n.data:void 0,c=function(e){const t=Va.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand))return t.data}(e.minClientVersions);return{entry:{name:s,displayName:ic(e.displayName),source:r,description:ic(e.description),version:ic(e.version),author:uc(e.author),publisher:ic(e.publisher),homepage:ic(e.homepage),repository:ic(e.repository),license:ic(e.license),keywords:ac(e.keywords),logo:ic(e.logo),category:ic(e.category),tags:ac(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:cc(e.commands),agents:cc(e.agents),skills:cc(e.skills),rules:cc(e.rules),hooks:hc(e.hooks),variables:pc(e.variables),mcpServers:dc(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?s.push(r.skippedEntry):n.has(r.entry.name)?s.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(n.add(r.entry.name),o.push(r.entry))})),{success:!0,data:{name:sc(r,t),owner:nc(r),description:ic(r.description),plugins:o,metadata:lc(r),skippedPluginEntries:s}}}function mc(e){if(e.length>ja)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=Na(Da(t)),o=tc.safeParse(t);return o.success?{success:!0,data:o.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${o.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:o.error}}function gc(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 wc(e){return!e.includes("..")&&!(0,i.isAbsolute)(e)&&!e.includes("://")}function yc(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}new Ta.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var vc=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const bc=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Sc(e,t){return kc(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 kc(e,t){if("string"==typeof e)return e.replace(bc,((e,r,o,s)=>{if(void 0!==r)return t(r)??e;const n=t(o);return void 0!==n?n:void 0!==s?s:e}));if(Array.isArray(e))return e.map((e=>kc(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[o,s]of Object.entries(e))r[o]=kc(s,t);return r}return e}function Ec(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Cc=[".mcp.json","mcp.json"],xc=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function _c(e,t){if(!function(e){return xc.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 Pc(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Rc(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Cc.map((e=>void 0!==t?`${t}/${e}`:e))}function Ic(e,t,r){if(!e.mcpServers)return e;const o={};for(const[r,s]of Object.entries(e.mcpServers)){const e={...s};if("string"==typeof s.command&&(e.command=Ec(s.command,t)),Array.isArray(s.args)&&(e.args=s.args.map((e=>"string"==typeof e?Ec(e,t):e))),s.env&&"object"==typeof s.env){const r={};for(const[e,o]of Object.entries(s.env))r[e]="string"==typeof o?Ec(o,t):o;e.env=r}"string"==typeof s.cwd&&(e.cwd=Ec(s.cwd,t)),o[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,o=t?.configuredVariables;return Sc(e,void 0!==r?r:e=>{const t=process.env[e];if(void 0!==t)return t;const r=o?.[e];return null!=r?"string"==typeof r?r:String(r):void 0})}({...e,mcpServers:o},r)}function Tc(e,t,r){try{const o=(0,vc.qg)(e),s=Da(o);if(void 0!==s){const e=r?.log??ua;"unsupported"===Na(s).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${s}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Oa(e),o=Oa(t);return void 0!==r&&void 0!==o&&r!==o}(r?.pluginSchemaId,s)&&e.log("debug",`mcp.json $schema ${s} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const n=ha.safeParse(o),i=!0===r?.skipExpansion;if(n.success&&n.data.mcpServers&&Object.keys(n.data.mcpServers).length>0)return i?n.data:Ic(n.data,t,r);const a={};for(const[e,t]of Object.entries(o))"mcpServers"!==e&&!_c(e,t)&&Pc(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=ha.safeParse({mcpServers:a});if(e.success)return i?e.data:Ic(e.data,t,r)}return null}catch{return null}}function Ac(e,t,r){for(const[o,s]of Object.entries(t))e.mcpServers[o]=s,e.mcpServerSourcePaths[o]=r}async function Mc(e,t,r,o={}){const s=o.toSourcePath??(e=>e),n=o.installPathForExpansion??"",i=o.fallbackFileNames??Cc,a=o.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Tc(r,n,o.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=s(t))}if(void 0!==t){const i=await async function(e,t,r={}){const o=r.toSourcePath??(e=>e),s=r.installPathForExpansion??"",n={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!wc(i))return;const a=await t(i);if(null===a)return;const c=Tc(a,s,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Ac(n,c.mcpServers,o(i))},a=e=>{const t=Tc(JSON.stringify(e),s,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Ac(n,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 n}(t,e,{toSourcePath:s,manifestSourcePath:r,installPathForExpansion:n,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 Dc(e,t,r,o,s,n){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:s,pluginSource:n,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:s,pluginSource:n,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 Oc=r("node:stream"),Nc=r("node:stream/promises"),jc=r("node:zlib"),$c=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const Fc=".cache-complete";function Lc(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function Uc(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function Bc(e){return yt(e)}function zc(e,t){return function(e,t,r,o){const s=[e,t,r];return void 0!==o&&s.push(o),(0,i.join)(...s)}(e,Lc(t.marketplaceSlug),Uc(t.pluginId),void 0!==t.version?Bc(t.version):void 0)}class Wc{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,i.join)(r,".cursor","plugins/cache")}getCacheDir(e){return zc(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=(0,i.join)(t,Fc);return(await(0,Qs.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,Qs.mkdir)(t,{recursive:!0});const r=Oc.Readable.from(e.tarball);return await(0,Nc.pipeline)(r,(0,jc.createGunzip)(),(0,$c.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=Lc(e.marketplaceSlug),r=Uc(e.pluginId),o=(0,i.join)(this.cacheRoot,t,r);try{return(await(0,Qs.readdir)(o,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Qs.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=zc(this.cacheRoot,e);await(0,Qs.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=>Bc(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,Qs.writeFile)((0,i.join)(t,Fc),"")}}function Hc(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 qc=r("node:child_process");const Gc=[["safe.bareRepository","explicit"]],Vc=[["core.fsmonitor","false"],["core.hooksPath",n.devNull],["core.attributesFile",n.devNull]];function Jc(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(String(t),10);return!Number.isFinite(r)||r<0?0:r}(e),o={...e},s=new Set;for(let e=0;e<r;e++){const r=o[`GIT_CONFIG_KEY_${e}`];for(const[n,i]of t)r===n&&(o[`GIT_CONFIG_VALUE_${e}`]=i,s.add(n))}let n=r;for(const[e,r]of t)s.has(e)||(o[`GIT_CONFIG_KEY_${n}`]=e,o[`GIT_CONFIG_VALUE_${n}`]=r,n++);return n!==r&&(o.GIT_CONFIG_COUNT=String(n)),o}(t,function(e){const t="allow-hooks"===e?Vc.filter((([e])=>"core.hooksPath"!==e)):Vc;return[...Gc,...t]}(e.repoConfigExecution??"block"))}const Kc=(0,Gn.promisify)(qc.execFile);function Zc(e){const t=new Set(["-c","-C","--git-dir","--work-tree"]);for(let r=0;r<e.length;r++){const o=e[r];if(t.has(o))r++;else if(!o.startsWith("-"))return o}}function Qc(e,t){return Jc({command:Zc(e),optionsEnv:t})}async function Xc(e,t,r){const{env:o,encoding:s="utf8",...n}=r??{},i=await Kc(e,t,{...n,encoding:s,env:Qc(t,o)});return{stdout:String(i.stdout),stderr:String(i.stderr)}}function Yc(e,t,r){const{env:o,...s}=r??{};return(0,qc.spawn)(e,t,{...s,env:Qc(t,o)})}function el(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function tl(e){return"function"==typeof e?e():e}async function rl(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,s]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=o,t[`GIT_CONFIG_VALUE_${e}`]=s}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig});return Xc("git",[...el(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const ol=/^[0-9a-f]{7,40}$/i,sl=/^[0-9a-f]{40}$/i;function nl(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 il(e,t,r){const o=t.trim();if(sl.test(o))return{fullSha:o.toLowerCase()};if(ol.test(o)){try{const t=await async function(e,t,r){const{stdout:o}=await rl(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return nl(o)?.toLowerCase()}(e,o,r);if(t)return{fullSha:t}}catch{}return{fullSha:o.toLowerCase()}}let s;try{if("HEAD"===o.toUpperCase()){const t=await rl(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),o=nl(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}}s=(await rl(["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),s=new Error(`Failed to resolve git ref "${o}" for ${e}: ${r}`);throw s.cause=t,s}const n=nl(s);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for ref "${o}" (${e})`);return{fullSha:n.toLowerCase()}}const al=Ua.map((e=>e.split("/")[0]));let cl;function ll(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 ul(e){const t=[];for(const r of e){const e=ll(r);if(null===e)return"all";t.push(e)}return t}async function dl(e,t){const r="all"===e?"all":ul(e),o=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(cl??=(async()=>{try{const{stdout:e}=await rl(["--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}})(),cl));return{materialize:r,sparse:o,sparseDirs:o?(s=r,[...new Set([...al,...s])]):[]};var s}function hl(e){return e.toLowerCase().includes("filtering not recognized by server")}async function pl(e,t,r){await rl(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function fl(e){try{await(0,Qs.access)((0,i.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await rl(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function ml(e,t,r){if("all"!==t&&0===t.length)return;if(!await fl(e))return;const o={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await rl(["sparse-checkout","disable"],o);const s=ul(t);"all"!==s?await rl(["sparse-checkout","add","--",...s],o):await rl(["sparse-checkout","disable"],o)}const gl=/\.git$/i,wl=new Set(["account","dashboard"]);function yl(e){return e.replace(gl,"")}function vl(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function bl(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Sl(e){return e.toLowerCase().split(".").includes("gitlab")}function kl(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function El(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map,new Map([["cursor.com","origin.cursor.com"],["www.cursor.com","origin.cursor.com"],["staging.cursor.com","origin-staging.cursor.com"]]);const Cl=new Map;function xl(e){if(void 0===e)return;if(Cl.has(e))return Cl.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||!El(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(),s=2===r.length&&"git"!==r[0]?.toLowerCase();if(!o&&!s)return;const n=o?r[1]:r[0],i=o?r[2]:r[1];return n&&i?Object.freeze({hostname:t.hostname,owner:n,name:i}):void 0}(e);return Cl.size>=2048&&Cl.clear(),Cl.set(e,t),t}function _l(e){return void 0!==function(e){const t=xl(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}function Pl(e){const t=e.toLowerCase();return Sl(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Rl(e){return bl(e)?"github":Sl(e)?"gitlab":kl(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Il(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);El(r)&&"git"===o[0]?.toLowerCase()&&(o=o.slice(1)),o.length>=3&&"scm"===o[0].toLowerCase()&&(o=o.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const o=yl(r);return o?{owner:t,repo:o,hasSubpath:e.length>2}:void 0}(o);return void 0===s?null:{provider:Rl(r),owner:s.owner,repo:s.repo,host:r}}function Tl(e){const t=Al(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean);return r.length>=3&&"scm"===r[0].toLowerCase()}function Al(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function Ml(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Il(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Sl(r.host)){const e=Al(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 s=yl(o[o.length-1]);return s?(o[o.length-1]=s,{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=Al(e.trim());if(null!==t&&kl(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const o=vl(t),s=vl(r);if(void 0===o||void 0===s||wl.has(o.toLowerCase()))return;const n=yl(s);return n?{workspace:encodeURIComponent(o),repo:encodeURIComponent(n),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=Al(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 s=yl(o);if(!s)return;const n=2===t?e[1]:s;return n?{organization:r,project:n,repo:s,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 s=r.host.replace(/^www\./i,"");return{url:`https://${s}/${o.organization}/${o.project}/_git/${o.repo}`,owner:o.organization,repo:o.repo,host:s,provider:"azure_devops",project:o.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!El(e.host)&&null===Pl(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=Ol(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Tl(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const o=Pl(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==o?` ${o} is not supported yet.`:"")}}function Dl(e){const t=Ml(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 Ol(e){return bl(e)?"github.com":e}function Nl(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 jl(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function $l(e,t){const r=(0,i.resolve)(e),o=(0,i.resolve)(e,t),s=(0,i.relative)(r,o);if(s.startsWith("..")||(0,i.isAbsolute)(s))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return o}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Fl=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 Ll(e){const t=yt(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":Fl.has(t.toLowerCase())?`_${t}`:t}const Ul=18e5,Bl=6e5,zl={recursive:!0,force:!0,maxRetries:3},Wl=["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"],Hl=["enotempty: directory not empty, rename","/_staging/"],ql=["upload-pack: not our ref","server does not allow request for unadvertised object"];function Gl(e){const t=String(e).toLowerCase().replaceAll("\\","/");return Wl.some((e=>t.includes(e)))?"user_git_access":Hl.every((e=>t.includes(e)))?"local_cache_race":ql.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function Vl(e){return"object"==typeof e&&null!==e&&(!0===e.killed||Vl(e.cause))}function Jl(e){return Vl(e)?"killed_by_budget":Gl(e)}function Kl(e){const t=Ml(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=Il(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:Ol(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const Zl=new Map;class Ql{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?Ul:void 0}localTimeoutMs(){return this.sparsePluginClones?Bl:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,o){const s={cwd:e,sshBatchMode:o?.sshBatchMode,extraGitConfig:{...tl(this.options?.extraGitConfig),"safe.directory":e}},{sparse:n,sparseDirs:i}=await dl(o?.materialize??"all",this.sparsePluginClones);await rl(["init"],{...s,timeoutMs:this.localTimeoutMs()}),n&&await pl(e,i,{sshBatchMode:o?.sshBatchMode,extraGitConfig:tl(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await rl(["fetch","--depth","1",...n?["--filter=blob:none"]:[],t,r],{...s,timeoutMs:this.remoteTimeoutMs()});return await rl(["checkout","FETCH_HEAD"],{...s,timeoutMs:this.remoteTimeoutMs()}),{strategy:n?"sparse":"full",filterIgnoredByServer:n&&hl(a??"")}}async createStagingDir(){const e=(0,i.join)(this.cacheRoot,"_staging",(0,s.randomUUID)());return await(0,Qs.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Qs.mkdir)((0,i.dirname)(t),{recursive:!0}),await(0,Qs.rm)(t,zl),await(0,Qs.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,i.join)(this.cacheRoot,"_staging");try{const t=await(0,Qs.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const o=(0,i.join)(e,t.name),s=await(0,Qs.stat)(o);r-s.mtimeMs>Ql.STALE_STAGING_THRESHOLD_MS&&await(0,Qs.rm)(o,zl)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,i.join)(this.cacheRoot,Ll(e),Ll(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:o}=Kl(e);return(0,i.join)(this.cacheRoot,Ll(r),...o.map(Ll),Ll(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=Kl(e);return(0,i.join)(this.cacheRoot,Ll(t),...r.map(Ll))}async pruneSiblingCloneDirs(e,t,r){const o=this.getCanonicalRepoRootDir(e),s=Ll(t);try{const e=await(0,Qs.readdir)(o,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==s)).map((e=>(0,Qs.rm)((0,i.join)(o,e.name),zl))))}catch{}if(void 0!==r)try{await(0,Qs.rm)(r,zl)}catch{}}async ensureCloned(e,t,r,o=ua,s){const n=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,o,s?.materialize??"all")));return this.sparsePluginClones?n:(0,vt.wj)(n,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=ua){const o=this.serializedOnRepo((0,i.dirname)(e),(async()=>{const o=performance.now();try{await ml(e,t,{extraGitConfig:tl(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(s){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(s),errorCategory:Jl(s)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:Jl(s)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o,{outcome:"error"}),s}}));return this.sparsePluginClones?o:(0,vt.wj)(o,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,o=(Zl.get(r)??Promise.resolve()).catch((()=>{})).then(t);Zl.set(r,o);try{return await o}finally{Zl.get(r)===o&&Zl.delete(r)}}async ensureClonedImpl(e,t,r,o,s){o.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const n=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:Dl(t);if(null!==a)try{i=(await il(a,n,{sshBatchMode:!0,extraGitConfig:tl(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&Vl(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:Gl(e)}),a=null,i=(await il(t,n,{extraGitConfig:tl(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await il(t,n,{extraGitConfig:tl(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,n);o.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:n});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 fl(c);return e&&await ml(c,s,{extraGitConfig:tl(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,s)}async cloneViaStaging(e,t,r,o,s,n,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${n} into staging directory: ${l}`,{gitUrl:t,ref:n,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Qs.utimes)(l,e,e).catch((()=>{}))}),Ql.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&&Vl(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:n,error:String(e),errorCategory:Jl(e)}),await(0,Qs.rm)(l,zl),await(0,Qs.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:n}),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,s),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=Jl(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:n,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,Qs.rm)(l,zl)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Qs.stat)(e)).isDirectory())return!1;const t=await(0,Qs.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Qs.stat)((0,i.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return $l(e,t)}async copyPluginToDir(e,t){await(0,Qs.mkdir)(t,{recursive:!0}),await(0,Qs.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 Ua){const o=(0,i.join)(e,r);let s;try{s=await(0,Qs.readFile)(o,"utf-8")}catch{continue}const n=fc(s,t);if(n.success)return n.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 s=gc(o.source,r.metadata?.pluginRoot);return s&&wc(s)?s: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 s=gc(e,t);null!==s?r.push({entry:o,kind:"local",localPath:s}):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:s,version:n}=e.entry,i={name:r,displayName:o,description:s,version:n};switch(e.kind){case"local":wc(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):[]}}Ql.STALE_STAGING_THRESHOLD_MS=3e5,Ql.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const Xl=(0,Gn.debuglog)("cursor-plugins");function Yl(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function eu(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 tu(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!hu(e,t.gitUrl)?e:r:e}function ru(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function ou(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=eu(e.plugin,t),o=e.plugin?.gitUrl,s=r?.gitUrl;return o&&s&&o!==s||!r?.gitRef?"main":r.gitRef}const su="backend-git://";function nu(e,t,r){const o=r?`#${encodeURIComponent(r)}`:"";return`${su}${encodeURIComponent(e)}@${encodeURIComponent(t)}${o}`}function iu(e){if(!e.startsWith(su))return null;const t=e.slice(14),r=t.indexOf("#"),o=r>=0?t.slice(0,r):t,s=r>=0?t.slice(r+1):void 0,n=o.lastIndexOf("@");return n<0?null:{gitUrl:decodeURIComponent(o.slice(0,n)),ref:decodeURIComponent(o.slice(n+1)),gitPath:s?decodeURIComponent(s):void 0}}const au="backend-release://";function cu(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${au}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function lu(e){if(!e.startsWith(au))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const o=decodeURIComponent(t.slice(0,r)),s=t.slice(r+1),n=s.lastIndexOf("@");return{repo:o,asset:n>=0?decodeURIComponent(s.slice(0,n)):decodeURIComponent(s),tag:n>=0?decodeURIComponent(s.slice(n+1)):void 0}}const uu=/^[0-9a-f]{7,40}$/i;function du(e){let t;try{t=Kl(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function hu(e,t){if(e.trim()===t.trim())return!0;const r=du(e),o=du(t);return null!==r&&r===o}const pu=104857600;async function fu(e,t,r,o,a,c){const l=await async function(e){const{repo:t,asset:r,tag:o}=e,{apiBase:n,ownerRepo:i,host:a}=function(e){const t=e.split("/");if(3===t.length)return{apiBase:`https://${t[0]}/api/v3`,ownerRepo:`${t[1]}/${t[2]}`,host:t[0]};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),c="github.com"===a&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},l=o?`${n}/repos/${i}/releases/tags/${encodeURIComponent(o)}`:`${n}/repos/${i}/releases/latest`,u=await fetch(l,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...c}});if(!u.ok)throw new Error(`Failed to fetch release from ${l}: ${u.status} ${u.statusText}`);const d=await u.json(),h=d.assets.find((e=>e.name===r));if(!h){const e=d.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(h.size>pu)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${h.size})`);const p=new URL(h.browser_download_url);if("https:"!==p.protocol||!mu(p.hostname,a))throw new Error(`Refusing to download release asset from untrusted host: ${p.hostname}`);const f=await fetch(h.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...c}});if(!f.ok)throw new Error(`Failed to download release asset: ${f.status} ${f.statusText}`);if(f.url){const e=new URL(f.url);if("https:"!==e.protocol||!mu(e.hostname,a))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const m=Buffer.from(await f.arrayBuffer());if(m.byteLength>pu)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${m.byteLength})`);if(e.expectedSha256){const t=(0,s.createHash)("sha256").update(m).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return m}({repo:e,asset:t,tag:r,expectedSha256:a,githubToken:c}),u=l.byteLength;await(0,Qs.mkdir)(o,{recursive:!0});const d=await(0,Qs.mkdtemp)((0,i.join)((0,n.tmpdir)(),"release-asset-")),h=(0,i.join)(d,"asset.tar.gz"),p=(0,i.join)(d,"extracted");try{await(0,Qs.writeFile)(h,l),await(0,Qs.mkdir)(p,{recursive:!0});let e=0,t=0;await $c.x({file:h,cwd:p,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(u>0&&e/u>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Qs.readdir)(p,{withFileTypes:!0}),s=r.filter((e=>e.isDirectory())),n=r.filter((e=>e.isFile()));let a=p;if(1===s.length&&0===n.length){const e=(0,i.join)(p,s[0].name);(await(0,Qs.readdir)(e)).some((e=>La.includes(e)))&&(a=e)}const c=await(0,Qs.readdir)(a);await Promise.all(c.map((e=>(0,Qs.cp)((0,i.join)(a,e),(0,i.join)(o,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Qs.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}function mu(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class gu{constructor(e,t,r,o,s){this.getEffectiveUserPlugins=e;const n="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:o,listOptions:s}:t,i=n.marketplaceCacheOptions??o;this.pluginLogger=n.pluginLogger??r??ua,this.extraGitConfig=n.extraGitConfig,this.awaitAuthReady=n.awaitAuthReady,this.githubToken=n.githubToken,this.sparsePluginClones=n.sparsePluginClones??!1,this.marketplaceCache=n.marketplaceCacheRoot?new Ql(n.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??n.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=n.listOptions??s;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??[],i=[],a=[],c=new Map,l=async(e,t)=>{const r=`${e}\0${t}`;let o=c.get(r);if(!o){const s=tl(this.extraGitConfig),n=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:Dl(e),a=async(e,r)=>{const o={};return r&&(o.sshBatchMode=!0),void 0!==s&&(o.extraGitConfig=s),void 0!==n&&(o.timeoutMs=n),(Object.keys(o).length>0?await il(e,t,o):await il(e,t)).fullSha};if(null!==i)try{o=await a(i,!0)}catch(t){if(this.sparsePluginClones&&Vl(t))throw t;o=await a(e,!1)}else o=await a(e,!1);c.set(r,o)}return o},u=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:o,pluginId:s}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${o}`,n=!c.has(e);let i;n&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await l(t,o),gitUrl:t}}catch(e){n&&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:s,preferredGitUrl:t,sourceGitUrl:r,gitRef:o,error:String(e)})}if(void 0!==i){if(n)try{this.pluginLogger.log("info",`Resolved plugin ${s} from Origin distribution mirror ${t}@${o}`,{pluginId:s,preferredGitUrl:t,gitRef:o})}catch{}return i}}return{sha:await l(r,o),gitUrl:r}};for(const e of o){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=eu(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=Yl({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),c=o;if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${o} without gitUrl (enableInlinePlugins=false)`,{pluginId:c});continue}const n=e.inlineContentJson;if(!n){this.pluginLogger.log("info",`Skipping DB-inline plugin ${o}: no inline content provided`,{pluginId:c});continue}const a=(0,s.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),l=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: ${c}`,{pluginId:c,marketplaceId:l?.id??"unknown",version:a}),i.push({pluginId:c,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:o,version:a,downloadUrl:`inline://${t.id??c}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:l,inlineContentJson:n});continue}const l=t.gitUrl,d=tu(l,r),h=ou(e,n),p=Hc(t,h),f=r?.gitRef??h;let m,g,w=d;try{if(void 0!==p)m=`release/${p.releaseTag}`;else{const e=await u({preferredGitUrl:d,sourceGitUrl:l,gitRef:h,pluginId:c});m=e.sha,w=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${o}@${h}, skipping plugin`,{pluginId:c,ref:h,error:String(e)});const s=e instanceof Error?e.message:String(e);a.push({pluginName:o,pluginId:c,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:s,errorType:/timed?\s*out/i.test(s)?"timeout":"clone"});continue}g=void 0!==p?cu({repo:p.releaseRepo,asset:p.releaseAsset,tag:p.releaseTag}):nu(w,h,t.gitPath??void 0);const y=ru(r);let v=y,b=r?.gitUrl,S=f;if(r?.gitUrl&&y){const e=hu(l,r.gitUrl),t=e?w:y,s=e?l:r.gitUrl,n=e?h:f;b=s;try{const e=await u({preferredGitUrl:t,sourceGitUrl:s,gitRef:n,pluginId:c});S=e.sha,v=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}@${n}, falling back to raw ref`,{pluginId:c,cacheRepoUrl:t,cacheRef:n,error:String(e)}),v=s}}const k=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...v&&{gitUrl:v,gitRef:S}}:void 0,E=void 0!==p||w===l&&v===b?void 0:{downloadUrl:nu(l,h,t.gitPath??void 0),marketplaceGitUrl:b};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${c} from ${S} at ${t.gitPath}`,{pluginId:c,marketplaceId:k?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:S}),i.push({pluginId:c,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:o,version:m,downloadUrl:g,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:k,gitPath:t.gitPath??void 0,isOriginBacked:void 0===p&&w!==l||void 0,originSourceFallback:E})}return{plugins:i,listFailures:a}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=iu(e.downloadUrl);return!(!r||!hu(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,s=JSON.parse(r);await(0,Qs.mkdir)(t,{recursive:!0});const n={};if(s.rules&&s.rules.length>0){const e=(0,i.join)(t,"rules");await(0,Qs.mkdir)(e,{recursive:!0});const r=[];for(const t of s.rules){if(!t.content)continue;if(!1===t.isActive)continue;const o=`${yt(t.name)}.md`,s=[];s.push(`description: ${jl(t.name)}`),t.globs&&t.globs.length>0&&s.push(`globs: ${jl(t.globs.join(", "))}`),s.push(`alwaysApply: ${!0===t.isRequired}`);const n=`---\n${s.join("\n")}\n---\n\n`;await(0,Qs.writeFile)((0,i.join)(e,o),n+t.content,"utf-8"),r.push(`rules/${o}`)}r.length>0&&(n.rules=r)}if(s.commands&&s.commands.length>0){const e=(0,i.join)(t,"commands");await(0,Qs.mkdir)(e,{recursive:!0});const r=[];for(const t of s.commands){if(!t.content)continue;if(!1===t.isActive)continue;const o=`${yt(t.name)}.md`,s=t.description?`---\ndescription: ${jl(t.description)}\n---\n\n`:"";await(0,Qs.writeFile)((0,i.join)(e,o),s+t.content,"utf-8"),r.push(`commands/${o}`)}r.length>0&&(n.commands=r)}if(s.hooks&&s.hooks.length>0){const e=(0,i.join)(t,"hooks");await(0,Qs.mkdir)(e,{recursive:!0});const r={};for(const e of s.hooks){const t=e.hookStep;t&&!1!==e.isActive&&Nl(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,Qs.writeFile)((0,i.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(s.mcpServers&&s.mcpServers.length>0){const e={};for(const t of s.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Qs.writeFile)((0,i.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:o,...n},c=(0,i.join)(t,".cursor-plugin");await(0,Qs.mkdir)(c,{recursive:!0}),await(0,Qs.writeFile)((0,i.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,Qs.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===lu(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)&&Vl(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=ua,o,s){const a=s?.sparsePluginClones??!1,c=a?Ul:void 0,l=lu(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Qs.mkdtemp)((0,i.join)((0,n.tmpdir)(),"release-plugin-"));try{await fu(l.repo,l.asset,l.tag,r,s?.expectedReleaseAssetSha256,s?.githubToken);const o=$l(r,e.gitPath);await(0,Qs.mkdir)(t,{recursive:!0}),await(0,Qs.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Qs.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await fu(l.repo,l.asset,l.tag,t,s?.expectedReleaseAssetSha256,s?.githubToken);return}const u=iu(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Qs.mkdtemp)((0,i.join)((0,n.tmpdir)(),"backend-plugin-"));try{let s;if(await async function(e,t,r,o=ua,s,n="all",i=!1){const a=performance.now(),c=uu.test(t),l="HEAD"===t.toUpperCase(),u={...s,"safe.directory":r},d=i?Ul:void 0,h=i?Bl:void 0,{sparse:p,sparseDirs:f}=await dl(n,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await pl(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,o)=>{let s="";return l?(({stderr:s}=await rl(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:o})),await w(d)):c?(await rl(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await rl(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:s}=await rl(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:o})),await rl(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:o})):(({stderr:s}=await rl(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:o})),await w(d)),s},v=e.startsWith("git@")||e.startsWith("ssh://")?null:Dl(e);let b="";if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&Vl(t))throw t;await(0,Qs.rm)(r,{recursive:!0,force:!0}),await(0,Qs.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&hl(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);Xl("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?ul([u.gitPath]):[],a),u.gitPath)s=$l(d,u.gitPath);else{const t=await async function(e,t){for(const r of Ua){const o=(0,i.join)(e,r);let s;try{s=await(0,Qs.readFile)(o,"utf-8")}catch{continue}const n=fc(s);if(!n.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${n.error}`};const a=n.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=gc(c.source,a.metadata?.pluginRoot);return l&&wc(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 ml(d,ul([t.gitPath]),{extraGitConfig:o,timeoutMs:c}),s=$l(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 ml(d,"all",{extraGitConfig:o,timeoutMs:c}),s=d}}await(0,Qs.mkdir)(t,{recursive:!0}),await(0,Qs.cp)(s,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Qs.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,tl(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",s=`${e.id}\0${e.gitUrl}\0${o}`;let n=r.get(s);void 0===n&&(n={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:o,gitPaths:[]},r.set(s,n)),t.gitPath&&n.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=ul(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 s=await r.ensureCloned(o.id,o.gitUrl,o.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?ul([e.gitPath]):[]}),n=e.gitPath??await r.resolvePluginPath(s,e.name);if(!n)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(s,ul([n]),this.pluginLogger);const i=r.getPluginDir(s,n);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 s=await o.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return o.discoverPlugins(s)}}function wu(e,t,r,o,s){return new gu(e,t,r,o,s)}var yu=r("node:url"),vu=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const bu=()=>({});function Su(e,t){return vu(e,{...t,engines:{...t?.engines,js:bu,javascript:bu}})}function ku(e,t,r){return vu.stringify({content:e,data:{}},t,r)}function Eu(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Cu(e,t,r,o){const s=e?.plugins;if(!s||"object"!=typeof s)return[];const n=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==o?Eu(o):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(s)){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)&&(Eu(t.projectPath)===a&&!0===i[e])))),r||!0!==n[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 xu=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const _u=[".md",".mdc",".markdown"],Pu=[..._u,".txt"],Ru=/^---\s*\n([\s\S]*?)\n---/;function Iu(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function Tu(e){const t=e.match(Ru);if(!t)return{};try{const e=xu.Ay.load(t[1],{schema:xu.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const r=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,o=Au(e.environments??r?.environments);return{disabledEnvironments:Au(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 Au(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 Mu(e){return Iu((0,i.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function Du(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 Ou{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",o=e.manifest;let s;try{s=await this.fetcher.listDirectory(t)}catch{s=[]}const n=new Set(s.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Cc.filter((e=>s.some((t=>"file"===t.type&&t.name===e)))),a=s.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,_u):n.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==o?.agents?this.discoverFromManifestPaths(r,o.agents,!1,_u):n.has("agents")?this.discoverMarkdownComponents(`${r}agents`,_u):Promise.resolve([]),void 0!==o?.hooks?this.discoverHooksFromManifest(r,o.hooks):n.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==o?.commands?this.discoverFromManifestPaths(r,o.commands,!1,Pu):n.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Pu):Promise.resolve([]),void 0!==o?.rules?this.discoverFromManifestPaths(r,o.rules,!1,_u):n.has("rules")?this.discoverMarkdownComponents(`${r}rules`,_u):Promise.resolve([]),this.discoverMcpServers(r,o?.mcpServers,i)]);return{skills:Du(c?[c,...l]:l),agents:Du(u),hooks:d,commands:Du(h),rules:Du(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:Iu(t),path:e,description:`Hook: ${t}`})))}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!wc(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:Iu(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,o=_u){if("string"==typeof t){if(!wc(t))return[];const s=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(s):this.discoverMarkdownComponents(s,o)}const s=[];for(const o of t)try{if(!wc(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);s.push(...r);continue}let r=Mu(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:o}=await this.fetcher.fetchFile(e),n=Tu(o);if(r=n.name??r,r){const t={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:Iu(r),path:e};void 0!==n.description&&(t.description=n.description),s.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=Mu(t);const{content:r}=await this.fetcher.fetchFile(t),o=Tu(r);e=o.name??e;const n=o.description;if(e){const r={name:Iu(e),path:t};void 0!==n&&(r.description=n),s.push(r)}}}catch{}return s}async discoverMarkdownComponents(e,t=_u,r=new Set){let o;try{o=await this.fetcher.listDirectory(e,r)}catch{return[]}const s=o.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),n=o.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(s.map((async e=>{try{let t=Mu(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),o=Tu(r);t=o.name?Iu(o.name):t;const s=o.description;if(!t)return null;const n={name:t,path:e.path};return void 0!==s&&(n.description=s),n}catch{return null}}))),Promise.all(n.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=Iu((0,i.basename)(e.replace(/[\\/]+$/,"")));const{content:o}=await this.fetcher.fetchFile(t),s=Tu(o);if(r=s.name?Iu(s.name):r,!r)return null;const n={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:r,path:t};return void 0!==s.description&&(n.description=s.description),n}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=Tu(r),s=o.name?Iu(o.name):Iu(e.name);if(!s)return null;const n={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:s,path:t};return void 0!==o.description&&(n.description=o.description),n}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const o=new Map,s=async t=>{const r=o.get(t);if(void 0!==r)return r;const s=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return o.set(t,s),s},n=async o=>Mc(s,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:o,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await n("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await n("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:Iu(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Ia(a??i),configs:l}}}function Nu(e){const t=e??process.env.HOME??"";return(0,i.join)(t,".claude")}async function ju(e){const t={enabledPlugins:{}};let r=!1;const o=(0,i.join)(e,".claude","settings.json");try{const e=await(0,Qs.readFile)(o,"utf-8"),s=JSON.parse(e);s.enabledPlugins&&(Object.assign(t.enabledPlugins,s.enabledPlugins),r=!0)}catch{}const s=(0,i.join)(e,".claude","settings.local.json");try{const e=await(0,Qs.readFile)(s,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch{}return r?t:null}async function $u(e){try{return(await(0,Qs.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Fu(e){if(await $u(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Qs.readFile)(e,"utf-8")}async function Lu(e){if((await(0,Qs.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Uu(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 Bu({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,i.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Qs.realpath)(e),o=$l(t,r),s=await(0,Qs.realpath)(o);if($l(t,s),!(await(0,Qs.stat)(s)).isFile())return;return await Lu(s),(0,yu.pathToFileURL)(s).href}catch{return}}function zu(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 Wu(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Hu(e,t){return zu({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function qu(e,t,r){let o;for(const s of Fa){const n=(0,i.join)(e,s);let a;try{if(await $u(n))continue;if(!(await(0,Qs.stat)(n)).isFile())continue;await Lu(n),a=await Fu(n)}catch{continue}const c=mc(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 Bu({installPath:e,logo:l.logo}),S=zu(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&&!Wu(S))continue;if(!g&&!C){o=o?{...o,fields:Hu(o.fields,S)}:{fields:S,path:n,relPath:s,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${s} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const x=Hu(S,o?.fields);return{manifestFilePath:n,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Wu(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 Gu(e,t){const r=function(e,t){const r=new Map,o=(0,i.resolve)(e),s=(0,i.resolve)(t?.symlinkTargetRoot??o),n=(0,Qs.realpath)(s).catch((()=>s));function a(e){const t=(0,i.resolve)(e);try{return $l(o,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await n,o=await(0,Qs.realpath)(t);try{return $l(r,o)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const o=a(t?(0,i.join)(e,t):e);try{const e=await c(o);if(r?.has(e))return[];r?.add(e);const s=await(0,Qs.readdir)(e,{withFileTypes:!0}),n=[];for(const e of s){const r=(0,i.join)(o,e.name);let s=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);s=(await(0,Qs.stat)(e)).isDirectory()?"dir":"file"}catch{continue}n.push({name:e.name,type:s,path:t?`${t}/${e.name}`:e.name})}return n}catch{return[]}},async fetchFile(t){const o=r.get(t);if(void 0!==o)return{content:o};const s=a((0,i.join)(e,t)),n=await c(s);await Lu(n);const l=await(0,Qs.readFile)(n,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,i.join)(e,t)),o=await c(r);return(await(0,Qs.stat)(o)).isFile()}catch{return!1}}}}(e),o=new Ou(r),s=await o.discoverComponents({manifest:t}),[n,a,c,l]=await Promise.all([Vu(r,s.skills,e),Ku(r,s.agents,e),Zu(r,s.commands,e),Ju(r,s.rules,e)]);return{skills:n,agents:a,commands:c,rules:l}}async function Vu(e,t,r){const o=[];for(const s of t)try{const{content:t}=await e.fetchFile(s.path),n=Xu({content:Ec(t,r),relativePath:s.path});n&&o.push(n)}catch{}return o}async function Ju(e,t,r){const o=[];for(const s of t)try{const{content:t}=await e.fetchFile(s.path),n=Xu({content:Ec(t,r),relativePath:s.path});n&&o.push({...n,name:s.name})}catch{}return o}async function Ku(e,t,r){const o=[];for(const s of t)try{const{content:t}=await e.fetchFile(s.path),n=Yu({content:Ec(t,r),relativePath:s.path});n&&o.push(n)}catch{}return o}async function Zu(e,t,r){const o=[];for(const s of t)try{const{content:t}=await e.fetchFile(s.path),n=ed({content:Ec(t,r),relativePath:s.path});n&&o.push(n)}catch{}return o}function Qu(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,o=0;for(let s=0;s<e.length;s++){const n=e[s];if("{"===n)o++;else if("}"===n&&o>0)o--;else if(","===n&&0===o){const o=e.slice(r,s).trim();o&&t.push(o),r=s+1}}const s=e.slice(r).trim();return s&&t.push(s),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 Xu({content:e,relativePath:t}){try{const r=Su(e),o=t.replace(/\\/g,"/"),s=o.split("/").filter((e=>e.length>0)),n=s.length>=2?s[s.length-2]:void 0,i=s[s.length-1]??o,a=n??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=Au(r.data.environments??r.data.metadata?.environments),u=Au(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:Qu(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Yu({content:e,relativePath:t}){try{const o=Su(e),s=o.content.trim();if(!s)return null;let n;"string"==typeof o.data.tools?n=o.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(o.data.tools)&&(n=o.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=o.data.permissionMode??o.data.permissionmode,c=(0,i.basename)(t);return{path:t,name:"string"==typeof o.data.name?o.data.name:(0,i.basename)(c,(0,i.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof o.data.description?o.data.description:void 0,tools:n,model:"string"==typeof o.data.model?o.data.model:"inherit",prompt:s,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function ed({content:e,relativePath:t}){try{const r=Su(e);let o;const s=r.data["argument-hint"];"string"==typeof s?o=s:Array.isArray(s)&&(o=`[${s.join(" ")}]`);const n=(0,i.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,i.basename)(n,(0,i.extname)(n)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:o,content:r.content.trim()}}catch{return null}}function td(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function rd(e,t,r){const o=r??td(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let o,s,n;for(const t of Fa){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}n=Da(a);const c=mc(i);if(c.success){void 0!==c.data.mcpServers&&(o=c.data.mcpServers,s=r(t));break}}return Mc(e,o,s,void 0===n?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:n}})}(function(e){return async t=>{if(!wc(t))return null;const r=(0,i.join)(e,t);try{return await $u(r)?null:(await(0,Qs.stat)(r)).isFile()?(await Lu(r),await Fu(r)):null}catch{return null}}}(e),{fallbackFileNames:Rc(),manifestPrecedence:"override",toSourcePath:t=>(0,i.join)(e,t),installPathForExpansion:e,parserOptions:o})}async function od(e,t,r){const o=await rd(e,void 0,{log:r});if(o)return o;for(const o of Ua){const s=(0,i.join)(e,o);try{if(!(await(0,Qs.stat)(s)).isFile())continue;const o=await(0,Qs.readFile)(s,"utf-8"),n=JSON.parse(o).plugins;if(!Array.isArray(n))continue;const a=t.name,c=n.find((e=>e.name===a));if(!c?.mcpServers?.length)continue;for(const t of c.mcpServers){const o=t.replace(/^\.\//,"");if(!wc(o))continue;const s=(0,i.join)(e,o);try{await Lu(s);const t=Tc(await Fu(s),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,s])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}function sd(e,t){const r={};for(const[o,s]of Object.entries(e.hooks))Array.isArray(s)&&(r[o]=s.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ec(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ec(e.prompt,t)}:e)));return{...e,hooks:r}}async function nd(e,t,r,o){if("object"==typeof r){const s=id(r,t);return s&&"config"in s?{config:sd(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let s,n,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!wc(t))return;s=t.endsWith(".json")?(0,i.join)(e,t):(0,i.join)(e,t,"hooks.json")}else s=(0,i.join)(e,"hooks","hooks.json");try{if(await $u(s))return;if(!(await(0,Qs.stat)(s)).isFile())return}catch{return}try{await Lu(s),n=await(0,Qs.readFile)(s,"utf-8")}catch{return}try{a=JSON.parse(n)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${s}: invalid JSON`}}}const c=id(a,t);return c&&"config"in c?{config:sd(c.config,e),sourcePath:s}:c}function id(e,t){const r=function(e){if("object"!=typeof e||null===e)return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if("object"!=typeof t||null===t)continue;const r=t;if("hooks"in r&&Array.isArray(r.hooks))return"claude-code";if("command"in r||"prompt"in r||"type"in r)return"cursor"}return"unknown"}(e);if("cursor"===r){const r=e,o=Ve(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 s=me(o),n=Ve(s);return n.isValid?{config:s}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${n.errors.join("; ")}`}}}}async function ad(e,t,r,o){const s=o?.log??ua,n=await qu(e,t,s),i={...td(r)??(o?.configuredVariables?{configuredVariables:o.configuredVariables}:void 0),log:s},[a,c,l]=await Promise.all([Gu(e,n?.manifestOptions),rd(e,r,i),nd(e,t,n?.manifestOptions?.hooks,n?.manifestFilePath)]);return{...a,...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},variablesSchema:n?.metadata?.variables,mcpConfig:c,capabilities:n?.metadata?.capabilities??[],hooks:l}}async function cd(e,t,r){const o=r?.log??ua,s=await qu(e,t.raw,o),[n,i,a]=await Promise.all([Gu(e,s?.manifestOptions),od(e,t,o),nd(e,t.raw,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...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},...n,mcpConfig:i??void 0,capabilities:s?.metadata?.capabilities??[],hooks:a}}async function ld(e,t,r,o){const s=`${r.name}@${r.version}`,{displayName:n,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 ad(e,s,r,{log:o?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==n&&{displayName:n},...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 ud(e,t,r={}){const o=r.log??ua,s=performance.now(),n=await async function(e){const t=Nu(e),r=(0,i.join)(t,"plugins","installed_plugins.json");try{const e=await(0,Qs.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}(r.userHomeDir);if(!n?.plugins)return o.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-s).toFixed(1)}ms)`),[];const a=await async function(e){const t=Nu(e),r=(0,i.join)(t,"settings.json");try{const e=await(0,Qs.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,i.resolve)(e);r.has(t)||(r.add(t),o.push(t))}return o}(e),l=function(e,t,r){if(0===r.length)return Cu(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 s=new Set,n=[];for(const{workspacePath:i,settings:a}of r){const r=Cu(e,t,a,i);for(const e of r)s.has(e.pluginId)||o.has(e.pluginId)||(s.add(e.pluginId),n.push(e))}return n}(n,a,await(0,vt.PH)(c,(async e=>({workspacePath:e,settings:await ju(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),s=ga(e),n=await cd(t,s,{log:o});u.push(n),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(ga(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()-s).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}Error;async function dd(e){const t=e.log??ua,r=performance.now(),{client:o,userId:s,teamId:n,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new Wc(e.userHomeDir),h=performance.now();let p;try{p=await o.listEnabledPlugins(s,n)}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 s=`${r}/${e.pluginId}`;let n,a=m.get(s);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(s,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))n=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${n}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,Qs.mkdir)(s,{recursive:!0});try{await o.installPlugin(e,s),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,Qs.rm)(s,{recursive:!0,force:!0})}catch{}throw e}n=s}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 ld(n,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:Uu(o)});const s=e.marketplace?.name,n=void 0!==s&&"cursor-public"!==s&&s.length>0;f.push({identifier:{source:n?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:s,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 hd(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 pd(e){return hd(e)??`path:${e.installPath}`}function fd(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function md(e,t){const r=[];for(const s of e){const e=wa(s.identifier),n=`plugin:${e}`,a=ya(s.identifier),c=va(s.identifier),l=ba(s.identifier),u=Sa(s.identifier);for(const d of t(s)){const t=(0,i.join)(s.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:n,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var o;return r}(0,i.join)((0,n.homedir)(),".claude","plugins","marketplaces");const gd=io.z.object({path:io.z.string(),name:io.z.string().optional(),description:io.z.string().optional(),globs:io.z.array(io.z.string()).optional(),alwaysApply:io.z.boolean().optional(),content:io.z.string(),environments:io.z.array(io.z.string()).optional(),disabledEnvironments:io.z.array(io.z.string()).optional()}),wd=gd.extend({name:io.z.string()}),yd=io.z.object({path:io.z.string(),name:io.z.string(),description:io.z.string().optional(),tools:io.z.array(io.z.string()).optional(),model:io.z.string().optional(),prompt:io.z.string(),permissionMode:io.z.enum(["default","readonly"]).optional()}),vd=io.z.object({path:io.z.string(),name:io.z.string(),description:io.z.string().optional(),argumentHint:io.z.string().optional(),content:io.z.string()}),bd=io.z.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),Sd=io.z.object({config:bd,sourcePath:io.z.string().optional()}),kd=io.z.custom((e=>"object"==typeof e&&null!==e));function Ed(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.z.object({schemaVersion:io.z.number().int(),displayName:io.z.string().optional(),description:io.z.string().optional(),authorName:io.z.string().optional(),skills:io.z.array(gd),rules:io.z.array(wd),agents:io.z.array(yd),commands:io.z.array(vd),mcpConfig:ha.extend({mcpServerSourcePaths:io.z.record(io.z.string(),io.z.string()).optional()}).optional(),hooks:Sd.optional(),hooksError:io.z.string().optional(),capabilities:io.z.array(io.z.string()),variablesSchema:kd.optional()}),Error;class Cd extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function xd(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function _d(e){try{return xd(await(0,Qs.readFile)(function(e){return(0,i.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 Pd(e){const t=await _d(e);return void 0===t?[]:function(e){const t=function(e){const t=xd(e);if(0===t.trim().length)return{};const r=[],o=(0,vc.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,vc._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Cd(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof o||null===o||Array.isArray(o))return{};const s=o;return void 0===s.plugins||"object"==typeof s.plugins&&null!==s.plugins&&!Array.isArray(s.plugins)?s:{}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||Ed(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function Rd(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var Id=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),Td=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Ad=(0,Gn.debuglog)("agent-skills-catalog-cache");function Md(e){return(0,s.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function Dd(e){try{return(await(0,Qs.stat)(e)).mtimeMs}catch{return}}const Od={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},Nd=[{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},Od],jd=(new Set(Nd.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function $d(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return Nd.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),s="SKILL.md"===o?t.at(-2):o;return void 0!==s&&jd.has(s)}function Fd(e){return{dirPath:(0,i.join)(e,Od.configDir,Od.subdir),scope:"builtin",source:"builtin"}}function Ld(e){return Nd.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Ud(e,t){return Ld(t).map((t=>({dirPath:(0,i.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Bd(e,t){return Ld(t).map((t=>({dirPath:(0,i.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var zd=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Wd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Hd=Nd.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Wd(e)}[/\\\\]${Wd(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),qd=/[/\\]\.cursor[/\\]rules[/\\]/i,Gd=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Vd=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Jd(e,t){const r=e.replace(/\\/g,"/"),o=(0,i.basename)(r);if(Vd.has(o))return"AGENTS.md"===o||t&&("CLAUDE.md"===o||"CLAUDE.local.md"===o)?"markdown":void 0;if(qd.test(r)&&o.endsWith(".mdc"))return"rules";if("SKILL.md"===o)for(const{pattern:e,requiresThirdParty:o}of Hd)if(e.test(r)){if(o&&!t)continue;return"skills"}if(o.endsWith(".md"))for(const{pattern:e,requiresThirdParty:o}of Gd)if(e.test(r)){if(o&&!t)continue;return"agents"}}class Kd{constructor(e,t,r,o){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=o}static getRipwalkCache(){return Kd.ripwalkCache??=new Ai,Kd.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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("NestedExtensibilityService.discover")),!1),o={rules:[],skills:[],markdown:[],agents:[]};if((0,i.resolve)(this.root)===(0,i.resolve)(this.userHomeDirectory))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),o;if(!await Mi(e,this.gitExecutor,(0,i.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 s=this.getThirdPartyExtensibilityEnabled(),n=this.buildIncludeGlobs(s),a={root:this.root,includeGlobs:n,excludeGlobs:ji,followSymlinks:!0,source:"nested_extensibility"},l={rules:[],skills:[],markdown:[],agents:[]},u=Kd.getRipwalkCache();try{const e=u.walk(r.ctx,a);try{for await(const t of e.lines){const e=Jd(t,s);e&&l[e].push((0,i.resolve)(this.root,t))}}finally{u.delete(a)}}catch{}return r.span.setAttribute("nested_extensibility.rules",l.rules.length),r.span.setAttribute("nested_extensibility.skills",l.skills.length),r.span.setAttribute("nested_extensibility.markdown",l.markdown.length),r.span.setAttribute("nested_extensibility.agents",l.agents.length),l}catch(e){t.error=e,t.hasError=!0}finally{zd(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Zd=new Set(["node_modules","__pycache__","dist","build"]);async function Qd({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:o}){const s=[],n=[{dir:e,depth:0}],a=new Set,c=void 0!==o?await(0,Qs.realpath)(o):null,l=e=>{if(null===c)return!0;const t=(0,i.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,i.isAbsolute)(t)};for(;n.length>0;){const e=n.pop();if(void 0===e)continue;const{dir:o,depth:c}=e;if(c>r)continue;try{const e=await(0,Qs.realpath)(o);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Qs.readdir)(o,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,i.join)(o,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Qs.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Zd.has(u))continue;n.push({dir:r,depth:c+1})}else l&&t(e.name)&&s.push(r)}}var u;return s.sort(((e,t)=>e.localeCompare(t))),s}const Xd={agentStoreSkillsDirs:[],userHomeDirectory:""};function Yd(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function eh(e,t){const r=Yd(t.userHomeDirectory),o=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Yd(e);if(t.length>0&&o.startsWith(`${t}/`))return{key:`${r}::skills/${o.slice(t.length+1)}`,inAgentStore:!0}}return{key:th(e),inAgentStore:!1}}function th(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),o=r.indexOf("/.cursor/"),s=r.indexOf("/.claude/"),n=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+9)}`:-1!==n?`${t.slice(0,n)}::${t.slice(n+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function rh(e,t){const r=new Map,o=[];for(const s of e){const{key:e,inAgentStore:n}=eh(s.fullPath,t),i=r.get(e);void 0!==i?n&&!o[i].inAgentStore&&(o[i]={item:s,inAgentStore:n}):(r.set(e,o.length),o.push({item:s,inAgentStore:n}))}return o.map((e=>e.item))}var oh=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},sh=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 nh=(0,d.h)("local-exec:cursor-rules");async function ih(e){return await Qd({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function ah(e){const t=await un(e);try{return{...await fh(e),realSkillFilePath:t}}catch(r){return{skillFilePath:e,realSkillFilePath:t,error:r instanceof Error?r.message:String(r)}}}function ch(e){return dh(e.data?.environments??e.data?.metadata?.environments)??[]}function lh(e){return dh(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function uh(e){return dh(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function dh(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 hh(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 ph(e){return e.slice(0,1536)}async function fh(e){const t=await hi(e);return{skillFilePath:e,content:t,parsed:Su(t)}}function mh(e){return!0===e.data?.alwaysApply}function gh({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---`:ku("",e.data??{}).trim()}(e)}(r);if(mh(r))return new Td.DX({fullPath:e,content:t,frontmatter:o,type:new Td.f5({type:{case:"global",value:new Td.i9}}),environments:ch(r),disabledEnvironments:lh(r),scopedTo:uh(r)});const s="string"==typeof r.data?.description?ph(r.data.description):void 0;return s?new Td.DX({fullPath:e,content:t,frontmatter:o,type:new Td.f5({type:{case:"agentFetched",value:new Td.Xo({description:s})}}),environments:ch(r),disabledEnvironments:lh(r),scopedTo:uh(r)}):new Td.DX({fullPath:e,parseError:"Description is required",frontmatter:o,scopedTo:uh(r),type:new Td.f5({type:{case:"agentFetched",value:new Td.Xo}})})}function wh({skillFilePath:e,content:t,parsed:r}){const o="string"==typeof r.data?.description?ph(r.data.description):"",s=Qu(r.data?.paths??r.data?.globs);return new Id.N({fullPath:e,content:t,description:o,globs:s??[],parseError:o?void 0:"Description is required",environments:ch(r),disabledEnvironments:lh(r),scopedTo:uh(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function yh({rules:e,agentSkills:t,skillFilePath:r,errorMessage:o}){e.push(function({skillFilePath:e,errorMessage:t}){return new Td.DX({fullPath:e,parseError:t,type:new Td.f5({type:{case:"agentFetched",value:new Td.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${o}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new Id.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${o}`}))}function vh(e,t,r){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void yh({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});hh(t.parsed,r)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(gh(t)),mh(t.parsed)||e.agentSkills.push(wh(t)))}const bh=(0,Gn.debuglog)("cursor-rules-service");function Sh(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function kh(e){return t=>(bh("%s: %O",e,t),Sh())}function Eh(e,t){return Md({kind:"agent-store",surface:e,roots:[...t].sort()})}function Ch(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function xh(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function _h(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(),s=r.slice(1).join("---").trim(),n={};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=n[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(),s=e.slice(r+1).trim(),c=xh(s),l=`${i}.${o}`;""===s?(n[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(n[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(n[l]=c,a=null);continue}i=null,a=null;const s=t.indexOf(":");if(-1===s)continue;const c=t.slice(0,s).trim(),l=t.slice(s+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){n.globs=[],a="globs";continue}const u=xh(l);n[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:n,rawFrontmatter:`---\n${o}\n---`,body:s}}class Ph{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=oh(t,(0,c.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),o=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Gn.debuglog)("Failed to load cursor rules from service:",e),[])))));return rh((await Promise.all(o)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{sh(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()}),Ph.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()}}Ph.CHANGE_COALESCE_MS=1e3;class Rh{constructor(e,t,r,o,s,a,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=o,this.getThirdPartyExtensibilityEnabled=s,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Kd(r,t,(0,n.homedir)(),s),this.ignoreService=l??new Ui(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{nh.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Gn.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,re.q6)(),o=oh(t,(0,c.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,i.basename)(e))return Rh.getRipwalkCache().clear(),void this.reload(o.ctx);this.reloadAtPath(o.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Gn.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return Rh.ripwalkCache??=new Ai,Rh.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1),s=this._rules;this._rules=(async()=>{const e=(await s).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(o.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Gn.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{sh(r)}}isRuleMarkdownFile(e){return"CLAUDE.md"===e||"CLAUDE.local.md"===e||"AGENTS.md"===e}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),s=(0,i.basename)(t);if(".cursorrules"===s){const e=(0,i.resolve)(this.rootDirectory),t=await Mi(o.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(o.ctx,t);return r?[r]:[]}if(s.endsWith(".mdc"))try{const e=_h(await hi(t));if(e)return[{filename:(0,i.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(s))try{return await this.loadRulesFromMarkdownFile(o.ctx,(0,i.dirname)(t),s)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{sh(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=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=o.span.spanContext().traceId;const s=(0,i.resolve)(this.rootDirectory),n=await Mi(o.ctx,this.gitExecutor,s)||s,a=this.loadCursorRulesRule(o.ctx,n).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(o.ctx,s);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([a,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);return[...p.values()].map((e=>this.toCursorRule(e)))}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,i.join)(t,".cursorrules");if((await(0,Qs.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await hi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return oh(t,(0,c.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Td.i9};else{const r=Qu(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Td.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Td.Xo({description:ph(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Td._u}}const r=e.frontmatter["metadata.environments"],o=Array.isArray(r)?r:[],s=e.frontmatter["metadata.disabledEnvironments"],n=Array.isArray(s)?s:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Td.DX({fullPath:e.path,content:e.body,type:new Td.f5({type:t}),environments:o,disabledEnvironments:n,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=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),s=[];let n=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,i.join)(n,".cursor","rules"),t=n;s.push((async()=>await this.dirIsDirectory(o.ctx,e)?this.loadRulesFromDirectory(o.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)s.push(this.loadRulesFromMarkdownFile(o.ctx,n,e));const c=(0,i.dirname)(n);if(c===n)break;n=c}const l=(await Promise.all(s)).flat();return o.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}async loadRulesFromMarkdownFile(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{oh(o,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,i.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Qs.stat)(e)).isFile()){const t=await hi(e);return[{filename:(0,i.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){o.error=e,o.hasError=!0}finally{sh(o)}}async isCursorIgnored(e){try{const t=await Fi((0,i.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=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),s=(await Promise.all(t.map((async e=>{try{const t=_h(await hi(e));if(t)return{filename:(0,i.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",s.length),s}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),s=(await Promise.all(t.map((async e=>{try{const t=(0,i.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,i.dirname)(e);return await this.loadRulesFromMarkdownFile(o.ctx,r,t)}catch{}return[]})))).flat();return o.span.setAttribute("markdownFiles",s.length),s}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),s=[];try{(0,i.join)(t,".cursorignore");const e={root:(0,i.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=Rh.getRipwalkCache().walk(o.ctx,e);for await(const t of r.lines){const r=(0,i.join)(e.root,t);s.push(...await this.readRulesAtPath(o.ctx,r))}}catch{}return o.span.setAttribute("rules",s.length),s}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{oh(r,(0,c.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Qs.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}}class Ih{constructor(e,t,r,o,s,n,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=o,this.initialBuiltinSkillsSyncPromise=a,this.agentStoreLoadInFlight=!1,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=n,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.workspaceCatalogKey=Md({kind:"workspace",surface:c,loadNestedSkills:s,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=s?t.map((e=>new Kd(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{nh.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,kh("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 s=e.fileMtimesMs[o];void 0!==s&&await Dd(r)===s&&t.set(r,o)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Td.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>Id.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void Ad("snapshot failed to decode: %O",e)}}(t)}catch(e){return void bh("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 Dd(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=>{bh("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,i.join)(r,".cursor","rules"));for(const o of Ud(r,e))t.add(o.dirPath)}for(const r of Bd(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(Fd(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,re.q6)(),o=oh(t,(0,c.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(o.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{sh(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,vt.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(kh("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()}}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=oh(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),s=t.endsWith("SKILL.md")?t:(0,i.join)(t,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>Ch(s,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>Ch(s,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,i.relative)(e,t))))return void this.reload(o.ctx);const n=this._loaded,a=(async()=>{const e=await n,{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([s]));if($d(s)||this.isPrunedByExtensibilityScan(s))return r;const i=t.get(s);if(void 0===i){try{await(0,Qs.stat)(s)}catch{return r}return await this.loadAll(o.ctx)}let a;try{a=await(0,Qs.realpath)(s)}catch{return await this.loadAll(o.ctx)}if(a!==i)return await this.loadAll(o.ctx);try{return vh(r,{...await fh(s),realSkillFilePath:a},this.surface),r}catch{return await this.loadAll(o.ctx)}})().catch(kh("Failed to load Agent Skills at path"));this._loaded=a,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{sh(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)},s=new Set;for(const[e,n]of t.realSkillFilePathsByFullPath)o.realSkillFilePathsByFullPath.has(e)||r.has(n)?s.add(e):o.realSkillFilePathsByFullPath.set(e,n);for(const e of t.rules)s.has(e.fullPath)||o.rules.push(e);for(const e of t.agentSkills)s.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}this.agentStoreLoadInFlight?this.agentStoreLoadRequestedWhileInFlight=!0:(this.agentStoreLoadInFlight=!0,(0,vt.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(Eh(this.surface,e),r))}),(e=>{bh("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreLoadInFlight=!1,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})))}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(Eh(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=Sh(),r=(await Promise.all(e.map((e=>ih(e))))).flat().filter((e=>!$d(e))),o=await Promise.all(r.map((e=>ah(e)))),s=new Set;for(const e of o)s.has(e.realSkillFilePath)||(s.add(e.realSkillFilePath),vh(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=oh(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const s=[],n=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(o.ctx)).catch((e=>{bh("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 ih(e)).filter((e=>!$d(e)));return Promise.all(t.map((e=>ah(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)i.set(t.skillFilePath,t.realSkillFilePath),yh({rules:s,agentSkills:n,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(hh(t.parsed,this.surface))continue;i.set(t.skillFilePath,t.realSkillFilePath),s.push(gh(t)),mh(t.parsed)||n.push(wh(t))}const h=(await a).flatMap((e=>e?.skills??[])).filter((e=>!$d(e))),p=await Promise.all(h.map((e=>un(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=>ah(e))));for(const e of m)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),yh({rules:s,agentSkills:n,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(hh(e.parsed,this.surface))continue;i.set(e.skillFilePath,e.realSkillFilePath),s.push(gh(e)),mh(e.parsed)||n.push(wh(e))}return o.span.setAttribute("agent_skills.total",s.length),o.span.setAttribute("agent_skills_proto.total",n.length),{rules:s,agentSkills:n,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}}function Th(e){let t;switch(e.type){case"global":t=new Td.f5({type:{case:"global",value:new Td.i9}});break;case"fileGlobbed":t=new Td.f5({type:{case:"fileGlobbed",value:new Td.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Td.f5({type:{case:"agentFetched",value:new Td.Xo({description:ph(e.description??"")})}});break;case"manuallyAttached":t=new Td.f5({type:{case:"manuallyAttached",value:new Td._u}});break;default:e.type,t=new Td.f5({type:{case:"manuallyAttached",value:new Td._u}})}return new Td.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 Ah{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 s=performance.now();this.startLoad(e,!1,(t=>{try{nh.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-s),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const o=++this._loadGeneration,s=this.loadAll(e,t).catch((e=>((0,Gn.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))),n=(0,vt.wj)(s,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(nh.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),s.then((e=>{o===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded)));this._rules=n.then((e=>e.rules)),this._agentSkills=n.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=oh(r,(0,c.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),s=[],n=[];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 md(e,(e=>e.skills))}(e),a=function(e){return md(e,(e=>e.rules))}(e);for(const e of[...r,...a])s.push(Th(e));for(const t of e){const e=`plugin:${wa(t.identifier)}`,r=ya(t.identifier),o=va(t.identifier),s=ba(t.identifier),a=Sa(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===Su(c.content).data?.["disable-model-invocation"]}catch{}n.push(new Id.N({fullPath:(0,i.join)(t.installPath,c.path),content:c.content,description:ph(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:o,pluginId:s,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){o.span.setAttribute("cursor_plugins.error",String(e))}return o.span.setAttribute("cursor_plugins.total",s.length),o.span.setAttribute("cursor_plugins_proto.total",n.length),{rules:s,agentSkills:n}}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}}const Mh=(0,Gn.debuglog)("local-subagents");class Dh{async getAllSubagents(){return[]}async reload(){return[]}}function Oh(e){return"true"===(e??"").trim().toLowerCase()}function Nh(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 s={};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(),n=t.slice(r+1).trim();0!==o.length&&(s[o]=n)}const n=s.name??"",i=s.description,a=s.model,c=Oh(s["force-default-model"]),l="true"===(s.readonly??"").trim().toLowerCase()?Ur.b$.READONLY:Ur.b$.DEFAULT,u=Oh(s.background??s.is_background),d=s.tools;return{name:n,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 jh(e){const t=(0,i.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function $h(e){return(0,i.basename)(e,(0,i.extname)(e)).replace(/[\s_]+/g,"-")}async function Fh(e,t){return await Qd({rootDir:e,includeFile:jh,containmentRootDir:t})}class Lh{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=>(Mh("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(Mh("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,i.resolve)(this.workspacePath),t=[{dirPath:(0,i.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,i.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,i.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 Fh(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,i.basename)(r);try{if(!(await(0,Qs.stat)(r)).isFile())continue}catch(e){Mh("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const s=Nh(await hi(r));if(!s)continue;t.push(new Ur.zz({fullPath:r,name:s.name||$h(e),description:s.description??"",tools:s.tools,model:s.model??"inherit",forceDefaultModel:s.forceDefaultModel,prompt:s.prompt,permissionMode:s.permissionMode,isBackground:s.isBackground,source:o}))}catch(e){Mh("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Uh=new Set(["claude-code-tutor"]);class Bh{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(Mh("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Uh.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 zh{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&&(Mh("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=ya(o.identifier),s=va(o.identifier),n=ba(o.identifier),a=Sa(o.identifier);for(const c of o.agents){const l=fd(c,t),u=(0,i.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:s,pluginId:n,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of o){const r="readonly"===e.permissionMode?Ur.b$.READONLY:Ur.b$.DEFAULT;t.push(new Ur.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 Wh=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),Hh=r("../utils/dist/workload-spawn.js");const qh=(0,Gn.promisify)(qc.execFile);function Gh(e,t,r,o){const s=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:s.width,height:o??s.height}}}async function Vh(e){const{stdout:t}=await(0,Hh.D9)(qh,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,o;for(const s of e.split("\n"))if(s.includes("*")){const e=s.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const n=s.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(n){const e=parseFloat(n[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:Gh(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}r("node:timers/promises");const Jh=qc.execFile;function Kh(e,t,r){return new Promise(((o,s)=>{r?.signal?.throwIfAborted();const n={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,Hh.D9)(Jh,e,t.map(String),{...n,encoding:"utf8"},((e,t)=>{e?s(e):o(t)}))}))}Wh.w3.UNSPECIFIED,Wh.w3.LEFT,Wh.w3.MIDDLE,Wh.w3.RIGHT,Wh.w3.BACK,Wh.w3.FORWARD,Wh.Dh.UNSPECIFIED,Wh.Dh.UP,Wh.Dh.DOWN,Wh.Dh.LEFT,Wh.Dh.RIGHT,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Zh=r("../proto/dist/runtime/compact.js");Zh.HL;var Qh=(0,Zh.QT)(bt.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);bt.proto3,bt.proto3,bt.proto3,bt.proto3;class Xh{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 Yh={left_ptr:Qh.ARROW,arrow:Qh.ARROW,default:Qh.ARROW,top_left_arrow:Qh.ARROW,hand:Qh.POINTER,hand1:Qh.POINTER,hand2:Qh.POINTER,pointer:Qh.POINTER,pointing_hand:Qh.POINTER,xterm:Qh.TEXT,ibeam:Qh.TEXT,text:Qh.TEXT,watch:Qh.WAIT,wait:Qh.WAIT,progress:Qh.WAIT,left_ptr_watch:Qh.WAIT,crosshair:Qh.CROSSHAIR,cross:Qh.CROSSHAIR,tcross:Qh.CROSSHAIR,move:Qh.MOVE,fleur:Qh.MOVE,size_all:Qh.MOVE,sb_v_double_arrow:Qh.RESIZE_NS,v_double_arrow:Qh.RESIZE_NS,ns_resize:Qh.RESIZE_NS,row_resize:Qh.RESIZE_NS,top_side:Qh.RESIZE_NS,bottom_side:Qh.RESIZE_NS,sb_h_double_arrow:Qh.RESIZE_EW,h_double_arrow:Qh.RESIZE_EW,ew_resize:Qh.RESIZE_EW,col_resize:Qh.RESIZE_EW,left_side:Qh.RESIZE_EW,right_side:Qh.RESIZE_EW,top_left_corner:Qh.RESIZE_NWSE,bottom_right_corner:Qh.RESIZE_NWSE,nwse_resize:Qh.RESIZE_NWSE,size_fdiag:Qh.RESIZE_NWSE,top_right_corner:Qh.RESIZE_NESW,bottom_left_corner:Qh.RESIZE_NESW,nesw_resize:Qh.RESIZE_NESW,size_bdiag:Qh.RESIZE_NESW,not_allowed:Qh.NOT_ALLOWED,no_drop:Qh.NOT_ALLOWED,forbidden:Qh.NOT_ALLOWED,circle:Qh.NOT_ALLOWED,grab:Qh.GRAB,openhand:Qh.GRAB,grabbing:Qh.GRABBING,closedhand:Qh.GRABBING};class ep{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 Xh(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},s=this.getExpectedPositionAfterAction(e,o);this.lastKnownPosition=s;const n=async()=>{let n,i;try{[n,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=n}catch{n=s,i=Qh.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:o,positionAfter:n,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>n())).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 Kh("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),s=parseInt(r[1],10);return this.scaler.displayToApi(o,s)}async detectCursorType(){try{const e=(await Kh("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Yh[t]??Qh.ARROW}try{const e=await Kh("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Yh))if(e.toLowerCase().includes(t))return r}catch{}return Qh.ARROW}catch{return Qh.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var tp=r("node:net");class rp extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const op=io.z.object({rpcSocketPath:io.z.string().min(1).optional(),appControlSocketPath:io.z.string().min(1).optional()}).passthrough(),sp=io.z.object({data:io.z.string(),mimeType:io.z.string().min(1)}).strip(),np=io.z.object({message:io.z.string(),screenshot:sp.optional(),screenshotBefore:sp.optional(),structuredContent:io.z.unknown().optional(),isError:io.z.boolean()}).strip(),ip=io.z.object({accessibilityTrusted:io.z.boolean(),screenRecordingGranted:io.z.boolean()}).strip(),ap=io.z.union([io.z.object({id:io.z.number().int(),result:np,ok:io.z.never().optional(),error:io.z.never().optional(),errorCode:io.z.never().optional(),permissionStatus:io.z.never().optional(),sessionId:io.z.never().optional()}).strip(),io.z.object({id:io.z.number().int(),sessionId:io.z.string().min(1),ok:io.z.literal(!0).optional(),result:io.z.never().optional(),error:io.z.never().optional(),errorCode:io.z.never().optional(),permissionStatus:io.z.never().optional()}).strip(),io.z.object({id:io.z.number().int(),ok:io.z.literal(!0),result:io.z.never().optional(),error:io.z.never().optional(),errorCode:io.z.never().optional(),permissionStatus:io.z.never().optional(),sessionId:io.z.never().optional()}).strip(),io.z.object({id:io.z.number().int().nullable().optional(),error:io.z.string().min(1),errorCode:io.z.string().min(1).optional(),result:io.z.never().optional(),ok:io.z.never().optional(),permissionStatus:io.z.never().optional(),sessionId:io.z.never().optional()}).strip(),io.z.object({id:io.z.number().int(),permissionStatus:ip,result:io.z.never().optional(),ok:io.z.never().optional(),error:io.z.never().optional(),errorCode:io.z.never().optional(),sessionId:io.z.never().optional()}).strip()]);function cp(e,t){try{return JSON.parse(e)}catch{throw new rp(`local-cua ${t} is not valid JSON`)}}const lp={responseMaxBytes:33554432,parseServiceState(e){const t=op.safeParse(cp(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rp("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=ap.safeParse(cp(e.toString("utf8"),"RPC response"));if(!r.success)throw new rp("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rp("local-cua RPC response ID did not match");return r.data}};class up extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dp(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?hp(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}function hp(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 pp{constructor(e){this.mode=e}static isInstalled(){return!!(0,Ys.existsSync)(pp.serviceExecutablePath())||(0,Ys.existsSync)(pp.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;pp.throwIfAborted(e.signal);const t=(0,s.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:pp.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw pp.rpcError(r);if(void 0===r.sessionId)throw new up("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 pp.readServiceState();if(void 0===e)return;const r=await pp.sendOnce(pp.socketPathFrom(e),{id:pp.requestID,method:"control/release",requestID:(0,s.randomUUID)(),mode:this.mode,sessionId:t},pp.defaultCallTimeoutMs);if(void 0!==r.error)throw pp.rpcError(r)}catch(t){pp.logger.warn(e,"local-cua control release failed",{error:dp(t)})}}}async callTool(e,t,r){pp.throwIfAborted(e.signal);const o=pp.defaultCallTimeoutMs,n=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,n=this.activeSessionId;return{id:pp.requestID,method:"tools/call",requestID:(0,s.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 pp.rpcError(n,t);const i=n.result;if(void 0===i)throw new up(`local-cua tool ${t} returned no result`,{tool:t});if(i.isError){const e=i.message.trim();throw new up(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return i}async sendWithRelaunchRetry(e,t,r){const o=pp.defaultCallTimeoutMs,s=await this.ensureSocketPath(e);pp.throwIfAborted(e.signal);try{return await pp.sendOnce(s,t(),o,e.signal)}catch(s){if(!pp.isPreDeliveryConnectionError(s))throw s;pp.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:pp.spawnErrorCode(s)});const n=await this.ensureSocketPath(e,!0);return pp.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await pp.sendOnce(n,t(),o,e.signal)}}static rpcError(e,t){return new up(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(pp.throwIfAborted(e.signal),!t){const e=await pp.readServiceState();if(e)return pp.socketPathFrom(e)}await this.launchAndWait(e);const r=await pp.readServiceState();if(!r)throw new up("local-cua sidecar did not publish service.json after launch");return pp.socketPathFrom(r)}async launchAndWait(e){const t=pp.serviceAppPath();pp.logger.info(e,"launching local-cua sidecar",pp.sidecarLaunchLogFields(t)),"1"===process.env[pp.directLaunchEnv]?await pp.spawnSidecarProcess(e,pp.serviceExecutablePath(),[],{detached:!0}):await pp.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+pp.launchReadyTimeoutMs;for(;Date.now()<r;){pp.throwIfAborted(e.signal);const t=await pp.readServiceState();if(t)try{if("ok"in await pp.sendOnce(pp.socketPathFrom(t),{id:pp.requestID,method:"ping"},2e3,e.signal))return}catch{}await(0,vt.cb)(pp.launchPollIntervalMs)}throw new up("local-cua sidecar did not become ready in time")}static isPreDeliveryConnectionError(e){const t=dp(e);return"ENOENT"===t||"ECONNREFUSED"===t}static appSupportDirectory(){const e=process.env[pp.appSupportOverrideEnv];return e&&e.length>0?e:i.join(n.homedir(),"Library","Application Support",pp.appSupportFolder)}static serviceStatePath(){return i.join(pp.appSupportDirectory(),"service.json")}static serviceAppPath(){const e=process.env[pp.serviceAppOverrideEnv];return e&&e.length>0?e:i.join(n.homedir(),".cursor","cursor-computer-use",`${pp.serviceAppBundleName}.app`)}static sidecarLaunchLogFields(e){const t=`${pp.serviceAppBundleName}.app`;return{appName:i.basename(e)===t?t:"custom",appPathHash:(0,s.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[pp.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dp(e)}static socketError(e){const t=dp(e);return new up(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return i.join(pp.serviceAppPath(),"Contents","MacOS","CUCursorService")}static spawnSidecarProcess(e,t,r,o){return new Promise(((s,n)=>{const i=(0,qc.spawn)(t,[...r],{detached:!0===o?.detached,stdio:"ignore"}),a=e=>{n(new up(`local-cua sidecar launch failed: ${pp.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{pp.logger.warn(e,"local-cua sidecar process error after launch",{error:pp.spawnErrorCode(t)})})),i.unref(),s()}))}))}static async readServiceState(){try{const e=await(0,Qs.readFile)(pp.serviceStatePath(),"utf8");return lp.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rp)return;throw new up("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 up("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw pp.abortError(e)}static sendOnce(e,t,r,o){return o?.aborted?Promise.reject(pp.abortError(o)):new Promise(((s,n)=>{let i=!1,a=[],c=0,l=!1;const u=(0,tp.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),o?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>n(void 0===o?new up("local-cua RPC aborted"):pp.abortError(o))))},p=setTimeout((()=>{d((()=>n(new up(`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((()=>n(pp.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lp.responseMaxBytes)return void d((()=>n(new up("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=lp.parseResponse({line:o,expectedID:pp.requestID});d((()=>s(e)))}catch(e){d((()=>n(e)))}})),u.on("error",(e=>{d(l?()=>n(new up("local-cua RPC connection failed after request delivery")):()=>n(pp.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((()=>n(new up(e))))})))}))}}let fp;function mp(){if(void 0===fp){const e=async function(){const[{createJimp:e},{default:t},{default:o},{default:s,msBmp:n},{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,s,n,i,a],plugins:[c]})}().catch((t=>{throw fp===e&&(fp=void 0),t}));fp=e}return fp}pp.logger=(0,d.h)("local-cua:rpc"),pp.serviceAppBundleName="Cursor Computer Use",pp.appSupportFolder="cursor-computer-use",pp.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",pp.serviceAppOverrideEnv="CUA_SERVICE_APP",pp.directLaunchEnv="CUA_DIRECT_LAUNCH",pp.defaultCallTimeoutMs=45e3,pp.launchReadyTimeoutMs=8e3,pp.launchPollIntervalMs=200,pp.requestID=1;var gp=r("node:module"),wp=r.t(gp,2);const yp="mac-webp-runtime.cjs";let vp,bp;function Sp(){return vp??=(()=>{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=wp,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,i.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),vp}function kp(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?e:(bp??=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,i.dirname)((o=e).startsWith("file:")?(0,yu.fileURLToPath)(o):o);r((0,i.join)(t,yp)),r((0,i.join)(t,"..","..","src","computer-use",yp))}var o;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,i.join)((0,i.dirname)(process.argv[1]),yp)),r((0,i.join)(process.cwd(),"src","computer-use",yp)),r((0,i.join)(process.cwd(),"computer-use",yp));try{const e=(0,i.dirname)(Sp().resolve("@anysphere/local-exec/package.json"));r((0,i.join)(e,"src","computer-use",yp)),r((0,i.join)(e,"dist","computer-use",yp))}catch{}for(const t of e)try{const e=Sp()(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")}(),bp)}function Ep(...e){return t=["@jsquash","webp",...e].join("/"),Sp().resolve(t);var t}async function Cp(...e){return await(t=(0,yu.pathToFileURL)(Ep(...e)).href,kp()(t));var t}const xp=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},_p=(xp((async()=>{const e=await Cp("decode.js");return await e.init({wasmBinary:await Ys.promises.readFile(Ep("codec","dec","webp_dec.wasm"))}),e})),xp((async()=>{const[e,t,r]=await Promise.all([Cp("utils.js"),Cp("meta.js"),Cp("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ys.promises.readFile(Ep("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Pp="image/png",Rp={async normalize(e){if(e.mimeType!==Pp)throw new Error(`Mac screenshot must be ${Pp}, received ${e.mimeType}`);const t=await mp(),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 _p(),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 Ip{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=>Ip.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:Ip.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:Ip.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:Ip.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Ip.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:Ip.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===Wh.EB.DOWN||t.value.stroke===Wh.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 Wh.ks({result:{case:"success",value:new Wh.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=Ip.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=Ip.cursorFromResult(e)??Ip.coordinateFromPoint(t)??this.cursor}async errorResult(e){let t;if(Ip.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dp(e)}),!function(e){return e instanceof up&&("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){Ip.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dp(e)})}const r=function(e){if(e instanceof up&&e.userFacing&&e.message.trim().length>0&&!hp(e.message))return e.message.trim()}(e);return new Wh.ks({result:{case:"error",value:new Wh.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 Wh.ks({result:{case:"error",value:new Wh.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Wh.ks({result:{case:"error",value:new Wh.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime})}})}static mouseButtonName(e){return Ip.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Ip.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 Rp.normalize(e),failed:!1}}catch(r){const o=dp(r);return Ip.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 Wh.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 Wh.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(s),r(this.ctx.signal.reason??new Error("Computer use aborted"))},s=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",o),t()}),e);this.ctx.signal.addEventListener("abort",o,{once:!0}),this.ctx.signal.aborted&&o()}))}}Ip.logger=(0,d.h)("local-cua:actions"),Ip.mouseButtonNames={[Wh.w3.UNSPECIFIED]:"left",[Wh.w3.LEFT]:"left",[Wh.w3.RIGHT]:"right",[Wh.w3.MIDDLE]:"middle",[Wh.w3.BACK]:"left",[Wh.w3.FORWARD]:"left"},Ip.scrollDirectionNames={[Wh.Dh.UNSPECIFIED]:"down",[Wh.Dh.UP]:"up",[Wh.Dh.DOWN]:"down",[Wh.Dh.LEFT]:"left",[Wh.Dh.RIGHT]:"right"},i.join("Contents","MacOS","CUCursorService");const Tp=1048576,Ap=52428800;var Mp;!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Mp||(Mp={}));var Dp=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Op{constructor(e,t,r,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=o,this.onDeleteForAiTracking=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const o=t.path,s=(0,ln.o1)(o,this.workspacePath),n=await this.permissionsService.shouldBlockWrite(e,s,"");if(n){const e=await Wi(n,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Vt.Pi({result:{case:"rejected",value:new Vt.iq({path:s,reason:e||""})}}),onPermissionDenied:(e,t)=>new Vt.Pi({result:{case:"permissionDenied",value:new Vt.QG({path:s,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const i=await this.pendingDecisionProvider.requestApproval({type:Mp.Delete,details:{path:s},toolCallId:t.toolCallId});if(!i.approved)return new Vt.Pi({result:{case:"rejected",value:new Vt.iq({path:s,reason:i.reason||""})}});let a;try{a=await(0,Qs.stat)(s)}catch(e){return"ENOENT"===e.code?new Vt.Pi({result:{case:"fileNotFound",value:new Vt.n0({path:s})}}):new Vt.Pi({result:{case:"error",value:new Vt.GU({path:s,error:e.message})}})}if(!a.isFile()){const e=a.isDirectory()?"directory":"other";return new Vt.Pi({result:{case:"notFile",value:new Vt.LX({path:s,actualType:e})}})}const l=a.size;let u;if(l<=Ap)try{u=await hi(s)}catch{}const d=u??"";try{await(0,Qs.unlink)(s)}catch(e){return"EACCES"===e.code?new Vt.Pi({result:{case:"permissionDenied",value:new Vt.QG({path:s,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new Vt.Pi({result:{case:"fileBusy",value:new Vt.vX({path:s})}}):new Vt.Pi({result:{case:"error",value:new Vt.GU({path:s,error:e.message})}})}if(this.fileChangeTracker&&void 0!==u){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(s,u,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:s}).catch((()=>{})),new Vt.Pi({result:{case:"success",value:new Vt.fl({path:s,deletedFile:s,fileSize:BigInt(l),prevContent:d})}})}catch(e){r.error=e,r.hasError=!0}finally{Dp(r)}}}class Np{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===tt));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 ro.I0({serverIdentifier:tt,serverName:tt,instructions:`User-defined tools for this session (server "${tt}"). 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 jp extends Np{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var $p=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Fp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Lp{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.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 $p.uN({result:{case:"success",value:new $p.Uk({url:o,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new $p.uN({result:{case:"error",value:new $p.fk({url:o,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{Fp(r)}}}class Up{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 s=this.changes.get(e);if(s){const t=s.before,n=o||s.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:n};this.changes.set(e,o),this.notify(o)}}else{const s={path:e,before:t,after:r,metadata:o};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Qs.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:s}=await pi(e,t,r,o);await(0,Qs.writeFile)(e,s)}(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 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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 zp{async exec(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":o?.caller}}),!1);const{stdout:n,stderr:i}=await Xc("git",r,{cwd:t,timeout:o?.timeout});return{exitCode:0,stdout:n.toString(),stderr:i.toString()}}catch(e){s.error=e,s.hasError=!0}finally{Bp(s)}}}var Wp=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const Hp=-(2**31),qp=2**31-1;function Gp(e){return Number.isNaN(e)?0:e<Hp?Hp:e>qp?qp:e}function Vp(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Gp(Math.trunc(e))}class Jp{constructor(){this.lineEnd=0,this.nextStart=0}}function Kp(e,t,r){const o=e.length;if(t>=o)return!1;const s=e.indexOf("\n",t);if(-1!==s){for(let o=t;o<s;o++)if(13===e.charCodeAt(o)&&o+1!==s)return r.lineEnd=o,r.nextStart=o+1,!0;const o=s>t&&13===e.charCodeAt(s-1);return r.lineEnd=o?s-1:s,r.nextStart=s+1,!0}const n=e.indexOf("\r",t);return-1!==n?(r.lineEnd=n,r.nextStart=n+1,!0):(r.lineEnd=o,r.nextStart=o,!0)}const Zp="agent-tools",Qp=51380224,Xp=new ca.AsyncLocalStorage;function Yp(e,t){return Xp.run(e,t)}var ef=r("../mcp-core/dist/index.js"),tf=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 rf extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class of extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class sf{constructor(e){this.disabledService=e}async load(e,t,r,o,s){if(await this.disabledService.isServerDisabled(t))throw new rf(t);return await s(e,r)}}class nf{constructor(e){this.approvalService=e}async load(e,t,r,o,s){const n={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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,o))throw new of(t);return await s(e,r)}catch(e){n.error=e,n.hasError=!0}finally{tf(n)}}}class af{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,s.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,Qs.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,Qs.mkdir)(i.dirname(this.approvalsPath),{recursive:!0}),await(0,Qs.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var cf=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},lf=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 uf{async load(e,t,r,o,s){const n=s(e,r);return new hf(e,t,n,r)}}function df(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class hf{constructor(e,t,r,o){this.serverName=t,this.clientPromise=r,this.config=o,this.clientPromiseTraceId=(0,c.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=cf(t,(0,c.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const o=df(this.toolsPromise);return void 0!==o?o:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{lf(t)}}async callTool(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{const i=cf(n,(0,c.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,o,s)}catch(e){n.error=e,n.hasError=!0}finally{lf(n)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=cf(t,(0,c.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{lf(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=cf(t,(0,c.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{lf(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=cf(t,(0,c.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const o=df(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{lf(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=cf(r,(0,c.VI)(e.withName("CachedMcpClient.readResource")),!1),s=await this.getClient(o.ctx);return null===s?{contents:[]}:s.readResource(o.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{lf(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=cf(t,(0,c.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const o=df(this.promptsPromise);return void 0!==o?o:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{lf(t)}}async getPrompt(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=cf(o,(0,c.VI)(e.withName("CachedMcpClient.getPrompt")),!1),n=await this.getClient(s.ctx);return null===n?{messages:[]}:n.getPrompt(s.ctx,t,r)}catch(e){o.error=e,o.hasError=!0}finally{lf(o)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=cf(t,(0,c.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{lf(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function pf(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"}]`}}}var ff=r("../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/mini/schemas.js"),mf=r("../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js");const gf=ff.Ik({CLIENT_ID:ff.Yj(),CLIENT_SECRET:ff.lq(ff.Yj()),scopes:ff.lq(ff.YO(ff.Yj()))}),wf=ff.re({caBundle:ff.Yj().check(mf.WN(),mf.m9(1),mf.Eb(131072))}),yf=ff.Ik({type:ff.lq(ff.eu("stdio")),command:ff.Yj(),args:ff.lq(ff.YO(ff.Yj())),env:ff.lq(ff.g1(ff.Yj(),ff.Yj())),envFile:ff.lq(ff.Yj()),cwd:ff.lq(ff.Yj()),enabledTools:ff.lq(ff.YO(ff.Yj()))}),vf=ff.Ik({type:ff.lq(ff.k5(["http","sse"])),url:ff.Yj(),headers:ff.lq(ff.g1(ff.Yj(),ff.Yj())),auth:ff.lq(gf),tls:ff.lq(wf),placement:ff.lq(ff.k5(["server","client"])),enabledTools:ff.lq(ff.YO(ff.Yj()))}),bf=ff.KC([yf,vf]),Sf=ff.Ik({mcpServers:ff.g1(ff.Yj(),bf)});Error;const kf=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Ef(e,t){if("string"==typeof e)return function(e,t){return e.replace(kf,((e,r,o,s)=>{if(void 0!==r){const o=t(r);return void 0!==o?o:e}const n=t(o);return void 0!==n?n:void 0!==s?s:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Ef(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[o,s]of Object.entries(e))r[o]=Ef(s,t);return r}return e}async function Cf(e,t=e=>process.env[e]){try{const r=await(0,Qs.readFile)(e,"utf8"),o=Ef((0,vc.qg)(r),t);return Sf.parse(o)}catch{return{mcpServers:{}}}}var xf=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js"),_f=r("../constants/dist/mcp.js"),Pf=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),Rf=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),If=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Tf=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),Af=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),Mf=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Df="mcpStdioStderrTail";function Of(e){if(!(e instanceof Error))return;const t=e[Df];return"string"==typeof t?t:void 0}var Nf=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},jf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 $f(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Ff=["authorization_code","refresh_token"],Lf=["code"];class Uf{constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,(!0===e.restMcpProviderMetadata?.omitResourceIndicator||(0,_f.AB)(e.serverUrl))&&(this.validateResourceURL=async()=>{}),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,s.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,ef.E_S)(e,this._scopes),void 0!==this._serverUrl&&(0,_f.uS)(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||(0,_f.NC)(e))&&(0,_f.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 Bf(e){const{serverName:t,config:r,tokenStorage:o}=e,s=await(0,ef.Ezk)(r.url,e.fetchImpl),n=(0,_f.OY)({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),i=function(e,t){const r=(0,ef.qFm)(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:(0,_f.RJ)(t),grant_types:[...Ff],response_types:[...Lf],token_endpoint_auth_method:"none"}}(r.auth,n),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 Uf({identifier:t,redirectUrl:n,serverUrl:r.url,restMcpProviderMetadata:s,clientMetadata:{redirect_uris:(0,_f.RJ)(n),token_endpoint_auth_method:"none",grant_types:[...Ff],response_types:[...Lf],client_name:"Cursor",logo_uri:_f.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 zf=new Set;let Wf=!1;function Hf(){for(const e of zf)try{process.kill(e,"SIGKILL")}catch{}}class qf{constructor(e,t,r){this._callToolLock=Promise.resolve(),this._stateEnteredAtMs=Date.now(),this.serverName=e,this.client=t,this.tools=new ef.B1j,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._resumedInstructions=r.resumedInstructions,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._stdioChildPid=r.stdioChildPid,this.setupElicitationHandler()}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,o){if(!this._oauthLifecycleLogger)return;const s=this._stateKindLabel(e),n=this._stateKindLabel(t);if(s===n)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,ef.VDJ)({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:s,to:n,cause:r,serverUrlHost:a,previousStateDurationMs:i,...o}})}static createClient(){return new Rf.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}setupElicitationHandler(){this.client.setRequestHandler(Mf.$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,s,n,i,a){const c=new URL(t.url);s=s??_f.tl;const l=await r.loadTokens(),u=await Bf({serverName:e,config:t,tokenStorage:r,authRedirectUrl:s,fetchImpl:n}),d=(0,ef.mtU)(t.url,o),h=d.headers,p=n??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),f=void 0!==d.cursorAuthHeaderValue&&void 0!==d.cursorAuthOrigin&&void 0!==p?(0,ef.utF)((()=>d.cursorAuthHeaderValue),d.cursorAuthOrigin,p):p,m=e=>void 0===f||void 0===i?f:(0,ef.jIB)({fetch:f,logger:i.logger,metadata:{...i.metadata,transportType:e}}),g=qf.createClient(),w=e=>e instanceof Pf.D_||(0,ef.Gpm)(e),y=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,Pf.j2)(u,{serverUrl:c.toString(),authorizationCode:t,...void 0!==f?{fetchFn:f}:{}}),a&&(0,ef.VDJ)({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...(0,ef.q2e)(c.toString()),...(0,ef.tBH)(u.tokens(),{expiresInIsFresh:!0})}})},v=r=>{const o=u.lastRedirectUrl?.toString?.()??"",s=new qf(e,g,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:o,callback:async e=>{try{await y(e),s.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:u,authCodeExchange:y,sessionId:r,config:t});return s},b=async()=>{const r=new If.A(c,{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...h??{}}},fetch:m("sse")});try{return await g.connect(r),new qf(e,g,{initialState:{kind:"ready"},authProvider:u,authCodeExchange:y,config:t,oauthLifecycleLogger:a})}catch(t){if(await r.close().catch((()=>{})),w(t))return a&&(0,ef.VDJ)({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(l?.refresh_token),...(0,ef.q2e)(c.toString()),...(0,ef.X5z)(t)}}),v();throw t}};if("sse"===t.type)return b();const S=new Af.j(c,{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...h??{}}},fetch:m("streamableHttp")});try{return await g.connect(S),new qf(e,g,{initialState:{kind:"ready"},authProvider:u,authCodeExchange:y,sessionId:S.sessionId,config:t,oauthLifecycleLogger:a})}catch(t){if(w(t))return a&&(0,ef.VDJ)({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(l?.refresh_token),...(0,ef.q2e)(c.toString()),...(0,ef.X5z)(t)}}),v(S.sessionId);if((0,ef.PKk)(t))return b();throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const o=qf.createClient(),s=new Af.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await o.connect(s),new qf(e,o,{initialState:{kind:"ready"},sessionId:s.sessionId,config:t})}static async fromCachedSession(e,t,r,o,s,n=_f.tl,i,a,c){const l=new URL(t.url),u=await Bf({serverName:e,config:t,tokenStorage:o,authRedirectUrl:n,fetchImpl:i}),d=(0,ef.mtU)(t.url,s),h=d.headers,p=i??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),f=void 0!==d.cursorAuthHeaderValue&&void 0!==d.cursorAuthOrigin&&void 0!==p?(0,ef.utF)((()=>d.cursorAuthHeaderValue),d.cursorAuthOrigin,p):p,m=new Af.j(l,{authProvider:u,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...h??{}}},fetch:void 0!==f&&void 0!==a?(0,ef.jIB)({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"}}):f}),g=qf.createClient();return await g.connect(m),new qf(e,g,{initialState:{kind:"ready"},authProvider:u,sessionId:m.sessionId,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c})}get sessionId(){return this._sessionId}static async fromCommand(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{Nf(n,(0,c.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(a=s?.spawn,void 0!==a||"linux"!==process.platform?a:(e,t,r)=>(0,Hh.D9)(qc.spawn,e,t,r)),u=new Tf.oQ({command:r.command,args:r.args??[],env:o,cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),d=function(e){let t="",r=null===e;return null!==e&&(e.on("data",(e=>{const r=ef.uOd-t.length;r<=0||(t+=e.toString().slice(0,r))})),e.once("end",(()=>{r=!0}))),{read:()=>(0,ef.eaG)(t.replace(/\s+/g," ").trim(),{maxLength:ef.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)}))}}}(u.stderr),h=qf.createClient(),p=h.connect(u),f=s?.connectTimeoutMs??6e4;let m;const g=new Promise(((e,r)=>{m=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([p,g])}catch(e){throw p.catch((()=>{})),await u.close().catch((()=>{})),await d.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,Df,{value:t,enumerable:!1,configurable:!0,writable:!0}),r}(e,d.read())}finally{void 0!==m&&clearTimeout(m)}const w=u.pid??void 0;return"number"==typeof w&&(i=w,zf.add(i),Wf||(Wf=!0,process.on("exit",Hf))),new qf(t,h,{initialState:{kind:"ready"},config:r,stdioChildPid:w})}catch(e){n.error=e,n.hasError=!0}finally{jf(n)}var i,a}async close(){var e;void 0!==this._stdioChildPid&&(e=this._stdioChildPid,zf.delete(e)),await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Nf(t,(0,c.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",$f(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,ef.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 Pf.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,ef.X5z)(e)}),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){t.error=e,t.hasError=!0}finally{jf(t)}}async callTool(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{const l=Nf(n,(0,c.VI)(e.withName("McpSdkClient.callTool")),!1);l.span.setAttribute("toolName",t),l.span.setAttribute("serverName",this.serverName),l.span.setAttribute("mcp.transport",$f(this.config));const u=this._callToolLock;let d;this._callToolLock=new Promise((e=>{d=e}));try{if(await u,"requires_authentication"===this.stateValue.kind)throw new Pf.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=o,this._currentToolName=t,this._currentElicitationProvider=s;try{const e=await this.client.callTool({name:t,arguments:r});return{content:e.content,isError:!0===e.isError,structuredContent:(i=e.isError,a=e.structuredContent,!0!==i||"object"!=typeof a||null===a||Array.isArray(a)?void 0:a)}}catch(e){if(e instanceof Pf.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,ef.X5z)(e)}),this._stateEnteredAtMs=Date.now()}throw e}finally{this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{d()}}catch(e){n.error=e,n.hasError=!0}finally{jf(n)}var i,a}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(Nf(t,(0,c.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{jf(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(Nf(t,(0,c.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await(0,ef.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{jf(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return Nf(r,(0,c.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{jf(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return Nf(t,(0,c.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await(0,ef.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{jf(t)}}async getPrompt(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{return Nf(o,(0,c.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{jf(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 Gf extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function Vf(e){if(e instanceof Gf)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}class Jf 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 Kf{constructor(e){this.tools=e}async execute(e,t,r,o){const s=this.tools[e];if(!s)throw new Gf(e,Object.keys(this.tools));return s.execute(t,r,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class Zf{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new Kf({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class Qf{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=Nf(t,(0,c.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{jf(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Nf(t,(0,c.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{jf(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Nf(t,(0,c.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{jf(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 Xf{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=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()}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=Nf(t,(0,c.VI)(e.withName("McpManager.getToolSet")),!1),o=await(0,vt.PH)(Object.entries(this.clients),(([e,t])=>t.getTools(r.ctx).then((r=>r.map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:4}),s=Array.from(o.values()).flat(),n={};for(const e of s)n[`${e.clientName}-${e.name}`]={definition:{...e,clientKey:e.clientKey,providerIdentifier:e.clientName,toolName:e.name},execute:async(t,o,s)=>{const n=s?.createProvider(e.clientName,e.name,o);return await e.client.callTool(r.ctx,e.name,t,o,n)}};return new Kf(n)}catch(e){t.error=e,t.hasError=!0}finally{jf(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Nf(t,(0,c.VI)(e.withName("McpManager.getInstructions")),!1),o=await(0,vt.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new ro.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:4});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{jf(t)}}}function Yf(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,s)=>t.error(r,e,o,s)}}({ctx:e,logger:t})}Error;class em{constructor(e){this.options=e,(0,ef.VDJ)({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:(0,ef.q2e)(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return(0,ef.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...(0,ef.tBH)(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),(0,ef.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...(0,ef.tBH)(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){(0,ef.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){(0,ef.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...(0,ef.X5z)(e)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return(0,ef.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...(0,ef.O3I)(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),(0,ef.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...(0,ef.O3I)(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&((0,ef.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 tm{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 rm{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 om=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},sm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 nm=(0,d.h)("DefinitionMcpLoader");function im(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?i.join(n.homedir(),t.slice(1)):t.startsWith("./")||"."===t?i.resolve(r??process.cwd(),t):t}function am(e){return"function"==typeof e.getMcpNetworkControlsConfig}function cm(e){return e?.length??0}function lm(e){if(void 0!==e)return(0,s.createHash)("sha256").update((0,ef.Fmf)(e)).digest("hex")}class um{constructor(e){this.configPath=e,this.configPromise=Cf(e)}clearCache(){this.configPromise=Cf(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 dm{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{om(r,(0,c.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 s={};return await(0,vt.PH)([...o],(async r=>{try{const o=t?this.clientCache.get(r.identifier):void 0,n=o??await this.loadDefinitionClient(e,r);o||this.clientCache.set(r.identifier,n),s[r.identifier]=n}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r){nm.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:Of(r)})}(e,r,t)}}),{max:this.options.maxConcurrency??Math.max(o.length,1)}),new Xf(s,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{sm(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(am);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,ef.Fmf)(t)]}))))}catch{return}const s=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=o,void 0!==s&&s!==o&&(nm.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,vt.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{om(o,(0,c.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const s=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,s),!r){const e=this.clientCache.get(t);if(e)return e}const n=s.find((e=>e.identifier===t));if(!n)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,n,r)}catch(t){throw this.handleDefinitionLoadError(e,n,t),t}return r||this.clientCache.set(t,i),i}catch(e){o.error=e,o.hasError=!0}finally{sm(o)}}async loadDefinitionClient(e,t,o){const s=t.authStorageKey??t.identifier,n=new tm(this.tokenStorage,s),i=Yf(e,nm),a=new em({inner:n,logger:i,identifier:s,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),l=o?new rm(a):a;return async function(e,t,o,s,n={middlewares:[],configPath:""},i){const a={stack:[],error:void 0,hasError:!1};try{const{middlewares:l,configPath:u}=n,d=om(a,(0,c.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let h=async(e,o)=>{const n={stack:[],error:void 0,hasError:!1};try{const a=om(n,(0,c.VI)(e.withName("loadServer.next")),!1);a.span.setAttribute("serverName",t);const u=a.ctx;if("command"in o){a.span.setAttribute("kind","command");const e=l.find(am);return await async function(e,t,o,s){const n=o.cwd?im({filePath:o.cwd}):void 0;let i,a;if(o.args&&o.args.length>0)i=im({filePath:o.command,baseDir:n}),a=o.args.map((e=>im({filePath:e,baseDir:n})));else{const e=(0,xf.A)(o.command);i=im({filePath:e[0],baseDir:n}),a=e.slice(1).map((e=>im({filePath:e,baseDir:n})))}const c=o.env??{},l=await(s?.getMcpNetworkControlsConfig?.({command:[o.command,...o.args??[]].join(" ")})),u=(0,ef.$HQ)(l);if(void 0!==u){const{buildMcpSandboxPolicy:o}=await Promise.resolve().then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:s,spawnInSandbox:d}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),h=n??process.cwd(),p=await o(u,h);nm.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=${cm(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${cm(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${cm(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${lm(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:l,sandboxNetworkControlsConfig:u}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:cm(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:cm(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:cm(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:lm(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:l,sandboxNetworkControlsConfig:u}));try{return await qf.fromCommand(e,t,{command:i,args:a,cwd:n},c,{spawn:(e,t,r)=>d(e,t,r,p)})}catch(e){if(e instanceof s)throw new ef.c8u(t,e);throw e}}return!0===l?.enabled&&"no_sandbox"===l.mcpNetworkMode&&(!0===l.win32UserExtensionUnsandbox?nm.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):nm.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),qf.fromCommand(e,t,{command:i,args:a,cwd:n},c)}(u,t,o,e)}if("url"in o){a.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,o,s){const n=Yf(e,nm),i=function(e,t){return{logger:{debug:(t,r)=>nm.debug(e,t,r),info:(t,r)=>nm.info(e,t,r),warn:(t,r)=>nm.warn(e,t,r),error:(t,r,o)=>nm.error(e,t,r,o)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t);return qf.fromStreamableHttp(t,r,o,r.headers,s,void 0,i,n)}(u,t,o,s,e)}throw new Error(`Invalid server: ${JSON.stringify(o)}`)}catch(e){n.error=e,n.hasError=!0}finally{sm(n)}};for(const e of l){const r=h;h=async(o,s)=>await e.load(o,t,s,u,r)}return await h(d.ctx,o)}catch(e){a.error=e,a.hasError=!0}finally{sm(a)}}(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){nm.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 rf||e instanceof of||e instanceof hm}(r)}}class hm 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"}}class pm{constructor(e){this.blockingService=e}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async load(e,t,r,o,s){const n={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(n))??{blocked:await this.blockingService.isServerBlocked(n)};if(i.blocked)throw new hm(t,i.reason??"teamPolicy",i.message);return s(e,r)}}class fm extends dm{constructor(e,t,r=[],o,s){super(new um(e),t,r,{authRedirectUrlGenerator:o,elicitationFactory:s}),this.configPath=e,this.elicitationFactory=s}static init(e,t,r=[]){return new fm(t,e,r)}}function mm(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 gm{constructor(e){this.mcpAuthPath=e;const t=gm.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,gm.mcpAuthPromises.set(e,t),t.catch((()=>{gm.mcpAuthPromises.get(e)===t&&gm.mcpAuthPromises.delete(e)}))}gm.saveLocks.has(e)||gm.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,Qs.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=gm.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;gm.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,Qs.mkdir)(i.dirname(this.mcpAuthPath),{recursive:!0}),await(0,Qs.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}gm.mcpAuthPromises=new Map,gm.saveLocks=new Map;var wm=r("../proto/dist/generated/agent/v1/utils_pb.js");const ym=Buffer.from([137,80,78,71,13,10,26,10]),vm=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),bm=e=>1===e||e>=208&&e<=216,Sm=e=>192===e||193===e||194===e,km=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e;const Em=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},Cm=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),xm=e=>Em().encode(e),_m=[{width:1280,height:800},{width:1456,height:840}],Pm=1048576,Rm=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Im=(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 s=Math.min(e,t);if(s<8)return{width:e,height:t,needsResize:!1};let n=r/o,i=Math.max(1,Math.round(e*n)),a=Math.max(1,Math.round(t*n));return(i<8||a<8)&&(n=8/s,i=Math.max(8,Math.round(e*n)),a=Math.max(8,Math.round(t*n))),{width:i,height:a,needsResize:i!==e||a!==t}}(e,t,r),Tm=(e,t,r)=>{e.resize({w:t,h:r})};const Am=async(e,t)=>{if(Cm(e))return(async(e,t)=>{const r=(e=>{if(!Cm(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)}}})(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Rm(e),mimeType:"image/webp"};const o=void 0!==r&&_m.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(o||!Im(r.width,r.height,1280).needsResize)&&e.length<=Pm)return{data:Rm(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Rm(e),mimeType:"image/webp"};const s=await(n=e,Em().decode(n));var n;const i=(await mp()).fromBitmap({data:Buffer.from(s.data),width:s.width,height:s.height});let{width:a,height:c,needsResize:l}=o?{width:i.bitmap.width,height:i.bitmap.height,needsResize:!1}:Im(i.bitmap.width,i.bitmap.height,1280);l&&Tm(i,a,c);let u=await xm({data:i.bitmap.data,width:i.bitmap.width,height:i.bitmap.height});for(;u.length>Pm&&a>8&&c>8;)a=Math.max(8,Math.round(.8*a)),c=Math.max(8,Math.round(.8*c)),Tm(i,a,c),u=await xm({data:i.bitmap.data,width:i.bitmap.width,height:i.bitmap.height});return{data:Rm(u),mimeType:"image/webp"}})(e,t);const r=(e=>{if(e.length<ym.length+25+vm.length||!e.subarray(0,ym.length).equals(ym)||13!==e.readUInt32BE(8)||"IHDR"!==e.toString("ascii",12,16)||!e.subarray(e.length-vm.length).equals(vm))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(bm(r)){t+=2;continue}if(218===r||217===r||km(r))return;const o=e.readUInt16BE(t+2);if(o<2)return;if(Sm(r)){if(o<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),s=e.readUInt16BE(t+7);if(s<1||r<1)return;return{mimeType:"image/jpeg",width:s,height:r}}t+=2+o}})(o);var o;if(void 0!==r&&e.length<=Pm&&!Im(r.width,r.height).needsResize)return{data:Rm(e),mimeType:r.mimeType};const s=await mp(),n=await s.read(e),i=(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"}})(n),a=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==i&&"image/jpeg"!==i?"image/png":i,{width:c,height:l,needsResize:u}=Im(n.width,n.height);if(!u&&e.length<=Pm&&a===i)return{data:Rm(e),mimeType:i};let d=c,h=l;u&&Tm(n,d,h);let p=await n.getBuffer(a);for(;p.length>Pm&&d>8&&h>8;)d=Math.max(8,Math.round(.8*d)),h=Math.max(8,Math.round(.8*h)),Tm(n,d,h),p=await n.getBuffer(a);return{data:Rm(p),mimeType:a}};var Mm=r("../mcp-core/dist/mcp-tool-annotations.js"),Dm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},Om=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Nm=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),jm=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),$m=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),Fm=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),Lm=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),Um=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),Bm=(0,d.h)("McpFileSystemWriter"),zm="mcpFsStructuredLogOptIn";function Wm(e,t){return t?.includeStructuredLogs?{...e??{},[zm]:!0}:e}const Hm={debug(e,t,r,o){Bm.debug(e,t,Wm(r,o))},info(e,t,r,o){Bm.info(e,t,Wm(r,o))},warn(e,t,r,o){Bm.warn(e,t,Wm(r,o))},error(e,t,r,o,s){Bm.error(e,t,r,Wm(o,s))}},qm="mcps",Gm="tools",Vm="~staging",Jm="~prev",Km="mcp_auth",Zm="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.",Qm="# >>> CURSOR MANAGED BLOCK >>>",Xm="# <<< CURSOR MANAGED BLOCK <<<",Ym=["# 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 eg(e,t,r=15e3){let o;return Promise.race([e.catch((()=>t)),new Promise((e=>{o=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(o)))}function tg(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function rg(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function og(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 sg(e){if(Array.isArray(e))return e.map((e=>sg(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,sg(t)]));return Object.fromEntries(t)}return e}function ng(e){return JSON.stringify(sg(e))}function ig(e){const t=e.map((e=>({value:e,key:ng(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function ag(e){const t=ig(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=ig(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),o=ig(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return ng({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 cg{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.useDirectClientTools=r?.useDirectClientTools??!1,this.enabledToolsByServerProvider=r?.getEnabledToolsByServer,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=>{Hm.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),Hm.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,i.join)(e,".gitignore"),r=`${Qm}\n${Ym}\n${Xm}\n`;let o;await(0,Qs.mkdir)(e,{recursive:!0});try{o=await(0,Qs.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==e?.code)throw e}if(void 0===o)return void await(0,Qs.writeFile)(t,r);const s=o.indexOf(Qm),n=o.indexOf(Xm,s+30);if(-1===s||-1===n)await(0,Qs.writeFile)(t,r);else{const e=`${o.slice(0,s)}${r}${o.slice(n+30).replace(/^\n/,"")}`;e!==o&&await(0,Qs.writeFile)(t,e)}})((0,i.join)((0,n.homedir)(),".cursor")).catch((e=>{Hm.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,i.join)(this.projectDir,qm);try{const e=await(0,Qs.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(Vm))).map((e=>(0,Qs.rm)((0,i.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==e?.code&&Hm.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:at(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:at(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){Hm.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,re.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return rg(this.mcpAuthCopyOverrides?.authToolDescription)??Zm}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&ot(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return rg(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=rg(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:Km},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&ot(e)?this.getNeedsAuthStatusMessage(e):rg(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){Hm.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${o}`);const s=await this.mcpLease.getTools(e).catch((e=>(Hm.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),n=new Set(t);return s.filter((e=>n.has(e.clientKey)))}}async getEnabledToolsByServer(e){if(this.useDirectClientTools&&void 0!==this.enabledToolsByServerProvider)try{return await this.enabledToolsByServerProvider(e)}catch(t){return void Hm.warn(this.getLogContext(e),`getEnabledToolsByServer() threw, falling back to raw direct client tool lists: ${t}`)}}async fetchClientDataForServer(e,t,r,o){const s=this.getLogContext(e),n=await eg(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||Hm.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),i="ready"===n.kind||"requires_authentication"===n.kind,[a,c,l,u]=await Promise.all([i&&this.useDirectClientTools?eg(r.getTools(e),[]).then((e=>(0===e.length&&Hm.info(s,`Direct client getTools() returned 0 tools for "${t}" (state=${n.kind})`),e))):Promise.resolve([]),i?eg(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),i?eg(r.listPrompts(e),[]):Promise.resolve([]),i&&o?.fetchInstructions?eg(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,clientTools:a.map((e=>({...e,clientKey:t,providerIdentifier:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,toolName:e.name}))),resources:c.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:l.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:u,status:og(n)}}buildServerDataMap(e,t,r,o,s){const n=new Map(r.map((e=>[e.clientKey,e.clientTools]))),a=new Map;for(const e of r){const t=mg(e.clientKey);a.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,i.join)(this.projectDir,qm,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const e of t){let t=a.get(e.clientKey);if(!t){const r=mg(e.clientKey);t={serverIdentifier:e.clientKey,serverName:e.providerIdentifier,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:r,folderPath:(0,i.join)(this.projectDir,qm,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},a.set(e.clientKey,t)}t.tools.push(e)}for(const[t,r]of a)if(0===r.tools.length){const s=n.get(t);if(s&&s.length>0){const n=o?.[t],i=void 0!==n?s.filter((e=>n.includes(e.toolName))):s;if(void 0!==n&&0===i.length){Hm.info(e,`Skipping direct client tool fallback for "${t}": settings report 0 enabled tools`);continue}Hm.info(e,`Using direct client tool fallback for "${t}": lease had 0 tools, client has ${s.length}, writing ${i.length}`),r.tools=i}}if(void 0!==s)for(const e of s){const t=e.serverIdentifier?.trim();let r=t?Array.from(a.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(a.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of a.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===Km))||e.tools.push({clientKey:(c={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:c.serverName,plugin:c.plugin,marketplace:c.marketplace,pluginId:c.pluginId,marketplaceId:c.marketplaceId,toolName:Km,name:Km,description:c.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var c;return a}buildServersToWrite(e,t){const r=[],o=new Set;for(const s of t.values()){const t=s.tools.length>0||s.resources.length>0||s.prompts.length>0||s.instructions,n="error"===s.status||"needsAuth"===s.status||"initializing"===s.status;t||n?o.has(s.sanitizedId)?Hm.warn(e,`Skipping server "${s.serverIdentifier}" — sanitizedId "${s.sanitizedId}" collides with another server`):(o.add(s.sanitizedId),r.push(s)):Hm.info(e,`Server "${s.serverIdentifier}" excluded from write: tools=${s.tools.length}, resources=${s.resources.length}, prompts=${s.prompts.length}, hasInstructions=${!!s.instructions}, status=${s.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===Km))){const t=e.tools.find((e=>e.toolName===Km));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??[])];Hm.info(r,`fetchAndWrite: refreshing ${o.length} targeted servers`,{serverIdentifiers:o});const s=await this.getToolsForServers(e,o),n=await this.mcpLease.getInstructions(e).catch((e=>(Hm.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 Hm.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=>{Hm.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,u]=await Promise.all([Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),this.getEnabledToolsByServer(e)]),d=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),h=this.buildServerDataMap(e,s,l,u,n),p=new Set(o),f=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=d.get(e),o=h.get(e);if(void 0===o)c.has(e)?d.delete(e):Hm.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(f.has(e)&&void 0!==t){d.set(e,this.mergeScopedRefreshWithCachedServerData(t,o)),Hm.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}d.set(e,o)}}const m=new Map(Array.from(d.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!p.has(e)&&!d.has(e)){const t=mg(e);m.set(t,e)}const g=this.buildServersToWrite(e,d);await this.writeServerData(e,g,m),this.cachedServerData=g,this.fireOnDidWrite(g)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{Dm(r,(0,c.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const o=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!at(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,s,n,i]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(Hm.warn(o,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(Hm.warn(o,`getClients() threw, defaulting to {}: ${e}`),{}))),this.getEnabledToolsByServer(e)]),a=Object.keys(n);Hm.info(o,`fetchAndWrite: lease returned ${r.length} tools across ${a.length} clients`);const c=Object.entries(n).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),l=await Promise.all(c),u=this.buildServerDataMap(e,r,l,i,s),d=this.buildServersToWrite(e,u),h=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,d,h),this.cachedServerData=d,this.fireOnDidWrite(d)}catch(e){Hm.error(o,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{Om(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,i.join)(e.folderPath,Gm,`${tg(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Dm(o,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const n=this.getLogContext(e),a=(0,i.join)(this.projectDir,qm);await(0,Qs.mkdir)(a,{recursive:!0});const l=new Map;for(const e of t)try{l.set(e.serverIdentifier,ag(e))}catch(t){Hm.error(n,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),l.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const u=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==l.get(e.serverIdentifier)&&(u.push(e),void 0!==t&&Hm.info(n,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!u.includes(e))try{await(0,Qs.stat)((0,i.join)(a,e.sanitizedId))}catch{Hm.info(n,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),u.push(e)}const d=new Set;for(const[e]of this.cachedFingerprints)if(!l.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),o=t?.sanitizedId??mg(e);r.has(o)?(Hm.info(n,`Server "${e}" (sanitized="${o}") still in lease but excluded from write, preserving directory`),l.set(e,this.cachedFingerprints.get(e))):(Hm.info(n,`Server "${e}" (sanitized="${o}") left the lease, scheduling directory removal`),d.add(o))}const h=void 0===this.cachedServerData;if(h)try{const e=await(0,Qs.readdir)(a),t=new Set(e.filter((e=>!e.endsWith(Vm)&&!e.endsWith(Jm))));for(const r of e)if(r.endsWith(Vm))await(0,Qs.rm)((0,i.join)(a,r),{recursive:!0,force:!0});else if(r.endsWith(Jm)){const e=r.slice(0,-5);if(t.has(e))await(0,Qs.rm)((0,i.join)(a,r),{recursive:!0,force:!0});else try{await(0,Qs.rename)((0,i.join)(a,r),(0,i.join)(a,e)),t.add(e)}catch{await(0,Qs.rm)((0,i.join)(a,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);l.has(t)||l.set(t,`__preserved_${e}`)}else d.add(e)}catch(e){Hm.error(n,"Error clearing mcps directory",e)}const p=Array.from(d);if(u.length>0||d.size>0){const e=u.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));Hm.info(n,`Incremental write: ${u.length} changed, ${d.size} removed, ${t.length-u.length} unchanged`,{changedServerCount:u.length,changedServers:e,removedServerCount:d.size,removedServerSanitizedIds:p,unchangedServerCount:t.length-u.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:h,projectDirHash:(0,s.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const f=await Promise.allSettled(u.map((t=>this.writeServerAtomic(e,t,a))));for(let t=0;t<u.length;t++){const r=f[t];if("rejected"===r.status){const o=u[t],s=this.cachedFingerprints.get(o.serverIdentifier);void 0!==s?l.set(o.serverIdentifier,s):l.delete(o.serverIdentifier),Hm.error(e,"Error writing server directory",r.reason,{serverIdentifier:o.serverIdentifier,sanitizedId:o.sanitizedId},{includeStructuredLogs:!0})}}const m=await Promise.allSettled(p.map((e=>(0,Qs.rm)((0,i.join)(a,e),{recursive:!0,force:!0}))));for(let r=0;r<m.length;r++){const o=m[r];if("rejected"===o.status){const s=p[r];Hm.error(e,"Error removing server directory",o.reason,{sanitizedId:s,removalIndex:r,removalAttemptCount:m.length,removedServerCount:p.length,removedServerSanitizedIds:p,changedServerCount:u.length,unchangedServerCount:t.length-u.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=l}catch(e){o.error=e,o.hasError=!0}finally{Om(o)}}async writeServerAtomic(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Dm(o,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const s=`${t.sanitizedId}${Vm}`,n=`${t.sanitizedId}${Jm}`,a=(0,i.join)(r,s),l=(0,i.join)(r,n),u=(0,i.join)(r,t.sanitizedId);await(0,Qs.rm)(a,{recursive:!0,force:!0});try{await(0,Qs.rename)(l,u)}catch{await(0,Qs.rm)(l,{recursive:!0,force:!0})}await this.writeServerDirectory(e,t,{basePath:r,dirName:s});try{try{await(0,Qs.rename)(u,l)}catch{}await(0,Qs.rename)(a,u)}catch(r){Hm.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0});try{await(0,Qs.rename)(l,u)}catch{}throw await(0,Qs.rm)(a,{recursive:!0,force:!0}),r}await(0,Qs.rm)(l,{recursive:!0,force:!0}).catch((()=>{}))}catch(e){o.error=e,o.hasError=!0}finally{Om(o)}}async writeServerDirectory(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Dm(o,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const s=(0,i.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,Qs.mkdir)(s,{recursive:!0}),t.tools.length>0){const e=(0,i.join)(s,Gm);await(0,Qs.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=tg(r.toolName),o=(0,i.join)(e,`${t}.json`),s=nt(r);await(0,Qs.writeFile)(o,JSON.stringify(s,null,2))}}if(t.resources.length>0){const e=(0,i.join)(s,"resources");await(0,Qs.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=tg(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),o=(0,i.join)(e,`${t}.json`),s={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,Qs.writeFile)(o,JSON.stringify(s,null,2))}}if(t.prompts.length>0){const e=(0,i.join)(s,"prompts");await(0,Qs.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=tg(r.name),o=(0,i.join)(e,`${t}.json`),s={name:r.name,description:r.description,arguments:r.arguments};await(0,Qs.writeFile)(o,JSON.stringify(s,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,i.join)(s,"INSTRUCTIONS.md");await(0,Qs.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,i.join)(s,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,Qs.writeFile)(e,r)}const n=(0,i.join)(s,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,Qs.writeFile)(n,JSON.stringify(a,null,2))}catch(e){o.error=e,o.hasError=!0}finally{Om(o)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;Dm(r,(0,c.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const o=this.getLogContext(e),s=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!s)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&s&&Hm.warn(o,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const n=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=tg(t.toolName),o=(0,i.join)(e.folderPath,Gm,`${r}.json`);return new ro.E$({toolName:t.toolName,definitionPath:o,...(0,Mm.hT)(t.annotations)})}));return new ro.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,n,"workbench_lease"),new ro.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:n})}catch(e){r.error=e,r.hasError=!0}finally{Om(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&&Hm.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){Hm.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return o&&Hm.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),o}try{await this.writePromise}catch(e){Hm.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{Dm(t,(0,c.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),o=Date.now(),s=await this.snapshotProvider.getAllSnapshots(e),n=(0,i.join)(this.projectDir,qm),a=s.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=mg(e.serverIdentifier),r=(0,i.join)(n,t),o=e.tools.map((e=>{const t=tg(e.name);return new ro.E$({toolName:e.name,definitionPath:(0,i.join)(r,Gm,`${t}.json`),...(0,Mm.hT)(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===Km))){const e=tg(Km);o.push(new ro.E$({toolName:Km,definitionPath:(0,i.join)(r,Gm,`${e}.json`)}))}return new ro.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=a.reduce(((e,t)=>e+t.tools.length),0);return Hm.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-o}ms: ${s.length} snapshots, ${a.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new ro.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{Om(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),s=Date.now();s-this.lastDivergenceCheckMs<cg.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=s,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{Hm.warn(o,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const o=this.getLogContext(e),s=(0,i.join)(this.projectDir,qm),n=new Set,a=new Map;for(const e of t){const t=mg(e.serverIdentifier);n.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Qs.readdir)(s),c=c.filter((e=>!e.endsWith(Vm)&&!e.endsWith(Jm)))}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+"}(n.size);for(const t of n)l.has(t)||(u=!1,d++,Nm.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),Hm.warn(o,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:n.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)n.has(t)||(u=!1,h++,Nm.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of n){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,i.join)(s,t,Gm);let h=0;try{h=(await(0,Qs.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,Nm.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),Hm.warn(o,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:n.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}jm.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),$m.gauge(e,n.size,this.getMetricTags({mcp_source:r})),Fm.gauge(e,l.size,this.getMetricTags({mcp_source:r})),Lm.gauge(e,d,this.getMetricTags({mcp_source:r})),Um.gauge(e,p,this.getMetricTags({mcp_source:r})),Hm.info(o,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:n.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:n.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||Hm.warn(o,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:n.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:n.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())}}cg.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var lg=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},ug=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 dg=(0,d.h)("local-exec:mcp");function hg(e,t){const r=i.relative(e,t);return""===r||!i.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${i.sep}`)}function pg(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function fg(e){return new mt._Z({content:{case:"text",value:new mt.zN({text:e})}})}function mg(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 gg(e,t,r){const o=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t,r.toolDef?.annotations);if(!o)return;const s=await Wi(o,{onNeedsApproval:async(e,o)=>{if("mcp"!==o.type)return new mt.iz({result:{case:"error",value:new mt.Nh({error:"Invalid approval details type for MCP execution"})}});const s=await r.pendingDecisionProvider.requestApproval({type:Mp.Mcp,details:{name:o.name,toolName:o.toolName,providerIdentifier:o.providerIdentifier,source:r.toolDef?.source,args:o.args,reason:o.reason??e,canAllowlist:o.canAllowlist,smartModeApprovalReason:o.smartModeApprovalReason,smartModeApprovalRequestId:o.smartModeApprovalRequestId},toolCallId:t.toolCallId});return s.approved?t.smartModeApprovalOnly?new mt.iz({result:{case:"approved",value:new mt.Ke}}):null:new mt.iz({result:{case:"rejected",value:new mt.xo({reason:`User rejected MCP: ${t.name}${s.reason?` - ${s.reason}`:""}`})}})},onUserRejected:e=>new mt.iz({result:{case:"error",value:new mt.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const o=`MCP tool execution blocked: ${t.name} - ${e}`;return new mt.iz({result:{case:"permissionDenied",value:new mt.HQ({error:o,isReadonly:r?.isReadonly??!1})}})}});return s??void 0}class wg{constructor(e,t,r,o,s=4e4,n,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=o,this.fileOutputThresholdBytes=s,this.elicitationFactory=n,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 s=Object.entries(o).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===s)return;const[n,i]=s;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}}(ct(a));return void 0!==c?`MCP server "${n}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=lg(r,(0,c.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,n=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[n]));const a=await this.toolSet.getTools(o),l=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),u=a.find((e=>e.clientKey===n&&e.toolName===t.toolName)),d=await gg(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u});if(void 0!==d)return d;const h=await this.toolSet.getToolSet(o);let p;try{p=await h.execute(t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(Vf(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new Jf(t.providerIdentifier,l)),r instanceof Jf){const e=await this.describeDisconnectedServer(o,[n,t.providerIdentifier]);return void 0!==e?new mt.iz({result:{case:"error",value:new mt.Nh({error:e})}}):new mt.iz({result:{case:"serverNotFound",value:new mt.JL({name:r.serverName,availableServers:r.availableServers})}})}if(Vf(r))return new mt.iz({result:{case:"toolNotFound",value:new mt.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const f=[];for(const e of p.content){const t=e.type;if("text"===t){const t=e;f.push(fg(t.text))}else if("resource"===t){const t=e;t.resource?.text&&f.push(fg(t.resource.text))}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),o=await Am(r);f.push(new mt._Z({content:{case:"image",value:new mt.do({data:o.data,mimeType:o.mimeType})}}))}else if("image"!==t){const t=pf(e);f.push(fg(t))}}const m=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 s=await r(o);if(void 0===s)return;const n=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(n.push(new mt._Z({content:{case:"text",value:new mt.zN({text:"",outputLocation:s})}})),i=!0):n.push(t);return n}({contentItems:f,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=i.join(t,Zp),o=i.join(r,`${(0,s.randomUUID)()}.txt`);await(0,Qs.mkdir)(i.dirname(o),{recursive:!0});const n=e.slice(0,Qp),a=n.split("\n").length,c=Buffer.byteLength(n,"utf8");return await(0,Qs.writeFile)(o,n,"utf8"),new wm.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir)});if(void 0===m)throw new Error("Failed to materialize MCP text output");const g=p.structuredContent&&"object"==typeof p.structuredContent&&!Array.isArray(p.structuredContent)?bt.Struct.fromJson(p.structuredContent):void 0,w=new mt.QW({content:m,isError:p.isError,structuredContent:g});return new mt.iz({result:{case:"success",value:w}})}catch(e){r.error=e,r.hasError=!0}finally{ug(r)}}}class yg{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=lg(r,(0,c.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 mt.kP({result:{case:"error",value:new mt.w2({error:`Server "${t.server}" not found`})}});const s=await this.listResourcesFromClient(o,r,t.server,!0);return new mt.kP({result:{case:"success",value:new mt.T2({resources:s})}})}const e=await this.mcpLease.getClients(o),r=new Set,s=await this.mcpLease.getTools(o);for(const e of s)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const n=[];for(const[t,s]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(o,s,t);n.push(...e)}return new mt.kP({result:{case:"success",value:new mt.T2({resources:n})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new mt.kP({result:{case:"error",value:new mt.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ug(r)}}async listResourcesFromClient(e,t,r,o=!1){const s=await t.getState(e);if("ready"!==s.kind&&(!o||"loading"!==s.kind))return[];const n=await t.listResources(e);return n&&n.resources?n.resources.map((e=>new mt.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class vg{constructor(e,t=".",r,o=[],s,n){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=s,this.ensureMcpServersLoaded=n,this.workspacePaths=o.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(Qe),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=lg(r,(0,c.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,s=t.smartModeApproval?.reason;if(void 0!==s){if(void 0===this.pendingDecisionProvider)return new mt.ZD({result:{case:"error",value:new mt.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Mp.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:bt.Value.fromJson(t.server),uri:bt.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:bt.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:s,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new mt.ZD({result:{case:"rejected",value:new mt.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(o,[t.server]));const n=await this.mcpLease.getClients(o),a=n[t.server]??Object.values(n).find((e=>e.serverName===t.server));if(!a)return new mt.ZD({result:{case:"error",value:new mt.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(o)).kind)return new mt.ZD({result:{case:"error",value:new mt.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(o,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new mt.ZD({result:{case:"notFound",value:new mt.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=i.resolve(e),o=await(0,Qs.realpath)(r),s=i.resolve(r,t.replace(/^\/+/,""));if(!hg(r,s))throw new Error("downloadPath must stay within the workspace");let n=i.dirname(s);for(;;)try{if(!hg(o,await(0,Qs.realpath)(n)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==pg(e))throw e;const t=i.dirname(n);if(t===n)throw e;n=t}if(await(0,Qs.mkdir)(i.dirname(s),{recursive:!0}),!hg(o,await(0,Qs.realpath)(i.dirname(s))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,Qs.lstat)(s)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==pg(e))throw e}return s}(this.resolveProjectDir(o),t.downloadPath);if(r.text)await(0,Qs.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,Qs.writeFile)(e,t)}return new mt.ZD({result:{case:"success",value:new mt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType})}})}if(r.text)return new mt.ZD({result:{case:"success",value:new mt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new mt.ZD({result:{case:"success",value:new mt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"blob",value:e}})}})}return new mt.ZD({result:{case:"error",value:new mt.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return dg.warn(o,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new mt.ZD({result:{case:"error",value:new mt.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ug(r)}}}async function bg(e,t){const r=mg(t),o=(0,i.join)(e,"mcps",r,"tools");let s;try{s=await(0,Qs.readdir)(o)}catch(e){if("ENOENT"===e?.code)return{toolNames:[],toolsDirExists:!1};throw e}const n=await Promise.all(s.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,Qs.readFile)((0,i.join)(o,e),"utf8"))}catch{return}}))),a=new Set;for(const e of n)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Sg=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),kg="/mcps/",Eg=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Cg=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),xg=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),_g=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),Pg=new Map;function Rg(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Ig({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:o,readDiskCatalog:s,state:n}){let i=n;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Sg.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>mg(e.serverIdentifier)===o));if(void 0===a)return;let c;try{c=await s(r,a.serverIdentifier)}catch(t){return void Sg.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 s=new Set(o),n=new Set(r),i=r.filter((e=>!s.has(e))),a=o.filter((e=>!n.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Eg.increment(e,1,{...l,outcome:c}),Cg.histogram(e,i.length,l),xg.histogram(e,a.length,l),_g.histogram(e,i.length+a.length,l),"mismatch"===c&&Sg.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 Tg(e,t,r,o=bg){if(void 0===r||(void 0===(s=r)||!Rg(s).includes(kg)))return;var s;const n=function(e){const t=Rg(e),r=t.indexOf(kg);if(-1===r)return;const o=t.slice(0,r),s=t.slice(r+6).split("/").filter(Boolean);return 0!==o.length?0===s.length?{projectDir:o,kind:"mcps_root"}:{projectDir:o,kind:"server",sanitizedServerFolder:s[0]}:void 0}(r);if(void 0===n)return;let i,a;const c="mcps_root"===n.kind;"mcps_root"===n.kind?(i=`${n.projectDir}\0__mcps_root__`,a=void 0):(i=`${n.projectDir}\0${n.sanitizedServerFolder}`,a=n.sanitizedServerFolder);const l=Pg.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{Pg.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const s=mg(r.serverIdentifier);await Ig({ctx:u,mcpStateAccessor:t,projectDir:n.projectDir,sanitizedServerFolder:s,readDiskCatalog:o,state:e})}}else void 0!==a&&await Ig({ctx:u,mcpStateAccessor:t,projectDir:n.projectDir,sanitizedServerFolder:a,readDiskCatalog:o})})().catch((e=>{Sg.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);Pg.set(i,d)}var Ag=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},Mg=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Dg(e,t,r){const o=function(e,t){let r;for(const o of t)(0,ln.ZU)({basePath:o,targetPath:e})&&(void 0===r||o.length>r.length)&&(r=o);return r}((0,i.resolve)(e,t),r);return void 0===o||o===e}const Og=(0,d.h)("local-exec/grep");function Ng(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function jg(e){try{return(0,Ys.existsSync)(e)}catch{return"check_failed"}}function $g(e,t,r,o){return{...Lg(e),...o,cwd:t,cwdExists:jg(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function Fg(e){return new Error(`Path does not exist: ${e}`)}function Lg(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,Ys.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ys.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,i.dirname)(e);try{t.parentDirExists=(0,Ys.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ys.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const o=(0,i.dirname)(r);try{t.grandparentDirExists=(0,Ys.existsSync)(o),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ys.readdirSync)(o).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ys.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 s="node_modules.asar.unpacked";if(e.includes(s)){const r=e.split(s)[0];if(r){const e=r.concat("node_modules.asar");try{t.asarExists=(0,Ys.existsSync)(e)}catch{t.asarExists="check_failed"}const o=r.concat(s);try{if(t.asarUnpackedDirExists=(0,Ys.existsSync)(o),t.asarUnpackedDirExists){const e=(0,i.join)(o,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,Ys.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class Ug{constructor(e,t,r,o){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;const s=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:s,this.mcpStateAccessor=o?.mcpStateAccessor,this.permissionsService=o?.permissionsService}computeRelativeTarget(e,t){const r=(0,ln.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,i.relative)(t,r)}isRootIndependentSearchPath(e){return(0,i.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const o=(0,i.resolve)(t);return{root:t,resolvedRoot:o,target:(0,ln.o1)(e,r?void 0:o)}}))}clampGrepArgsToWorkspace(e,t){if(void 0===e.path||""===e.path)return e;const r=this.resolveSearchTargets(e.path,t);if(this.isRootIndependentSearchPath(e.path)?r.some((({resolvedRoot:e,target:t})=>(0,ln.BJ)(t,e))):r.every((({resolvedRoot:e,target:t})=>(0,ln.BJ)(t,e))))return e;const o=e.clone();return o.path=void 0,o}async buildArgs(e,t,r){const o=[],s=await this.ignoreService.listCursorIgnoreFilesByRoot(e);for(const e of s)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push("-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${r}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&o.push("--iglob",t.glob),t.multiline&&o.push("--multiline","--multiline-dotall");const n=t.sort??"modified";if("none"!==n){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,n)}return o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow"),o.push("--regexp",t.pattern),o.push("--"),o.push(t.path?this.computeRelativeTarget(t.path,e):"."),o}async filterBlockedFiles(e,t){const r=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ln.o1)(s.file,t),n=await Fi(e);null===n||await this.isPostRipgrepBlocked(n)||void 0!==r&&await r(e,n)||o.push(s)}return o}async isPostRipgrepBlocked(e){const[t,r]=await Promise.all([this.ignoreService.isCursorIgnored(e),this.ignoreService.isRepoBlocked(e)]);return t||r}async runFilesMode(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{const u=Ag(n,(0,c.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),d=await this.buildArgs(t,r,"files_with_matches"),h=await this.executeRg(u.ctx,t,d,void 0,o,s);if((""!==h.stderr||2===h.exitCode)&&""===h.stdout.trim())throw new Error(h.stderr||`ripgrep exited with code ${h.exitCode}`);const{files:p,totalFiles:f,clientTruncated:m,ripgrepTruncated:g}=(i=h.stdout,a=Ug.CLIENT_LIMIT_LINES,l=Ug.HARD_MAX_OUTPUT_LINES,function(e,t,r){const o=e.trim();if(""===o)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const s=[],n=new Jp;let i=0,a=0;for(;Kp(o,a,n);){const e=a,r=n.lineEnd;a=n.nextStart,i<t&&s.push(o.slice(e,r)),i++}return{files:s,totalFiles:Gp(i),clientTruncated:i>t,ripgrepTruncated:i>=r}}(i,a,l)),w=(await this.filterBlockedFiles(p.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=p.length-w.length,v=new Wp.T7({files:w,totalFiles:Gp(f-y),clientTruncated:m,ripgrepTruncated:g});return new Wp.vD({result:{case:"files",value:v}})}catch(e){n.error=e,n.hasError=!0}finally{Mg(n)}var i,a,l}async runCountMode(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{const u=Ag(n,(0,c.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),d=await this.buildArgs(t,r,"count"),h=await this.executeRg(u.ctx,t,d,void 0,o,s);if((""!==h.stderr||2===h.exitCode)&&""===h.stdout.trim())throw new Error(h.stderr||`ripgrep exited with code ${h.exitCode}`);const{counts:p,totalFiles:f,totalMatches:m,clientTruncated:g,ripgrepTruncated:w}=(i=h.stdout,a=Ug.CLIENT_LIMIT_LINES,l=Ug.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 s=[],n=new Jp;let i=0;for(;Kp(o,i,n);){const e=i,t=n.lineEnd;if(i=n.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)&&s.push({file:o.slice(e,r),count:c})}const a=s.length;let c=0;for(let e=0;e<s.length;e++){const t=s[e];void 0!==t&&(c+=t.count)}const l=[],u=a<t?a:t;for(let e=0;e<u;e++){const t=s[e];void 0!==t&&l.push(t)}return{counts:l,totalFiles:Gp(a),totalMatches:Gp(c),clientTruncated:a>t,ripgrepTruncated:a>=r}}(i,a,l)),y=await this.filterBlockedFiles(p,t),v=y.reduce(((e,t)=>e+t.count),0),b=p.length-y.length,S=p.reduce(((e,t)=>e+t.count),0)-v,k=new Wp.xA({counts:y.map((e=>new Wp.sS({file:e.file,count:Gp(e.count)}))),totalFiles:Gp(f-b),totalMatches:Gp(m-S),clientTruncated:g,ripgrepTruncated:w});return new Wp.vD({result:{case:"count",value:k}})}catch(e){n.error=e,n.hasError=!0}finally{Mg(n)}var i,a,l}async runContentMode(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{const i=Ag(n,(0,c.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),a=await this.buildArgs(t,r,"content"),l=await this.executeRg(i.ctx,t,a,void 0,o,s);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{byFile:u,totalLines:d,totalMatchedLines:h,clientTruncated:p,ripgrepTruncated:f}=function(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{return Ag(s,(0,c.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 s=new Map,n=new Set,i=new Jp;let a=0,c=0,l=0,u=0;for(;Kp(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(n.has(v)||n.add(v),c>=t)continue;const b=e.slice(f+1,o);let S=s.get(v);void 0===S&&(S={file:v,matches:[]},s.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:s,totalLines:Gp(l),totalMatchedLines:Gp(a),totalFiles:Gp(n.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){s.error=e,s.hasError=!0}finally{Mg(s)}}(l.stdout,Ug.CLIENT_LIMIT_LINES,Ug.HARD_MAX_OUTPUT_LINES,i.ctx),m=Array.from(u.values()),g=await this.filterBlockedFiles(m,t),w=m.filter((e=>!g.includes(e))),y=w.reduce(((e,t)=>e+t.matches.length),0),v=w.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),b=new Wp.Zp({matches:g.map((e=>new Wp.uI({file:e.file,matches:e.matches.map((e=>new Wp.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Gp(d-y),totalMatchedLines:Gp(h-v),clientTruncated:p,ripgrepTruncated:f});return new Wp.vD({result:{case:"content",value:b}})}catch(e){n.error=e,n.hasError=!0}finally{Mg(n)}}async executeIndexedGrepWithTimeout(e,t,r,o){if(void 0===this.grepProvider.executeIndexedGrep)return;const[s,n]=e.withTimeoutAndCancel(Ug.INDEXED_GREP_CONTEXT_TIMEOUT_MS),i={phase:"provider"},a=performance.now();try{return await(0,vt.wj)(this.grepProvider.executeIndexedGrep(s,t,r,i),Ug.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${Ug.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof vt.MU)return void Og.debug(e,"indexed_grep.timeout_fallback",{...o,totalMs:Math.round(performance.now()-a),...i});throw t}finally{n()}}async executeRg(e,t,r,o,s,n){const i=(0,c.VI)(e.withName("LocalGrepExecutor.executeRg")),a="utf8",l=8388608;return o=o??Ug.HARD_MAX_OUTPUT_LINES,new Promise(((c,u)=>{let d=!1,h=!1;const p=()=>{h||(h=!0,i.span.end())};let f,m;try{const e=s;f=(0,en.spawnInSandbox)((0,en.Ko)(),r,{cwd:t},e),0}catch(r){if(p(),Ng(r)){const o=r,s=(0,en.Ko)();if(Og.error(e,"rg_diagnostics.spawn_throw",void 0,$g(s,t,o,n)),!1===jg(t))return u(Fg(t))}return u(r)}const g=[],w=[];let y=0,v=0,b=0,S=!1;m=setTimeout((()=>{if(!d)try{p(),u(new Error(`Timed out after ${Ug.MAIN_TIMEOUT_MS/1e3}s`)),f.kill()}catch{}}),Ug.MAIN_TIMEOUT_MS),f.stdout?.on("data",(e=>{if(y+=e.length,void 0!==o&&!0!==S){let t=-1,r=0;for(let s=0;s<e.length;s++)if(10===e[s]&&(r++,b+r>=o)){t=s+1,S=!0;try{f.kill()}catch{}break}b+=r;const s=t>=0?e.subarray(0,t):e;y<=l&&g.push(s)}else!0!==S&&y<=l&&g.push(e)})),f.stderr?.on("data",(e=>{v+=e.length,v<=l&&w.push(e)})),f.on("error",(r=>{if(clearTimeout(m),p(),Ng(r)){const o=(0,en.Ko)(),s=r;if(Og.error(e,"rg_diagnostics.spawn_enoent",void 0,$g(o,t,s,n)),!1===jg(t))return void u(Fg(t))}u(r)})),f.on("close",(e=>{d=!0,clearTimeout(m);const t=Buffer.concat(g).toString(a),r=Buffer.concat(w).toString(a);p(),c({stdout:t,stderr:r,exitCode:e??0})}))}))}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=Ag(o,(0,c.VI)(e.withName("LocalGrepExecutor.execute")),!1),n=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],a=t.outputMode??"content",l={toolCallId:t.toolCallId,execId:r?.execId,outputMode:a,targetPath:t.path,workspacePaths:n},u=An(t.sandboxPolicy),d=this.grepProvider.getWorktreeGuardInfo?.(n);if((0,ln.fl)({targetPath:t.path,workspacePaths:n,mainWorktreePath:d?.mainWorktreePath}))return new Wp.Ud({result:{case:"error",value:new Wp.ts({error:ln.PS})}});const h=this.clampGrepArgsToWorkspace(t,n);let p=n;try{if(h.path){const t=[];let r=!1,o=!1;for(const{root:s,resolvedRoot:i,target:a}of this.resolveSearchTargets(h.path,n)){if(!(0,ln.BJ)(a,i))continue;const n=await Fi(a);null!==n?await this.ignoreService.isCursorIgnored(n)?r=!0:(t.push(s),void 0!==this.mcpStateAccessor&&Tg(e,this.mcpStateAccessor,n)):o=!0}if(0===t.length){const e=r?`Path '${h.path}' is filtered out by .cursorignore`:o?`Path '${h.path}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`:`Path '${h.path}' is outside the workspace`;return new Wp.Ud({result:{case:"error",value:new Wp.ts({error:e})}})}p=t}let t={};const r=await this.executeIndexedGrepWithTimeout(s.ctx,p,h,l);if(void 0!==r){t=r;for(const[e,r]of Object.entries(t)){const t=r.result;switch(t.case){case"content":t.value.matches=await this.filterBlockedFiles(t.value.matches,e);break;case"files":t.value.files=(await this.filterBlockedFiles(t.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":t.value.counts=await this.filterBlockedFiles(t.value.counts,e)}}}else for(const e of p){if(!1===jg(e))return new Wp.Ud({result:{case:"error",value:new Wp.ts({error:`Path does not exist: ${e}`})}});let r;if("content"===a)r=await this.runContentMode(s.ctx,e,h,u,l);else if("files_with_matches"===a)r=await this.runFilesMode(s.ctx,e,h,u,l);else{if("count"!==a)throw new Error(`Unknown output mode: ${a}`);r=await this.runCountMode(s.ctx,e,h,u,l)}t[e]=r}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,i.resolve)(e))))],o={};for(const[t,s]of Object.entries(e)){const e=(0,i.resolve)(t),n=t=>Dg(e,t,r),a=s.result;switch(a.case){case"content":{const e=a.value,r=[];let s=0,i=0;for(const t of e.matches)n(t.file)?r.push(t):(s+=t.matches.length,i+=t.matches.filter((e=>!e.isContextLine)).length);o[t]=new Wp.vD({result:{case:"content",value:new Wp.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-s),totalMatchedLines:Math.max(0,e.totalMatchedLines-i)})}});break}case"files":{const e=a.value,r=e.files.filter((e=>n(e)));o[t]=new Wp.vD({result:{case:"files",value:new Wp.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=a.value,r=[];let s=0;for(const t of e.counts)n(t.file)?r.push(t):s+=t.count;o[t]=new Wp.vD({result:{case:"count",value:new Wp.xA({...e,counts:r,totalFiles:Math.max(0,e.totalFiles-(e.counts.length-r.length)),totalMatches:Math.max(0,e.totalMatches-s)})}});break}default:o[t]=s}}return o}(t,p),c=new Wp._0({pattern:h.pattern,path:h.path,outputMode:a,workspaceResults:o});return new Wp.Ud({result:{case:"success",value:c}})}catch(e){if(h.path){const e=(0,ln.o1)(h.path,this.singleWorkspacePath);try{await(0,Qs.stat)(e)}catch(t){return new Wp.Ud({result:{case:"error",value:new Wp.ts({error:`Path does not exist: ${e}`})}})}}return new Wp.Ud({result:{case:"error",value:new Wp.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{Mg(o)}}}Ug.MAIN_TIMEOUT_MS=25e3,Ug.INDEXED_GREP_TIMEOUT_MS=25e3,Ug.INDEXED_GREP_CONTEXT_TIMEOUT_MS=Ug.INDEXED_GREP_TIMEOUT_MS+100,Ug.HARD_MAX_OUTPUT_LINES=1e4,Ug.CLIENT_LIMIT_LINES=2e3,io.z.object({record_v:io.z.number().int().nullish(),pid:io.z.number().int().nonnegative().nullish(),version:io.z.string().nullish(),started_at:io.z.number().nullish(),control_sock:io.z.string().nullish(),runtime_dir:io.z.string().nullish(),data_dir:io.z.string().nullish(),config_path:io.z.string().nullish(),log_path:io.z.string().nullish(),metrics_addr:io.z.string().nullish(),exe:io.z.string().nullish()}),io.z.object({mountpoint:io.z.string().nullish(),capabilities:io.z.array(io.z.string()).nullish(),nfs_transport:io.z.string().nullish(),bind_ignored:io.z.object({active:io.z.array(io.z.string()).nullish()}).passthrough().nullish()}),io.z.object({daemon_alive:io.z.boolean().nullish(),mounts:io.z.array(io.z.unknown()).nullish(),data_plane:io.z.object({enabled:io.z.boolean().nullish()}).passthrough().nullish()});const Bg=io.z.number().int().nonnegative(),zg=io.z.object({line_no:io.z.number().int().positive(),kind:io.z.enum(["match","before","after"]),text:io.z.string().optional(),bytes:io.z.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:io.z.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));io.z.object({type:io.z.literal("file"),path:io.z.string(),lines:io.z.array(zg)}),io.z.object({type:io.z.literal("summary"),files_searched:Bg,more:io.z.boolean(),stop_reason:io.z.string().nullable(),skipped:io.z.object({over_size:Bg,size_unknown:Bg,budget_exhausted:Bg,fetch_failed:Bg,unreadable:Bg})}),io.z.object({type:io.z.string()}),(0,d.h)("local-exec/grove-grep");var Wg=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),Hg=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},qg=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Gg{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{Hg(r,(0,c.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const o=(0,ln.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Qs.stat)(o)}catch(e){return"ENOENT"===e.code?function(e){const t=wt(e,"terminals");return null!==t&&0===t.remainingPath.length}(o)?new Wg.fv({result:{case:"error",value:new Wg.uj({path:o,error:"No active terminals."})}}):new Wg.fv({result:{case:"error",value:new Wg.uj({path:o,error:`Path does not exist: ${o}`})}}):new Wg.fv({result:{case:"error",value:new Wg.uj({path:o,error:e.message})}})}if(!r.isDirectory())return new Wg.fv({result:{case:"error",value:new Wg.uj({path:o,error:`Path is not a directory: ${o}`})}});const s=An(t.sandboxPolicy),n=t.timeoutMs??5e3,i=e.withTimeout(n),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,o,t.ignore,s);return c?new Wg.fv({result:{case:"timeout",value:new Wg.ze({directoryTreeRoot:a})}}):new Wg.fv({result:{case:"success",value:new Wg.PC({directoryTreeRoot:a})}})}catch(e){return new Wg.fv({result:{case:"error",value:new Wg.uj({path:o,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{qg(r)}}async getDirectoryTree(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{return Hg(s,(0,c.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,o,2500)}catch(e){s.error=e,s.hasError=!0}finally{qg(s)}}async buildTreeFromRipgrepStream(e,t,r,o,s){const n={stack:[],error:void 0,hasError:!1};try{Hg(n,(0,c.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,i.resolve)(t),l=new Wg.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(a,l);const d={charactersUsed:a.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=Ri(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,i.resolve)(t,e),o=await Fi(r);null===o||await this.ignoreService.isCursorIgnored(o)||await this.ignoreService.isRepoBlocked(o)||this.addPathToTree(r,a,u,d,s)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){n.error=e,n.hasError=!0}finally{qg(n)}}addPathToTree(e,t,r,o,s){const n=(0,i.basename)(e),a=(0,i.dirname)(e);this.ensureDirectoryPath(a,t,r,o.budgetExceeded);const c=r.get(a);if(!c)return;const l=n.length;if(!o.budgetExceeded&&o.charactersUsed+l<=s){const e=new Wg.ur({name:n});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,i.dirname)(e);if(o===e)break;e=o}}const s=(0,i.extname)(e);let n=a;for(;n.startsWith(t);){const e=r.get(n);e&&(e.fullSubtreeExtensionCounts[s]??=0,e.fullSubtreeExtensionCounts[s]=Gp(e.fullSubtreeExtensionCounts[s]+1),e.numFiles??=0,e.numFiles=Gp(e.numFiles+1));const t=(0,i.dirname)(n);if(t===n)break;n=t}}}ensureDirectoryPath(e,t,r,o){if(r.has(e)||e===t)return;const s=(0,i.dirname)(e);s!==e&&s.startsWith(t)&&this.ensureDirectoryPath(s,t,r,o);const n=new Wg.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!o,fullSubtreeExtensionCounts:{}});r.set(e,n);const a=r.get(s);a&&a.childrenDirs.push(n)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,i.basename)(e.absPath).localeCompare((0,i.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}var Vg=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Jg=1e4,Kg={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class Zg{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<Jg){const r=Math.min(e.length,Jg-t);this.fullOutput+=e.slice(0,r)}this.totalChars>Jg&&(this.fullOutput="")}getOutput(){return this.totalChars<=Jg?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=Jg))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-Jg}}}function Qg(e,t){const r=Tp-e.length;return r<=0?e:e+t.slice(0,r)}function Xg(e,t){return null!==e?e:null===t?-1:-n.constants.signals[t]}class Yg{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:o}){const s={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},n=r.exceptionInfo.length>0,i=0!==r.returncode||n?{case:"failure",value:new Jt.xC({...s,aborted:n,abortReason:r.abortReason})}:{case:"success",value:new Jt.QR(s)};return new Jt.W4({result:i,sandboxPolicy:Mn(o)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:o,timeoutMs:s}){const n=performance.now(),i=this.defaultCwd,a=(await(0,en.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 Zg;let a,l,u="",d="",h=!1,p=!1,f="",m=()=>{};const g=(0,en.Xw)({...process.env,...Kg,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,Hh.D9)(qc.spawn,y.executable,y.args,w):(0,en.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:Vp(performance.now()-n)}))};l=setTimeout((()=>{if(p=!0,void 0===a&&(f=`An error occurred while executing the command: Command timed out after ${s}ms`,a=Jt.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),s);const k=()=>{if(void 0===a){if(f="An error occurred while executing the command: Command aborted",a=Jt.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=Qg(u,t),i.append(t)})),b.stderr?.on("data",(e=>{const t=e.toString();d=Qg(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:Xg(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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,c.HF)(o,"LocalMiniSweAgentBashExecutor.execute");const s=t.command,n=(0,ln.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new Jt.W4({result:{case:"spawnError",value:new Jt.mJ({command:s,workingDirectory:n,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?An(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(o,s,{workingDirectory:n,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new Jt.W4({result:{case:"permissionDenied",value:new Jt.jn({command:s,workingDirectory:n,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Jt.W4({result:{case:"rejected",value:new Jt.pZ({command:s,workingDirectory:n,reason:Hi(l.reason)})}});a=l.policy,vn()&&(a=xn(s,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:o,args:t,workingDirectory:n,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:n,processResult:u,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{Vg(r)}}}var ew=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),tw=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const rw=51200;function ow(e){return Buffer.byteLength(e,"utf8")}function sw(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function nw(e){return new tw.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 iw(e,t){const r=t?.maxLines??2e3,o=t?.maxBytes??rw,s=e.split("\n"),n=s.length;if(ow(s[0]??"")>o)return{content:"",truncation:nw({truncated:!0,truncatedBy:"bytes",totalLines:n,outputLines:0,outputBytes:0,maxLines:r,maxBytes:o,firstLineExceedsLimit:!0})};const i=[];let a,c=0;for(let e=0;e<s.length;e++){if(i.length>=r){a="lines";break}const t=s[e],n=i.length>0?1:0,l=ow(t)+n;if(c+l>o){a="bytes";break}i.push(t),c+=l}return{content:i.join("\n"),truncation:nw({truncated:void 0!==a,truncatedBy:a,totalLines:n,outputLines:i.length,outputBytes:c,maxLines:r,maxBytes:o})}}function aw(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var cw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 lw(e){const{content:t,truncation:r}=function(e){const t=rw,r=e.split("\n"),o=r.length,s=[];let n,i=0,a=!1;for(let e=r.length-1;e>=0;e--){if(s.length>=2e3){n="lines";break}const o=r[e],c=s.length>0?1:0,l=ow(o)+c;if(i+l>t){if(n="bytes",0===s.length){const e=Buffer.from(o,"utf8");s.unshift(e.subarray(Math.max(0,e.length-t)).toString("utf8")),i=ow(s[0]),a=!0}break}s.unshift(o),i+=l}return{content:s.join("\n"),truncation:nw({truncated:void 0!==n,truncatedBy:n,totalLines:o,outputLines:s.length,outputBytes:i,maxLines:2e3,maxBytes:t,lastLinePartial:a})}}(e||"(no output)");if(!r.truncated)return{output:t};const o=await(0,Qs.mkdtemp)((0,i.join)((0,n.tmpdir)(),"pi-bash-")),s=(0,i.join)(o,"output.log");await(0,Qs.writeFile)(s,e,"utf8");const a=r.totalLines-r.outputLines+1,c=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${sw(r.outputBytes)} of line ${c} (${sw(rw)} limit). Full output: ${s}]`:`[Showing lines ${a}-${c} of ${r.totalLines}. Full output: ${s}]`}`,fullOutputPath:s,truncation:r}}class uw{constructor(e){this.shellExecutor=e}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiBashExecutor.execute")),!1),n=await this.shellExecutor.execute(s.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 Jt.a({command:e.command,timeout:r,toolCallId:t?.execId??"",fileOutputThresholdBytes:BigInt(0),parsingResult:new Jt.HO({parsingFailed:!1,executableCommands:[{name:o,fullText:e.command,args:[]}]})})}(t,r),r);switch(n.result.case){case"success":{const e=await lw(`${n.result.value.stdout}${n.result.value.stderr}`);return new ew.AH({result:{case:"success",value:new ew.cV(e)}})}case"failure":{const e=await lw(`${n.result.value.stdout}${n.result.value.stderr}`);return new ew.AH({result:{case:"success",value:new ew.cV({...e,output:`${e.output}\n\nCommand exited with code ${n.result.value.exitCode}`})}})}case"timeout":return this.error(`Command timed out after ${Math.round(n.result.value.timeoutMs/1e3)} seconds`);case"rejected":return this.error(n.result.value.reason||"Command aborted");case"permissionDenied":case"spawnError":return this.error(n.result.value.error);default:return this.error("Command failed")}}catch(e){o.error=e,o.hasError=!0}finally{cw(o)}}error(e){return new ew.AH({result:{case:"error",value:new ew.bD({error:e})}})}}var dw=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function hw(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;case"adminCommandDenylist":return Wn(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 pw=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function fw(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function mw(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 gw(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 ww(e,t){const r=e.split("\n"),o=t.split("\n"),s=Math.max(r.length,o.length);for(let e=0;e<s;e++)if(r[e]!==o[e])return e+1}const yw=new Map;async function vw(e,t){const r=await async function(e){try{return await(0,Qs.realpath)(e)}catch{return e}}(e),o=yw.get(r)??Promise.resolve();let s;const n=new Promise((e=>{s=e})),i=o.then((()=>n));yw.set(r,i),await o;try{return await t()}finally{s(),yw.get(r)===i&&yw.delete(r)}}function bw(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,yu.fileURLToPath)(r)),("~"===r||r.startsWith("~/"))&&(r=(0,i.join)((0,n.homedir)(),r.slice(2))),(0,i.normalize)((0,i.isAbsolute)(r)?r:(0,i.resolve)(t??process.cwd(),r))}var Sw=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 kw{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 s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiEditExecutor.execute")),!1),n=bw(t.path,this.workspacePath);return vw(n,(async()=>{const e=await this.permissionsService.shouldBlockRead(n);if(e)return this.error(`Read blocked: ${hw(e)}`);try{if((await(0,Qs.stat)(n)).isDirectory())return this.error(`Path is a directory: ${n}`);const e=(await(0,Qs.readFile)(n)).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:s}=65279===(n=t).charCodeAt(0)?{bom:n[0],text:n.slice(1)}:{bom:"",text:n};var n;const i=function(e){return e.includes("\r\n")?"\r\n":"\n"}(s),a=fw(s),{matches:c,matchedContent:l}=function(e,t){const r=[];let o=!1;for(const s of t){if(0===s.oldText.length)throw new Error("oldText must not be empty.");const t=fw(s.oldText),n=gw(e,t);if(1!==n){if(n>1)throw new Error("oldText must be unique in the file.");o=!0;break}r.push({index:e.indexOf(t),length:t.length,replacement:fw(s.newText)})}if(!o)return{matches:r,matchedContent:e};const s=mw(e),n=[];for(const e of t){const t=mw(fw(e.oldText)),r=gw(s,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.");n.push({index:s.indexOf(t),length:t.length,replacement:mw(fw(e.newText))})}return{matches:n,matchedContent:s}}(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,pw.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:h,patch:h,firstChangedLine:ww(a,u)}}(t.path,e,t.edits),i=await this.writeExecutor.execute(s.ctx,new Kt.hY({path:n,fileText:o.newContent,toolCallId:r?.execId??""}),r);switch(i.result.case){case"success":return new dw.u7({result:{case:"success",value:new dw.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 dw.u7({result:{case:"rejected",value:new dw.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{Sw(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 dw.u7({result:{case:"error",value:new dw.Nd({error:e})}})}}var Ew=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),Cw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 xw(e){return e.split(i.sep).join("/")}class _w{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiFindExecutor.execute")),!1);const o=bw(t.path||".",this.workspacePath),s=await this.permissionsService.shouldBlockRead(o);if(s)return this.error(`Find blocked: ${hw(s)}`);try{if(!(await(0,Qs.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(s){if(o.length>=t)return;const n=await(0,Qs.readdir)(s,{withFileTypes:!0});for(const a of n){if(o.length>=t)return;if(".git"===a.name||"node_modules"===a.name)continue;const n=(0,i.join)(s,a.name);await r(n)&&(o.push(n+(a.isDirectory()?i.sep:"")),a.isDirectory()&&await e(n))}}(e),o}(o,e,(async e=>!await this.permissionsService.shouldBlockRead(e))),s=t.pattern.includes("/")&&!t.pattern.startsWith("**/")?`**/${t.pattern}`:t.pattern,n=r.map((e=>({raw:e,relative:xw((0,i.relative)(o,e))}))).filter((({relative:e})=>(0,la.xF)(e,s,{dot:!0})));if(0===n.length)return this.success("No files found matching pattern");const a=iw(n.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(`${sw(rw)} 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{Cw(r)}}success(e,t){return new Ew.bT({result:{case:"success",value:new Ew.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new Ew.bT({result:{case:"error",value:new Ew.Uy({error:e})}})}}var Pw=r("node:readline"),Rw=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),Iw=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Tw=qc.spawn;class Aw{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiGrepExecutor.execute")),!1);const o=bw(t.path||".",this.workspacePath),s=await this.permissionsService.shouldBlockRead(o);if(s)return this.error(`Search blocked: ${hw(s)}`);try{const e=(await(0,Qs.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 s=(0,Hh.D9)(Tw,(0,en.Ko)(),r,{stdio:["ignore","pipe","pipe"]}),n=[];let i="",a=!1;const c=Math.max(1,t.limit??100),l=(0,Pw.createInterface)({input:s.stdout});s.stderr.on("data",(e=>{i+=e.toString()})),l.on("line",(e=>{if(n.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&&(n.push({filePath:r,lineNumber:o,lineText:t.data?.lines?.text?.replace(/\n$/,"")}),n.length>=c&&(a=!0,s.kill()))}));const u=await new Promise(((e,t)=>{s.on("error",t),s.on("close",e)}));if(l.close(),!a&&0!==u&&1!==u)return this.error(i.trim()||`ripgrep exited with code ${u}`);if(0===n.length)return this.success("No matches found");const d=[];for(const e of n)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=iw(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(`${sw(rw)} 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{Iw(r)}}async formatMatches(e,t,r,o){const s=[];let n=!1;for(const a of e){const e=r?(0,i.relative)(t,a.filePath):(0,i.basename)(a.filePath);if(0===o&&void 0!==a.lineText){const t=aw(a.lineText);n=n||t.wasTruncated,s.push(`${e}:${a.lineNumber}: ${t.text}`);continue}const c=(await(0,Qs.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=aw(c[t-1]??"");n=n||r.wasTruncated,s.push(t===a.lineNumber?`${e}:${t}: ${r.text}`:`${e}-${t}- ${r.text}`)}}return{output:s.join("\n"),linesTruncated:n}}success(e,t){return new Rw.mr({result:{case:"success",value:new Rw.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new Rw.mr({result:{case:"error",value:new Rw.hP({error:e})}})}}var Mw=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),Dw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Ow{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiLsExecutor.execute")),!1);const o=bw(t.path||".",this.workspacePath),s=await this.permissionsService.shouldBlockRead(o);if(s)return this.error(`List blocked: ${hw(s)}`);try{if(!(await(0,Qs.stat)(o)).isDirectory())return this.error(`Not a directory: ${o}`);const e=Math.max(1,t.limit??500),r=(await(0,Qs.readdir)(o)).sort(((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))),s=[];let n=!1;for(const t of r){if(s.length>=e){n=!0;break}try{const e=(0,i.join)(o,t);if(await this.permissionsService.shouldBlockRead(e))continue;const r=await(0,Qs.stat)(e);s.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===s.length)return this.success("(empty directory)");const a=iw(s.join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),c=[];return n&&c.push(`${e} entries limit reached. Use limit=${2*e} for more`),a.truncation.truncated&&c.push(`${sw(rw)} limit reached`),this.success(c.length>0?`${a.content}\n\n[${c.join(". ")}]`:a.content,{entryLimitReached:n?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{Dw(r)}}success(e,t){return new Mw.pX({result:{case:"success",value:new Mw.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new Mw.pX({result:{case:"error",value:new Mw.iG({error:e})}})}}var Nw=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),jw=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 $w{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiReadExecutor.execute")),!1);const o=function(e,t){const r=bw(e,t);if((0,Ys.existsSync)(r))return r;for(const e of function(e){const t=(0,i.dirname)(e),r=e.slice(t.length+1),o=new Set;return o.add(e),o.add((0,i.join)(t,r.normalize("NFD"))),o.add((0,i.join)(t,r.replace(/'/g,"’"))),o.add((0,i.join)(t,r.replace(/ /g," "))),o.add((0,i.join)(t,r.replace(/'/g,"’").normalize("NFD"))),[...o]}(r))if((0,Ys.existsSync)(e))return e;return r}(t.path,this.workspacePath),s=await this.permissionsService.shouldBlockRead(o);if(s)return this.error(`Read blocked: ${hw(s)}`);try{if((await(0,Qs.stat)(o)).isDirectory())return this.error(`Path is a directory: ${o}`);const e=(await(0,Qs.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 s=void 0!==t.limit?e.slice(r,r+t.limit).join("\n"):e.slice(r).join("\n"),{content:n,truncation:i}=iw(s),a=r+1;let c=n;if(i.firstLineExceedsLimit)c=`[Line ${a} is ${sw(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${sw(rw)} 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 Nw.Q({result:{case:"success",value:new Nw.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{jw(r)}}error(e){return new Nw.Q({result:{case:"error",value:new Nw.tB({error:e})}})}}var Fw=r("../proto/dist/generated/agent/v1/pi_write_exec_pb.js"),Lw=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Uw{constructor(e,t){this.writeExecutor=e,this.workspacePath=t}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalPiWriteExecutor.execute")),!1),n=bw(t.path,this.workspacePath);return vw(n,(async()=>{const e=await this.writeExecutor.execute(s.ctx,new Kt.hY({path:n,fileText:t.content,toolCallId:r?.execId??""}),r);switch(e.result.case){case"success":return new Fw.hO({result:{case:"success",value:new Fw.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new Fw.hO({result:{case:"rejected",value:new Fw.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new Fw.hO({result:{case:"error",value:new Fw.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new Fw.hO({result:{case:"error",value:new Fw.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){o.error=e,o.hasError=!0}finally{Lw(o)}}}var Bw=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function zw(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class Ww{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:zw(t.cursor),advance:!1!==t.advance});return new Bw.Ev({result:{case:"success",value:new Bw.iS({events:e.events.map((e=>new Bw.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 Bw.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new Bw.Ev({result:{case:"error",value:new Bw.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class Hw{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Gt.nt({result:{case:"error",value:new Gt.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Gt.nt({result:{case:"success",value:new Gt.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}class qw{constructor(e){this.source=e,this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume()}async consume(){try{for await(const e of this.source){this.pastElements.push(e);const t=[];for(const r of this.forks)t.push(r.write(e).catch((()=>{})));await Promise.allSettled(t)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Gw(e,t){return`${e}:${(0,s.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Vw(e,t){const r=new Xs.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,o,s){if(!s?.execId)return e.execute(t,o,s);const n=Gw(s.execId,o),i=r.get(n);if(void 0!==i)return i;const a=await e.execute(t,o,s);return r.set(n,a),a}}}var Jw=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),Kw=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class Zw{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const o=new Promise((e=>{r=e}));let s;if(void 0===this.beginCanvasSave)s=Promise.resolve(void 0);else try{s=this.beginCanvasSave(t.path,{typecheckOutcome:o}).catch((()=>{}))}catch{s=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),Qw(Xw(t.path,"diagnostics unavailable"),await s)):(r(e.some((e=>1===e.severity))?"failed":"passed"),Qw(new Jw.GL({result:{case:"success",value:new Jw.uX({path:t.path,diagnostics:e.map(Yw)})}}),await s))}catch(e){return r("unavailable"),Qw(Xw(t.path,e instanceof Error?e.message:String(e)),await s)}}}function Qw(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function Xw(e,t){return new Jw.GL({result:{case:"error",value:new Jw.HW({path:e,error:t})}})}function Yw(e){return new Kw.oQ({severity:ey(e.severity),range:new wm.Q6({start:new wm.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new wm.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function ey(e){switch(e){case 1:return Kw.h_.ERROR;case 2:return Kw.h_.WARNING;case 3:return Kw.h_.INFORMATION;case 4:return Kw.h_.HINT;default:return Kw.h_.UNSPECIFIED}}class ty{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 ty(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new ty(e)}static fromString(e){return new ty(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 ry=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 oy{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,o]=e.withTimeoutAndCancel(1e4);try{const r=(0,ln.o1)(t.path,this.workspacePath);try{const e=await(0,Qs.stat)(r);if(!e.isFile()&&!e.isDirectory())return new Kw.Ek({result:{case:"fileNotFound",value:new Kw.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new Kw.Ek({result:{case:"fileNotFound",value:new Kw.Mu({path:t.path})}});if("EACCES"===e.code)return new Kw.Ek({result:{case:"permissionDenied",value:new Kw.RP({path:t.path})}});throw e}const o=(0,ln.o1)(r,this.workspacePath),s=new ty(o);await this.diagnosticsProvider.open(e,s);const n=(await this.diagnosticsProvider.getDiagnostics(e,s)).map((e=>this.convertDiagnostic(e)));return new Kw.Ek({result:{case:"success",value:new Kw.a1({path:t.path,diagnostics:n,totalDiagnostics:n.length})}})}catch(r){return e.canceled?new Kw.Ek({result:{case:"error",value:new Kw.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new Kw.Ek({result:{case:"error",value:new Kw.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{o()}}catch(e){r.error=e,r.hasError=!0}finally{ry(r)}}convertDiagnostic(e){return new Kw.oQ({severity:this.convertSeverity(e.severity),range:e.range?new wm.Q6({start:new wm.yX({line:e.range.start.line,column:e.range.start.character}),end:new wm.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:e.message,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return Kw.h_.ERROR;case 2:return Kw.h_.WARNING;case 3:return Kw.h_.INFORMATION;case 4:return Kw.h_.HINT;default:return Kw.h_.UNSPECIFIED}}}async function sy(e){const{repoRoot:t,filePaths:r,getContent:o}=e,s=new Map;if(0===r.length)return s;const n=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const o=await new Promise(((r,o)=>{const s=(0,qc.spawn)("git",["check-attr","linguist-generated","--stdin"],{cwd:e});let n="";s.stdout.on("data",(e=>{n+=e.toString()})),s.stdin.write(`${t.join("\n")}\n`),s.stdin.end(),s.on("close",(e=>{r(n)})),s.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=n.get(e);if(!0!==t)if(!1!==t)if(function(e){return new ny(e).isGeneratedByPath()}(e))s.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(o){const t=await o(e);if(void 0!==t&&function(e,t){return new ny(e,(()=>t)).isGeneratedByContent()}(e,t))return void s.set(e,{isGenerated:!0,source:"content-heuristic"})}s.set(e,{isGenerated:!1,source:"none"})}else s.set(e,{isGenerated:!1,source:"gitattributes"});else s.set(e,{isGenerated:!0,source:"gitattributes"})}))),s}class ny{constructor(e,t){this.name=e,this.extname=i.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 iy=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ay=/^(a|b|i|w|c|o|1|2)\//,cy=e=>{const t=e?.match(iy);return t?.map((e=>e.replace(ay,"").replace(/("|')$/,"")))},ly=/^\\?['"]|\\?['"]$/g,uy=e=>{let t=dy(e,"-+").trim();return t=py(t),t.replace(ly,"").replace(ay,"")},dy=(e,t)=>{if(e=my(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=fy(t);return e.replace(new RegExp(`^${r}+`),"")},hy=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,py=e=>{const t=hy.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},fy=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${my(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,my=e=>`${e??""}`,gy=(0,d.h)("local-git-diff");async function wy(e,t,r={}){const o=await new Promise(((o,s)=>{const n=Yc("git",t,{cwd:e});let i="",a="";n.stdout.on("data",(e=>{i+=e.toString()})),n.stderr.on("data",(e=>{a+=e.toString()})),n.on("close",(e=>{0===e||!0===r.ignoreErrors?o(i):s(new Error(`Git command failed with code ${e}: ${a}`))})),n.on("error",(e=>{!0===r.ignoreErrors?o(i):s(e)}))}));return!0===r.shouldNotTrimOutput?o:o.trim()}function yy(e){const t=(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,s=null,n=0,i=0,a=null;const c=e=>{const[t,s]=cy(e)??[];o={chunks:[],deletions:0,additions:0,from:t,to:s},r.push(o)},l=()=>{o&&!o.chunks.length||c()},u=e=>+(e||1),d=e=>{if(!s)return;const[t]=s.changes.slice(-1);s.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},h=[[/^diff\s/,c],[/^new file mode (\d+)$/,(e,t)=>{l(),o.new=!0,o.newMode=t[1],o.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{l(),o.deleted=!0,o.oldMode=t[1],o.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{l(),o.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{l(),o.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{l(),o.index=e.split(" ").slice(1),t[1]&&(o.oldMode=o.newMode=t[1].trim())}],[/^---\s/,e=>{l(),o.from=uy(e)}],[/^\+\+\+\s/,e=>{l(),o.to=uy(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{o||c(e);const[r,l,d,h]=t.slice(1);n=+r,i=+d,s={content:e,changes:[],oldStart:+r,oldLines:u(l),newStart:+d,newLines:u(h)},a={oldLines:u(l),newLines:u(h)},o.chunks.push(s)}],[/^\$/,d]],p=[[/^\$/,d],[/^-/,e=>{s&&(s.changes.push({type:"del",del:!0,ln:n++,content:e}),o.deletions++,a.oldLines--)}],[/^\+/,e=>{s&&(s.changes.push({type:"add",add:!0,ln:i++,content:e}),o.additions++,a.newLines--)}],[/^\s+/,e=>{s?.changes.push({type:"normal",normal:!0,ln1:n++,ln2:i++,content:e}),a.oldLines--,a.newLines--}]],f=e=>{a?(e=>{for(const[t,r]of p){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 h){const o=e.match(t);if(o){r(e,o);break}}})(e)};for(const e of t)f(e);return r})(e);return new no.o$({diffs:t.map((e=>function(e){const t=new no.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new no.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:no.Wf.UNSPECIFIED})}const vy=["main","master","develop"];class by{async execute(e,t){return async function(e,t,r){const o=function(e){switch(e){case no.ek.NAME_STATUS:return no.ek.NAME_STATUS;case no.ek.NAME_STATUS_AND_NUMSTAT:return no.ek.NAME_STATUS_AND_NUMSTAT;case no.ek.FILE_DIFFS:return no.ek.FILE_DIFFS;case no.ek.DIFFS_WITH_BEFORE_AND_AFTER:return no.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return no.ek.FILE_DIFFS}}(r.outputFormat),s=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await wy(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of vy){const r=`origin/${t}`;try{return await wy(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await wy(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await wy(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 wy(t,["merge-base",e,r.ref.length>0?r.ref:"HEAD"])).trim()),e})(),n=["diff","--no-color"];r.includeSpaceChanges||n.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&n.push(`-U${r.unifiedContextLines}`),n.push(s),r.ref.length>0&&n.push(r.ref),r.targetPaths.length>0&&(n.push("--"),n.push(...r.targetPaths));const a=await wy(t,n,{shouldNotTrimOutput:!0}),c=yy(a);let l=[];if(r.maxUntrackedFiles>0){l=await async function(e,t){let r=(await wy(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 Qs.readFile(i.join(e,t),"utf8"),path:t}}catch{return}})))).filter((e=>void 0!==e))}(t,r.maxUntrackedFiles);for(const e of l){const r=await wy(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});c.diffs.push(...yy(r).diffs)}}if(o!==no.ek.FILE_DIFFS)for(const e of c.diffs)e.chunks=[];if(o===no.ek.DIFFS_WITH_BEFORE_AND_AFTER){const o=r.ref.length>0?r.ref:"HEAD";await Promise.all(c.diffs.map((async n=>{try{if("/dev/null"!==n.from)try{n.beforeFileContents=await wy(t,["show",`${s}:${n.from}`],{shouldNotTrimOutput:!0})}catch{n.beforeFileContents=""}else n.beforeFileContents="";if("/dev/null"!==n.to)if(r.ref.length>0)try{n.afterFileContents=await wy(t,["show",`${o}:${n.to}`],{shouldNotTrimOutput:!0})}catch{n.afterFileContents=""}else try{n.afterFileContents=await Qs.readFile(i.join(t,n.to),"utf8")}catch{try{n.afterFileContents=await wy(t,["show",`${o}:${n.to}`],{shouldNotTrimOutput:!0})}catch{n.afterFileContents=""}}else n.afterFileContents=""}catch(t){gy.error(e,"Error fetching file contents for diff",t)}})))}const u=new Map;for(const e of c.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&u.set(t,e)}const d=[...u.keys()],h=r.ref.length>0?r.ref:"HEAD";try{const e=await sy({repoRoot:t,filePaths:d,getContent:async e=>{const r=u.get(e);if(r){if(void 0!==r.afterFileContents)return r.afterFileContents;try{if(r.to&&"/dev/null"!==r.to)return await wy(t,["show",`${h}:${r.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=u.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){gy.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const p=!0===r.computePatchId?await async function(e,t){if(0!==t.length)return(await new Promise(((r,o)=>{const s=Yc("git",["patch-id","--stable"],{cwd:e});let n="",i="";s.stdout.on("data",(e=>{n+=e.toString()})),s.stderr.on("data",(e=>{i+=e.toString()})),s.on("close",(e=>{0===e?r(n):o(new Error(`git patch-id failed with code ${e}: ${i}`))})),s.on("error",o),s.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`}(a,function(e){const t=[];for(const r of e){const e=r.contents.split("\n"),o=e.length;t.push(`diff --git a/${r.path} b/${r.path}`),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),t.push(`@@ -0,0 +1${1===o?"":`,${o}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(l))):void 0,f=!0===r.returnHeadSha?(await wy(t,["rev-parse","HEAD"])).trim():void 0,m=!0===r.returnHeadSha?(await wy(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,g=new no.df({diff:c,submoduleDiffs:[],patchId:p,headSha:f,hasUncommittedChanges:m}),w=r.maxResponseBytes??0;if(w>0){const e=g.toBinary().byteLength;if(e>w)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${w} byte limit`)}return g}(e,t.cwd,t)}}var Sy=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class ky{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 Sy.M({allowlisted:r})}}const Ey=BigInt(0),Cy=BigInt(8),xy=BigInt(16),_y=BigInt(65535);function Py(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Ry(e){const t=e.split(".");if(4!==t.length)return;let r=Ey;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<Cy|BigInt(t)}return{version:4,value:r}}function Iy(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 s=Ry(o);if(!s)return;t.push(Number(s.value>>xy&_y)),t.push(Number(s.value&_y))}else{if(!/^[0-9a-f]{1,4}$/i.test(o))return;t.push(Number.parseInt(o,16))}}return t}function Ty(e){return Ry(e)??function(e){const t=Py(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Iy(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<xy|BigInt(t)),Ey)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),s=t.slice(r+2),n=Iy(o),i=Iy(s);if(!n||!i)return;const a=n.length+i.length;return a>7?void 0:{version:6,value:[...n,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<<xy|BigInt(t)),Ey)}}(e)}function Ay(e,t){const r=Py(e),o=Py(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=Ty(t.slice(0,r)),s=Ty(e);if(!o||!s||o.version!==s.version)return!1;const n=Number(t.slice(r+1)),i=4===o.version?32:128;if(!Number.isInteger(n)||n<0||n>i)return!1;const a=BigInt(i-n);return s.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 My(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=>Ay(e,t)))}(r.hostname,t)}var Dy=r("../mcp-core/dist/admin-mcp-tool-allowlist.js");const Oy=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Ny(e){return e.trim().split(/\s+/).filter(Boolean)}function jy(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 Ny(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),o=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Oy.has(o)}function $y(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 Fy(e,t){return e.commandName.localeCompare(t.commandName)}function Ly(e){return e.split(" ")[0]??e}function Uy(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 s=Ny(e),n=s[0]??e;r.push({id:e,label:e,value:e,commandName:n,tokenCount:s.length,indentLevel:0,tokens:s,ancestorIds:[e]})}r.sort(Fy);for(let e=0;e<r.length;e++){const t=r[e],o=new Set(t.tokens);let s,n=!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=$y(e.tokens,t.tokens);void 0!==s?e.tokenCount>s.tokenCount?(s=e,n=c):e.tokenCount===s.tokenCount&&c&&!n&&(s=e,n=!0):(s=e,n=c)}void 0!==s&&(t.indentLevel=s.indentLevel+1,t.ancestorIds=[...s.ancestorIds,t.id])}const o=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCount<e.tokenCount&&$y(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 s=[],n=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){s.push(t.id),n.add(Ly(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));s.push(e.id),n.add(Ly(e.id))}else if(o.length>0){const e=o.reduce(((e,t)=>e.id.length<t.id.length?e:t));s.push(e.id),n.add(Ly(e.id))}}if(0===s.length)return{defaultSelectedOptionIds:o,hasClassifierSuggestions:!1};const i=o.filter((e=>!n.has(Ly(e))));return{defaultSelectedOptionIds:[...new Set([...i,...s])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const By="win32"===process.platform;function zy(e,t){return By&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==i.sep&&(e+=i.sep),t.startsWith(e))}process.platform;const Wy=(0,i.join)((0,n.homedir)(),".cursor","projects"),Hy=(0,i.join)((0,n.homedir)(),".cursor","worktrees");function qy(e){return zy(Wy,e)&&e!==Wy}function Gy(e){return zy(Hy,e)&&e!==Hy}function Vy(e,t){const r=function(e){if(!zy(Wy,e))return;if(e===Wy)return;const t=(0,i.relative)(Wy,e).split(i.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function Jy(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function Ky(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 Zy(e,t){const r=(0,ln.o1)(e,t);try{return Jy(await(0,Qs.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return Jy(r,r,Ky(t));try{if((await(0,Qs.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Qs.readlink)(r)}catch{}return Jy(r,r,{status:"danglingSymlink",symlinkTarget:e})}return Jy(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,i.dirname)(e);const r=[(0,i.basename)(e)];for(;(0,i.dirname)(t)!==t;){try{const o=await(0,Qs.realpath)(t);return Jy((0,i.join)(o,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return Jy(e,e,Ky(r))}r.unshift((0,i.basename)(t)),t=(0,i.dirname)(t)}return Jy(e,e,{status:"newFile"})}(r):Jy(r,r,Ky(t))}}}function Qy(e){return"resolved"===e.status||"newFile"===e.status}function Xy(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 Yy({requestedAbsolutePath:e,realAbsolutePath:t,setting:r,resolvedWorkspaceRoots:o,resolvedAllowFolders:s}){return"workspace"===r.boundary&&![...o,...s].some((e=>(0,ln.BJ)(t,e)))&&!(tv(t,r.allowPaths)||e!==t&&tv(e,r.allowPaths))}function ev(e){return e.flatMap((e=>{const t=(0,ln.jl)(e.trim());return!t.includes("*")&&(0,i.isAbsolute)(t)?[(0,i.resolve)(t)]:[]}))}function tv(e,t){const r="win32"===process.platform?ln.oL:e=>e,o=r(e);return t.some((e=>{const t=(0,ln.jl)(e.trim());return!(!t.includes("*")&&(0,i.isAbsolute)(t))&&$n(r(t),o)}))}var rv=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},ov=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 sv=(0,d.h)("permissions-service"),nv=(0,h.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 iv(e){return Promise.all(e.map((async e=>{const t=await Zy(e);return Qy(t.resolution)?t.resolvedPath:(0,ln.o1)(e)})))}function av(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 cv(e){return[...new Set(e)]}function lv(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function uv({basePath:e,targetPath:t,pathModule:r}){const o=r.resolve(e),s=r.resolve(t),n=r.relative(o,s);return""===n||".."!==n&&!n.startsWith(`..${r.sep}`)&&!r.isAbsolute(n)}function dv(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function hv(e){return"<"!==e.operator&&"<&"!==e.operator}function pv(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function fv(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function mv({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:o,resolvePathForPermissions:s,pathModule:n,tempPathOptions:i}){if(""!==n.parse(e).root&&!n.isAbsolute(e))return;const a=await s(e,t);if(Qy(a.resolution)){for(const e of r){const t=await s(e);if(Qy(t.resolution)&&uv({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:n}))return"workspace-file"}return o&&xv(a.resolvedPath,i)?"tmp-file":void 0}}function gv(e){return cv(e.map((e=>e.trim())).filter(Boolean))}function wv(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,s=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===s.length)return[o];const n=`${t} ${s.join(" ")}`;return n===o?[o]:[o,n]}function yv(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function vv(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new Jt.r6({type:"word",value:e})));return new Jt.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function bv(e,t={}){return{type:e,...t}}function Sv(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 kv(e,t){if("workspace"===e&&void 0!==t)return t}const Ev={workspace:0,system:1};function Cv(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1],o=t[2]?.trim()??"",s=o.indexOf(":");return-1!==s?{shellType:r,fullPattern:o,commandPattern:o.slice(0,s).trim(),argsPattern:o.slice(s+1).trim()}:{shellType:r,fullPattern:o,commandPattern:o,argsPattern:null}}function xv(e,{platform:t,env:r,pathModule:o,homeDirectory:s}){if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=o.normalize(t).toLowerCase(),s=o.normalize(e).toLowerCase(),n=r.endsWith(o.sep)?r:r+o.sep;return s===r||s.startsWith(n)}return!1}const n=e=>{const r=o.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=n(e);return(void 0===s||!uv({basePath:n(s),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 _v(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,en.$b)(e.networkPolicy),o=(0,en.$b)(t.networkPolicy);if(r&&!o)return!1;const s=(0,en._B)(e.networkPolicy),n=(0,en._B)(t.networkPolicy);if(s&&o&&!n)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!(Ev[i]>Ev[a])}class Pv{constructor(e,t,r,o){this.command=e,this.requestedPolicy=t;const s=void 0!==r&&_v(t,r);this.state=s?"preapproved":"approvable";const n=[e.fullText.trim()].filter(Boolean);this.matchForms=o&&o.length>0?[...o]:n}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!_v(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Rv(e){return e?.type??"undefined"}const Iv=["skills","skills-cursor","rules","plugins"];class Tv{constructor(e,t,r,o,s,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=o,this.adminNetworkControlsEnabled=a,this.rootDirectories=Array.isArray(s)?s:[s??process.cwd()],this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,i.join)((0,n.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog}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();if("workspace"!==t.boundary||"unrestricted"===e.approvalMode)return;const[r,o]=await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths)]);return async(e,s)=>Yy({requestedAbsolutePath:e,realAbsolutePath:s,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:o})}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:Sv(r.allow)}})}}resolvedReadAllowFolders(e){return iv([...ev(e),...(0,en.r5)()])}async resolveWorkspaceReadRoots(e){const t=(0,i.join)((0,n.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,i.join)(t,"projects",(0,Js.r_)(e)))),...Iv.map((e=>(0,i.join)(t,e)))];return iv([...this.rootDirectories,...r])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const o=(0,ln.o1)(e),s=await Fi(o);if(null===s)return{type:"unsafeResolution",message:av("Read","path",o)};if(await this.ignoreService.isRepoBlocked(s))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",o))return{type:"permissionsConfig"};if(!qy(s)&&!Gy(s)&&!t&&await this.ignoreService.isCursorIgnored(s))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:s,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[s,n]=await Promise.all([this.resolveWorkspaceReadRoots(r.userSandboxDataFolderName),this.resolvedReadAllowFolders(o.allowPaths)]);return!!Yy({requestedAbsolutePath:t,realAbsolutePath:e,setting:o,resolvedWorkspaceRoots:s,resolvedAllowFolders:n})&&{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{rv(o,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const s=await Zy(t);if(!Qy(s.resolution))return{type:"unsafeResolution",message:Xy(s.originalPath,s.resolution)};const l=s.resolvedPath,u=l;if(await this.ignoreService.isRepoBlocked(u))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",l))return{type:"permissionsConfig"};const d=s.originalPath.split(i.sep).pop()?.toLowerCase()??"",h=l.split(i.sep).pop()?.toLowerCase()??"";if(".cursorignore"===d||".cursorignore"===h)return{type:"permissionsConfig"};const p=qy(u),f=Gy(u),m=!p&&!f&&await this.ignoreService.isCursorIgnored(u);if(p||f);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",l))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(l))return!1;const g=await this.getPermissions();if("workspace_readonly"===g.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===g.approvalMode)return!1;for(const e of this.rootDirectories){const t=await Zy(e);if(!Qy(t.resolution))continue;const r=t.resolvedPath;if((0,ln.BJ)(l,r)){const e=(0,i.relative)(r,l).split(i.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const w=async()=>{let e=!1,t="";try{t=await hi(l),e=!1}catch{e=!0}let o="";if(e)o=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:s}=(0,pw.YB)("a","b",e(t),e(r),"","",{context:2});o=s.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 y,v=!1;for(const e of this.rootDirectories){const t=await Zy(e);if(!Qy(t.resolution))continue;const r=t.resolvedPath;if((0,ln.BJ)(l,r)){v=!0,y=r;break}}const b=v?void 0:function(e){if(!Gy(e))return;const t=(0,i.relative)(Hy,e).split(i.sep).filter(Boolean);return 0!==t.length?(0,i.join)(Hy,t[0]):void 0}(l);if(!v&&void 0===b){if(function(e){return xv(e,{platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,n.homedir)()})}(l))return!1;if(Vy(l,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,n.homedir)()}${i.sep}.cursor${i.sep}`;if(l.startsWith(e)){const e=l.split(i.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await w();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const S=y??b,k=l;let E=(0,i.relative)(S,k).split(i.sep);if(E=E.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&E.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await w();return{type:"needsApproval",approvalReason:`Protected config file: ${E[E.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,en.OK)(l,S)){const e=E[E.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await w();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}const C=await this.checkCursorFileProtection(E);if(C)return C;if(!0===g.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await w();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{ov(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 s=await Fi(t.workingDirectory);if(null===s){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:av("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(s))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const n=(await this.getPermissions()).userConfiguredPolicy,i=r??n;return"workspace_readonly"===n.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,o){const s="insecure_none"===o?.type,n=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},o);if("block"===n.kind)return n;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(sv.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Rv(l),requestedPolicyType:Rv(o),effectiveRequestedPolicyType:Rv(o??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:fr(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 sv.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Rv(l),requestedPolicyType:Rv(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(vv):d,k=void 0!==v?v.map(wv):S.map((e=>[e.fullText.trim()].filter(Boolean))),E=void 0!==y?y.commands.map(wv):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,en.$b)(l.networkPolicy)&&"insecure_none"!==o.type&&!(0,en._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,en.XX)(e.readBoundary,t.readBoundary),o="workspace"===r?(0,en.wG)(kv(e.readBoundary,e.additionalReadPaths),kv(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:o}}({requestedPolicy:o,userConfiguredPolicy:l}),m&&sv.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=[],R=[],I=[];const T=gv(i.smartAllowlistDenylist??[]);if(T.length>0){R=[];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=>yv(r,e)))){const r=t[e];r&&R.push(r)}}R.length>0&&(sv.info(e,"Command blocklist: commands require approval",{count:R.length}),x.push(`In blocklist: ${R.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));sv.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))))))),s=o.every(Boolean),n=[];for(let e=0;e<m.commands.length;e++){if(o[e])continue;const t=m.commands[e];t&&n.push(t)}if(P=gv(n.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(jy(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),o=e.arguments.map((e=>e.trim())).filter(Boolean),s=[t],n=[t];for(const e of r)n.push(e),s.push(n.join(" "));const i=[t,...o].join(" ");return s.includes(i)||s.push(i),gv(s)}(e)))),I=n.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=Uy(P,I),t=e.length>0?e.join(", "):P.join(", ");_.push(`Not in allowlist: ${t}`)}C=s&&0===R.length,C&&sv.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 Pv(e,o,A,k[t])));if((0===S.length||f&&!b)&&!c){sv.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Rv(o),userConfiguredPolicyType:Rv(l),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w});const s={type:Mp.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}},n=await this.pendingDecisionStore.requestApproval(s);return n.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(o)}:{kind:"block",reason:{type:"userRejected",reason:n.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(),j={type:"insecure_none"};for(const e of M)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:O,autoRunControls:N,applyTeamAllowlist:u})&&e.approveWithPolicy(j);for(const e of M)N&&this.isInTeamBlocklist(N,e)&&e.deny();const $=await this.teamSettingsService.getDeleteFileProtection();if($)for(const e of M)"rm"===e.command.name&&e.deny();const F=this.buildShellApprovalDecisionFacts({commands:M,autoRunControls:N,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:$,softDenylistedCommands:R});if("workspace_readonly"===l.type&&"workspace_readonly"!==o.type)return sv.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=fr(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason;let B=L?void 0:this.getShellAutoApprovalPolicy({approvalMode:a,isUnrestricted:c,requestedPolicy:o,facts:F,preserveRequestedPolicyForAllowlistedCommands:b});const z=void 0!==B&&F.allCommandsAllowlisted&&"insecure_none"===B.type&&"allowlistEscalated"in B&&!0===B.allowlistEscalated;if("insecure_none"===B?.type){const{readBoundary:e}=await this.getAdminReadSandboxing();"workspace"===e&&(s?B=void 0:"insecure_none"!==o.type&&(B=o))}const W=void 0!==B&&z;if(B&&(c||void 0===g||W)){b&&F.allCommandsPreapproved&&!F.allCommandsAllowlisted&&sv.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(B);return sv.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Rv(o),userConfiguredPolicyType:Rv(l),autoApprovalPolicyType:Rv(B),mergedPolicyType:Rv(t),isSmartAllowlistActive:b,smartModeApprovalBypassedByAllowlist:W,allCommandsRunnable:F.allCommandsRunnable,allCommandsAllowlisted:F.allCommandsAllowlisted,allCommandsPreapproved:F.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==g,commandCount:M.length}),{kind:"allow",policy:t}}let H=(b||(!h||p||D)&&!f)&&("allowlist"===a||"ask-every-time"===a)&&F.canAllowlistInPrompt;const q=[],G=void 0!==g,V=F.notInTeamAllowlist.length>0&&(F.hasSecurityDenies||F.hasSoftDenies||!F.allCommandsRunnable);if(void 0!==g&&q.push(g),L&&(G||q.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),H=!1),x.length>0&&(G||q.push(...x),H=!1),!G)if(b&&_.length>0)q.push(..._);else if(F.unapprovedCommands.length>0){const e=Uy(this.generateAllowlistPatterns(F.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):F.unapprovedCommands.map((e=>e.command.fullText)).join(", ");q.push(`Not in allowlist: ${t}`)}if(F.hasSecurityDenies&&(G||(F.rmDeniedByDeleteProtection.length>0&&q.push("Delete protection is enabled"),F.teamBlocklistedCommands.length>0&&q.push(`In team blocklist: ${F.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),H=!1),V){const t=F.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");sv.info(e,"Shell permissions: commands not in team allowlist",{commandCount:F.notInTeamAllowlist.length}),G||q.push(`Not in team allowlist: ${t}`),H=!1}const J=q.join(" • "),K=[];if(H){const e=void 0!==g?M.filter((e=>"allowlisted"!==e.state)):F.unapprovedCommands;K.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const Z=b&&_.length>0,Q=Z?P:K,X=Z&&I.length>0?I:void 0,Y="insecure_none"!==o.type&&"insecure_none"!==l.type,ee="insecure_none"!==o.type,te=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,x.length>0?"command_blocklist":void 0,b&&_.length>0?"smart_allowlist_miss":void 0,F.unapprovedCommands.length>0?"unapproved_commands":void 0,F.hasSecurityDenies?"security_denies":void 0,V?"team_allowlist_miss":void 0].filter((e=>void 0!==e));sv.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Rv(o),userConfiguredPolicyType:Rv(l),isSandboxAvailable:Y,isSandboxEnabled:ee,canAllowlist:H,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:L,approvalReasonTypes:te,commandCount:M.length,unapprovedCommandCount:F.unapprovedCommands.length,deniedCommandCount:F.deniedCommands.length,notInTeamAllowlistCount:F.notInTeamAllowlist.length,notAllowedCommandCount:Q.length,suggestedAllowlistEntryCount:X?.length??0,allCommandsRunnable:F.allCommandsRunnable,allCommandsAllowlisted:F.allCommandsAllowlisted,allCommandsPreapproved:F.allCommandsPreapproved,hasSecurityDenies:F.hasSecurityDenies,hasSoftDenies:F.hasSoftDenies});const re={type:Mp.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:J,isSandboxAvailable:"allowlist"===a&&Y,isSandboxEnabled:"allowlist"===a&&ee,canAllowlist:H,notAllowedCommands:Q,suggestedAllowlistEntries:X,smartModeApprovalReason:g,smartModeApprovalRequestId:w}},oe=await this.pendingDecisionStore.requestApproval(re);if(oe.approved){const e="unrestricted"===a?{type:"insecure_none"}:o;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:oe.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const o=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),s=await this.getPermissions(),n=!s.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==s.approvalMode)return!1;if("workspace_readonly"===s.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===s.userConfiguredPolicy.type||"workspace"!==s.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(s.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands,d=l?c.commands.map(vv):u;if(0===d.length)return!1;const h=l?c.commands.map(wv):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(wv):h,f={type:"insecure_none"},m=d.map(((e,t)=>new Pv(e,f,void 0,h[t])));if(await this.hasHardDeny(o,m))return!1;const g=gv(s.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>yv(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:n}))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,i.join)((0,n.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,o=await this.foldPerUserFilePolicy(e,r),s=o.skipStatsigDefaults?o:await this.applyStatsigDefaults(o),a=await this.loadPerRepoFilePolicy(s.type),c=await this.buildTeamAdminPolicy(s.type),l=(0,en._B)(e.networkPolicy),{policy:u}=await(0,en.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:s,perRepo:a,teamAdmin:c});return l?{...u,networkPolicy:(0,en.T6)()}:u}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,en.tv)(t,(0,n.homedir)());if(!r||"insecure_none"===r.type)return e;let o=(0,en.fZ)(r.networkPolicy,e.networkPolicy);o&&void 0!==e.networkPolicy?.default&&(o={...o,default:e.networkPolicy.default});const s=(0,en.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,en.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,en._B)(e.networkPolicy))return e;const r={default:"deny",allow:cv(t.allowlist)};return{...e,networkPolicy:(0,en.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,en.tv)((0,i.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?bv(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:s}=await this.getAdminReadSandboxing();return void 0===r?t:{...t??bv(e),readBoundary:r,additionalReadPaths:o,allowUserOverrideReadPaths:s}}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 bv(e,{networkPolicy:(0,en.Po)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=cv(t.allowlist)),t.denylist.length>0&&(r.deny=cv(t.denylist)),bv(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,s=e.parsingFailed,i=!0===e.allRedirectsAreDevNull,c=!(!o||i||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:o=!0,resolvePathForPermissions:s=Zy,pathModule:i=a,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:i,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=lv();for(const e of l){if(fv(e))continue;const n=u?lv():d,{operator:a,targetText:l}=e,p=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=pv(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("<&"===a){const e=pv(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(!dv(a)||void 0===l){for(const e of p)n.fdTargets.set(e,"unsafe");return!1}const f=await mv({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:o,resolvePathForPermissions:s,pathModule:i,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:s}){return!(!t||r||o||s)&&(0===e.redirects.length||e.redirects.some(hv))}({parsingResult:e,hasRedirects:o,parsingFailed:s,allRedirectsAreAllowlistSafe:i,allRedirectsAreWorkspaceFileSafe:c});return{allRedirectsAreAllowlistSafe:i,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:s}){const n=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=n.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=s?n.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:n.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===n.length&&0===a.length,unapprovedCommands:i,deniedCommands:n,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:o,preserveRequestedPolicyForAllowlistedCommands:s}){if(!o.hasSecurityDenies&&!o.hasSoftDenies&&o.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return o.allCommandsAllowlisted&&!s?{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),s=await this.pendingDecisionStore.requestApproval({type:Mp.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 s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:s.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=zn({matchForms:t.parsingResult?Fn({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==o?(sv.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!==Cv(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Cv(e);if(!r)return!1;const o=t.trim(),s=this.extractBaseCommand(o);if(null!==r.argsPattern){const e=o.includes(" ")?o.slice(o.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,s)||this.matchGlob(r.commandPattern,o),n=this.matchGlob(r.argsPattern,e);if(t&&n)return!0}return!!this.matchGlob(r.fullPattern,o)||!!o.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,s)||s===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)jy(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)]}matchesPathEntry(e,t,r){const o=new RegExp(`^\\s*${e}\\s*\\((.*)\\)\\s*$`),s=t.match(o);if(!s)return!1;const n=(s[1]??"").trim();return this.matchGlob((0,ln.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return $n(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){const o={stack:[],error:void 0,hasError:!1};try{rv(o,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:n,providerIdentifier:i,args:a}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:(0,Mm.yC)(r.annotationsJson)}(t,r),u=e=>{this.mcpAllowlistLog?.(e)};u(`[permissions-service] shouldBlockMcp: toolName="${n}", providerIdentifier="${i}"`);const d=await this.getPermissions(),h=await this.teamSettingsService.getMcpToolControls(),p=!0===h?.enabled;if(await this.isMcpExplicitlyDenied(e,i,n))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${n}", providerIdentifier="${i}"`),{type:"permissionsConfig"};const f=t.smartModeApproval?.reason;if(void 0!==f)return"workspace_readonly"===d.userConfiguredPolicy.type&&"unrestricted"!==d.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${n}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${n}", providerIdentifier="${i}"`),!(p?this.isMcpInTeamAllowlist(h,{providerIdentifier:i,toolName:n,annotations:l}):await this.isMcpExplicitlyAllowed(e,i,n))&&!("unrestricted"===d.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:f,approvalDetails:{type:"mcp",name:s,toolName:n,providerIdentifier:i,args:a,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:f,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(p){const t=this.isMcpInTeamAllowlist(h,{providerIdentifier:i,toolName:n,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${n}", providerIdentifier="${i}"`),!1}else{const t=await this.isMcpExplicitlyAllowed(e,i,n);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${n}", providerIdentifier="${i}"`),!1}if("workspace_readonly"===d.userConfiguredPolicy.type&&"unrestricted"!==d.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${n}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===d.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${n}", providerIdentifier="${i}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${n}", providerIdentifier="${i}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${n}", providerIdentifier="${i}", approvalMode="${d.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${n}`,approvalDetails:{type:"mcp",name:s,toolName:n,providerIdentifier:i,args:a,canAllowlist:!0}}}catch(e){o.error=e,o.hasError=!0}finally{ov(o)}}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:o,toolName:s}=t,n=t.annotations??(0,Mm.yC)(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,o,s))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:o,toolName:s,annotations:n}):await this.isMcpExplicitlyAllowed(r,o,s)}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 s=o.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,s)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,s)))}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 s=e.indexOf(":");if(-1===s)return!1;const n=e.slice(0,s).trim().toLowerCase(),i=e.slice(s+1).trim().toLowerCase(),a=t.lastIndexOf("::mcpScope:"),c=(-1===a?t:t.slice(0,a)).toLowerCase().trim(),l=r.toLowerCase().trim(),u="*"===n||this.matchGlob(n,c),d="*"===i||this.matchGlob(i,l),h=u&&d,p=`[permissions-service] ${o}: serverPattern="${n}", toolPattern="${i}", normalizedProviderIdentifier="${c}", normalizedToolName="${l}", serverMatches=${u}, toolMatches=${d}, result=${h}`;return this.mcpAllowlistLog?.(p),h}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){nv.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 s=o[1]?.trim()??"";return this.matchesMcpPattern({pattern:s,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Ay(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 s=this.findTeamMcpServerPolicy(e,t);return void 0!==s&&"reads"===s.mode&&(0,Dy.rh)(s,{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 isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var Av=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Mv=(0,d.h)("LocalReadExecutor"),Dv=async(e,t,r,o)=>{const s=setTimeout((()=>{Mv.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await o()}finally{clearTimeout(s)}};function Ov(e){return e>=32&&e<=126||9===e||10===e||13===e}const Nv=Buffer.from("\n---\n");const jv=[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 $v(e){const t=(0,i.extname)(e).toLowerCase(),r=""===t?"Binary files without an extension are not supported by the read executor":`Binary files of type ${t} are not supported by the read executor`;return new gt.sV({result:{case:"invalidFile",value:new gt.cW({path:e,reason:r})}})}function Fv(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{content:e,rangeApplied:!1};if(""===e)return{content:e,rangeApplied:!1};const o=r.offset??1,s=r.limit??(o<0?Math.abs(o):t),n=o<0?Math.max(0,t+o):Math.max(0,o-1);if(n>=t)return{content:e,rangeApplied:!1};const i=Math.min(t,n+s);return{content:e.split("\n").slice(n,i).join("\n"),rangeApplied:!0}}function Lv(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 Uv(e,t){const r=Lv(e,t);return{text:r.text,truncated:r.truncated}}function Bv(e,t,r){let o=e;return t.forEach(((e,t)=>{const s=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=Lv(o,"\n")),o=Lv(o,s.text),s.truncated&&(o={text:o.text,truncated:!0})})),o}function zv(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 Wv extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function Hv(e,t,r,o){const s=void 0!==r.offset||void 0!==r.limit,n=(r.offset??1)<0,i=r.offset??1,a=Math.max(0,i-1),c=void 0===r.limit?void 0:a+r.limit,l=n?Math.abs(i):0,u=[];let d=0,h=!1;const p=[];let f=0,m=!1;const g=[];let w=0,y=!1,v={text:"",truncated:!1},b=0,S=0,k=0,E=!1,C=!1;const x=e=>{let t=e;return!E&&t.length>0&&(E=!0,65279===t.charCodeAt(0)&&(C=!0,t=t.slice(1))),t},_=(e,t)=>{const r=b;if(t&&(e.text.endsWith("\r")?S++:k++),((e,t)=>{if(h&&d>=ft)return;const r=u.length>0?1:0;let o=ft-d;if(r>0){if(o<=0)return void(h=!0);o--}const s=e.text.length>o?{line:{text:e.text.slice(0,o),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};u.push(s),d+=r+s.line.text.length,(e.truncated||s.line.truncated)&&(h=!0)})(e,t),n){if(l>0){for(g.push({line:e,hasNewline:t}),w+=e.text.length+1;g.length>l;){const e=g.shift();void 0!==e&&(w-=e.line.text.length+1)}for(;g.length>1&&w>ft;){const e=g.shift();void 0!==e&&(w-=e.line.text.length+1,y=!0)}}}else s&&r>=a&&(void 0===c||r<c)&&((e,t)=>{if(m&&f>=ft)return;const r=p.length>0?1:0;let o=ft-f;if(r>0){if(o<=0)return void(m=!0);o--}const s=e.text.length>o?{line:{text:e.text.slice(0,o),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};p.push(s),f+=r+s.line.text.length,e.truncated&&(m=!0),s.line.truncated&&(m=!0)})(e,t);b++};for await(const r of async function*(e,t,r){if("strictUtf8"===r.kind){const r=new Gn.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),o=(0,Ys.createReadStream)(t,{highWaterMark:65536,signal:e.signal});try{for await(const e of o){const t=r.decode(e,{stream:!0});t.length>0&&(yield t)}const e=r.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new Wv;throw e}return}const o=(0,Ys.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe(Vn.decodeStream(r.decoderEncoding));for await(const e of o)yield"string"==typeof e?e:String(e)}(e,t,o)){const e=x(r);let t=0,o=e.indexOf("\n",t);for(;-1!==o;)v=Uv(v,e.slice(t,o)),_(v,!0),v={text:"",truncated:!1},t=o+1,o=e.indexOf("\n",t);t<e.length&&(v=Uv(v,e.slice(t)))}_(v,!1);const P=S+k,R=P>0&&S/P*100>=5;!function(e,t){if(ii.has(e)&&ii.delete(e),ii.set(e,t),ii.size<=100)return;const r=ii.keys().next().value;void 0!==r&&ii.delete(r)}(t,"utf8"===o.cacheEncoding&&C?"utf8bom":o.cacheEncoding);let I={text:"",truncated:h};if(I=Bv(I,u,R),!s)return{content:I.text,totalLines:b,truncated:I.truncated,rangeApplied:!1};if(""===I.text)return{content:"",totalLines:b,truncated:!1,rangeApplied:!1};if(n){const e=r.limit??l;let t={text:"",truncated:y};return t=Bv(t,g.slice(0,e),R),{content:t.text,totalLines:b,truncated:t.truncated,rangeApplied:!0}}if(a>=b)return{content:I.text,totalLines:b,truncated:I.truncated,rangeApplied:!1};let T={text:"",truncated:m};return T=Bv(T,p,R),{content:T.text,totalLines:b,truncated:T.truncated,rangeApplied:!0}}class qv{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path,s=(0,ln.o1)(o,this.workspacePath),n=await Dv(e,"permissionsService.shouldBlockFileRead",3e3,(()=>async function(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}(this.permissionsService,s)));if(n){const r=await Dv(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Wi(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 s=await o({type:Mp.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return s.approved?null:{kind:"rejected",reason:s.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(n,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new gt.sV({result:{case:"rejected",value:new gt.f4({path:s,reason:r.reason??""})}});if("denied"===r.kind)return new gt.sV({result:{case:"permissionDenied",value:new gt.lW({path:s})}})}void 0!==this.mcpStateAccessor&&Tg(e,this.mcpStateAccessor,s);try{const r=await Dv(e,"stat",3e3,(()=>(0,Qs.stat)(s)));if(r.isDirectory())return new gt.sV({result:{case:"invalidFile",value:new gt.cW({path:s,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new gt.sV({result:{case:"invalidFile",value:new gt.cW({path:s,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=wt(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 s=Number.parseInt(o[1],10);return Number.isNaN(s)?null:{id:s}}(e)}(s),n=function(e){const t=wt(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(s);if(o||n)return await this.readTerminalFile(e,s,r,t,n&&!o);const a=await Dv(e,"getFormatForFile",3e3,(()=>fi(s))),c=a.isImageFile,l=function(e){return".pdf"===(0,i.extname)(e).toLowerCase()}(s),u=ui(s);if(c){const t=await Dv(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,Qs.readFile)(s);return Am(e)}));return new gt.sV({result:{case:"success",value:new gt.mE({path:s,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(l){const t=await Dv(e,"readPdfBinary",3e3,(()=>(0,Qs.readFile)(s)));return new gt.sV({result:{case:"success",value:new gt.mE({path:s,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(a.isBinaryFile&&u){const t=await Dv(e,"readBinaryFile",3e3,(()=>(0,Qs.readFile)(s)));return new gt.sV({result:{case:"success",value:new gt.mE({path:s,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(a.isBinaryFile)return $v(s);{const o=this.useStreamingRead;if(!o||await Dv(e,"useStreamingRead",3e3,(()=>o()))){const o=await Dv(e,"readTextStreaming",7e3,(()=>async function(e,t,r,o){const s=function(e,t,r){const o=function(e,t,r){return zv(r??ii.get(e)??t.encoding)}(e,t,r),s=function(e){const t=zv(e);return"utf8bom"===t?"utf8":t}(o);return"utf8"===s?{kind:"strictUtf8",cacheEncoding:"utf8"}:Vn.encodingExists(s)?{kind:"iconv",decoderEncoding:s,cacheEncoding:o}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,o.encodingHint);try{return await Hv(e,t,o,s)}catch(r){if(r instanceof Wv)return await Hv(e,t,o,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,s,a,t)));return new gt.sV({result:{case:"success",value:new gt.mE({path:s,output:{case:"content",value:o.content},totalLines:o.totalLines,fileSize:BigInt(r.size),truncated:o.truncated,rangeApplied:o.rangeApplied})}})}const n=await Dv(e,"readText",3e3,(()=>hi(s,t.encodingHint))),i=await Dv(e,"countLines",3e3,(()=>mi(n))),c=Fv(n,i,t);let l=c.content,u=!1;return l.length>ft&&(l=l.substring(0,ft),u=!0),new gt.sV({result:{case:"success",value:new gt.mE({path:s,output:{case:"content",value:l},totalLines:i,fileSize:BigInt(r.size),truncated:u,rangeApplied:c.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new gt.sV({result:{case:"fileNotFound",value:new gt.Ko({path:s})}}):"EACCES"===t.code||"EPERM"===t.code?new gt.sV({result:{case:"permissionDenied",value:new gt.lW({path:s})}}):new gt.sV({result:{case:"error",value:new gt.F_({path:s,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Av(r)}}async readTerminalFile(e,t,r,o,s){const n=await Dv(e,"readTerminalFile",3e3,(()=>(0,Qs.readFile)(t)));if(s&&(i=n,jv.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return $v(t);var i;let a=function(e){const t=function(e){if(e.length<5||45!==e[0]||45!==e[1]||45!==e[2]||10!==e[3])return 0;const t=Buffer.from("\n---\n"),r=e.indexOf(t,4);return-1===r?0:r+t.length}(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",o=function(e,t){const r=e.length;if(r<2*Nv.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),s=e.lastIndexOf(Nv,r-Nv.length-1);return-1===s||s<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(s+Nv.length,r-4).toString("utf-8"))?s:r}(e,t),s=o<e.length?e.subarray(o).toString("utf-8"):"",n=e.subarray(t,o),i=function(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,o=0;for(let s=0;s+1<t;s+=2){const t=e[s],n=e[s+1];0===n&&Ov(t)&&r++,0===t&&Ov(n)&&o++}return r>=8&&r>=4*Math.max(1,o)?"utf-16le":o>=8&&o>=4*Math.max(1,r)?"utf-16be":"utf-8"}(n);let a;if("utf-16le"===i)a=n.toString("utf16le");else if("utf-16be"===i){const e=n.length-n.length%2,t=Buffer.from(n.subarray(0,e));t.swap16(),a=t.toString("utf16le")}else a=n.toString("utf-8");return 65279===a.charCodeAt(0)&&(a=a.slice(1)),r+a+s}(n).replaceAll("\r\n","\n");const c=mi(a),l=Fv(a,c,o);a=l.content;let u=!1;return a.length>ft&&(a=a.substring(0,ft),u=!0),new gt.sV({result:{case:"success",value:new gt.mE({path:t,output:{case:"content",value:a},totalLines:c,fileSize:BigInt(r.size),truncated:u,rangeApplied:l.rangeApplied})}})}}var Gv=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),Vv=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Jv(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function Kv(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function Zv(e){return e instanceof Error?e.message:String(e)}function Qv(e,t,r,o){const s=[],n=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!==n&&s.push(n),void 0!==r&&s.push(`stop failed: ${Zv(r)}`),s.length>0?`${e} (${s.join("; ")})`:e}const Xv=(0,Gn.promisify)(qc.execFile);class Yv{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(!Jv(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,vt.wj)(Promise.all(e),Yv.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 Qs.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 Qs.mkdir(this.stagingDir,{recursive:!0}),await Qs.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return i.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:Gv.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:Gv.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:Gv.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 Qs.rename(e,t)}catch(e){if(!Kv(e,"EXDEV"))throw e}try{await Qs.copyFile(e,t)}catch(e){throw await Qs.rm(t,{force:!0}).catch((()=>{})),e}try{await Qs.unlink(e)}catch(e){throw await Qs.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=i.parse(e),r=t.name||"recording",o=t.ext||".mp4";let s=`${r}${o}`,n=2;for(;;){const e=i.join(this.artifactsDir,s);try{const t=await Qs.open(e,"wx");return await t.close(),e}catch(e){if(!Kv(e,"EEXIST"))throw e;s=`${r}-${n}${o}`,n++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let o,s;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?s=e.filename:(o=e.reason,s=`${i.basename(r)}.mp4`)}else s=`${i.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(s),requestedFilePathRejectedReason:o}}async getVideoDurationMs(e){const{stdout:t}=await(0,Hh.D9)(Xv,"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,Hh.D9)(Xv,"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"),s=Number.parseInt(r,10),n=Number.parseInt(o,10);if(!Number.isFinite(s)||!Number.isFinite(n))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(s<=0||n<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:s,height:n}}async renderPolished(e){const t=i.join(e,"recording"),r=i.join(t,"recording_full.mp4");return await this.polishedRenderer.renderRecordingSession({stagingSessionDir:e,outputVideoPath:r,fps:Yv.PROXY_TARGET_FPS,includeBrandTag:!0}),await Qs.access(r,Qs.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await(0,Hh.D9)(Xv,"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),s=Number.parseFloat(t);if(Number.isFinite(o)&&Number.isFinite(s)&&0!==s){const e=o/s;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 ${Yv.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${Yv.PROXY_TARGET_FPS}fps`)}return Yv.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=i.join(t,"recording");await Qs.mkdir(r,{recursive:!0});const o=i.join(r,"recording_render_proxy_1080p.mp4");let s;try{s=(await Vh(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${Yv.DEFAULT_REFRESH_RATE}Hz`),s=Yv.DEFAULT_REFRESH_RATE}const n=["-video_size",e,"-framerate",String(s),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${Yv.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${Yv.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",Yv.PROXY_PRESET,"-crf",String(Yv.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,Hh.D9)(qc.spawn,"ffmpeg",n,{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 s=setTimeout((()=>{o||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);a.once("exit",((e,r)=>{clearTimeout(s),o||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.once("error",(e=>{clearTimeout(s),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 s=(0,Hh.D9)(qc.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let n="";s.stderr?.on("data",(e=>{n.length<2e4&&(n+=e.toString())})),s.once("error",(t=>{o(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),s.once("close",(t=>{0===t?r():o(new Error(`ffmpeg ${e} exited with code ${t}: ${n.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:o,ffmpegStartedEpochMs:s,inputEvents:n,resolution:a,renderProxies:c}=e,l=i.join(t,"recording"),u=i.join(l,"recording-data.json"),d=s-o,h=n.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:s,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Qs.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(Jv(t)||!t.pid)return;const r=t.pid;return new Promise(((e,o)=>{const s=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(s),e()})),t.once("error",(e=>{clearTimeout(s),o(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(s),Kv(t,"ESRCH"))return void e();o(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t){const r=Date.now();try{const o=await t.inputEventLogger.stop(),s=t.inputEventLogger.getRecordingStartTime();let n;this.invokeStoppedCallbackIfCurrent(t);try{!Jv(t.childProcess)&&t.childProcess.pid&&await this.stopFfmpegRecording(t)}catch(e){n=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${Zv(e)}`)}const a=t.ffmpegStartedEpochMs??s,c=t.sessionDir,l=i.join(c,"recording"),u=i.join(l,"recording_render_proxy_1080p.mp4");let d,h,p;try{await Qs.access(u,Qs.constants.R_OK)}catch(e){await this.cleanupRecording(t),this.clearActiveRecordingIfCurrent(t);const o=Kv(e,"ENOENT")?`Recording proxy not found at ${u}`:`Recording proxy at ${u} could not be validated: ${Zv(e)}`;return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:Qv(o,t,n,r)})}})}try{if([d,h,p]=await Promise.all([this.getVideoDurationMs(u),this.getVideoDimensions(u),this.getVideoFramerate(u)]),d<=0)throw new Error(`Recording proxy has zero duration at ${u}`)}catch(e){await this.cleanupRecording(t);const o=Zv(e),s=o.includes(u)?o:`Recording proxy at ${u} could not be validated: ${o}`;return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:Qv(s,t,n,r)})}})}const f={profileVersion:Yv.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:h.width,height:h.height,durationMs:d,fps:p},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:h.width,height:h.height,fps:Yv.PROXY_TARGET_FPS,codec:"h264",profile:Yv.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:c,durationMs:d,recordingStartEpochMs:s,ffmpegStartedEpochMs:a,inputEvents:o,resolution:t.resolution,renderProxies:f});const{finalVideoPath:m,requestedFilePathRejectedReason:g}=await this.resolveArtifactVideoPath({saveAsFilename:e.saveAsFilename,stagingSessionDir:c});try{if(this.disablePolishedRendering)await Qs.copyFile(u,m);else{const e=await this.renderPolished(c);await this.movePolishedVideo(e,m)}}catch(e){throw await Qs.rm(m,{force:!0}).catch((()=>{})),e}try{await Qs.rm(c,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${c}: ${Zv(e)}`)}return this.clearActiveRecordingIfCurrent(t),new Gv.Tj({result:{case:"saveSuccess",value:new Gv.ol({path:m,recordingDurationMs:bt.protoInt64.parse(d.toString()),requestedFilePathRejectedReason:g})}})}catch(e){return await this.cleanupRecording(t),this.invokeStoppedCallbackIfCurrent(t),new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:Zv(e)})}})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new Gv.Tj({result:{case:"failure",value:new Gv.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===Gv.$u.UNSPECIFIED)return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case Gv.$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 Qs.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r=null,o=null,s=null;try{s=this.buildSessionDir(t.toolCallId||"recording"),await Qs.mkdir(s,{recursive:!0});const{resolutionString:n,resolution:i}=await Vh(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(n,s);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 ep({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:s,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 Gv.Tj({result:{case:"startSuccess",value:new Gv.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 s&&await Qs.rm(s,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:e instanceof Error?e.message:String(e)})}})}}case Gv.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:"No active recording to save"})}});const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case Gv.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!Jv(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await Qs.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new Gv.Tj({result:{case:"discardSuccess",value:new Gv.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let o=!1;try{await Qs.rm(r,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;const s=t instanceof Error?t.message:String(t),n=o?"":`. Session may remain at: ${r}`;return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:`Failed to discard recording: ${s}${n}`})}})}}default:{const e=t.mode;return new Gv.Tj({result:{case:"failure",value:new Gv.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{Vv(r)}}}async function eb(e){const t=await(0,Qs.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const o of t){const t=i.join(e,o.name),s={name:o.name,path:t,isDirectory:o.isDirectory()};o.isDirectory()&&(s.children=await eb(t)),r.push(s)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function tb(e,t="",r=!0){const o=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],s=e.children;if(s?.length){const e=t+(r?" ":"│ ");s.forEach(((t,r)=>{const n=r===s.length-1;o.push(...tb(t,e,n))}))}return o}async function rb(e){if(!await(0,Qs.access)(e,Qs.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await eb(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>tb(e,"",r===t.length-1))).join("\n")}async function ob(e,t){return rb(i.join(e,"agent-notes",t))}async function sb(e){return rb(i.join(e,"agent-notes","shared"))}Yv.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,Yv.PROXY_TARGET_WIDTH=1920,Yv.PROXY_TARGET_FPS=60,Yv.PROXY_CRF=17,Yv.PROXY_PRESET="veryfast",Yv.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",Yv.DEFAULT_REFRESH_RATE=60;var nb=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 ab=(0,d.h)("local-exec:request-context");async function cb(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{nb(s,(0,c.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){s.error=e,s.hasError=!0}finally{ib(s)}}async function lb(e,t,r,o){try{const s=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:o,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===s||0===s.length)return;return s}catch{return}}async function ub(e,t,r={}){const{projectDir:o,notesSessionId:s,metaAgentNotesEnabled:i,getSmartModeClassifierAutoModeEnabled:a,devForceNextSmartModeClassifierBlockToken:c,isWorkingDirHomeDir:l,getSandboxEnabled:u,getSandboxSupported:d,getNetworkAllowlistInfo:h,userTerminalHint:p,artifactsFolder:f,secretRedactionEnabled:m,getComputerUseSupported:g,getMockPromptTime:w}=r,y=`${n.platform()} ${n.release()}`,v=(0,en.G6)(p),b=w?.(),S=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),k=o,E=o?`${o}/terminals`:void 0,C=o&&!0!==i?`${o}/agent-notes/shared`:void 0,x=o&&s?`${o}/agent-notes/${s}`:void 0,_=o?`${o}/agent-transcripts`:void 0,P=!!u&&u(),R=d?.(),I=a?.();let T;if(h)try{T=await h()}catch{T=void 0}return new lr.GE({osVersion:y,workspacePaths:t,shell:v,sandboxEnabled:P,projectFolder:k,terminalsFolder:E,agentSharedNotesFolder:C,agentConversationNotesFolder:x,agentTranscriptsFolder:_,timeZone:S,processWorkingDirectory:process.cwd(),artifactsFolder:f,...void 0!==I&&{smartModeClassifierAutoModeEnabled:I},...void 0!==c&&{devForceNextSmartModeClassifierBlockToken:c},...void 0!==b&&{devMockPromptTime:bt.Timestamp.fromDate(b)},...void 0!==m&&{secretRedactionEnabled:m},...void 0!==R&&{sandboxSupported:R},...void 0!==T?.hasDefaults&&{sandboxNetworkHasDefaults:T.hasDefaults},...T?.explicitEntries&&T.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:T.explicitEntries},...void 0!==g&&{computerUseSupported:g()},...void 0!==l&&{isWorkingDirHomeDir:l}})}const db={type:"object",properties:{},additionalProperties:!1};function hb(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>st.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new ro.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?bt.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function pb(e,t){const r=!0===t?.slimDescriptors,o=e.servers.map((e=>{const o=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),s=e.tools.map((e=>new ro.E$({toolName:e.toolName,...(0,Mm.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?bt.Value.fromJson(e.inputSchema):void 0}}})));return!ot(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||s.some((e=>e.toolName===Km))||s.push(new ro.E$({toolName:Km,...r?{}:{description:Zm,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(db)}:{inputSchema:bt.Value.fromJson(db)}}})),new ro.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:o||void 0,tools:s})}));return new ro.U_({enabled:!0,mcpDescriptors:o})}function fb(e){const t=e?.trim();return t||void 0}function mb(e,t){const r=function(e){return fb(e.serverIdentifier)}(e);if(r)return r;const o=fb(e.serverName);return o?t.get(o)??o:void 0}class gb{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(ab.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(ab.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>mb(e,o))).filter((e=>Boolean(e)));return{servers:[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])].map((s=>{const n=e.filter((e=>e.clientKey===s));return{serverName:n[0]?.providerIdentifier??s,serverIdentifier:s,plugin:n[0]?.plugin,marketplace:n[0]?.marketplace,tools:n,instructions:t.filter((e=>mb(e,o)===s)),status:r?.get(s)?.status,errorMessage:r?.get(s)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(ab.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:ct(o),errorMessage:"error"===o.kind&&void 0!==o.message?o.message:void 0}]})));return new Map(o)}(e,this.mcpLease))}}function wb(e){return new mt._W({result:{case:"success",value:new mt.pv({servers:e.servers.map((e=>new mt.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new ro.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?bt.Value.fromJson(e.inputSchema):void 0,...(0,Mm.hT)(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class yb{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!==mt.ew.FORCE_IF_MISSING&&t.refreshPolicy!==mt.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 wb({...r,servers:o})}return wb(r)}}class vb{constructor(e,t,r,o,s,n,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=o,this.grepProvider=s,this.mcpStateAccessor=n,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,createFileWatcher:f,getSandboxEnabled:m,getSandboxSupported:g,getNetworkAllowlistInfo:w,userTerminalHint:y,getMcpFileSystemOptions:v,mcpMetaToolEnabled:b,mcpMetaToolSlimDescriptors:S,mcpInputSchemaJson:k,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:C,secretRedactionEnabled:x,attributionConfigProvider:_,isAttributionDisabledByAdmin:P,getAgentSkills:R,additionalRules:I,getComputerUseSupported:T,getMockPromptTime:A}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.getSandboxEnabled=m,this.getSandboxSupported=g,this.getNetworkAllowlistInfo=w,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=A,this.userTerminalHint=y,this.getMcpFileSystemOptions=v,this.mcpMetaToolEnabled=b??!1,this.mcpMetaToolSlimDescriptors=S??!1,this.mcpInputSchemaJson=k??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=C,this.secretRedactionEnabled=x,this.attributionConfigProvider=_,this.isAttributionDisabledByAdmin=P,this.getAgentSkills=R,this.additionalRules=I??[],this.getComputerUseSupported=T,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),void 0!==f&&(this.fileWatcher=f(),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,re.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=nb(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),s=await async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"getGitRepoPathForWorkspacePath"})).stdout.trim()}catch{return null}}(o.ctx,this.gitExecutor,t),n=s?await Di(o.ctx,this.gitExecutor,s):void 0,i={repoPath:s??void 0,remoteUrl:void 0!==n?Oi(n):void 0};this.cachedWorkspaces.set(t,i)}catch(e){r.error=e,r.hasError=!0}finally{ib(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,re.q6)(),r=nb(e,(0,c.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const o=this.computeGlobalCache(r.ctx);return this.globalCache=o,this.reduceContextHotPath&&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{ib(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=nb(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),o=AbortSignal.timeout(1e3),s=performance.now(),n={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{n[e]=Math.round(performance.now()-r)}))},[a,l,u,d]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,o).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),h=Math.round(performance.now()-s);return h>1e3&&ab.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...n,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{ib(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=nb(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let s;if(this.grepProvider.getTrackedState)try{s=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{s=void 0}let n=!0;const i=(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return n=!1,void this.ensureWorkspaceCacheWarm(o.ctx,e);if(await this.ensureWorkspaceCacheWarm(o.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(n=!1)}const i=s?.[e];if(void 0!==i)return new lr.DS({path:r.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:_l(r.remoteUrl)});if(void 0===r.repoPath)return;const{status:a,branchName:c}=await async function(e,t,r,o){const s=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)}))},[n,i]=await Promise.all([s(cb(e,t,r,o)),s(lb(e,t,r,o))]);return{status:n,branchName:i}}(o.ctx,this.gitExecutor,r.repoPath,3e3);return new lr.DS({path:r.repoPath,status:a,branchName:c,remoteUrl:r.remoteUrl,isOriginBacked:_l(r.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:i,gitRepoInfoComplete:n}}catch(e){r.error=e,r.hasError=!0}finally{ib(r)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=nb(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,n=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=nb(e,(0,c.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)}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{ib(e)}},i=performance.now(),a={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{a[e]=Math.round(performance.now()-r)}))},[u,d,h,{gitRepos:p,gitRepoInfoComplete:f},m,g,w,y,v,b]=await Promise.all([l("globalCache",n()),l("mcpState",this.mcpStateAccessor.getState(o.ctx)),l("env",ub(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,metaAgentNotesEnabled:!1,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})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache})),l("conversationNotes",s&&t.notesSessionId?ob(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",s?sb(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",this.getAgentSkills?this.getAgentSkills(o.ctx):Promise.resolve([])),l("adminCommandDenylist",this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0))]),S=performance.now()-i;for(const[e,t]of Object.entries(a))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(S)),S>1e3&&ab.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(S),...a});const k=this.mcpMetaToolEnabled?pb(d,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,E=this.attributionConfigProvider?.get(),C=!y&&(E?.attribution?.attributeCommitsToAgent??!0),x=!y&&(E?.attribution?.attributePRsToAgent??!0),_=new lr.bb({rules:u.rules,env:h,gitRepos:p,gitRepoInfoComplete:f,repositoryInfo:u.codebaseReference?[{relativeWorkspacePath:u.codebaseReference.relativeWorkspacePath,repoName:u.codebaseReference.repoName,repoOwner:u.codebaseReference.repoOwner,isTracked:u.codebaseReference.isTracked,isLocal:u.codebaseReference.isLocal,orthogonalTransformSeed:u.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:u.codebaseReference.pathEncryptionKey}]:[],...hb(d,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:m,sharedNotesListing:g,customSubagents:u.customSubagents,mcpFileSystemOptions:w,mcpMetaToolOptions:k,supportsMcpAuth:!0,commitAttributionMessage:C?"enabled":void 0,prAttributionMessage:x?"enabled":void 0,agentSkills:v,adminCommandDenylist:b?.rules??[]});return null!==u.cloudRule&&void 0!==u.cloudRule&&(_.cloudRule=u.cloudRule),_}catch(e){r.error=e,r.hasError=!0}finally{ib(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=nb(r,(0,c.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 lr._G({result:{case:"success",value:new lr.yW({requestContext:e})}})}catch(e){return o.span.recordException(e),new lr._G({result:{case:"error",value:new lr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{ib(r)}}}function bb(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Jt._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var Sb=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 kb{constructor(e,t,r,o){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new Jt.W4({result:{case:"success",value:new Jt.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Mn(e.sandboxPolicy)}):new Jt.W4({result:{case:"failure",value:new Jt.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Mn(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,o,s){const n=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=s?{perRepo:s}:void 0;for await(const s 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"===s.type?d+=s.data:"stderr"===s.type?h+=s.data:"exit"===s.type&&(p=null!=s.code?0|s.code:null,l=s.outputLocation,o=s.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?Jt.Lv.TIMEOUT:Jt.Lv.USER_ABORT:Jt.Lv.UNSPECIFIED:void 0,u=Vp(s.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-n,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:s,outputLocation:l};return this.buildResultFromExit(g)}catch(n){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new Jt.W4({result:{case:"timeout",value:new Jt.eG({command:t.command,workingDirectory:r,timeoutMs:o})},sandboxPolicy:Mn(s)}):e.signal.aborted?new Jt.W4({result:{case:"rejected",value:new Jt.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Mn(s)}):new Jt.W4({result:{case:"spawnError",value:new Jt.mJ({command:t.command,workingDirectory:r,error:n instanceof Error?n.message:"Unknown error"})},sandboxPolicy:Mn(s)})}}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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,c.HF)(o,"LocalShellExecutor.execute");const s=t.command,n=t.requestedSandboxPolicy?An(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=bb(t),l=(0,ln.o1)(i);if(!t.parsingResult)return new Jt.W4({result:{case:"spawnError",value:new Jt.mJ({command:s,workingDirectory:l,error:"Parsing result is required"})}});let u;if(t.skipApproval){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(o,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:s,parsingResult:t.parsingResult,toolCallId:t.toolCallId},n);if("block"===e.kind)return new Jt.W4({result:qi(s,l,e.reason)});u=n}else{const e=await this.permissionsService.shouldBlockShellCommand(o,s,{workingDirectory:l,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:pr(t)},n);if("block"===e.kind)return new Jt.W4({result:qi(s,l,e.reason)});u=e.policy}if(vn()&&(u=xn(s,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await Li(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(o,t,i,a,u)}catch(e){r.error=e,r.hasError=!0}finally{Sb(r)}}}var Eb=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class Cb{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new Jt.HO,o=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new Eb.e({allowlisted:o})}}class xb{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new Jt.jK({status:Jt.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}var _b=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},Pb=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Rb=(0,d.h)("local-exec:shell-core"),Ib="win32"===process.platform,Tb=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Ab(e){return`'${e.replace(/'/g,"'\\''")}'`}function Mb(e,t){return e[t]??process.env[t]}const Db=/^[A-Za-z_][A-Za-z0-9_]*$/,Ob=/CURSOR_SANDBOX/i;function Nb(e){return Db.test(e)&&!Ob.test(e)}function jb(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}class $b{constructor(e,t,r,o,s){this.executor=e,this.workspacePath=t,this.projectDir=r,this.shellOutputBackpressureOptions=o,this.extraEnvProvider=s,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{_b(r,(0,c.VI)(e.withName("ShellCoreExecutor.execute")),!1);const o=performance.now(),n=this.executorFor(t.conversationId),a=t.workingDirectory||await n.getCwd(),l=(0,ln.o1)(a,this.workspacePath);let u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(u={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,Js.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=i.join(this.projectDir,Js.O2));const y=this.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&&Nb(e)&&(w[e]=t);!function(e,t){const r=Object.keys(t).filter((e=>Nb(e)&&!Tb.includes(e))),o=`builtin unset ${[...Tb,...r].join(" ")} 2>/dev/null || true`,s=[];for(const t of Tb){const r=Mb(e,t);void 0!==r&&s.push(`builtin export ${t}=${Ab(r)}`)}for(const e of r){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Ab(r)}`)}const n=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),i=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,i,n,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v);const b=function(e,t){const r=Mb(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[]}}(Mb(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===o.length)return e;const s=e?.perUser,n=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==n?.type&&"workspace_readonly"!==n?.type)return e;const i=s?.type===n.type?{...s}:{type:n.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=jb(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=jb(i.additionalReadwritePaths,a));for(const e of o)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=jb(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=jb(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),S=(0,en.CG)(b??en.BM);b&&(yield{type:"start",sandboxed:"workspace_readonly"===S||"workspace_readwrite"===S}),t.askpassConfig&&!Ib&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let k=0,E="";for await(const r of n.execute(e,t.command,{signal:g,workingDirectory:l,env:w,sandboxPolicy:b,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,bufferOutputEvents:this.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.shellOutputBackpressureOptions?.outputLimiterOptions})){if(k=0,E="",("stdout"===r.type||"stderr"===r.type)&&(E=r.data.toString(),k=r.data.length,u))if(u.size+=k,u.lineCount+=E.split("\n").length-1,u.size>Qp);else if(u.file)u.file.write(E);else if(u.buffer+=E,u.size>u.threshold){const e=i.join(this.projectDir,Zp);u.path=i.join(e,`${(0,s.randomUUID)()}.txt`),await(0,Qs.mkdir)(i.dirname(u.path),{recursive:!0}),u.file=(0,Ys.createWriteStream)(u.path),u.file.write(u.buffer),u.buffer=""}switch(r.type){case"stdout":p||(d+k>Tp?(p=!0,yield{type:"stdout_trimmed"}):(d+=k,yield{type:"stdout",data:E}));break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:en.Ls});break;case"stderr":f||(h+k>Tp?(f=!0,yield{type:"stderr_trimmed"}):(h+=k,yield{type:"stderr",data:E}));break;case"exit":{const e=Math.max(0,Math.round(performance.now()-o));let t;u?.file&&(await new Promise((e=>u.file.end(e))),t=new wm.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})),yield{type:"exit",code:r.code,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}}catch(e){r.error=e,r.hasError=!0}finally{Pb(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 Fb{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{_b(r,(0,c.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Rb.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{Pb(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Lb{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()}}var Ub=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Bb=(0,d.h)("local-exec:shell-stream");class zb{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===Jt.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:Jt.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:Jt.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 Wb{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 Jt.jK({status:Jt.iA.ACCEPTED,shellResult:r}):new Jt.jK({status:Jt.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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?An(t.requestedSandboxPolicy):void 0;const n=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=bb(t),a=(0,ln.o1)(n),l=Date.now(),u=new Jt.HO(an(o).structured),d=Hn({command:o,parsingResult:u,blockedCommands:t.adminCommandDenylist});if(void 0!==d)return void(yield new Jt.FI({event:{case:"rejected",value:new Jt.pZ({command:o,workingDirectory:a,reason:d})}}));const h=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:u,toolCallId:t.toolCallId},s);if("block"===h.kind)return"permissionsConfig"===h.reason.type?void(yield new Jt.FI({event:{case:"permissionDenied",value:new Jt.jn({command:o,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:h.reason.isReadonly??!1})}})):void(yield new Jt.FI({event:{case:"rejected",value:new Jt.pZ({command:o,workingDirectory:a,reason:Hi(h.reason)})}}));if(Bb.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:u.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),t.skipApproval)Bb.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined"});else{const r=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:a,timeout:i,parsingResult:u,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:pr(t)},s);if("block"===r.kind){if(Bb.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 Jt.FI({event:{case:"permissionDenied",value:new Jt.jn({command:o,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const s=Hi(r.reason);return void(yield new Jt.FI({event:{case:"rejected",value:new Jt.pZ({command:o,workingDirectory:a,reason:s})}}))}s=r.policy,Bb.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}if(vn()&&(s=xn(o,u)),s&&"insecure_none"!==s.type){const e=await Li(this.ignoreService);s={...s,ignoreMapping:e}}yield new Jt.FI({event:{case:"start",value:new Jt.tD({sandboxPolicy:Mn(s)})}});const p=t.timeoutBehavior===Jt._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=s?{perRepo:s}:void 0,v=this.coreExecutor.execute(e,{command:o,workingDirectory:n,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()),i));const S=p?new zb(v[Symbol.asyncIterator](),i):null;let k,E,C,x="",_=!1;const P=t.toolCallId&&S?{requestBackground:()=>{if(S.requestBackground())return C=C??this.backgroundShellManager.generateShellId(),new Jt.W4({result:{case:"success",value:new Jt.QR({shellId:C,pid:E,command:o,workingDirectory:a,msToWait:Vp(Date.now()-l),backgroundReason:Jt.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&P&&this.activeForegroundExecutions.set(t.toolCallId,P);const R=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===P&&this.activeForegroundExecutions.delete(t.toolCallId)};let I;S&&e.signal&&e.signal.addEventListener("abort",(()=>{S.backgroundRequested||(m.abort(),S.abort())}),{once:!0});const T=t.hardTimeout;void 0!==T&&T>0&&(I=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 Jt.FI({event:{case:"stdout",value:new Jt.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new Jt.FI({event:{case:"stderr",value:new Jt.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?Jt.Lv.USER_ABORT:S?.timedOut||m.signal.aborted?Jt.Lv.TIMEOUT:Jt.Lv.USER_ABORT),yield new Jt.FI({event:{case:"exit",value:new Jt.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:o,localExecutionTimeMs:Vp(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof en.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return Bb.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new Jt.FI({event:{case:"sandboxUnsupported",value:new Jt.rI({command:o,workingDirectory:a,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(b),S?.backgroundRequested||clearTimeout(I),R()}if(S?.backgroundRequested&&!_){const r=C??this.backgroundShellManager.generateShellId();C=r;const s=S.backgroundReasonValue===Jt.Jg.USER_REQUEST?Jt.Jg.USER_REQUEST:Jt.Jg.TIMEOUT,n=s===Jt.Jg.USER_REQUEST?Date.now()-l:i;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:a,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}),yield new Jt.FI({event:{case:"backgrounded",value:new Jt.Y9({shellId:r,command:o,workingDirectory:a,pid:E,msToWait:w?n:void 0,reason:s})}})}else e.signal?.aborted&&void 0!==S?.stopReasonValue?(clearTimeout(I),yield new Jt.FI({event:{case:"exit",value:new Jt.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:Jt.Lv.USER_ABORT})}})):clearTimeout(I)}catch(e){r.error=e,r.hasError=!0}finally{Ub(r)}}}var Hb=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class qb{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new Hb.M({allowlisted:r})}}var Gb=r("node:constants");class Vb extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}var Jb=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Kb=(0,d.h)("LocalWriteExecutor"),Zb=async(e,t,r,o)=>{const s=setTimeout((()=>{Kb.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await o()}finally{clearTimeout(s)}};class Qb{constructor(e,t,r,{workspacePaths:o,workspacePath:s,worktreeMainPath:n,onWriteForAiTracking:i,writeFileMutationGuard:a}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=o,this.workspacePath=s,this.worktreeMainPath=n,this.onWriteForAiTracking=i,this.writeFileMutationGuard=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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,s=t.path,n=t.fileText,a=t.fileBytes.length>0?t.fileBytes:void 0,l=(0,ln.o1)(s,this.workspacePath),u=Vy(l,["assets","agent-tools","swarm-agents"]);if((0,ln.fl)({targetPath:l,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Kt.v3({result:{case:"error",value:new Kt.QM({path:l,error:ln.PS})}});let d,h=!1;try{(await(0,Qs.stat)(l)).size<=Ap?d=await Zb(o,"readText before write",3e3,(()=>hi(l,t.encodingHint))):h=!0}catch{}const p=(await Zy(l)).resolvedPath,f=(".cursorignore"===(l.split(i.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await Zb(o,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(o,p,n)));if(f){const e=await Zb(o,"handleBlockReason",3e3,(()=>Wi(f,{onNeedsApproval:async(e,r)=>{const o="fileEdit"!==r?.type||r.isNewFile,s="fileEdit"===r?.type?r.diffString:n,i="fileEdit"===r?.type?r.blockReason:void 0,a=await this.pendingDecisionProvider.requestApproval({type:Mp.Write,details:{path:l,reason:e,isNewFile:o,diffString:s,before:d,after:n,blockReason:i},toolCallId:t.toolCallId});return a.approved?null:new Kt.v3({result:{case:"rejected",value:new Kt.en({path:l,reason:a.reason||""})}})},onUserRejected:e=>new Kt.v3({result:{case:"rejected",value:new Kt.en({path:l,reason:e||""})}}),onPermissionDenied:(e,t)=>new Kt.v3({result:{case:"permissionDenied",value:new Kt.U7({path:l,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const m=(0,i.dirname)(p);try{await Zb(o,"mkdir",3e3,(()=>(0,Qs.mkdir)(m,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new Kt.v3({result:{case:"permissionDenied",value:new Kt.U7({path:l,directory:m,operation:"create_directory",error:"Permission denied"})}}):new Kt.v3({result:{case:"error",value:new Kt.QM({path:l,error:e.message})}})}let g,w;if(void 0!==a)g=a,w=0;else{const e=await Zb(o,"getBufferForWrite",3e3,(()=>pi(p,n,this.workspacePath,t.encodingHint)));g=e.buffer,w=e.lines}const y=()=>Zb(o,"writeFile",3e3,(async()=>{let e;await async function(e,t,r){let o;try{o=await(0,Qs.open)(e,function(){const e=Ys.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 Ys.constants.O_NOFOLLOW}(t))throw new Vb(e,`Refusing to write through a symlink at ${e}`);throw t}try{let s;try{s=(0,Ys.realpathSync)(e)}catch{throw new Vb(e,`Cannot verify canonical path before writing: ${e}`)}if(s!==e)throw new Vb(e,`Refusing write: ${e} now resolves through a symlinked parent to ${s}`);if(!(await o.stat()).isFile())throw new Vb(e,`Refusing to write to non-regular file at ${e}`);await o.truncate(0);const n=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let i=0;for(;i<n.length;){const{bytesWritten:e}=await o.write(n,i,n.length-i,i);if(0===e)break;i+=e}r?.flush&&await o.sync()}finally{await o.close()}}(p,g,{flush:!0});try{e=await(0,Qs.open)((0,i.dirname)(p),Gb.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}));let v,b=!1;const S=async()=>{try{await y()}catch(e){throw v=e,b=!0,e}};try{void 0===this.writeFileMutationGuard?await y():await this.writeFileMutationGuard.runExclusive(p,S)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!b||e!==v))return new Kt.v3({result:{case:"error",value:new Kt.QM({path:l,error:e instanceof Error?e.message:String(e)})}});if(e instanceof Vb)return new Kt.v3({result:{case:"permissionDenied",value:new Kt.U7({path:l,directory:"",operation:"create_file",error:e.message})}});const t=e.code;return"EACCES"===t||"EPERM"===t?new Kt.v3({result:{case:"permissionDenied",value:new Kt.U7({path:l,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new Kt.v3({result:{case:"noSpace",value:new Kt.bM({path:l})}}):"EDQUOT"===t?new Kt.v3({result:{case:"error",value:new Kt.QM({path:l,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 Kt.v3({result:{case:"error",value:new Kt.QM({path:l,error:e.message})}})}if(this.fileChangeTracker&&void 0===a&&!u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(l,d,n,e)}if(this.onWriteForAiTracking&&void 0===a&&!u){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:l,beforeContent:d,afterContent:n,metadata:e})}catch(e){Kb.warn(o,"onWriteForAiTracking failed (write succeeded)",{path:l,error:e instanceof Error?e.message:String(e)})}}const k=g.byteLength;let E;if(t.returnFileContentAfterWrite)try{E=await Zb(o,"readText after write",3e3,(()=>hi(l,t.encodingHint)))}catch{}return new Kt.v3({result:{case:"success",value:new Kt.j6({path:l,linesCreated:w,fileSize:k,...void 0!==E&&{fileContentAfterWrite:E}})}})}catch(e){r.error=e,r.hasError=!0}finally{Jb(r)}}}const Xb=(0,d.h)("local-exec:provider");class Yb extends U{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}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,i.join)(e,".cursor/sandbox.json");try{const r=(0,Ys.readFileSync)(t,"utf-8"),o=JSON.parse(r),s=(0,en.$6)(o);return(0,en.l7)(s,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 s=this.terminalExecutor??(0,en.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,i.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new $b(s,t??(0,n.homedir)(),this.projectDir,e.shellOutputBackpressureOptions,e.shellExtraEnvProvider);e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Lb(c,this.askpassConfig)),this.shellManager&&(c=new Fb(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new kb(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(Zt,Vw(l)),this.register(Ft,Vw(new Yg(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=e.overrideWriteExecutor??new Qb(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard});this.register(Xt,Vw(u)),this.register(ee,Vw(new Op(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking))),this.register(oe,Vw(new Lp)),this.register(se,new by);const d=this.mcpStateAccessor??new gb(this.mcpLease),h=e.overrideGrepExecutor??new Ug(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:d,permissionsService:this.permissionsService});this.register(ne,Vw(h));const p=e.overrideReadExecutor??new qv(this.permissionsService,a,{mcpStateAccessor:d,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}),f=new Et(Vw(p));this.register(Ct,f),e.registerRedactedReadExecutor&&this.register(xt,f);const m=e.overrideLsExecutor??new Gg(this.permissionsService,this.ignoreService,a);this.register(Xe,Vw(m)),this.register(Ht,Vw(new $w(this.permissionsService,a))),void 0!==l&&this.register(Lt,Vw(new uw(l))),this.register(Ut,Vw(new kw(this.permissionsService,u,a))),this.register(qt,Vw(new Uw(u,a))),this.register(zt,Vw(new Aw(this.permissionsService,a))),this.register(Bt,Vw(new _w(this.permissionsService,a))),this.register(Wt,Vw(new Ow(this.permissionsService,a))),this.register(te,Vw(new oy(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(X,Vw(new Zw(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(lt,Vw(new $t(new wg(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),(()=>this.get(Ct))))),this.register(ut,Vw(new yg(this.mcpLease,e.ensureMcpServersLoaded))),this.register(dt,Vw(new vg(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(ht,Vw(new yb(d,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const g=Vw(this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(d,t,e));this.register(cr,{execute:async(t,r,o)=>{const s=await g.execute(t,r,o);if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const n=s.clone();if("success"!==n.result.case)return s;const i=n.result.value.requestContext;if(void 0===i)return n;const a=await d.getState(t),c=hb(a,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(i.tools=c.tools,i.mcpInstructions=c.mcpInstructions,i.mcpMetaToolOptions=this.mcpMetaToolEnabled?pb(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.getMountedAgentStores&&void 0!==i.env)try{const r=await e.getMountedAgentStores(t);i.env.mountedAgentStores=r.map((e=>e.clone()))}catch{i.env.mountedAgentStores=[],Xb.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return n}}),this.backgroundShellExecutor=new aa(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(J,Vw(this.backgroundShellExecutor));const w=new Wb(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(Qt,function(e,t){const r=new Xs.q({max:10,ttl:t?.ttl});return{async*execute(t,o,s){if(!s?.execId)return void(yield*e.execute(t,o,s));const n=Gw(s.execId,o),i=r.get(n);if(i)return void(yield*i.fork());const a=e.execute(t,o,s),c=new qw(a);r.set(n,c),yield*c.fork()}}}(w)),void 0!==e.agentStoreConflictDrainer&&this.register(G,new Ww(e.agentStoreConflictDrainer)),this.register(ur,new Cb(this.permissionsService)),this.register(pt,new ky(this.permissionsService)),this.register(Vr,new qb(this.permissionsService));const y=new xb(w);this.register(dr,Vw(y));const v=!1===e.enableWriteBackgroundShellStdin?new Hw((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new Hw(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(K,Vw(v)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(Y,Vw(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new Yv({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(ar,Vw(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const o=new vb(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,ln.yn)(t,(0,n.homedir)()),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});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=o,this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{o.rebuildAllCaches()}))),o}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.rebuildRequestContextOnRulesChange&&(this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function eS(e){return e.replace(/\\/g,"/")}function tS(e,t){for(const r of t){const t=eS(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var rS;function oS(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return rS.Plugin;const o=eS(e.fullPath);return tS(o,r.builtinDirs)?rS.Builtin:eh(e.fullPath,t).inAgentStore?rS.UserStore:tS(o,r.userDirs)?rS.UserHome:(tS(o,r.workspaceDirs),rS.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"}(rS||(rS={}));var sS=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 nS=(0,Gn.debuglog)("merged-agent-skills"),iS=(0,d.h)("merged-agent-skills");class aS{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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),o=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(nS("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),s=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return iS.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}}},[n,a]=await Promise.all([Promise.all(o),s()]),l=n.flat(),u=this.getPromptSortContext?.(),d=rh(l,u??Xd);let h=d;return a.ok?a.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,a.paths)))):h=d.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(cS));var t})),void 0!==u?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[Fd(e.userHomeDirectory).dirPath],r=Bd(e.userHomeDirectory,!0).map((e=>e.dirPath)),o=[];for(const t of e.workspacePaths){o.push((0,i.join)(t,".cursor","rules"));for(const e of Ud(t,!0))o.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:o}}(t),o=e.map(((e,o)=>({skill:e,index:o,tier:oS(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{sS(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()}),aS.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()}}aS.CHANGE_COALESCE_MS=1500;const cS=`/${Od.configDir}/${Od.subdir}/`,lS=(0,d.h)("skill-sync-manifest"),uS=".sync-manifest.json";async function dS(e,t){try{const r=await(0,Qs.readFile)((0,i.join)(e,uS),"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:(lS.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||lS.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function hS(e,t,r){e.skills[t]={lastSyncedAt:r}}function pS(e,t){delete e.skills[t]}var fS=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 mS=(0,d.h)("builtin-skills-sync");function gS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wS(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||i.posix.isAbsolute(t)||i.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===i.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function yS(e){const t=Su(e.content),r=gS(t.data)?t.data:{};return ku(`${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={...gS(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 vS(e,t,r){const o=(0,i.join)(t,r.id),s=(0,i.join)(o,"SKILL.md"),n=r.fileContent,a=Object.keys(r.resources),c=await bS(o);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",n],...Object.entries(r.resources)]),s=new Set(["SKILL.md",...c]);if(s.size===e.size&&[...e.keys()].every((e=>s.has(e)))){let t=!0;for(const[r,s]of e)try{if(await(0,Qs.readFile)((0,i.join)(o,...r.split("/")),"utf-8")!==s){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,i.join)(e,t.id),o=await(0,Qs.mkdtemp)((0,i.join)(e,`.${t.id}-staging-`)),s=`${o}-backup`;let n=!1;try{await(0,Qs.writeFile)((0,i.join)(o,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,i.join)(o,...e.split("/"));await(0,Qs.mkdir)((0,i.dirname)(t),{recursive:!0}),await(0,Qs.writeFile)(t,r,"utf-8")}try{await(0,Qs.rename)(r,s),n=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==e.code)throw e}try{await(0,Qs.rename)(o,r)}catch(e){throw n&&(await(0,Qs.rename)(s,r),n=!1),e}n&&(await(0,Qs.rm)(s,{recursive:!0,force:!0}),n=!1)}finally{await(0,Qs.rm)(o,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Qs.readFile)(s,"utf-8")===n)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||mS.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Qs.mkdir)(o,{recursive:!0}),await(0,Qs.writeFile)(s,n,"utf-8"),!0}async function bS(e,t=""){const r=t?(0,i.join)(e,...t.split("/")):e;let o;try{o=await(0,Qs.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===e.code)return[];throw e}const s=[];for(const r of o){const o=t?`${t}/${r.name}`:r.name;r.isDirectory()?s.push(...await bS(e,o)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==o&&s.push(o)}return s}async function SS(e,t){try{return(await(0,Qs.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||mS.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function kS(e,t={}){const r={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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),l=Fd((0,n.homedir)()).dirPath;await(0,Qs.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([dS(l,s),SS(s,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,o){try{const s=await Promise.all(r.map((async e=>{const r=(0,i.join)(t,e),[s,n]=await Promise.all([ES((0,i.join)(r,"SKILL.md")),"canvas"===e?ES((0,i.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:s,has_sdk_dir:n,last_synced_at:o.skills[e]?.lastSyncedAt??null}})));mS.info(e,"managed_skills.startup_inventory",{skills_on_disk:s,manifest_present:Object.keys(o.skills).length>0})}catch(t){mS.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(s,l,d,u),u.lastInventoryAt=a);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):mS.warn(s,"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?a-r.lastSyncedAt:0,n=void 0!==r&&o>2592e5,c=void 0!==t&&yc(t,"local"),h=void 0!==t&&!c,f=void 0!==r||d.includes(e);if(t&&!1!==t.enabled&&c)wS(t),await vS(s,l,{id:e,fileContent:yS(t),resources:t.resources??{}})?m++:g++,hS(u,e,a);else if(!1===t?.enabled||h||n){const o=!1===t?.enabled?"enabled_false":h?"environment_ineligible":"grace_expired";await(0,Qs.rm)((0,i.join)(l,e),{recursive:!0,force:!0}),pS(u,e),f&&(w.push(e),mS.info(s,"managed_skills.removed",{skill_id:e,reason:o,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||hS(u,e,a)}catch(t){mS.warn(s,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,i.join)(e,".sync-manifest.json.tmp"),o=(0,i.join)(e,uS);await(0,Qs.mkdir)(e,{recursive:!0}),await(0,Qs.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,Qs.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)?mS.warn(s,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):mS.debug(s,"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{fS(r)}var o}async function ES(e){try{return await(0,Qs.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const CS=(0,d.h)("managed-skills-sync");function xS(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 _S{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,s=r.identifier.sourceInfo.name,n="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...Dc(i,e,o,s,n,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=xS(o.url);r.has(e)||(r.add(e),t.push(o))}return t}(t)}}var PS=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 RS(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class IS{constructor(e,t,r,o,s,n){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=o,this.localPluginVariablesLookup=n,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=s??ua,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):[],s=[...e.plugins,...o],n=new Set(s.map((e=>e.installPath))),i=r.filter((e=>!n.has(e.installPath)));return this.plugins=[...s,...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(pd));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(pd(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=RS(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,s=t=>o(t)?.pluginDbId===e.pluginDbId,n=(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 dd({...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=>s(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(s);if(void 0!==d&&void 0===a){const e=o(d);a=d,c=t.failures.find((t=>n(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=>!n(e,t))),r]}return}const l=this.plugins.findIndex(s);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=>!n(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,i.resolve)(e),o=await(0,Qs.realpath)(r);if(!(await(0,Qs.stat)(o)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${o}`);const s=n.homedir();if(o.split(i.sep).filter(Boolean).length<3||o===s||"/"===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,i.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,i.resolve)(e);let s;try{s=await(0,Qs.realpath)(o)}catch{const e=this._extensionPluginOriginalPaths.get(t);s=e?.get(o)??o}const n=r.delete(s);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):n&&this._forgetExtensionPluginOriginalPath(t,s),n&&this.pluginLogger.log("info",`Unregistered extension plugin: ${s} (extension: ${t})`),n}async _loadExtensionPluginContent(e,t){const r=(0,i.basename)(e),o={name:r,localPath:e,extensionId:t},s=await ad(e,r,{name:r,version:"0.0.0"});return s.displayName&&(o.name=s.displayName),{identifier:{source:"extension",sourceInfo:o},installPath:e,...void 0!==s.displayName&&{displayName:s.displayName},...void 0!==s.description&&{description:s.description},...void 0!==s.authorName&&{authorName:s.authorName},...void 0!==s.logoUrl&&{logoUrl:s.logoUrl},...void 0!==s.version&&{version:s.version},...void 0!==s.homepage&&{homepage:s.homepage},...void 0!==s.repository&&{repository:s.repository},skills:s.skills,rules:s.rules,agents:s.agents,commands:s.commands,mcpConfig:s.mcpConfig??void 0,capabilities:s.capabilities,hooks:s.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),s=this._extensionPlugins.get(o);s&&s.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${e}`);const s=this._extensionPlugins.get(o),n=s?.get(r);n&&t.push(n)}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,re.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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,c.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})},s=this.getSettings(),n=RS(this.marketplaceOptions,this.userHomeDirectory),a=s.importThirdPartyPlugins,l=s.loadUserLocalPlugins??!0,u=s.loadCursorFirstParty??n.length>0;if(!a&&!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??ua,o=performance.now(),s=t.loadClaude??!0,n=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;s&&l.push(ud(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>dd({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),n&&l.push(async function(e={}){const t=e.log??ua,r=performance.now(),o=e.userHomeDir??process.env.HOME;if(!o)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const s=(0,i.join)(o,".cursor","plugins","local");let n;try{n=await(0,Qs.readdir)(s,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${s} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Qs.realpath)(s).catch((()=>(0,i.resolve)(s))),c=[];for(const r of n){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const o=(0,i.join)(s,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Qs.realpath)(o)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{$l(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${s}`);continue}}if(!(await(0,Qs.stat)(o)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const n=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 ad(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()-n).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,Qs.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=hd(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=>hd(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=${s}, userLocal=${n}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:l,loadCursorFirstParty:u&&n.length>0,marketplaceSources:n.length>0?n.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{PS(e)}}}var TS=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function AS({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||My(t.url,o)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class MS{constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new TS.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new TS.aYW({}))}}function DS(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 OS{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 NS{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settings=new OS((()=>this.fetchSettings())),this.teamRepos=new OS((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new OS((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings()}invalidateCache(){this.settings.invalidate(),this.defaultAllowlist.invalidate()}async fetchSettings(){try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,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,ef.YaX)(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const o=await this.getMcpNetworkControlsConfig(e),s=void 0===e.url?{allowed:!0}:(0,ef.MEY)(e.url,o);if(!s.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:s.message};const n=AS({failOpenWhenEmpty:!1,server:e,settings:t});if(n.blocked)return n}if(!o){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?AS({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 getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()){const o="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,ef._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,Dy.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===TS.h0i.WORKSPACE?"workspace":"system");var o;return{sandboxingDisabled:t?.sandboxing===TS.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===TS._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===TS.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:DS(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 jS=new zp,$S={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Mi((0,re.q6)(),jS,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?Zs(r):void 0),workspaceRoots:o,createdAt:new Date}}},FS=(0,d.h)("ControlledConversationActionManager");class LS{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const o=this.abortController,s=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new mr.QFf({action:{case:"cancelAction",value:new mr.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{o.abort(e);for(const e of s)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 f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new mr.QFf({action:{case:"userMessageAction",value:new mr.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){this.runActive=!0;try{for await(const r of this.clientStream)try{await t.write(r)}catch(t){FS.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.runActive=!1}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}let US={warn:console.warn.bind(console),error:console.error.bind(console)};const BS=new ca.AsyncLocalStorage;function zS(){return BS.getStore()??US}const WS={warn(...e){zS().warn(...e)},error(...e){zS().error(...e)}},HS="x-blob-encryption-key";function qS(e,t){const r={...t};return void 0!==r[HS]||(0,Yr.TU)(e)&&(r[HS]=e),r}const GS=new Map;function VS(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function JS(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 KS(e){return new mr.QFf({action:{case:"userMessageAction",value:new mr.Vtf({userMessage:new mr.RGk({text:e})})}})}function ZS(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function QS(e){e?.catch((e=>{WS.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}var XS=r("../mcp-core/dist/oauth/resolved-oauth-client-id.js"),YS=r("../mcp-core/dist/oauth/rest-mcp-provider-metadata.js");const ek=new Set(["mcp.slack.com","setup.shopify.com"]);class tk{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 s;try{s=new URL(e).hostname}catch{return t}if(!ek.has(s)&&void 0===(0,_f.Di)(e))return t;let n=await r.resolve(e);if(!n&&void 0!==(0,_f.Di)(e)){const t=(await(0,YS.Ez)(e,o))?.clientId;void 0!==t&&(n={CLIENT_ID:t})}return n?t?void 0===(0,XS.qF)(t.CLIENT_ID)?{...n,...t,CLIENT_ID:n.CLIENT_ID}:{...n,...t}:n: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 rk{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 ok{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class sk{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 s=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),n={};for(let e=0;e<s.length;e++){const t=s[e],r=this.loaders[e].prefix,o=t.getClients();for(const[e,t]of Object.entries(o)){const o=r+e;o in n||(n[o]=t)}}return new Xf(n)}async loadClient(e,t,r=!1){for(const{loader:o,prefix:s}of this.loaders)if(t.startsWith(s)){t=t.slice(s.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 nk{constructor(e,t,r,o,s=!1,a,c,l=i.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=i.join(t,".cursor","mcp.json"),o=`project-${e}-${i.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 i=s?"":n,d=new rk(t,i),h=new ok(o,i),p=e===l,m=[new uf,...p?[]:[new nf(h)],new pm(r),...c?[new sf(c)]:[]],g=u?new dm(new tk(new um(e),u),d,m,{authRedirectUrlGenerator:a}):new fm(e,d,m,a);f.push({prefix:i,loader:g})}this.loader=new sk(f)}static init(e,t,r,o=!1,s,n){const a=new gm(i.join(r,"mcp-auth.json"));(async function(e){await(0,Qs.rm)(i.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=o?{isServerApproved:()=>Promise.resolve(!0)}:new af(i.join(r,"mcp-approvals.json"),t);return new nk(t,a,e,c,!0,void 0,s,void 0,n)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const ik="cursor-plugins/local";function ak(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===ik)return r}class ck extends Qf{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class lk{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Qs.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,Qs.mkdir)((0,i.dirname)(this.storagePath),{recursive:!0}),await(0,Qs.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class uk{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return WS.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&mk(r))continue;const e=mm(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}}):WS.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 dk{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:fk(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function hk(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(s){const a=s.workspaceState,c=a.projectRoot??a.workingDirectory,l=a.projectDirectory;if(!c||!l)return new Zf;const u=new lk((0,i.join)(l,"mcp-disabled.json")),d=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:o,ignoreApprovals:s,disabledStore:a,includeProjectMcp:c,includeUserMcp:l}=e;if(c&&l)return nk.init(t,r,o,s,a);if(!c&&!l)return;const u=new gm((0,i.join)(o,"mcp-auth.json")),d=s?{isServerApproved:()=>Promise.resolve(!0)}:new af((0,i.join)(o,"mcp-approvals.json"),r),h=[new uf,new nf(d),new pm(t),new sf(a)],p=[];return c&&p.push({prefix:"",loader:new fm((0,i.join)(r,".cursor","mcp.json"),u,h)}),l&&p.push({prefix:"",loader:new fm((0,i.join)((0,n.homedir)(),".cursor","mcp.json"),u,h)}),pk(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 gm((0,i.join)(l,"mcp-auth.json")),r=[new uf,new pm(t)];h.push({prefix:"",loader:new dm(new dk(p),e,r)})}const f=ak(s.services.pluginBootstrapOutputs);if(f&&(e.includePluginMcp??1)){const e=new af((0,i.join)(l,"mcp-approvals.json"),c),s=new gm((0,i.join)(l,"mcp-auth.json")),n=[new uf];r||n.push(new nf(e)),n.push(new pm(t),new sf(u));const a=new _S(f.pluginsService),d=new dm(new uk(a,o),s,n);h.push({prefix:"",loader:d})}if(d&&h.push({prefix:"",loader:d}),0===h.length)return new Zf;const m=pk(h),g=await m.load(e.initializationCtx??(0,re.q6)(),e.cache);return new ck(g)}}}function pk(e){return 1===e.length?e[0].loader:new sk(e)}function fk(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function mk(e){return"claude-plugin"===e.pluginSource}function gk(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function wk(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class yk{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>yk.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===Xt.symbol||e===ee.symbol||e===qt.symbol||e===Ut.symbol?{kind:"path"}:e===Zt.symbol||e===Qt.symbol||e===J.symbol||e===Lt.symbol?{kind:"exposed"}:void 0}(e),o=this.resolveDrain,s=this.wake,n=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==s)try{if("path"===r.kind){const r=wk(e);void 0!==r&&(s.wakeForWrittenPath(r),l?.(r,t))}else s.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 s=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==s){const e=h.get(s);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(s);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const n=async t=>{const r=o(e);let n=[];try{const e=await r.peek();if(n=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==s&&d(s,e.carriers),e.carriers;n.length>0&&r.ack(n);const o=[];return void 0!==s&&d(s,o),o}catch{return n.length>0&&r.release(n),[]}};if(void 0===s)return await n(r);const i=n(r);p.set(s,i);try{return await i}finally{p.get(s)===i&&p.delete(s)}};return new Proxy(t,{get:(t,o,s)=>"execute"!==o?Reflect.get(t,o,s):(o,s,l)=>{const d=t.execute.call(t,o,s,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,n=!1;try{for await(const r of d)if(e===Qt.symbol&&gk(r)){if(!t){u(s,o);const e=await f(o,l);t=!0,e.length>0&&(yield new Jt.FI({event:{case:"hookContext",value:new Jt.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;n=!0}catch(e){throw r=!0,e}finally{u(s,o),t||r||!n||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(s,o),e===Xt.symbol&&!0===n?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,o){const s=e=>{try{o.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const n=wk(t);if(void 0===n)return;if(!(o.timeoutMs>0))return void s({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(n).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,vt.cb)(o.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&s({durationMs:Date.now()-i,outcome:c})}(i,s,r,{timeoutMs:a(),onWriteBarrier:c}),await f(o,l)),t}catch(e){throw u(s,o),e}})():(u(s,o),d);var h}})}}yk.CARRIERS_BY_EXEC_ID_MAX=32,Error,qc.execFileSync,new Map,Ys.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 vk=["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"];function bk(e){return function(e,t){let r=e;for(const e of t){const t=new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi");r=r.replace(t,"")}return r.replace(/\n{3,}/g,"\n\n").trim()}(e,vk)}function Sk(e){const t=(0,Js.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,Js.sh)(e.parentConversationId);return`${Js.O2}/${r}/subagents/${t}.${e.ext}`}return`${Js.O2}/${t}/${t}.${e.ext}`}function kk(e){const t=(0,Js.sh)(e.conversationId);return`${Js.O2}/${t}.${e.ext}`}function Ek(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,o=[],s=e=>{o.includes(e)||o.push(e)};for(const o of t)s(Sk({conversationId:e.conversationId,ext:o,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&s(Sk({conversationId:e.conversationId,ext:o,kind:"primary"})),r&&s(kk({conversationId:e.conversationId,ext:o}));return o}var Ck;(()=>{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"}(Ck||(Ck={}));var xk=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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},_k=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Pk(e){switch(e){case mr.xyI.AGENT:return"agent";case mr.xyI.ASK:return"ask";case mr.xyI.PLAN:return"plan";case mr.xyI.DEBUG:return"debug";case mr.xyI.TRIAGE:return"triage";case mr.xyI.PROJECT:return"project";case mr.xyI.MULTITASK:return"multitask";case mr.xyI.CUSTOM:return"custom";case mr.xyI.UNSPECIFIED:default:return"agent"}}function Rk(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 Ik(e,t){return t&&"object"==typeof t&&"Uint8Array"===t.__type&&"string"==typeof t.hex?function(e){return`[Binary data omitted from transcript: ${e} bytes]`}(t.hex.length/2):t}const Tk=new TextEncoder,Ak=new TextDecoder,Mk=new class{serialize(e){const t=JSON.stringify(e,Rk);return Tk.encode(t)}deserialize(e){const t=Ak.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Ik):JSON.parse(t)}};function Dk(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}async function Ok(e,t,r){const o=[];let s=0,n=0,i=0,a=0,c=0,l=0,u=0;for(const h of r){const r=await t.getBlob(e,h);if(r){if(r.length>5e6){o.push((void 0,{role:"assistant",content:`[Oversize transcript blob omitted: ${d=r.length,`${(d/1e6).toFixed(1)} MB`}]`})),c++,l+=r.length,u=Math.max(u,r.length);continue}try{const e=performance.now(),t=Mk.deserialize(r),c=performance.now()-e;o.push(t),s++,n+=r.length,i=Math.max(i,r.length),a+=c}catch{}}}var d;return{messages:o,hydratedBlobCount:s,hydratedBlobBytes:n,largestHydratedBlobBytes:i,totalDeserializeDurationMs:a,omittedOversizeBlobCount:c,omittedOversizeBlobBytes:l,largestOmittedOversizeBlobBytes:u}}function Nk(e,t){switch(e.type){case"text":return t?jk(e.text):e.text;case"image":return"[Image]";case"file":return e.filename?`[File: ${e.filename}]`:"[File]";case"reasoning":return`[Thinking] ${e.text}`;case"redacted-reasoning":return"[Thinking]";case"tool-call":return`[Tool call] ${e.toolName}${function(e){if(null==e)return"";if("object"!=typeof e)return String(e);const t=e,r=Object.entries(t);return 0===r.length?"":`\n${r.map((([e,t])=>{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function jk(e){return bk(e)}function $k(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function Fk(e,t,r){if(void 0===e)return"";if("string"==typeof e){const o=t?jk(e):e;return r?$k(o):o}return e.map((e=>{if(r&&"text"===e.type){const r=$k(t?jk(e.text):e.text);return Nk({...e,text:r},!1)}return Nk(e,t)})).filter(Boolean).join("\n")}function Lk(e,t){const r={role:e.role},o=e.content;if("string"==typeof o){const s=t?jk(o):o,n="assistant"===e.role?$k(s):s;n.trim()&&(r.text=n)}else if(Array.isArray(o)){const s=[],n=[],i=[];let a;for(const r of o)switch(r.type){case"text":{const o=t?jk(r.text):r.text,n="assistant"===e.role?$k(o):o;n.trim()&&s.push(n);break}case"reasoning":r.text.trim()&&n.push(r.text);break;case"redacted-reasoning":n.push("[REDACTED]");break;case"image":s.push("[Image]");break;case"file":s.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}}s.length>0&&(r.text=s.join("\n")),n.length>0&&(r.thinking=n.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function Uk(e){return e.endsWith("\n")?e:`${e}\n`}function Bk(e){const{turnEnded:t}=e,r=[],o={},s=[];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,s.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:o,jsonlLines:s}}function zk(e){if("system"===e.role||Dk(e))return;const t=Lk(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 s={role:e.role,message:{content:r}};return JSON.stringify(s)}class Wk{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,fallbackToFullWriteOnIncrementalFailure:o.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=Sk({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,o={}){const s={stack:[],error:void 0,hasError:!1};try{const n=xk(s,(0,c.VI)(e.withName("writeFromState")),!1);try{const e=await async function(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=xk(o,(0,c.VI)(e.withName("hydrateSummaryArchives")),!1);let n=0;const i=(0,c.OA)(s.ctx),a=[];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=>{n++;const r=await t.getBlob(i,e);if(r)try{const e=mr.Anz.fromBinary(r);return n+=e.summarizedMessages.length,await Ok(i,t,e.summarizedMessages)}catch{}return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}})));for(const e of g)a.push(...e.messages),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);s.span.setAttribute("getBlobCount",n),s.span.setAttribute("hydratedBlobCount",l),s.span.setAttribute("hydratedBlobBytes",u),s.span.setAttribute("largestHydratedBlobBytes",d),s.span.setAttribute("totalDeserializeDurationMs",h),s.span.setAttribute("omittedOversizeBlobCount",p),s.span.setAttribute("omittedOversizeBlobBytes",f),s.span.setAttribute("largestOmittedOversizeBlobBytes",m);const w=xk(o,(0,c.VI)(e.withName("hydratePromptMessages")),!1),y=await Ok(i,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((e=>"system"!==e.role&&!Dk(e)));return a.push(...v),a}catch(e){o.error=e,o.hasError=!0}finally{_k(o)}}(n.ctx,this.blobStore,t),{overviewFactory:s}=o,i=Bk(o);if(0===e.length&&0===i.jsonlLines.length)return!0;let a;if((this.options.writeText||s)&&(a=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,o="assistant"===e.role,s=Fk(e.content,t,o);s.trim()&&("tool"===e.role?r.push(s):r.push(`${e.role}:\n${s}`))}return r.join("\n\n")}(e)),this.options.writeText){const e=a??"",t=i.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${i.textSuffixes.join("\n")}`:i.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const o=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=Lk(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(e);if(o||i.jsonlLines.length>0){const e={mode:Pk(t.mode),messages:o?JSON.parse(o):[],...i.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(e,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=zk(e);t&&r.push(t)}return r.join("\n")}(e);let o=[t,...i.jsonlLines].filter((e=>e.length>0)).join("\n");if(o&&s&&a?.trim())try{const e=(await s(a)).trim();e&&(o=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(o,e))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}o&&await this.writeFile(this.resolveFilePath(r,"jsonl"),Uk(o))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){s.error=e,s.hasError=!0}finally{_k(s)}}async writeFromStateIncremental(e,t,r,o,s={}){const n={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=Bk(s),l=a.jsonlLines.length>0;if(i===o&&!l&&!s.overviewFactory)return i;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&o>0&&i>=o&&(i>o||l))||s.overviewFactory)return await this.writeFromStateFull(e,t,r,s)?i:0;const d=xk(n,(0,c.VI)(e.withName("writeFromStateIncremental")),!1);if(i===o&&l)try{return await u(this.resolveFilePath(r,"jsonl"),Uk(a.jsonlLines.join("\n"))),i}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,s)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(o),s=await Ok(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",s.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",s.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",s.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",s.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",s.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",s.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",s.largestOmittedOversizeBlobBytes);const n=[];for(const e of s.messages){const t=zk(e);t&&n.push(t)}if(n.push(...a.jsonlLines),n.length>0){const e=Uk(n.join("\n"));await u(this.resolveFilePath(r,"jsonl"),e)}return i}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,s)?i:0:0}}catch(e){n.error=e,n.hasError=!0}finally{_k(n)}}}class Hk extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class qk extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const Gk="To view or modify configured hooks, go to Cursor Settings > Hooks.",Vk="Agent note: Do not suggest workarounds to the blocked tool.";function Jk(e){return e.includes(Vk)?e:`${e}\n\n${Vk}`}function Kk(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function Zk(e,t){return Jk(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${Gk}`)}function Qk(e){return function(e){return e instanceof Hk}(e)||function(e){return e instanceof qk}(e)}function Xk(e){try{return(0,Ys.statSync)(e).isFile()}catch{return!1}}class Yk{constructor(e,t,r,o,s,n,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=o,this.promptHookClient=s,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.configReadyPromises=[],this.config=e,n&&this.addConfigReadyPromise(n)}addConfigReadyPromise(e){this.configReadyPromises.push(e.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,Nc.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}async getTranscriptPathIfExists(e){try{const t=(0,Js.Rv)((0,n.homedir)(),this.workspacePath),r=Ek({conversationId:e,kind:"primary"}).map((e=>(0,i.join)(t,e)));for(const e of r)try{return await(0,Qs.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,Js.Rv)((0,n.homedir)(),this.workspacePath),o=Ek({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,i.join)(e,t)));for(const e of o)try{return await(0,Qs.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?ge(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?ge(o,t):o).some((e=>_e(e)&&!0===e.failClosed)))return!0}return!1}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:s}=e,n=this.resolveUserEmail({conversation_id:o,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...n&&{CURSOR_USER_EMAIL:n},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...s}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const o=r.loop_count,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await Promise.all(this.configReadyPromises);const o=function(e){return Te.includes(e)}(e),s=t,n=o?null:s.conversation_id?await this.getTranscriptPathIfExists(s.conversation_id):null;let i;if(e===ie.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:s.session_id??s.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(s),...!o&&{transcript_path:n},...e===ie.subagentStop&&{agent_transcript_path:i??null}},l=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return t.command||void 0;case"beforeMCPExecution":case"afterMCPExecution":{const e=t;return e.tool_name?`MCP:${e.tool_name}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return t.subagent_type||void 0;case"preToolUse":case"postToolUse":case"postToolUseFailure":return t.tool_name||void 0;default:return}}(e,c),u=[],d=(e,t)=>{if(!e)return;const o=ge(e,l),s=r?.cwd??this.getCwdForSource(t);for(const e of o)xe(e)?this.promptHookClient&&u.push({type:"prompt",script:e,source:t}):_e(e)&&u.push({type:"command",script:e,cwd:s,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 s=r?.cwd??(e===ie.stop||e===ie.subagentStop?this.workspacePath:t.installPath),n={...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 ge(o,l))_e(e)&&u.push({type:"command",script:e,cwd:s,env:r?.env,source:"claude-plugin",attribution:n,pluginInstallPath:t.installPath})}if(0!==u.length)return this.executeAllAndMerge(e,u,c)}async executeAllAndMerge(e,t,r){const o=t.map((async(t,o)=>{const{source:s,attribution:n}=t;try{return"prompt"===t.type?this.executePromptHook(e,t.script,r,s,o,n):this.executeCommandHook(e,t.script,t.cwd,t.env,r,s,o,n,t.pluginInstallPath)}catch(r){if(!0===t.script.failClosed){const t=Kk(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),n=Ne(e,t);if(n)return{success:!0,data:n,source:s,index:o}}return{success:!1,source:s,index:o}}})),s=await Promise.all(o),n=[];for(const e of s)e.success&&void 0!==e.data&&n.push(e.data);return function(e,t){if(0===t.length)return;if(1===t.length)return t[0];const r=Ie.includes(e),o=e===ie.sessionStart,s=e===ie.workspaceOpen,n=Ce.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(s&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e]??[],r=new Set(t),o=[...t];for(const e of l)"string"!=typeof e||r.has(e)||(r.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?n&&"additional_context"===e&&"string"==typeof l?i[e]=Ae(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=o&&"env"===e&&"object"==typeof l&&null!==l?Me(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=Ae(i[e],l)}var a,c;return i}(e,n)}async executeCommandHook(e,t,r,o,s,n,i,a,c){if(this.shouldSkipHookDueToLoopLimit(e,t,s))return{success:!1,source:n,index:i};const l=Date.now(),u=Buffer.byteLength(JSON.stringify(s),"utf8");let d;try{d=await this.executeCommandScript({script:t,cwd:r,request:s,env:o,...void 0!==c&&{pluginInstallPath:c}})}catch(r){const o=r instanceof Error?r.message:String(r),s=o.toLowerCase().includes("timed out"),c=Date.now()-l,d=s?"timeout":"spawn_error";if(!0===t.failClosed){const r=Ne(e,Kk(`Hook "${t.command}" execution failed: ${o}`));if(r)return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:s?"timeout":"blocked",latencyMs:c,payloadSizeBytes:u,errorClass:d,failClosed:!0,timedOut:s,...a}),{success:!0,data:r,source:n,index:i}}return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:s?"timeout":"failed",latencyMs:c,payloadSizeBytes:u,errorClass:d,failClosed:!0===t.failClosed,timedOut:s,...a}),{success:!1,source:n,index:i}}if(2===d.exitCode){const r=function(e,t,r){const o=e.trim(),s=t.trim();return o||(s?`Hook blocked with message: ${s}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(d.stdout,d.stderr,t.command),o=Ne(e,r);return o?(this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:d.duration,payloadSizeBytes:u,failClosed:!0===t.failClosed,exitCode:d.exitCode,...a}),{success:!0,data:o,source:n,index:i}):(this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:d.duration,payloadSizeBytes:u,failClosed:!0===t.failClosed,exitCode:d.exitCode,...a}),{success:!1,source:n,index:i})}if(0!==d.exitCode&&null!==d.exitCode){if(!0===t.failClosed){const r=Ne(e,Kk(`Hook "${t.command}" failed with exit code ${d.exitCode}${d.stderr?`: ${d.stderr.trim()}`:""}`));if(r)return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"exit_nonzero",failClosed:!0,exitCode:d.exitCode,...a}),{success:!0,data:r,source:n,index:i}}return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:d.exitCode,...a}),{success:!1,source:n,index:i}}const h=d.stdout.trim();if(!h){if(!0===t.failClosed){const r=Ne(e,Kk(`Hook "${t.command}" returned no output.`));if(r)return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"empty_stdout",failClosed:!0,exitCode:d.exitCode??void 0,...a}),{success:!0,data:r,source:n,index:i}}return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:d.exitCode??void 0,...a}),{success:!1,source:n,index:i}}const p=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}}(h);if(void 0===p){const r=Oe({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:d.exitCode??void 0,...a}),{success:!0,data:r.blockResponse,source:n,index:i}):(this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:d.exitCode??void 0,...a}),{success:!1,source:n,index:i})}const f=Re(e,p,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(f.success){const r=f.data,o="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:o?"blocked":"success",latencyMs:d.duration,payloadSizeBytes:u,failClosed:!0===t.failClosed,exitCode:d.exitCode??void 0,...a}),{success:!0,data:f.data,source:n,index:i}}const m=Oe({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return m.blockResponse?(this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:d.exitCode??void 0,...a}),{success:!0,data:m.blockResponse,source:n,index:i}):(this.emitHookExecution({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:d.duration,payloadSizeBytes:u,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:d.exitCode??void 0,...a}),{success:!1,source:n,index:i})}async executePromptHook(e,t,r,o,s,n){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:o,index:s};if(!this.promptHookClient)return{success:!1,source:o,index:s};const i=1e3*(t.timeout??60),a=Date.now(),c=Buffer.byteLength(JSON.stringify(r),"utf8"),l=(0,re.q6)(),[u,d]=l.withTimeoutAndCancel(i);try{const i=JSON.parse(JSON.stringify(r)),l=await this.promptHookClient.evaluatePromptHook(u,{prompt:t.prompt,hookInputJson:i,modelName:t.model});if(l.ok){const r=function(e){return De(e)?{permission:"allow"}:e===ie.beforeSubmitPrompt||e===ie.sessionStart?{continue:!0}:e===ie.stop?{}:void 0}(e);return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:"success",latencyMs:Date.now()-a,payloadSizeBytes:c,failClosed:!0===t.failClosed,...n}),r?{success:!0,data:r,source:o,index:s}:{success:!1,source:o,index:s}}{const r=Ne(e,l.reason??"Prompt hook blocked this action");return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:"blocked",latencyMs:Date.now()-a,payloadSizeBytes:c,failClosed:!0===t.failClosed,...n}),r?{success:!0,data:r,source:o,index:s}:{success:!1,source:o,index:s}}}catch(r){const i=r instanceof Error?r.message:String(r),l=i.toLowerCase().includes("abort")||i.toLowerCase().includes("timed out"),u=l?"timeout":"prompt_error";if(!0===t.failClosed){const t=Ne(e,Kk(`Prompt hook failed: ${i}`));if(t)return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:l?"timeout":"blocked",latencyMs:Date.now()-a,payloadSizeBytes:c,errorClass:u,failClosed:!0,timedOut:l,...n}),{success:!0,data:t,source:o,index:s}}return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:l?"timeout":"failed",latencyMs:Date.now()-a,payloadSizeBytes:c,errorClass:u,failClosed:!0===t.failClosed,timedOut:l,...n}),{success:!1,source:o,index:s}}finally{d()}}async executeCommandScript(e){const{script:t,cwd:r,request:o,env:s,pluginInstallPath:a}=e,c=1e3*(t.timeout??60),l=Date.now(),u=JSON.stringify(o);let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),c);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 s=e.indexOf(o,t+1);for(;"'"===o&&-1!==s&&"'"===e.charAt(s+1);)s=e.indexOf("'",s+2);if(-1===s)return;return{prefix:r,quote:o,rawPath:e.slice(t+1,s),rest:e.slice(s+1)}}const s=/^\S+/.exec(e.slice(t));if(s)return{prefix:r,quote:"",rawPath:s[0],rest:e.slice(t+s[0].length)}}(e);if(!r)return e;const{prefix:o,quote:s,rawPath:n,rest:i}=r;if(0===n.length||!/[\\/]/.test(n))return e;if(i.length>0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(n)||""===s&&/['"]/.test(n))return e;const a=n.slice(Math.max(n.lastIndexOf("\\"),n.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===s?n.replace(/''/g,"'"):n,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=We.find((e=>t.isFile(l+e)));return void 0===d?e:""!==s?`${o}${s}${n}${d}${s}${i}`:`${o}'${n}${d}'${i}`}(t.command,{cwd:r,isFile:Xk}):t.command;let w;if(m)w=e?He(g):g;else if("windows_temp_file"===f){d=await(0,Qs.mkdtemp)((0,i.join)((0,n.tmpdir)(),"cursor-hooks-"));const e=(0,i.join)(d,"payload.json");await(0,Qs.writeFile)(e,u,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.Encoding]::UTF8; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw | & { $input | ${He(t)} }`}(e,g)}else w=e?`@'\n${u.replace(/'/g,"''")}\n'@ | & ${g}`:`${t.command} <<'CURSOR_HOOK_EOF'\n${u}\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:s}),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,re.q6)();let _="",P="",R=null,I=!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,u),I=!0);break;case"stdout":_+=e.data.toString("utf8");break;case"stderr":P+=e.data.toString("utf8");break;case"exit":R=e.code}if(m&&!I)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const T=Date.now()-l;if(h.signal.aborted)throw new Error(`Hook script timed out after ${c}ms`);return{stdout:_,stderr:P,exitCode:R,duration:T}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${c}ms`);throw e}finally{if(d)try{await(0,Qs.rm)(d,{recursive:!0,force:!0})}catch{}}}}function eE(e){switch(e??(0,n.platform)()){case"darwin":return i.join("/Library","Application Support","Cursor","hooks.json");case"win32":return i.join("C:\\","ProgramData","Cursor","hooks.json");default:return i.join("/etc","cursor","hooks.json")}}class tE{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,s=o?i.dirname(i.dirname(o)):void 0,n=(e,t)=>{if(!e||!s)return;if(t)return s;const r=i.relative(i.resolve(s),i.resolve(e));return".."===r||r.startsWith(`..${i.sep}`)||i.isAbsolute(r)?void 0:s},a=async(e,t,o,s,n,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:`${n} 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]=i.dirname(t)})(s,e)):h&&r.errors.push({source:t,message:`${n} 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:n(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:n(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:n(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:n(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:n(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:n(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:n(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 xe(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,s]of Object.entries(e.hooks)){if(!s)continue;const n=r.get(o);if(!n||0===n.size)continue;const i=s.filter((e=>{const r=this.getHookKey(e);return!n.has(r)||(this.logger.info(`Removed duplicate ${t} hook for ${o}: ${r}`),!1)}));i.length!==s.length&&(e.hooks[o]=i)}};o(e.claudeUserHooks,"claude-user"),o(e.claudeProjectHooks,"claude-project"),o(e.claudeProjectLocalHooks,"claude-project-local")}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if("object"!=typeof e||null===e)return!1;if(!("hooks"in e))return!1;const r=e.hooks;if("object"!=typeof r||null===r)return!1;const o=r;for(const[e,r]of Object.entries(o))if(e in ae&&Array.isArray(r)){const o=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if("object"==typeof e&&null!==e&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||o))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const o=me(r,this.logger),s=Ve(o);return s.isValid?{config:o}:{error:`Invalid transformed config: ${s.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const r=this.parseJSONC(e),o=Ve(r);if(!o.isValid)return{error:`Invalid ${t} config: ${o.errors.join("; ")}`};const s=r;return s.hooks?{config:s}:{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 rE{constructor(e){this.config=e,this.configuredSteps=tE.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var oE=r("node:perf_hooks");function sE(e,t){void 0!==e&&t.length>0&&e.push(...t)}class nE 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 iE=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function aE({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 nE({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new iE.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ce).map((e=>{if(!function(e){return e===ie.sessionStart||e===ie.beforeSubmitPrompt||e===ie.preToolUse||e===ie.postToolUse||e===ie.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 cE=(0,d.h)("generic-hooks");function lE(e,t,r,o){try{return aE({hookEventName:r,additionalContext:o})}catch(o){if(o instanceof nE)return cE.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:o.actualLength,maxLength:o.maxLength}),[];throw o}}const uE=e=>Math.round(1e3*e)/1e3;function dE(e,t,r,o,n,i){const a=o(e),c=n.getToolCallId?.(t)??(0,s.randomUUID)(),l=n.getExtraHookFields?.(t)??{},u={baseHookRequest:a,toolUseId:c,toolInput:n.createToolInput(t),extraHookFields:l,hookContextCollector:i?.hookContextCollector??n.getHookContextCollector?.(t)??[]},d=function(e,t,r,o){let{toolInput:s,extraHookFields:n,hookContextCollector:i}=o;const{baseHookRequest:a,toolUseId:c}=o;return{fireFailureAsync:async(o,l,u,d=!1)=>{try{const h=await Yp(e.signal,(()=>t.executeHookForStep(ie.postToolUseFailure,{...a,tool_name:r,tool_input:s,error_message:l,failure_type:u,duration:o,tool_use_id:c,is_interrupt:d,...n})));sE(i,lE(e,r,ie.postToolUseFailure,h?.additional_context))}catch(t){cE.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(o,l)=>{try{const u=await Yp(e.signal,(()=>t.executeHookForStep(ie.postToolUse,{...a,tool_name:r,tool_input:s,tool_output:l,duration:o,tool_use_id:c,...n})));sE(i,lE(e,r,ie.postToolUse,u?.additional_context))}catch(t){cE.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>s,setToolInput:e=>{s=e},setExtraHookFields:e=>{n=e,o.extraHookFields=e}}}(e,r,n.toolName,u);return{hookContext:u,helpers:d}}async function hE(e,t,r,o,s,n,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=o;try{const a=await Yp(e.signal,(()=>r.executeHookForStep(ie.preToolUse,{...c,tool_name:n.toolName,tool_input:s.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${n.toolName} blocked by preToolUse hook`,c=Jk(r);try{sE(o.hookContextCollector,aE({hookEventName:ie.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof nE))throw t;cE.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:n.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await s.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&n.applyUpdatedInput&&(n.applyUpdatedInput(t,a.updated_input),s.setToolInput(n.createToolInput(t)),n.getExtraHookFields&&s.setExtraHookFields(n.getExtraHookFields(t))),sE(o.hookContextCollector,aE({hookEventName:ie.preToolUse,additionalContext:a?.additional_context}))}catch(o){const a=r.hasFailClosedHooksForStep?.(ie.preToolUse,n.toolName)??!1,c=o instanceof nE;if(a){const e=Kk(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${o instanceof Error?o.message:"preToolUse hook error"}`);return await s.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}cE.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:n.toolName,error:o instanceof Error?o.message:String(o),...c?{actualLength:o.actualLength,maxLength:o.maxLength}:{}})}if(a)try{const n=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:s.getToolInput(),toolUseId:l,extraHookFields:o.extraHookFields});if(void 0!==n){const e="Pre-execution hook returned rejection";return await s.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:n,reason:e}}}catch(e){if(Qk(e))return await s.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function pE(e){return e.toolCallId}function fE(e,t,r,o){return{async execute(s,n,i){const{hookContext:a,helpers:c}=dE(s,n,t,r,o,i);let l;try{l=await hE(s,n,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=oE.performance.now();try{const r=await e.execute(s,n,i),l=uE(oE.performance.now()-u);if(o.runPostExecutionHooks)try{const e=await o.runPostExecutionHooks({ctx:s,args:n,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(n,e))),o.runCleanup?.(a.toolUseId),e}catch(e){if(Qk(e))return await c.fireFailureAsync(l,e.reason,e.failureType),o.runCleanup?.(a.toolUseId),o.createRejectedResult(n,e.reason);cE.warn(s,"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(n,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=uE(oE.performance.now()-u);throw await c.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),o.runCleanup?.(a.toolUseId),e}}}}function*mE(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function gE(e){const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class wE{async readFile(e){try{return await Qs.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Qs.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=i.resolve(e),o=i.resolve(t),s=i.relative(o,r);if(0===s.length||".."===s||s.startsWith(`..${i.sep}`)||i.isAbsolute(s))return"unsafe";const n=s.split(i.sep).filter((e=>e.length>0)),a=[];let c=o;for(const e of n)c=i.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Qs.lstat)(e)).isSymbolicLink())return!0}catch(e){if(gE(e))return!0;throw e}return!1}(e,t)}}class yE{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),s=await this.hooksAdditionalContextPromise,n=this.hooksConfigLease?new lr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===o.result.case&&(s||n)){const e=o.result.value.requestContext,t=new lr.bb({...e,...s&&{hooksAdditionalContext:s},...n&&{hooksConfig:n}});return new lr._G({result:{case:"success",value:new lr.yW({requestContext:t,servedFromDiskCache:o.result.value.servedFromDiskCache})}})}return o}}function vE(e){return!!e&&e.type!==_n.vc.INSECURE_NONE&&e.type!==_n.vc.UNSPECIFIED}const bE="Shell";async function SE({hookExecutor:e,baseHookRequest:t,command:r,cwd:o,sandbox:s}){const n=await e.executeHookForStep(ie.beforeShellExecution,{...t,command:r,cwd:o,sandbox:s});if("deny"===n?.permission){const e=Zk("Command execution",n.user_message);throw new Hk(e)}if("ask"===n?.permission)return i=n.user_message,new Jt.In({kind:Jt.b.FORCE_PROMPT,reason:i});var i}const kE={toolName:bE,getToolCallId:pE,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 Gt.Lt({result:{case:"rejected",value:new Jt.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}=e,s=t.workingDirectory||"",n=vE(t.sandboxPolicy);hr(t,await SE({hookExecutor:o,baseHookRequest:r,command:t.command,cwd:s,sandbox:n}))}};class EE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,kE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const CE={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Gt.nt({result:{case:"error",value:new Gt.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 xE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,CE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _E={toolName:"ComputerUse",getToolCallId:pE,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Wh.ks({result:{case:"error",value:new Wh.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 PE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,_E)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RE={toolName:"Delete",getToolCallId:pE,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Vt.Pi({result:{case:"rejected",value:new Vt.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 IE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,RE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TE={toolName:"ReadLints",getToolCallId:pE,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Kw.Ek({result:{case:"rejected",value:new Kw.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 AE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,TE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ME={toolName:"Fetch",getToolCallId:pE,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new $p.uN({result:{case:"error",value:new $p.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 DE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,ME)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OE={toolName:"Grep",getToolCallId:pE,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 Wp.Ud({result:{case:"error",value:new Wp.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 NE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,OE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jE={toolName:"List",getToolCallId:pE,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 Wg.fv({result:{case:"rejected",value:new Wg.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 $E{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,jE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FE=(0,d.h)("hooks-exec:mcp");function LE(e,t,r,o){try{return aE({hookEventName:r,additionalContext:o})}catch(o){if(o instanceof nE)return FE.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:o.actualLength,maxLength:o.maxLength}),[];throw o}}class UE{constructor(e,t,r,o,s){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=o,this.hooksConfigLease=s}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(ie.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(ie.beforeMCPExecution)))return new mt.iz({result:{case:"error",value:new mt.Nh({error:`"${_t}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const o=this.baseHookRequestExtractor(e),n=(0,s.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await this.hookExecutor.executeHookForStep(ie.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:n});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{sE(i,aE({hookEventName:ie.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof nE))throw t;FE.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,o,c,a,t,"permission_denied",0,n,!1,i),new mt.iz({result:{case:"permissionDenied",value:new mt.HQ({error:Zk("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]=bt.Value.fromJson(o));a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){FE.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}sE(i,aE({hookEventName:ie.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=this.hookExecutor.hasFailClosedHooksForStep?.(ie.preToolUse,c)??!1,s=t instanceof nE;if(r){const r=Kk(`${s?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,o,c,a,r,"error",0,n,!1,i),new mt.iz({result:{case:"permissionDenied",value:new mt.HQ({error:Zk("MCP tool execution",r),isReadonly:!1})}})}FE.warn(e,s?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...s?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),...p,...d},m=await this.hookExecutor.executeHookForStep(ie.beforeMCPExecution,f);if("deny"===m?.permission){const t=Zk("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,o,c,a,t,"permission_denied",0,n,!1,i),new mt.iz({result:{case:"permissionDenied",value:new mt.HQ({error:t,isReadonly:!1})}})}const g=oE.performance.now();try{const s=await this.innerExecutor.execute(e,t,r),l=uE(oE.performance.now()-g);let u="{}";if("success"===s.result.case)try{const e=s.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:s.result.value.isError})}catch(t){FE.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"===s.result.case?u=JSON.stringify({error:s.result.value.error}):"rejected"===s.result.case?u=JSON.stringify({rejected:!0,reason:s.result.value.reason}):"permissionDenied"===s.result.case&&(u=JSON.stringify({permissionDenied:!0,error:s.result.value.error}));const d={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:u,duration:l,...p};await this.hookExecutor.executeHookForStep(ie.afterMCPExecution,d);const h=await this.firePostToolUse(e,o,c,a,u,l,n,i);if(void 0!==h?.updated_mcp_tool_output)try{const e=h.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new mt._Z({content:{case:"text",value:new mt.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 mt._Z({content:{case:"text",value:new mt.zN({text:String(e.text)})}})):t.push(new mt._Z({content:{case:"text",value:new mt.zN({text:JSON.stringify(e)})}}))}else t.push(new mt._Z({content:{case:"text",value:new mt.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new mt.iz({result:{case:"success",value:new mt.QW({content:t,isError:r})}})}catch(t){return FE.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),s}return s}catch(t){const r=uE(oE.performance.now()-g),s=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,o,c,a,s,"error",r,n,!1,i),t}}async firePostToolUse(e,t,r,o,s,n,i,a){try{const c=await this.hookExecutor.executeHookForStep(ie.postToolUse,{...t,tool_name:r,tool_input:o,tool_output:s,duration:n,tool_use_id:i});return sE(a,LE(e,r,ie.postToolUse,c?.additional_context)),c}catch(t){return void FE.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,o,s,n,i,a,c,l){try{const u=await this.hookExecutor.executeHookForStep(ie.postToolUseFailure,{...t,tool_name:r,tool_input:o,error_message:s,failure_type:n,duration:i,tool_use_id:a,is_interrupt:c});sE(l,LE(e,r,ie.postToolUseFailure,u?.additional_context))}catch(t){FE.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BE={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new mt.kP({result:{case:"error",value:new mt.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 zE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,BE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const WE={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 mt.ZD({result:{case:"error",value:new mt.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 HE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,WE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const qE={toolName:"Read",getToolCallId:pE,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new gt.sV({result:{case:"rejected",value:new gt.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:s}=e;if("success"!==r.result.case)return;const n="content"===r.result.value.output.case?r.result.value.output.value:"",i=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${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${Gk}`}(t,e instanceof Error?e.message:String(e));throw new qk(r,e)}}((()=>s.executeHookForStep(ie.beforeReadFile,{...o,content:n,file_path:t.path,attachments:[]})),"File read");if("deny"===i?.permission){const e=Zk("File read",i.user_message);throw new Hk(e)}}};class GE{constructor(e,t,r){this.wrappedExecutor=new Et(fE(e,t,r,qE))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VE={toolName:"RecordScreen",getToolCallId:pE,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new Gv.Tj({result:{case:"failure",value:new Gv.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 JE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,VE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function KE(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZE={toolName:bE,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 Jt.W4({result:{case:"rejected",value:new Jt.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:KE(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o}=e,s=t.workingDirectory||"";hr(t,await SE({hookExecutor:o,baseHookRequest:r,command:t.command,cwd:s,sandbox:vE(t.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:o,hookExecutor:s,executionDurationMs:n}=e,i=KE(r);await s.executeHookForStep(ie.afterShellExecution,{...o,command:t.command,output:i,duration:n,sandbox:vE(t.requestedSandboxPolicy)})}};class QE{constructor(e,t,r){this.wrappedExecutor=fE(e,t,r,ZE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class XE{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 YE={toolName:bE,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 Jt.FI({event:{case:"rejected",value:new Jt.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new Jt.FI({event:{case:"hookContext",value:new Jt.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new XE,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o}=e,s=t.workingDirectory||"",n=vE(t.requestedSandboxPolicy);hr(t,await SE({hookExecutor:o,baseHookRequest:r,command:t.command,cwd:s,sandbox:n}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o,collector:s,executionDurationMs:n}=e,i=vE(t.requestedSandboxPolicy);await o.executeHookForStep(ie.afterShellExecution,{...r,command:t.command,output:s.getOutput(),duration:n,sandbox:i})}};class eC{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,o){return{async*execute(s,n,i){const{hookContext:a,helpers:c}=dE(s,n,t,r,o,i),l=o.runPreExecutionHooks?async e=>{await o.runPreExecutionHooks(e)}:void 0,u=await hE(s,n,t,a,c,o,((e,t)=>o.createRejectedEvent(e,t)),l);if("rejected"===u.type){yield u.result;for(const e of mE(o,a))yield e;return}const d=oE.performance.now(),h=o.createResultCollector();let p=!1;try{for await(const t of e.execute(s,n,i))h.onEvent(t),yield t}catch(e){p=!0;const t=uE(oE.performance.now()-d),r=e instanceof Error?e.message:String(e);await c.fireFailureAsync(t,r,"error");for(const e of mE(o,a))yield e;throw e}const f=uE(oE.performance.now()-d);if(o.runPostExecutionHooks)try{await o.runPostExecutionHooks({ctx:s,args:n,baseHookRequest:a.baseHookRequest,hookExecutor:t,toolInput:c.getToolInput(),toolUseId:a.toolUseId,extraHookFields:a.extraHookFields,collector:h,executionDurationMs:f})}catch(e){cE.warn(s,"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(n,h)));else{const e=o.getStreamErrorMessage?.(n,h)??`Command failed with exit code ${h.getExitCode()}`;await c.fireFailureAsync(f,e,"error")}for(const e of mE(o,a))yield e}}}(e,t,r,YE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tC{constructor(e,t,r){const o=new Map;this.wrappedExecutor=fE(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:pE,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 Kt.v3({result:{case:"error",value:new Kt.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async e=>{const{args:r,toolUseId:o}=e;let s,n=!1;try{(await(0,Qs.stat)(r.path)).size>262144?n=!0:s=await hi(r.path)}catch(e){}t.set(o,{contentBeforeWrite:s,fileTooLarge:n})},runCleanup:e=>{t.delete(e)},runPostExecutionHooks:async r=>{const{args:o,result:s,baseHookRequest:n,toolUseId:i}=r,a=t.get(i);if("success"!==s.result.case)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,pw.YB)("","",e,t,"","",{context:0});return 0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const o of e.lines)o.startsWith("-")?t.push(o.slice(1)):o.startsWith("+")&&r.push(o.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,o.fileText);const d={...n,file_path:o.path,edits:u},h=await e.executeHookForStep(ie.afterFileEdit,d);if(o.returnFileContentAfterWrite&&void 0!==h){const e=s.result.value.path;try{const t=await hi(e),r=mi(t),o=Buffer.byteLength(t,"utf8");return new Kt.v3({result:{case:"success",value:new Kt.j6({...s.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 rC{constructor(e,t,r,o,s,n,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=o,this.hooksAdditionalContextPromise=s,this.teamHooksReadyPromise=n,this.hooksConfigLease=i}get(e){if(e.symbol===Ke.symbol)return new Ze(this.hookExecutor);const t=this.innerAccessor.get(e);return e.symbol===Zt.symbol?new QE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Qt.symbol?new eC(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Xt.symbol?new tC(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===lt.symbol?new UE(t,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease,this.hooksConfigLease):e.symbol===Ct.symbol||e.symbol===xt.symbol?new GE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Xe.symbol?new $E(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ne.symbol?new NE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===oe.symbol?new DE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ee.symbol?new IE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===te.symbol?new AE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ut.symbol?new zE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===dt.symbol?new HE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===J.symbol?new EE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===K.symbol?new xE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Y.symbol?new PE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ar.symbol?new JE(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===cr.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new yE(t,this.hooksAdditionalContextPromise??Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease):t}*entries(){for(const[e,t]of this.innerAccessor.entries())e.symbol===Zt.symbol?yield[e,new QE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Qt.symbol?yield[e,new eC(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Xt.symbol?yield[e,new tC(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===lt.symbol?yield[e,new UE(t,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease,this.hooksConfigLease)]:e.symbol===Ct.symbol||e.symbol===xt.symbol?yield[e,new GE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Xe.symbol?yield[e,new $E(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ne.symbol?yield[e,new NE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===oe.symbol?yield[e,new DE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ee.symbol?yield[e,new IE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===te.symbol?yield[e,new AE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ut.symbol?yield[e,new zE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===dt.symbol?yield[e,new HE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===J.symbol?yield[e,new EE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===K.symbol?yield[e,new xE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Y.symbol?yield[e,new PE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ar.symbol?yield[e,new JE(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===cr.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[e,new yE(t,this.hooksAdditionalContextPromise??Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease)]:yield[e,t];yield[Ke,new Ze(this.hookExecutor)]}}const oC={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function sC(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>sC(e??t),async*execute(e,r,o={}){const s=o.workingDirectory??t;t=s;const n=function(e){return"win32"===process.platform?{executable:(0,en.oG)(),args:[...ze,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,qc.spawn)(n.executable,[...n.args],{cwd:s,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 nC(e,t,...r){for(const o of r){const r=t(e[o]);if(void 0!==r)return r}}function iC(e){return"string"==typeof e&&e.length>0?e:void 0}function aC(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function cC(e){if(Array.isArray(e)&&e.every(aC))return e.map((e=>({id:e.id,value:e.value})))}class lC{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 uC(e,t={}){const r=await new tE(new wE,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],o=t.includeProjectHooks??!0,s=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?eE():void 0,userConfigPath:s?(0,i.join)((0,n.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:s?(0,i.join)((0,n.homedir)(),".claude","settings.json"):void 0,projectConfigPath:o&&void 0!==r?(0,i.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:o&&void 0!==r?(0,i.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:o&&void 0!==r?(0,i.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),o=new rE(r),s=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...oC,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:s,hooksConfig:r,hooksConfigLease:o,globalContext:a,createSessionRuntime(){const e=new Yk(r,s,a,(t.createTerminalExecutor??sC)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(n=t.useCommandHookStdinTransport,!0===n?"stdin":"legacy")});var n;return{hookExecutor:e,hooksConfigLease:o,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function dC(e={}){return{createHooksRuntime:t=>uC(t.workspaceState,e)}}var hC=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function pC(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function fC(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 zp,l=(0,n.homedir)(),u=Fd(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,oo.createClient)(hC.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],o=await kS(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:o}}catch(t){return CS.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,re.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new TS.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:SC(),getAgentSkills:async e=>[]};const p=(0,re.q6)(),f=e.loadNestedRules??!0,m=o?i.map((e=>new Rh(p,c,e,f,t,void 0))):[],g=function(e,t){const r=mC(t);return{getAllCursorRules:async t=>gC(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?SC():1===m.length?m[0]:new Ph(m,(()=>Xd)),{allowedRoots:o?i:[],excludedRoots:[]}),w=function(e,t){const r=mC(t);return{getAllCursorRules:async t=>gC(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>gC(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new Ih(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 Lh(e,t))):[],v=0===y.length?new Dh:1===y.length?y[0]:new Bh(y),b=ak(n.services.pluginBootstrapOutputs),S=b&&a?new Ah(p,(()=>({importThirdPartyPlugins:r})),void 0,b.pluginsService):void 0,k=b&&a?new zh((()=>({importThirdPartyPlugins:r})),b.pluginsService):void 0,E=new Ph([g,w,...S?[S]:[]],(()=>Xd)),C=new aS([w,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:o?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Bh([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 pC(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function mC(e){const t=Promise.all(e.allowedRoots.map(vC)),r=Promise.all(e.excludedRoots.map(vC));return async e=>{const[o,s,n]=await Promise.all([bC(e.fullPath),t,r]);return void 0!==o&&!n.some((e=>wC(o,e)))&&s.some((e=>wC(o,e)))}}async function gC(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function wC(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function yC(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function vC(e){try{return yC(await(0,Qs.realpath)(e))}catch{return yC(e)}}async function bC(e){try{return yC(await(0,Qs.realpath)(e))}catch{return}}function SC(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function kC(e={}){const t=e.userHomeDirectory??(0,n.homedir)(),r=e.importThirdPartyPlugins??!1,o=e.pluginLogger??{log(e,t,r){switch(e){case"warn":WS.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":WS.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){WS.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},s=EC(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(s||a);return{async loadPluginBootstrapOutputs(s){const n=(a=s.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 Pd(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}]}}}(n),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,i.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,oo.createClient)(hC.I,e.dashboardTransport),o=wu((async()=>{try{return await r.getEffectiveUserPlugins(new TS.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),s=e.workspacePath,n=wu((async()=>{if(void 0===s)return{plugins:[]};try{const e=await Pd(s);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),o=e.filter((e=>!e.entry.gitUrl)),n=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||Ed(t)})).map((({key:e,entry:t})=>{const r=Rd(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=Rd(e.key);return new TS.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new TS.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...n,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:o,userId:"",cacheManager:new Wc(e.userHomeDirectory),pruneOldVersions:!0},{client:n,userId:"",cacheManager:new Wc(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:n,userHomeDirectory:t}):void 0),h=EC(d),p=new IS(void 0!==n?[n]:[],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:n,discoveredEntryCount:l.length}});const g={kind:ik,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)WS.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:n,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)WS.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:n,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function EC(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class CC{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const xC=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function _C(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 PC(e){const t=_C(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function RC(e){const t=_C(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 IC(e){const t=PC(e.value),r=[...new Set(e.hostRoots.filter((e=>e.length>0)))].sort(((e,t)=>PC(t).length-PC(e).length));for(const o of r){const r=PC(o);if(t===r)return RC({reportedWorkspacePath:e.reportedWorkspacePath,suffix:""});const s="/"===r?"/":`${r}/`;if(t.startsWith(s)){const o="/"===r?t:t.slice(r.length);return RC({reportedWorkspacePath:e.reportedWorkspacePath,suffix:o})}}}class TC extends Yb{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await pC(this.sessionMcpLease)}}}function AC(e){const t=new zp;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 s=r.workspaceServices.cursorRulesService??new CC,n=r.workspaceServices.subagentsService??new Dh,i=r.workspaceServices.mcpLease??new Zf,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 jp(l,u):new Np(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:s,subagentsService:n,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 Yb(l):new TC(l,a);return void 0!==r.options.reportedWorkspacePath&&function(e,t,r){const o=e.get(cr);void 0!==o&&e.register(cr,{execute:async(e,s,n)=>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 s=o.result.value.requestContext?.env;if(void 0===s)return o;s.workspacePaths=s.workspacePaths.map((e=>IC({value:e,hostRoots:r,reportedWorkspacePath:t})??e));for(const e of xC){const o=s[e];if(void 0===o||""===o)continue;const n=IC({value:o,hostRoots:r,reportedWorkspacePath:t});s[e]="processWorkingDirectory"===e?n??_C(t):n??o}return o}(await o.execute(e,s,n),t,r)})}(u,r.options.reportedWorkspacePath,[...l.workspacePaths,l.projectDir]),u}catch(e){throw await pC(a),e}}}}const MC=["cursorRulesService","getAgentSkills","subagentsService"],DC=new WeakSet;function OC(e){("object"==typeof e&&null!==e||"function"==typeof e)&&DC.add(e)}function NC(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&DC.has(e)}function jC(e,t){const r=Object.keys(t).filter((e=>!MC.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${MC.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of MC)Object.hasOwn(t,r)&&(e[r]=t[r])}async function $C(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 s=()=>({workspaceState:t,policy:r,services:o});o.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(s()):o.pluginBootstrapOutputs,o.mcpLease=e.mcp?await e.mcp.createLease(s()):void 0,o.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(s()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(s());const n=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(s()):void 0;void 0!==n&&(OC(n.cursorRulesService),OC(n.subagentsService),Object.assign(o,n));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(s());void 0!==e&&jC(o,e)}return o}catch(t){try{await FC(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 FC(e,t){const r=t?.preserveSharedContributorsFrom;let o;const s=async e=>{try{await pC(e)}catch(e){o??=e}};if(e.subagentsService===r?.subagentsService||NC(e.subagentsService)||await s(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||NC(e.cursorRulesService)||await s(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){o??=e}await s(e.hooksRuntime),await s(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await pC(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){o??=e}if(void 0!==o)throw o}async function LC(e){const t=new Set;let r;for(let o=e.length-1;o>=0;o-=1){const s=e[o];if(!t.has(s)){t.add(s);try{await pC(s)}catch(e){r??=e}}}if(void 0!==r)throw r}const UC=["project","user","team","mdm","plugins"],BC=new Set([...UC,"all"]);function zC(e){if(void 0===e||0===e.length)return HC([]);for(const t of e)if(!BC.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{...HC(UC),all:!0}}return HC(e)}function WC(e,t){return e[t]}function HC(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 qC=Object.freeze({}),GC=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:qC});async function VC(e={}){const t=function(e={}){return{workspace:e.workspace??$S,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({...GC.metadata,...e.metadata}),r={...GC,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let n=await $C(t,r,o),i=!1,a=Promise.resolve();const c=e=>{const t=a.then(e);return a=t.catch((()=>{})),t},l=t.localExtensibility?.disposeLocalExtensibility;return{state:r,get services(){return n},policy:o,async createSessionRuntime(e={}){if(i)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,s.randomUUID)(),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,i;const a=[];try{n=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(o):void 0,i=n,a.push(n);for(const t of e.adapters.resourceWrappers??[])i=await t.wrapResources({...o,baseResources:n,resources:i}),a.push(i);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await LC(a)}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 c=!1;return{state:t,resources:{base:n,wrapped:i},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!c){c=!0;try{await LC(a)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:n,policy:o,adapters:t})},async reload(){i||await c((async()=>{if(i)return;const e=n,s=await $C(t,r,o);i?await FC(s,{disposeLocalExtensibility:l}):(n=s,await FC(e,{preserveSharedContributorsFrom:s,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){i||(i=!0,await c((async()=>{try{await FC(n,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class JC{async requestApproval(e){return{approved:!0}}}class KC{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 ZC{async open(e,t){}async getDiagnostics(e,t){return[]}}class QC{async getCodebaseReference(e,t){}}class XC{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 YC{constructor(e){this.subagents=e.map((e=>new Ur.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Ur.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}const ex=Zs;async function tx(e,t){const r=(0,i.dirname)(e);await(0,Qs.mkdir)(r,{recursive:!0}),await(0,Qs.writeFile)(e,t,"utf-8")}class rx{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=ex(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=Sk({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,i.join)(this.projectDir,r)}:void 0;this.transcriptStore=new Wk(this.projectDir,e.blobStore,tx,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new Wk(this.projectDir,e.blobStore,tx,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=Sk({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,i.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){WS.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,Yr.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=Sk({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,i.join)(this.projectDir,e)}return function(e,t){const r=Sk({conversationId:t,ext:"jsonl",kind:"primary"});return(0,i.join)(ex(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const ox=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sx="User aborted/interrupted manually.";class nx{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 qr}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(!ox.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&Gr(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,s.randomUUID)(),n=function(e){const t=new Yr.We,r=(0,Yr.sh)(e),o=new Yr.pH(new Yr.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),i=new rx({workspacePath:this.workspacePath,conversationId:o,parentConversationId:this.parentConversationId,blobStore:n.getBlobStore()});return this.sessions.set(o,{agentStore:n,transcriptWriter:i,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 s=this.sessions.get(t);if(!s)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[o,n]=e.withCancel();return this.registerBackgroundRun(t,this.executeSubagent(o,t,r,s),r.parentConversationId,n),{status:"background",backgroundReason:Ur.qL.AGENT_REQUEST,toolCallCount:0}}const[n,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||!n.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(n,t,r,s),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:Ur.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 Lr.a3({status:Lr.jh.ACCEPTED}):new Lr.a3({status:Lr.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 s=this.lifecycleStore.startRun(e,{abort:o}),n=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:s,promise:n};this.backgroundRuns.set(e,i),this.backgroundPromises.add(n),n.then((t=>{this.lifecycleStore.finishRun(e,s);const r=this.backgroundRuns.get(e);if(r?.runId===s){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,s,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){WS.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(n)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){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,s){const n=s.maxLoops>0?s.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,o,s,n);if(!s.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,s.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new Lr.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),o,s,n),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,o,n,i){let a,c,l=0;for(let u=0;u<i;u++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};const i=0===u?r.prompt:this.computeContinuationNudge(n,l,a),d=0===u?new Lr.Pw({...r,runInBackground:!1}):new Lr.Pw({...r,prompt:i,resumeAgentId:t,runInBackground:!1});if(c=await this.executeSubagentOnce(e,t,d,o),"completed"!==c.status)return c;const h=c.toolCallCount??0,p=c.finalMessage??"";if(void 0!==a&&p.includes(a))return c;h>0?(l=0,a=void 0):(l+=1,a=l>=n.idleThreshold?`DONE_${(0,s.randomUUID)().replace(/-/g,"").slice(0,8)}`:void 0)}return c??{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 s,n=0;const i=new mr.QFf({action:{case:"userMessageAction",value:new mr.Vtf({userMessage:new mr.RGk({text:r.prompt})})}}),a=new mr.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const c=new LS,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&&n++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return xr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return Pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return Tr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Jo.tz({result:{case:"rejected",value:new Jo.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return Rr(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 B(f,function(e){const t=[[Xt,or(e.errorMessage)],[ee,sr(e.errorMessage)],[lt,nr(e.errorMessage)]];return e.wrapShell&&t.push([Zt,er(e.errorMessage)],[Qt,tr(e.errorMessage)],[J,rr(e.errorMessage)]),e.includeWriteBackgroundShellStdin&&t.push([K,ir(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,subagentTypeName:r.subagentType||void 0,headers:qS(o.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await o.transcriptWriter.writeTurnEndedFromState(e,o.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:sx}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:n}}catch(r){const s=r instanceof Error?r.message:String(r);return WS.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:s}),await o.transcriptWriter.writeTurnEndedFromState(e,o.agentStore.getLatestCheckpoint()??o.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,s)),e.signal.aborted?{status:"aborted",error:sx}:{status:"error",error:s}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:sx}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!Gr(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 Lr.zJ({result:{case:"stillRunning",value:new Lr.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 Lr.zJ({result:{case:"complete",value:new Lr.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new Lr.zJ({result:{case:"error",value:new Lr.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new Lr.zJ({result:{case:"stillRunning",value:new Lr.L5({agentId:r})}}):new Lr.zJ({result:{case:"notFound",value:new Lr.Hq({agentId:r})}})}const[s,n]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);s.signal.addEventListener("abort",t,{once:!0}),o.promise.then(e).finally((()=>{s.signal.removeEventListener("abort",t),n()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new Lr.zJ({result:{case:"stillRunning",value:new Lr.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,o.runId),"completed"===i.status?new Lr.zJ({result:{case:"complete",value:new Lr.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new Lr.zJ({result:{case:"error",value:new Lr.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,o]of this.queuedChildCompletions){const s=o.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===s)continue;const[n]=o.splice(s,1);return 0===o.length&&this.queuedChildCompletions.delete(r),n}}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 s=()=>{o(r)};t.addEventListener("abort",s,{once:!0}),e.promise.then(o).finally((()=>t.removeEventListener("abort",s)))}))}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 s=this.parentChildIds.get(r)??new Set;s.add(e),this.parentChildIds.set(r,s)}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 s=this.queuedChildCompletions.get(o)??[];s.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,s),this.removeParentChildLink(e);const n=this.childCompletionWaiters.get(o);if(n){this.childCompletionWaiters.delete(o);for(const e of n)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 s=this.childCompletionWaiters.get(e)??new Set,n=()=>{a(),r()},i=()=>{a(),o(new Error("aborted"))},a=()=>{s.delete(n),0===s.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};s.add(n),this.childCompletionWaiters.set(e,s),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 ix=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),ax=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),cx=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),lx=r("./src/agent/analytics.ts");function ux(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 dx("tool-call-started",e.message.value);case"partialToolCall":return dx("partial-tool-call",e.message.value);case"toolCallCompleted":return dx("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 s=o.delta.value.interactionUpdate;if(void 0===s)return null;const n=ux(s,t);return null!==n&&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}}(n)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:n}: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"promptSuggestion":case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case void 0:return null;default:return e.message,null}}function dx(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:wx(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:yx(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:vx(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:bx(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:kx(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:Ex(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:Cx(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:_x(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:Px(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:Ix(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:Tx(t.mode)},...r?{result:Ax(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:Rx(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:Mx(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:Ox(e.status)})))},...r?{result:Dx(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":case"computerUseToolCall":case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:hx(t),...r?{result:mx(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"updatePrCodeTourToolCall":case"getPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"stopAgentToolCall":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 hx(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:px(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:fx(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function px(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function fx(e){switch(e){case Ur.FL.AGENT:return"agent";case Ur.FL.PLAN:return"plan";default:return"unspecified"}}function mx(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:gx(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function gx(e){switch(e){case Ur.qL.AGENT_REQUEST:return"agentRequest";case Ur.qL.USER_REQUEST:return"userRequest";case Ur.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function wx(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 yx(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 vx(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 bx(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]=Sx(o);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:Sx(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function Sx(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 kx(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 Ex(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 Cx(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:xx(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function xx(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(xx)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function _x(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:Nx(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 Px(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 Rx(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 Ix(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 Tx(e){switch(e){case Gv.$u.START_RECORDING:return"START_RECORDING";case Gv.$u.SAVE_RECORDING:return"SAVE_RECORDING";case Gv.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function Ax(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 Mx(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 Dx(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:Ox(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function Ox(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function Nx(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}const jx={type:"object",properties:{},additionalProperties:!0};function $x(e){return"text"===e.type?new mt._Z({content:{case:"text",value:new mt.zN({text:e.text})}}):new mt._Z({content:{case:"image",value:new mt.do({data:o.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function Fx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Lx=r("./src/agent/errors.ts"),Ux=r("./src/agent/executor-common.ts"),Bx=r("./src/agent/native/vendored-tree-sitter.ts"),zx=r("./src/agent/platform-package-locator.ts"),Wx=r("./src/agent/sdk-config.ts"),Hx=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),qx=r("./src/agent/utils/logger.ts");const Gx={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},Vx=new Map;var Jx=r("./src/agent/tools-option.ts");class Kx{async requestApproval(){return{approved:!0}}}function Zx(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof Yb))throw new Lx.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const o=r.getMcpExecutionPolicyDeps(),s=r.get(lt),n=function(e){return{async execute(t,r,o){const s=r.toolName||function(e){const t=`${tt}-`;return e.startsWith(t)?e.slice(t.length):e}(r.name),n=e[s];if(void 0===n)return new mt.iz({result:{case:"error",value:new mt.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:Fx(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?bt.Struct.fromJson(t.structuredContent):void 0;return new mt.iz({result:{case:"success",value:new mt.QW({content:t.content.map($x),isError:t.isError??!1,structuredContent:r})}})}(await n.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(r),{toolCallId:r.toolCallId||void 0}))}catch(e){return new mt.iz({result:{case:"error",value:new mt.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t),i=new Kx;e.resources.base.register(lt,{async execute(e,t,r){if(function(e){return e.providerIdentifier===tt}(t)){const s=await gg(e,t,{...o,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==s?s:n.execute(e,t,r)}return s.execute(e,t,r)}})}function Qx(){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 Xx={warn(){},error(){}},Yx={log(){}};class e_{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${t_(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 t_(e){switch(e.type){case Mp.Shell:return"this shell command";case Mp.Mcp:return"this MCP tool call";case Mp.Write:return"this file edit";case Mp.Delete:return"this file deletion";default:return"this operation"}}function r_(e){return void 0!==e&&"insecure_none"!==e.type}async function o_(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,re.q6)().with(d._O,Yx);zC(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}`);Ii=e}((0,Wx.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(Ux.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const l=performance.now();let u=0,h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,Ux.ly)(r.apiKey),(0,Ux.mU)(r.apiKey)]),u=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,Bx.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,Bx.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,Js.Rv)((0,n.homedir)(),p);let m;const g="win32"===process.platform?"rg.exe":"rg",w=process.env.CURSOR_RIPGREP_PATH;m=w&&(0,i.isAbsolute)(w)?w:(0,zx.hQ)({binaryName:g,excludedWorkspaceDir:p}),m||(m=(0,en.xS)()),m&&(0,en.J)(m);let y,v={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{y=(0,Ux.KU)(r.apiKey);const e=(0,oo.createClient)(hC.I,y),t=performance.now(),o=await function(e){let t=Vx.get(e);return t||(t=async function(e){try{const t=await async function(e){const t=await(0,Ux.dC)(e,Ux.EV);if(!t)return;const r=Ux.EV.endsWith("/")?Ux.EV.slice(0,-1):Ux.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,Ux.tF)(),"x-ghost-mode":(0,Ux.U)(e)},body:JSON.stringify({})});if(!o.ok)return void qx.v.log(`Failed to bootstrap SDK Statsig: ${o.status} ${o.statusText}`);const s=await o.json();return"string"==typeof s.config&&s.config.length>0?s.config:void 0}(e);if(!t)return Gx;const r=new Hx.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,Ux.tF)()}}}catch(e){qx.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,Ux.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 qx.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),Gx}}(e),Vx.set(e,t),t.then((r=>{r===Gx&&Vx.get(e)===t&&Vx.delete(e)}),(()=>{Vx.get(e)===t&&Vx.delete(e)}))),t}(r.apiKey);h=performance.now()-t;const s={getDefaultNetworkAllowlist:async()=>o.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};v=new NS(new MS(e),s,{isMcpAccessNetworkAllowlistEnabled:()=>o.checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:e=>o.checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:e=>o.checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:()=>o.checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){qx.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const b=performance.now(),S=r.apiKey?await(0,en.tv)(`${(0,n.homedir)()}/.cursor/sandbox.json`,(0,n.homedir)()):void 0,k=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 s=r_(r)?r:!0===o?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,en.Po)()}):void 0;if(void 0===s)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,zx.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,en.St)({sandboxBinaryPath:r})}(t),!(0,en.K3)(void 0,{ctx:e.initializationCtx}))throw new Lx.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 n={};n.perUser=s;const{policy:i}=await(0,en.resolveSandboxPolicyForWorkspace)(t,n);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:n}}({cwd:p,perUserSandboxPolicy:S,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,E=performance.now()-b,C=k?.defaultSandboxPolicy,x=k?.defaultSandboxPolicySources,_=r_(C),P=performance.now(),R=(()=>{const e=[],t=new Set;for(const o of[p,...r.dirs??[]]){const r=(0,i.resolve)(o);t.has(r)||(t.add(r),e.push(o))}return e.length>1?e:void 0})(),I=await async function(e){const{workingDirectory:t,projectDir:r}=e,o=function(e,t){const r=[],o=new Set;for(const s of[e,...t??[]]){const e=(0,i.resolve)(s);o.has(e)||(o.add(e),r.push(s))}return r}(t,e.dirs),s=o.length>1?o:void 0,n=zC(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,en.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new zp,h=new Ui(d,a,o),p=new ZC,f=new QC,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new KC(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=WC(n,"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||WC(n,"project")||WC(n,"user")||b,_=WC(n,"project")||WC(n,"user")||WC(n,"mdm"),P=WC(n,"team"),R=P&&void 0!==e.dashboardTransport,I=WC(n,"project")||WC(n,"user")||P||R||b,T=i=>VC({workingDirectory:t,...void 0!==s?{workspaceRoots:s}:{},adapters:{...i.includeMcp?{mcp:hk({teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:WC(n,"project"),includeUserMcp:WC(n,"user"),includePluginMcp:b,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:kC({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},..._?{hooks:dC({includeProjectHooks:WC(n,"project"),includeUserHooks:WC(n,"user"),includeEnterpriseHooks:WC(n,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:fC({includeProjectExtensibility:WC(n,"project"),includeUserExtensibility:WC(n,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:AC({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 XC(new gb(e)),createSessionMcpLease:(t,r)=>hk({teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:!1,ignoreApprovals:!0,includeProjectMcp:!1,includeUserMcp:!1,includePluginMcp:!1,inlineMcpServers:r}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{const r=w??new JC;return{pendingDecisionStore:r,fileChangeTracker:new Up(t),permissionsService:new Tv(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 lC(new rC(e.resources,o.hookExecutor,(()=>function(e,t){const r=nC(t,iC,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:nC(t,iC,"generationId","generation_id")??r,model:nC(t,iC,"model")??"unknown",...Ee({modelId:nC(t,iC,"modelId","model_id"),modelParams:nC(t,cC,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),o)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new YC(e.customSubagents??[]),o=t.services.subagentsService;return{subagentsService:void 0===o?r:new Bh([r,o])}}}]}:{}}});if(!x)return T({includeMcp:!1});try{return await T({includeMcp:!0})}catch(e){return WS.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),T({includeMcp:!1})}}({workingDirectory:p,...void 0!==R?{dirs:R}:{},projectDir:f,teamSettingsService:v,initializationCtx:a,dashboardTransport:y,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:C,defaultSandboxPolicySources:x,approvalMode:_?"allowlist":void 0,pendingDecisionProvider:_||!0===r.autoReview?new e_:void 0,getNetworkAllowlistInfo:_?()=>async function(e,t,r){const[o,s]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),n=[...s.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,en.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&n.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,en.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&n.push(...t.networkPolicy.allow)}const c=[...new Set(n)];return{hasDefaults:o.available&&o.allowlist.length>0,explicitEntries:c}}(v,(0,n.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:Qx,respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),T=performance.now()-P;let A,M;return(0,lx.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(u),bootstrap_statsig_ms:Math.round(h),create_workspace_runtime_ms:Math.round(T),load_sandbox_policy_ms:Math.round(E),total_ms:Math.round(performance.now()-l)}),{run:async(e,t,n)=>function(e,t){return BS.run(e,t)}(Xx,(async()=>{const i=(0,c.VI)((0,re.q6)().withName("sdk.run").with(d._O,Yx)),[a,l]=i.ctx.withCancel(),u=t.sessionId??(0,s.randomUUID)(),h=t.mcpServersOverride,f=void 0===(m=t.customTools)?[]:Object.entries(m).map((([e,t])=>({clientKey:tt,providerIdentifier:tt,toolName:e,name:`${tt}-${e}`,description:t.description??"",inputSchema:t.inputSchema??jx,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:t.annotations},source:"internal"})));var m;let g;g=await I.createSessionRuntime({sessionId:u,mcpServersOverride:h,extraMcpTools:f});const w=new Map;try{const i=g.resources.wrapped;Zx(g,t.customTools);const c=t.blobStore??new Yr.ve;let d=t.initialState??new mr.Y9z({});const m=void 0!==t.model?new ax.G4({modelId:t.model.id,parameters:(t.model.params??[]).map((e=>new ax.SR({id:e.id,value:e.value})))}):void 0,v=Array.isArray(e.images)?e.images.map((e=>{const t=(0,s.randomUUID)(),r=new Uint8Array(o.Buffer.from(e.data,"base64")),n=(0,Ux.v8)(r);return new cx.d({uuid:t,...n?{mimeType:n}:{},dataOrBlobId:{case:"data",value:r}})})):[],b=v.length>0?new cx.xv({selectedImages:v}):void 0,S=function(e){switch(e){case"agent":return mr.xyI.AGENT;case"plan":return mr.xyI.PLAN;default:return}}(t.mode),k=new mr.QFf({action:{case:"userMessageAction",value:new mr.Vtf({userMessage:new mr.RGk({text:e.text,selectedContext:b,...void 0!==S?{mode:S}:{}})})}}),E={sendUpdate:async(e,t)=>{const r=ux(t,u);null!==r&&await n.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return Cr(e.id);case"webFetchRequestQuery":return _r(e.id);case"switchModeRequestQuery":return Ir(e.id);case"askQuestionInteractionQuery":return Rr(e.id,new Jo.tz({result:{case:"rejected",value:new Jo.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return Ar(e.id,new wr.bK({result:{case:"success",value:new wr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return Mr(e.id,new Qo.r$({result:{case:"success",value:new Qo.JH}}));case"replaceEnvArgs":return Dr(e.id,new Zo.dV({result:{case:"failure",value:new Zo.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return Or(e.id,new Ko.HL({result:{case:"error",value:new Ko.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Nr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return jr(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return $r(e.id,e.query.value.args?.description);case void 0:throw new Lx.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new Lx.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(A!==t.apiKey||!M){await Promise.all([(0,Ux.ly)(t.apiKey),(0,Ux.mU)(t.apiKey)]);const e=(0,Ux.KU)(t.apiKey),r=Vs((0,oo.createClient)(ix.N,e),{injectTraceHeaders:!0});M=new Us(r),A=t.apiKey}const C=(0,Ux.Vh)(M,(()=>{const e=(0,Ux.KU)(t.apiKey),r=Vs((0,oo.createClient)(ix.N,e),{injectTraceHeaders:!0}),o=new Us(r);return M=o,A=t.apiKey,o})),x=function(e){return{...void 0!==e.allowedTools?{[Jx.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[Jx.VJ]:e.disallowedTools.join(",")}:{}}}(t),_=new nx({agentClient:C,getResources:async({agentId:e})=>{let r=w.get(e);var o;return r||(r=await I.createSessionRuntime({sessionId:e,mcpServersOverride:h,extraMcpTools:f,...(o=t.subagentInherit,void 0===o?{}:{...void 0!==o.resourceProviderOptions?{localResourceProviderOptions:o.resourceProviderOptions}:{},...void 0!==o.reportedWorkspacePath?{reportedWorkspacePath:o.reportedWorkspacePath}:{}})}),Zx(r,t.customTools),r.resources.base.register(zr,P),r.resources.base.register(Wr,R),r.resources.base.register(Hr,T),w.set(e,r)),r.resources.wrapped},mcpTools:f,workspacePath:p,parentConversationId:u,...void 0!==t.subagentInherit&&Object.keys(x).length>0?{headers:x}:{},onSessionReleased:e=>{const t=w.get(e);t&&(t.dispose(),w.delete(e))}}),P=function(e){const t=new Map,r=new Map;async function o(t,r,o){let s;try{s=await e.createOrResumeSession(t,r);const n=await e.runSession(t,s,r,{execId:o?.execId});return"error"===n.status?new Lr.vS({result:{case:"error",value:new Lr.od({agentId:s,error:n.error})}}):"aborted"===n.status?new Lr.vS({result:{case:"error",value:new Lr.od({agentId:s,error:n.error??"Subagent was aborted by the user"})}}):"background"===n.status?new Lr.vS({result:{case:"success",value:new Lr.HJ({agentId:s,finalMessage:n.finalMessage,toolCallCount:n.toolCallCount??0,backgroundReason:n.backgroundReason,transcriptPath:n.transcriptPath})}}):new Lr.vS({result:{case:"success",value:new Lr.HJ({agentId:s,finalMessage:n.finalMessage,toolCallCount:n.toolCallCount??0})}})}catch(t){if(s&&e.releaseSession&&e.releaseSession(s),t instanceof Er)throw t;const o=t instanceof Error?t.message:String(t),n=s??function(e){if(e instanceof Br&&e.agentId)return e.agentId;if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.agentId?t.agentId:void 0}(t)??r.resumeAgentId;return new Lr.vS({result:{case:"error",value:new Lr.od({...n?{agentId:n}:{},error:o})}})}}return{execute(e,s,n){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(s);if(void 0===i)return o(e,s,n);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,s,n).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}}}(_),R=(y=_,{execute:(e,t)=>y.awaitBackgroundRunBounded(e,t)}),T=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(_);g.resources.base.register(zr,P),g.resources.base.register(Wr,R),g.resources.base.register(Hr,T);const D=I.services.hooksRuntime,O=D?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(ie.sessionStart)||t.hooksConfigLease.hasHookForStep(ie.sessionEnd)||t.hooksConfigLease.hasHookForStep(ie.stop)||t.hooksConfigLease.hasHookForStep(ie.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:o}=r;let s;return{async onSessionStart(e){if(s=e,o.hasHooksForStep(ie.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ee(e),is_background_agent:!1},r=await o.executeHookForStep(ie.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){WS.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(o.hasHooksForStep(ie.sessionEnd))try{const r={conversation_id:s?.conversationId??"",generation_id:s?.generationId??"",model:s?.model??"unknown",...s?Ee(s):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await o.executeHookForStep(ie.sessionEnd,r)}catch(e){WS.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{o.clearSessionEnvironment()}else o.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(o.hasHooksForStep(ie.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ee(e),prompt:e.promptText??"",attachments:[]};await o.executeHookForStep(ie.beforeSubmitPrompt,t)}catch(e){WS.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!o.hasHooksForStep(ie.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ee(e),status:"completed",loop_count:e.loopCount},r=await o.executeHookForStep(ie.stop,t),s="string"==typeof r?.followup_message?r.followup_message.trim():"";return s.length>0?s:void 0},async onTurnError(e){if(o.hasHooksForStep(ie.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ee(e),status:"error",loop_count:e.loopCount};await o.executeHookForStep(ie.stop,t)}catch(e){WS.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(o.hasHooksForStep(ie.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ee(e),status:"aborted",loop_count:e.loopCount};await o.executeHookForStep(ie.stop,t)}catch(e){WS.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:D,sessionState:g.state,metadata:g.metadata}):void 0,N=new rx({workspacePath:p,conversationId:u,blobStore:c}),j=function(e,t,r){const{hooks:o}=r,[n,i]=e.withCancel(),a=new LS;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),KS(e)},m=r.interactionListener,g={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),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup"}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=qS(function(e,t){if((0,Yr.TU)(t))return t;const r=GS.get(e);if(void 0!==r)return r;const o=(0,Yr.sh)(e).blobEncryptionKey;if(void 0===o)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return GS.set(e,o),o}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=JS(r,0,VS(t));try{const t=await(o?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;WS.warn("[agent-session-runner] sessionStart hook failed:",e)}let i=t,h=0;for(;i;){const e=JS(r,h,VS(i));try{await(o?.onBeforeSubmitPrompt?.(e))}catch(e){WS.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,s.randomUUID)();try{await r.agentClient.run(n,w,i,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=ZS(t)?"aborted":"error",QS("aborted"===v?o?.onTurnAborted?.(e):o?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(o?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const m="string"==typeof t?t.trim():"";let b;if(m.length>0)b=KS(m);else{const t=new AbortController;d=t;try{b=await(r.nextAction?.(e,AbortSignal.any([n.signal,t.signal])))}catch(r){if(n.signal.aborted||!t.signal.aborted)throw v=n.signal.aborted||ZS(r)?"aborted":"error",QS("aborted"===v?o?.onTurnAborted?.(e):o?.onTurnError?.(e)),r}finally{d=void 0}void 0===b?b=f():p("revert_to_followup")}void 0!==b?(h+=1,a.resetStream(),i=b):i=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(o?.onSessionEnd?.(v,e))}catch(e){WS.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(o?.dispose?.())}catch(e){WS.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){i()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,s.randomUUID)(),o=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new mr.QFf({action:{case:"injectContextAction",value:new mr.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new mr.oW$({userMessage:new mr.RGk({messageId:(0,s.randomUUID)(),text:e})})}})}})),await o}catch(e){return u(r,"revert_to_followup"),WS.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,k,{agentClient:C,interactionListener:E,resources:i,blobStore:c,initialState:d,conversationId:u,mcpTools:f,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,...Object.keys(x).length>0?{headers:x}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:O,async nextAction(e,t){const r=await _.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new mr.QFf({action:{case:"backgroundTaskCompletionAction",value:new mr.Kwc({completions:e.map((e=>new mr.KFq({taskId:e.agentId,kind:mr.aZc.SUBAGENT,status:"success"===e.status?mr.uHL.SUCCESS:"aborted"===e.status?mr.uHL.ABORTED:mr.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){d=e,N.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),$=j.done.finally((async()=>{try{await _.awaitBackgroundWorkers()}finally{await N.waitForPendingWrites().catch((()=>{}));for(const e of w.values())try{await e.dispose()}catch(e){qx.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}w.clear(),await g.dispose()}})).catch((e=>{throw e}));return{abort(){j.abort(),l()},done:$,steer:e=>j.steer(e)}}catch(e){for(const e of w.values())try{await e.dispose()}catch{}throw w.clear(),await g.dispose(),e}var y})),async reload(){await I.reload()},async dispose(){await I.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=r("./src/agent/native/vendored-tree-sitter.ts"),n=s({packageName:"tree-sitter",nativeRequire:require});e.exports=n.available?n.module:o(n.reason)},"../constants/dist/mcp.js"(e,t,r){"use strict";r.d(t,{AB:()=>f,Di:()=>l,G$:()=>y,NC:()=>g,OY:()=>C,Qy:()=>c,RJ:()=>x,TI:()=>o,TS:()=>w,sr:()=>u,tl:()=>S,uS:()=>m,vI:()=>d});const o="cursor/requiresConfirmation",s="https://grok.com/connectors-oauth-exchange-code/",n="https://x.com/i/connectors/oauth_callback",i={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"consent"}},a={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[s,n]},c="x-cursor-auth";function l(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return"https:"===t.protocol&&"api.cursor.com"===t.hostname.toLowerCase()&&""===t.port?u(e):void 0}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 e||null===e)return{};const t=e,r="string"==typeof t.cursor_client_id&&t.cursor_client_id.length>0?t.cursor_client_id:void 0;let o;if("object"==typeof t.cursor_authorization_params&&null!==t.cursor_authorization_params){const e=Object.entries(t.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==r?{clientId:r}:{},...!0===t.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===t.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===t.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===t.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===t.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===t.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={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},p=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,scopes:["tweet.read","users.read","follows.read","space.read","mute.read","like.read","list.read","list.write","block.read","block.write","bookmark.read","bookmark.write","dm.read","dm.write","developer.billing.write","developer.write","offline.access"],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",h],["connectors-gateway.grok.com",h],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}]]);function f(e){if(void 0===e)return!1;let t;try{t=new URL(e)}catch{return!1}return"https:"===t.protocol&&"gtm-api.corp.anysphere.co"===t.hostname&&""===t.port&&"/mcp"===t.pathname}function m(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 p.get(e.toLowerCase())}(t)}(t)?.authorizationParams;if(void 0!==r)for(const[t,o]of Object.entries(r))e.searchParams.set(t,o)}function g(e){return"login.microsoftonline.com"===e.hostname}function w(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([...p].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e)));const y="https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg",v="https://www.cursor.com/bot/mcp/oauth/callback",b="grokbot://mcp/oauth/callback",S="http://localhost:8787/callback",k="gb";function E(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 C(e){const t=e.redirectUrl??S;if(!0!==e.loopbackIpv4||!E(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function x(e){const t=new Set,r=void 0!==e&&E(e);return e&&!r&&t.add(e),t.add("https://www.cursor.com/agents/mcp/oauth/callback"),e===b&&t.add(v),t.add(S),e&&r&&t.add(e),Array.from(t)}new Map([[k,b],["gw",s],["gd",S],["xa",n]]),new Map([[b,k],[v,k],[s,"gw"],[n,"xa"]]),C({loopbackIpv4:!0})},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){"use strict";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){"use strict";r.d(t,{BJ:()=>a,rh:()=>n});var o=r("../mcp-core/dist/mcp-tool-annotations.js");function s(e){return e.trim().toLowerCase()}function n(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=s(e);return 0!==r.length&&t.some((e=>s(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?"":s(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(t??[]).map(s).filter((e=>e.length>0)),o=void 0===e?void 0:s(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:(n=[...o.flatMap((e=>[...e.flattened])),...r],[...new Set(n)]),policies:o.map((e=>({name:e.name,policy:e.policy})))};var n}r("../mcp-core/dist/transport/mcp-url-utils.js")},"../mcp-core/dist/index.js"(e,t,r){"use strict";r.d(t,{B1j:()=>a,c8u:()=>re,uOd:()=>ae,E_S:()=>ce,Ico:()=>X,O3I:()=>g,tBH:()=>p,MEY:()=>o.ME,eod:()=>c,Fmf:()=>te,jIB:()=>J,VDJ:()=>M,X5z:()=>T,$HQ:()=>o.$H,YaX:()=>i,Gpm:()=>ie,PKk:()=>fe,_NE:()=>o._N,Ezk:()=>ue.Ez,qFm:()=>le.qF,eaG:()=>R,q2e:()=>d,mtU:()=>he,utF:()=>pe});var o=r("../mcp-core/dist/transport/mcp-url-utils.js");function s(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function n(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=s(t.command),a=n(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=s(t.command),a=n(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)}}async function c(e){const t=[],r=new Set;let o;for(let s=1;;s++){const n=await e.fetchPage(o),i=e.itemsOf(n);t.push(...i);const a=e.nextCursorOf(n);if(!a||r.has(a))return t;if(s>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),o=a}}function l(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function u(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 d(e,t){return u(e,t)}var h=r("crypto");function p(e,t){const r=e?.access_token,o="string"==typeof r?r.length:0,s=Boolean(e?.refresh_token),n="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:o,refreshTokenPresent:s,expiresAtTimestamp:t?.expiresInIsFresh&&null!==n?Date.now()+Math.round(1e3*n):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function f(e){if(e)return(0,h.createHash)("sha256").update(e).digest("hex").slice(0,12)}function m(e){if(e&&0!==e.length)return f(JSON.stringify([...e].sort()))}function g(e){return{clientIdHash:f(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:m(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function w(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 y(e,t){for(const r of t)if("string"==typeof w(e,r.split(".")))return w(e,r.split("."))}function v(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function b(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 S(e){if(e instanceof Error){const t=e.message;return t&&t!==e.name?R(t):void 0}if(null!=e){const t=String(e);return t?R(t):void 0}}function k(e){if(e&&"object"==typeof e)return e.cause}function E(e,t=4){const r=[];let o=e;for(let e=0;e<t&&null!=o;e++){if(!(o instanceof Error)){r.push(R(String(o)));break}{const e=S(o);r.push(e?`${o.name}: ${e}`:o.name),o=k(o)}}return r.length>1?r.join(" > "):void 0}const C="[REDACTED]",x=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function _(e){return e.replace(/((?:access_token|refresh_token|id_token|client_secret|authorization|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${C}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${C}`)}function P(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function R(e,t){return P(_(e),t?.maxLength)}function I(e){if("string"==typeof e)return P(_(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")||x.test(t)}(e)?C:"string"==typeof t?_(t):t));if(!t)return;return P(t)}catch{return}}function T(e){const t=k(e),r=e instanceof Error?e.name:null!=e?typeof e:void 0,o=t instanceof Error?t.name:void 0,s=S(t),n=S(e)??s,i=y(e,["code","cause.code"]),a=v(e)??v(t)??y(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=w(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??b(n)??b(s),u=I(w(e,["response","body"])??w(e,["body"])??w(e,["data"])??w(e,["cause","body"])??w(e,["cause","response","body"])),d=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:n,code:i}),h=a?"oauth_error":d?"auth_transport_error":n?"generic_error":void 0;return l({errorName:r,errorMessage:n,errorType:null!=e?typeof e:void 0,httpStatus:c,oauthErrorCode:a,errorResponseSummary:u,networkClassification:d,causeName:o,causeMessage:s,causeChain:E(e),sdkErrorKind:h})}const A={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 M(e){const t=e.message??A[e.event],r={event:e.event,cursorMcp:{oauth:l({...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 D=4096;function O(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function N(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function j(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function $(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function F(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:$(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:$(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:$(t.get("content-length"))??o}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:$(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:$(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:$(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:$(t.get("content-length"))}}function L(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 s=e>=0?t.slice(e+1):"";try{return decodeURIComponent(s.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 U(e){const{input:t,init:r}=e,o=u(N(t)),s=function(e,t){const r=new Headers(O(e)?e.headers:void 0);return new Headers(t?.headers).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),n=j(s),i=s.get("content-type"),a=f(s.get("mcp-session-id")??void 0),c=s.get("authorization"),l=c?c.split(/\s+/,1)[0]??null:null;return{method:(r?.method??(O(t)?t.method:void 0)??"GET").toUpperCase(),url:o,headers:{names:n,count:n.length},contentType:i,body:F(r?.body,s),sessionIdHash:a??null,authorizationScheme:l}}function B(e,t){const r=j(e.headers),o=$(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:f(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:f(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null}}function z(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 W(e,t){const r=U({input:e,init:t});if(void 0!==L(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 H(e,t){try{const r=await e.clone().text();return r.length>t?r.slice(0,t):r}catch{return}}async function q(e){if(!W(e.input,e.init))return;const t=await H(e.response,D);if(void 0!==t)try{return I(JSON.parse(t))}catch{return R(t,{maxLength:D})}}async function G(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 H(t,D);if(void 0===o)return;return function(e){if("/mcp"!==(t=u(N(e.input)).path)&&!0!==t?.endsWith("/mcp"))return R(e.rawText,{maxLength:D});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,s="string"==typeof r.message?R(r.message,{maxLength:D}):void 0;return void 0!==o||void 0!==s?JSON.stringify({...void 0!==o?{code:o}:{},...void 0!==s?{message:s}:{}}):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 q({input:e.input,response:e.response,init:e.init}):void 0}}function V(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function J(e){const{fetch:t,logger:r,metadata:o,logSuccessfulExchanges:s=!0}=e;return async(e,n)=>{const i=Date.now();try{const a=await t(e,n),{responseErrorSummary:c,oauthTokenErrorBodySummary:l}=a.ok?{}:await G({input:e,init:n,response:a});return!s&&a.ok||V((()=>{!function(e){const{logger:t,response:r}=e,o=function(e){const{input:t,init:r,response:o,durationMs:s,metadata:n,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=U({input:t,init:r}),l=L(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:o.ok?"success":"http_error",durationMs:s,cursorMcp:{transport:{...n,request:c,response:B(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")&&!W(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:n,response:a,durationMs:Date.now()-i,metadata:o,responseErrorSummary:c,oauthTokenErrorBodySummary:l})}),r,"success"),a}catch(t){const s=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}=s?await G({input:e,init:n,response:s}):{};throw V((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:o,durationMs:s,metadata:n,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=T(o),u=U({input:t,init:r}),d=L(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:s,cursorMcp:{transport:{...n,request:u,response:void 0!==i?B(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},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:z(l)}}}}(e))}({logger:r,input:e,init:n,error:t,durationMs:Date.now()-i,metadata:o,responseFromError:s,responseErrorSummary:a,oauthTokenErrorBodySummary:c})}),r,"failure"),t}}}new Set(["InvalidGrantError","InvalidRequestError"]),new Set(["SiblingAlreadyRefreshedError","OAuthRefreshTransientError","AbortError","TimeoutError","ServerError","TemporarilyUnavailableError"]);const K=["0.0.0.0/0","::/0"];function Z(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 Q(e){const t=Z(e.mcpNetworkAllowlist),r=Z(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:[...K],...r.entries.length>0?{deny:r.entries}:{}};if("allowlist"===o||t.hasConfiguredEntries){const e=function(e){return e.entries.includes("*")?[...K]: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:[...K],...r.entries.length>0?{deny:r.entries}:{}}}async function X(e,t){const{resolveSandboxPolicyForWorkspace:o}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),s={type:"workspace_readwrite",sandboxWorkspaceRoot:t,networkPolicy:Q(e),networkPolicyStrict:!0},{policy:n}=await o(t,{perUser:s});return n}const Y=["0.0.0.0/0","::/0"];function ee(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 te(e){const t=!0===e.enabled,r=ee(e.mcpNetworkDenylist),s="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,n=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...Y];const t=ee(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...Y]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...Y];const r=(0,o.b6)(e);return r.includes("*")?[...Y]:r}(e):[],i=t?s?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:s?[]:n,deny:i})}class re 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=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=63cee2b55763348466f935d01670e7b7320e197e830_5717c2b3ad2e8aee1cd0dc4257547d9e/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,Error;const oe=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),se=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),ne=[/\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 ie(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&oe.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!se.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&&ne.some((e=>e.test(o)))}(e)}new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]),new Set([429,502,503,504]);const ae=8192;function ce(e,t){void 0!==t&&t.length>0&&e.searchParams.set("scope",t.join(" "))}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);var le=r("../mcp-core/dist/oauth/resolved-oauth-client-id.js"),ue=r("../mcp-core/dist/oauth/rest-mcp-provider-metadata.js");Error;var de=r("../constants/dist/mcp.js");function he(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()===de.Qy));if(void 0===o)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let s;try{s=new URL(e).origin}catch{s=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==de.Qy))),cursorAuthHeaderValue:o[1],cursorAuthOrigin:s}}function pe(e,t,r){return async(o,s)=>{let n;try{n=new URL("string"==typeof o?o:o.toString()).origin}catch{return r(o,s)}if(n!==t)return r(o,s);const i=await e();if(void 0===i||0===i.length)return r(o,s);const a=new Headers(s?.headers);return a.set(de.Qy,i),r(o,{...s,headers:a,redirect:"manual"})}}function fe(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 s=Number.parseInt(o[1],10);return Number.isNaN(s)?void 0:s}(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)}},"../mcp-core/dist/mcp-tool-annotations.js"(e,t,r){"use strict";r.d(t,{NY:()=>s,hT:()=>i,yC:()=>n});var o=r("../constants/dist/mcp.js");function s(e){return void 0!==e&&!0!==e.destructiveHint&&!0===e.readOnlyHint}function n(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){"use strict";r.d(t,{qF:()=>s});const o=/\$\{[^}]*\}/;function s(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){"use strict";r.d(t,{Ez:()=>n});var o=r("../constants/dist/mcp.js");const s=new Map;async function n(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}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>H,ME:()=>L,_N:()=>W,b6:()=>F,bi:()=>P,mD:()=>A,vc:()=>N});const o=BigInt(0),s=BigInt(8),n=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<<s|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 s=a(o);if(!s)return;t.push(Number(s.value>>n&i)),t.push(Number(s.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=j(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<<n|BigInt(t)),o)}}if(-1!==t.indexOf("::",r+1))return;const s=t.slice(0,r),i=t.slice(r+2),a=c(s),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<<n|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>=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value}}(j(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=j(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)),s=4===r.version?32:128;if(!Number.isInteger(o)||o<0||o>s)return{kind:"invalidCidr"};const n=BigInt(s-o);return{kind:"cidr",version:r.version,shift:n,shiftedNetwork:r.value>>n}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}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=j(e);return t.length>0&&t.length<=253&&g.test(t)}function E(e){const t=j(e);return v.test(t)||function(e){const t=j(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=j(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=j(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(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${j(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 s=t.trim().toLowerCase(),n=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}(s);return 0===n.length||!_(n)||n!==s&&"*"===n?void 0:n}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function 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 s;try{s=new URL(e)}catch{return!1}return""===s.username&&""===s.password&&""===o.username&&""===o.password&&s.protocol===o.protocol&&s.port===o.port&&(n=s.hostname,i=o.hostname,!n.includes("*")&&j(n)===j(i)&&(A(a=s.pathname,c=o.pathname)||A(M(a),M(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(s.search,o.search,r));var n,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=$(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!j(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),o=t.indexOf("]",e);if(-1===o)return;const s=t.slice(e+1,o);if(j(r.hostname)!==j(s))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>=R&&T.clear(),r=$(t),T.set(t,r)),!!r&&h(r.hostname,e)}function j(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}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}}function F(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=F(t);return r.length>0&&r.some((t=>function(e,t){const r=O(t);if(!r)return!1;if(!e.includes("://"))return h(j(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 z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function W({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:o,unmatchedServerAllowlist:s,aggregateManagedServerNetworkAllowlists:n=!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 s=e.slice(0,o).toLowerCase();if("http"!==s&&"https"!==s)return;const n=e.slice(o+3).split(/[/?#]/,1)[0];if(void 0===n||n.includes("@"))return;const i=P(n.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 s=U(e.command),n=U(e.serverUrl);if(void 0===s&&void 0===n)return!1;const i=void 0===s||void 0!==t.command&&A(s,t.command),a=void 0===n||void 0!==t.url&&N(n,t.url);return i&&a}(e,t)))}(c,t),d=z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?n?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,s),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 H(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>ar,Ls:()=>Qt,SandboxUnsupportedError:()=>Ue,J:()=>y,St:()=>ze,Fn:()=>ir,r5:()=>J,oG:()=>Nt,Ko:()=>k,CG:()=>ct,G6:()=>nr,_B:()=>pe,OK:()=>ce,$b:()=>he,K3:()=>qe,tv:()=>tr,wG:()=>ft,fZ:()=>gt,s9:()=>ut,XX:()=>pt,T6:()=>me,Po:()=>fe,$6:()=>er,l7:()=>rr,xS:()=>w,resolveSandboxPolicyForWorkspace:()=>vt,spawnInSandbox:()=>We,Xw:()=>S});var o=r("node:path"),s=r("node:fs"),n=r("../utils/dist/lru-cache.js");const i="undefined"!=typeof process&&"win32"===process.platform,a=new n.q({max:512});function c(e){try{return s.statSync(e)}catch{return null}}function l(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,s=a.get(r);if(void 0!==s)return s;const n=o.join(".",e);if(c(n))return a.set(r,n),n;const l=process.env.PATH.split(i?";":":");for(const s of l){const n=o.join(s,e);if(c(n)&&(!t||t.test(n)))return a.set(r,n),n}return a.set(r,e),e}function u(e,t,r){if("win32"!==process.platform)return{cmd:l(e),args:t};if(!s.existsSync(e)){const o=[".exe",".bat",".cmd",".ps1"],n=e.toLowerCase();if(o.some((e=>n.endsWith(e)))){const o=l(e,r);if(s.existsSync(o))return u(o,t,r)}for(const n of o){const o=l(`${e}${n}`,r);if(s.existsSync(o))return u(o,t,r)}}return e.match(/\.ps1$/i)?{cmd:o.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:o.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}}var d=r("node:fs/promises"),h=r("node:os"),p=r("../context/dist/otel.js"),f=r("../utils/dist/writable-iterable.js"),m=r("node:child_process");let g;function w(){const e=u("rg",[]).cmd;return"rg"!==e?e:void 0}function y(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");g=e}function v(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 b(e,t){const r=(0,o.dirname)(t);if(!r||"."===r)return e;const s=function(e){const t=v(e);return void 0!==t?e[t]??"":""}(e).split(o.delimiter).filter(Boolean);return function(e,t){const r=v(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,...s.filter((e=>e!==r))].join(o.delimiter))}function S(e){return g&&(0,o.isAbsolute)(g)?{...b(e,g),CURSOR_RIPGREP_PATH:g}:e}function k(){if(!g)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return g}var E=r("../utils/dist/workload-spawn.js");function C(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;return o}const x=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function _(e){const t={...e};for(const e of x)delete t[e];return t}var P=r("node:crypto"),R=r("../utils/dist/workspace-paths.js");let I;function T(e,t){const r=(0,s.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function A(e){try{(0,s.mkdirSync)(e,{mode:448})}catch(e){if("EEXIST"!==e.code)throw e}}const M='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ';function D(e=(0,o.join)((0,h.tmpdir)(),"cursor-sandbox-cache",function(){return I||(I=(0,P.randomBytes)(16).toString("hex")),I}())){return{NPM_CONFIG_CACHE:(0,o.join)(e,"npm"),PNPM_STORE_PATH:(0,o.join)(e,"pnpm-store"),GOCACHE:(0,o.join)(e,"go-build"),GOMODCACHE:(0,o.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,o.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,o.join)(e,"pip"),UV_CACHE_DIR:(0,o.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,o.join)(e,"bun"),YARN_CACHE_FOLDER:(0,o.join)(e,"yarn"),npm_config_devdir:(0,o.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,o.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,o.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,o.join)(e,"turbo"),GRADLE_USER_HOME:(0,o.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,o.join)(e,"conda"),POETRY_CACHE_DIR:(0,o.join)(e,"poetry"),GEM_SPEC_CACHE:(0,o.join)(e,"gem-specs"),BUNDLE_PATH:(0,o.join)(e,"bundle"),COMPOSER_HOME:(0,o.join)(e,"composer"),HOMEBREW_CACHE:(0,o.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,o.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,o.join)(e,"nx"),NUGET_PACKAGES:(0,o.join)(e,"nuget"),CCACHE_DIR:(0,o.join)(e,"ccache"),CP_HOME_DIR:(0,o.join)(e,"cocoapods")}}var O=r("../context/dist/logger.js"),N=r("../context/dist/core.js"),j=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),$=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class F extends Error{constructor(e,t,r,o,s,n){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=s,this.stderr=n,this.command=r,this.args=o,Error.captureStackTrace&&Error.captureStackTrace(this,F)}}function L(e,t,r){r=r??{};let o=new j.Observable((o=>{const{encoding:s,timeout:n,...i}=r,{cmd:a,args:c}=u(e,t),l=i.stdin;l&&(delete i.stdin,i.stdio??=["pipe","pipe","pipe"]),i.stdio??=["ignore","pipe","pipe"];const d=(0,m.spawn)(a,c,i);r.processInfo&&void 0!==d.pid&&(r.processInfo.pid=d.pid);let h=null;n&&n>0&&(h=setTimeout((()=>{d.killed||d.kill();const e=new F(`Process timed out after ${n}ms`,-1,a,c);o.error(e)}),n));const p=t=>n=>{if(n.length<1)return;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(n);let i="<< String sent back was too long >>";try{i="string"==typeof n?n.toString():n.toString(s||"utf8")}catch{i=`<< Lost chunk of process output for ${e} - length was ${n.length}>>`}o.next({source:t,text:i})},f=new j.Subscription;if(l)if(d.stdin){const e=d.stdin;f.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 g=null,w=null,y=!1;return d.stdout?(w=new j.AsyncSubject,d.stdout.on("data",p("stdout")),d.stdout.on("close",(()=>{w.next(!0),w.complete()}))):w=(0,j.of)(!0),d.stderr?(g=new j.AsyncSubject,d.stderr.on("data",p("stderr")),d.stderr.on("close",(()=>{g.next(!0),g.complete()}))):g=(0,j.of)(!0),d.on("error",(e=>{y=!0,h&&clearTimeout(h),o.error(e)})),d.on("close",(e=>{y=!0,h&&clearTimeout(h);const t=(0,j.merge)(w,g).pipe((0,$.TS)((e=>!0),!0));0===e?t.subscribe((()=>o.complete())):t.subscribe((()=>{const t=new F(`Process failed with exit code: ${e}`,e,a,c);o.error(t)}))})),f.add(new j.Subscription((()=>{y||(h&&clearTimeout(h),d.kill())}))),f}));if(r.retries&&r.retries>0){const e=r.retries,t=r.retryDelay??1e3;o=o.pipe((0,$.L5)({count:e,delay:(e,r)=>{if(e instanceof F&&0!==e.exitCode)return(0,j.timer)(t);throw e}}))}return r.split?o:o.pipe((0,$.Tj)((e=>e?.text)))}function U(e,t,r){return r?.split?(o=L(e,t,{...r??{},split:!0}),new Promise(((e,t)=>{let r="",s="";o.subscribe({next:e=>{"stdout"===e.source?r+=e.text:s+=e.text},error:e=>{if(e instanceof F){const o=new F(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,s);t(o)}else{const o=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(o)}},complete:()=>e([r,s])})}))):function(e){return new Promise(((t,r)=>{let o="";e.subscribe({next:e=>{o+=e},error:e=>{if(e instanceof F){const t=new F(`${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)})}))}(L(e,t,{...r??{},split:!1}));var o}var B=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const z=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],W=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],H=(e,t)=>t.flatMap((t=>W.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),q={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},G=e=>[...z,...q[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),V=[{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"},...G("linux"),...H("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"},...G("darwin"),...H("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 J(e=process.platform,t=h.homedir(),r={}){const n=[];for(const i of V){if(i.platform!==e)continue;if("global"===i.scope){n.push(i.path);continue}const a="bundled"===i.scope?r[i.path]:(0,o.join)(t,i.path);if(a)try{let e;switch(i.scope){case"home":e=(0,s.lstatSync)(a).isFile();break;case"home-dir":e=(0,s.lstatSync)(a).isDirectory();break;case"bundled":e=(0,s.statSync)(a).isFile()}e&&n.push(a)}catch{}}return n}const K=[{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 Z(e){const t=K.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function Q(e){const t=K.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}K.filter((e=>"git"===e.type)).map((e=>e.pattern)),K.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const X=[];let Y=null,ee=null;let te=null;const re=new Map;const oe="win32"===process.platform||"darwin"===process.platform;function se(e){if(!e.endsWith(o.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function ne(e){return e.endsWith(o.sep)?e:e+o.sep}function ie(e,t){const r=se(t);if(oe){const t=e.toLowerCase(),o=r.toLowerCase();return t===o||t.startsWith(ne(o))}return e===r||e.startsWith(ne(r))}function ae(e,t){const r=se(e);return oe?(0,o.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,o.relative)(r,t).replace(/\\/g,"/")}async function ce(e,t){if(ie(e,t)){const r=ae(t,e);if((null===Y&&(Y=B({ignoreCase:!0}),Y.add(K.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Y).ignores(r))return!0}const{isWorktree:r,gitDirParent:s}=await async function(e){const t=re.get(e);if(t)return t;const r=await(0,d.stat)((0,o.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return re.set(e,t),t}const s=await async function(e){try{const t=await U("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,o.dirname)((0,o.resolve)(e,t.trim()))}catch{return null}}(e),n={isWorktree:!0,gitDirParent:s??e};return re.set(e,n),n}(t);if(ie(e,s)){const t=ae(s,e);if((null===ee&&(ee=B({ignoreCase:!0}),ee.add(K.filter((e=>"git"===e.type)).map((e=>e.pattern)))),ee).ignores(t))return!0}if(r&&ie(e,t)&&".git"===ae(t,e))return!0;for(const t of function(){if(null!==te)return te;const e=h.homedir(),t=[];for(const r of K)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,o.join)(e,r.pattern))}return te=t,t}())if(ie(e,t))return!0;return!1}const le=m.execFile,ue=new WeakMap;function de(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}function he(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function pe(e){return void 0!==e&&"allow"===e.default}function fe(){return{version:1,default:"deny"}}function me(){return{version:1,default:"allow"}}let ge=0;function we(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?o.resolve(e):o.resolve(o.join(h.homedir(),".cursor","sandbox-policies"))}();s.mkdirSync(e,{recursive:!0,mode:448});try{s.chmodSync(e,448)}catch{}const t=Date.now();return t-ge>=9e5&&(ge=t,function(e){let t;try{t=s.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=o.join(e,n);try{const e=s.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&s.unlinkSync(t)}catch{}}}(e)),e}function ye(e){const t=we(),r=P.randomBytes(8).toString("hex"),n=o.join(t,`sandbox-policy-${r}`);return s.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ve="darwin"===process.platform,be="linux"===process.platform,Se=(0,O.h)("shell-exec:sandbox");function ke(e){const t=we();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Ee,Ce=!0;function xe(){return Ee}function _e(e){"linux"===process.platform&&Object.assign(e,S(e))}let Pe=null,Re=null,Ie=null,Te=null;function Ae(e){return{...e,additionalReadonlyPaths:ke(e.additionalReadonlyPaths)}}function Me(e,t,r){let n;e.ignoreMapping&&(n=function(e){return $e(e)}(e.ignoreMapping));const i=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,s.existsSync)(r)&&(0,s.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):"/",s=e>=0?r.slice(e+1):r;t[o]||(t[o]=[]),s?t[o].push(s,`${s}/**`):t[o].push("**")}}return t}(...e):{},i=function(e){let t=o.resolve(e);for(;;){try{const e=o.join(t,".git");if(s.existsSync(e))return!0}catch{}const e=o.dirname(t);if(e===t)return!1;t=e}}(r),a=!be||i?t??{}:{},c={...n};for(const[e,t]of Object.entries(a))c[e]?c[e]=[...c[e],...t]:c[e]=t;if(0!==Object.keys(c).length)return $e(c)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),a=(c=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Ce;return"function"==typeof e?e():e}()?c??"system":"system");var c;const l=function(e=process.platform){const t=[],r=new Set,o={};try{o.ripgrep=k()}catch{}for(const s of J(e,h.homedir(),o))r.has(s)||(r.add(s),t.push(s));return t}(),u="workspace"===a?function(e){const t=[],r=new Set;for(const s of e){let e=s.trim();if(!e)continue;"~"===e?e=h.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=o.join(h.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const n=o.basename(e);if((n.includes("*")||n.includes("?"))&&(e=o.dirname(e)),!e||"."===e)continue;const i=o.normalize(e);r.has(i)||(r.add(i),t.push(i))}return t}(e.additionalReadPaths??[]):[],d=[...l],p=new Set(l);for(const e of u)p.has(e)||(p.add(e),d.push(e));const f={cwd:t,readBoundary:a,hardcodedReadPaths:d,additionalReadonlyPaths:i,networkAccess:he(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...f}:{type:e.type,...f,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function De(e){if(null!==Pe)return!!Pe;try{const t=xe();return Se.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(Pe=s.existsSync(t),Pe?Se.info(e,`[checkBinaryAvailable] Binary path exists: ${Pe}`):(Re=new Error(`Sandbox binary not found at ${t}`),Se.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!Pe):(Re=new Error("Sandbox binary path was not configured"),Pe=!1,Se.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return Re=t,Pe=!1,Se.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function Oe(e){if(null!==Te)return Te;const t=e??(0,N.q6)();if(Se.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!De(t)){const e=Re?.message||"Binary check failed";return Ie=e,Se.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),Te=!1,Te}if("win32"===process.platform)return Ie="Windows sandbox helper only provides network proxy, not filesystem isolation",Se.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),Te=!1,Te;if("darwin"===process.platform)return Ie=null,Se.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),Te=!0,Te;const{binaryPath:r,args:o,env:s}=function(e,t){const r={sandbox:Me(Ae({type:"workspace_readwrite"}),t)},o=String(xe());Se.info(e,`[sandboxPreflight] Running preflight with binary: ${o}`),Se.info(e,`[sandboxPreflight] CWD: ${t}`);const s={...process.env};return _e(s),{binaryPath:o,args:["--policy",ye(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:s}}(t,process.cwd());try{const e=Date.now();(0,E.D9)(m.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:Ne,env:s,shell:!1});const n=Date.now()-e;return Ie=null,Se.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${n}ms, sandbox supported!`),Te=!0,Te}catch(e){const r=e;return function(e,t){const{message:r,status:o,stderrText:s}=t;return Se.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Se.error(e,`[sandboxPreflight] Exit status: ${o}`),s&&Se.error(e,`[sandboxPreflight] Stderr: ${s}`),Ie=2===o?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${s||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${o}. stderr: ${s||"none"}`,Te=!1,!1}(t,{message:r.message,status:r.status,stderrText:r.stderr?.toString?.()||""})}}const Ne=15e3;function je(e,t=[],r={},s){const n=(0,N.q6)();if(r.env=C(r.env),!De(n))throw new Error(`Sandbox binary not available: ${Re?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===s.type)return(0,E.D9)(m.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===s.type||"workspace_readonly"===s.type)return function(e,t,r,s){if("workspace_readwrite"!==s.type&&"workspace_readonly"!==s.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const n=String(r.cwd??process.cwd()),i=s.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 l=Me(Ae(s),i),u=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return function(e){const t=process.getuid?.();if(void 0===t)return;const r=(0,o.join)((0,h.tmpdir)(),`cursor-sandbox-${(0,R.r_)((0,o.resolve)(e))}`);try{for(const e of[r,(0,o.join)(r,"tmp")])if(A(e),!T(e,t))return;return r}catch{return}}(e.cwd)}(l);u&&(l.additionalReadwritePaths=[...l.additionalReadwritePaths??[],u]);const d=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!he(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(s),p={sandbox:l};void 0!==d&&(p.networkPolicy=d),!1===s.networkPolicyStrict&&(p.networkPolicyStrict=!1);const f=["--policy",ye(JSON.stringify(p)),"--",a,...c],g={..."linux"===process.platform?_(process.env):process.env,..."linux"===process.platform&&r.env?_(r.env):r.env,CURSOR_SANDBOX:"native"};if(_e(g),u){const e=function(e,t,r){const s=function(e){const t=(0,o.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,o.join)(t,"sh-")}}(e);if(r){const r=D();for(const[o,n]of Object.entries(D(e)))t[o]===r[o]&&(s[o]=n)}return s}(u,g,s.enableSharedBuildCache);Object.assign(g,e),g.__CURSOR_SANDBOX_OWNED_ENV=Object.keys(e).join(" "),g.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}const w={cwd:r.cwd||n,env:g,stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,E.D9)(m.spawn,String(xe()),f,w);return ve&&t.pid&&function(e,t){ue.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${e}`)}}(e,t,r,s);throw new Error(`Unsupported sandbox policy: ${String(s)}`)}function $e(e,t,r,o){const s={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Fe(t):t;s[e]=r;const o=Le(e);o!==e&&(s[o]=r)}return s}function Fe(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Le(e){try{return(0,s.realpathSync)(e)}catch{return e}}class Ue extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Be="darwin"===process.platform;function ze(e){!function(e){k();const{sandboxBinaryPath:t,workspaceReadEnabled:r}=e;Ee||(Ee=t),void 0!==r&&(Ce=r)}(e)}function We(e,t=[],r={},o){if(r.env=C(r.env),o.enableSharedBuildCache&&(r={...r,env:{...C(process.env),...D(),...r.env}}),"insecure_none"!==o.type){if(Oe())return je(e,t,r,o);const s=Ie;throw new Ue(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${s||"unknown"}`,s??void 0)}return function(e,t,r){return(0,E.D9)(m.spawn,e,t,{...r,windowsHide:!0})}(e,t,r)}function He(e){return Be?async function(e){const t=ue.get(e);return t?(r=t.pid,o=t.startTime,s=t.unrelatedPids,new Promise((e=>{try{const t=new Date,n=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-o.getTime())/1e3).toString()];(0,E.D9)(le,"/usr/bin/log",n,((t,o)=>{if(t)return void e([{raw:t.message}]);const n=o.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of n)try{const t=JSON.parse(e),o=t?.eventMessage??"";if(!o||"string"!=typeof o)continue;const n=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(o);if(n){const[,e,a,c,l,u,d]=n,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:de(h,r,s)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(o);if(a){const e=Number(a[1]),n=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(c){const[,n,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:n.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:o,relationship:de(p,r,s)})}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,s}(e):Promise.resolve([])}function qe(e,t){if(Be)try{(0,s.accessSync)("/usr/bin/sandbox-exec",s.constants.X_OK)}catch{return!1}return Oe(t?.ctx)}var Ge;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Ge||(Ge={}));const Ve={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Je(e,t,r){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{process.kill(-o,r)}catch{s()}return;case"windows_tree":try{(0,m.spawn)("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function Ke(e,t=[],r={},o,s){const n=We(e,t,{...r,env:S(r.env??process.env)},o);if(s){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(!n.pid)return;Je(n,e,"SIGTERM");const t=setTimeout((()=>{!n.killed&&n.pid&&Je(n,e,"SIGKILL")}),1e3);n.once("exit",(()=>{clearTimeout(t)}))};s.aborted?t():(s.addEventListener("abort",t,{once:!0}),n.once("exit",(()=>{s.removeEventListener("abort",t)})))}return n}function Ze(e){e?.on("error",(()=>{}))}function Qe(e,t){e&&(Ze(e),e.write(t),e.end())}function Xe(e,t){e&&(Ze(e),e.on("data",(e=>{t(e.toString())})))}function Ye(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function et(e,t){const r=`${t}\n`,o=e.indexOf(r);return o>=0?e.slice(o+r.length):e}const tt="__CURSOR_BASH_STATE_START__",rt="__CURSOR_BASH_STATE_END__",ot=50,st=262144;class nt{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??ot,this.maxBufferedBytes=t?.maxBufferedBytes??st}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 s=1;s<e.length;s++){const n=e[s];n.type!==r?(t.push({type:r,data:Buffer.concat(o)}),r=n.type,o=[n.data]):o.push(n.data)}return t.push({type:r,data:Buffer.concat(o)}),t}(e))try{await this.writable.write(t)}catch{}}}function it(e){if(!e.bufferOutputEvents){const t=(t,r)=>{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{t("stdout",e)})),e.stderr?.on("data",(e=>{t("stderr",e)})),{async waitForOutput(){},async flush(){}}}const t=new nt(e.writable,e.outputLimiterOptions);let r;const o=Promise.all([at(e.stdout,"stdout",t),at(e.stderr,"stderr",t)]).then((()=>{})).catch((e=>{r=e}));return{async waitForOutput(){if(await o,void 0!==r)throw(e=r)instanceof Error?e:new Error(String(e));var e},async flush(){await t.flush()}}}async function at(e,t,r){if(e)for await(const o of e)await r.push(t,o)}function ct(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function lt(...e){return e.some((e=>!0===e))}function ut(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(mt(e));return[...t]}const dt=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}}),ht=(...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=mt(o);t.has(e)||(t.add(e),r.push(o))}return r}(t[0]).map(mt);let r=new Set(t[0].map(mt));for(let e=1;e<t.length;e++){const o=new Set(t[e].map(mt));r=new Set([...r].filter((e=>o.has(e))))}return[...r]}(...e);function pt(...e){return dt.merge(...e)}function ft(...e){return ht(...e)}function mt(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function gt(...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 s=new Set;for(const e of t)if(e.allow)for(const t of e.allow)s.add(t);const n=s.size>0?[...s]: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!==n&&(a.allow=n),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 wt(...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 s=new Set(e);for(const e of o)s.has(e)&&s.delete(e),s.add(e);r[t]=[...s]}else r[t]=[...o]}return 0!==Object.keys(r).length?r:void 0}function yt(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function vt(e,t){if(!t)return{policy:{type:"insecure_none"}};const r=await(0,d.stat)((0,o.join)(e,".git")).then((e=>e),(()=>null)),s=r?.isFile()??!1,n=null!==r;if("workspace_readwrite"===ct(t)){let r=e;if(s){const s=await U("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,o.resolve)(e,t.trim())),(()=>null));if(s){r=(0,o.dirname)(s);const n=t.perRepo,i=n?.ignoreMapping;t={...t,perRepo:{...n,type:"workspace_readwrite",additionalReadwritePaths:[...n?.additionalReadwritePaths??[],s],ignoreMapping:i,writeProtectionMapping:wt(n?.writeProtectionMapping,Q(e))}}}}if(n)return bt(t,{workspaceDir:e,gitDirParent:r})}return bt(t,{workspaceDir:e})}function bt(e,t){const r=function(e){const{perUser:t,perRepo:r,teamAdmin:o}=e,s=[t,r,o].filter((e=>void 0!==e));if(0===s.length)return;const n=s[0].type;for(const e of s)if(e.type!==n)throw new Error(`Cannot merge policies of different types: found "${n}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return n}(e);if(void 0===r)return Et(e,t);switch(r){case"workspace_readwrite":return Et(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,o=St(e,t),s={policy:kt({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&&(s.debug={fieldSources:o.fieldSources}),s}(e,t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:o,teamAdmin:s}=e,n=t?.debug,i={type:"insecure_none",allowlistEscalated:lt(r?.allowlistEscalated,o?.allowlistEscalated,s?.allowlistEscalated)||void 0,debugOutputDir:yt(r?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),captureDenies:lt(r?.captureDenies,o?.captureDenies,s?.captureDenies)||void 0,enableSharedBuildCache:yt(r?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache)},a=Object.fromEntries(Object.entries(i).filter((([e,t])=>void 0!==t)));a.type="insecure_none";const c={policy:a};return n&&(c.debug={fieldSources:{}}),c}(e,t);default:throw new Error(`Unknown policy type: ${r}`)}}function St(e,t){const r=t?.debug,{perUser:s,perRepo:n,teamAdmin:i}=e,a=t?.workspaceDir??process.cwd(),c=function(e){const t=function(){if(0!==X.length)return{version:1,deny:[...X]}}(),r=h.homedir(),s=[];for(const e of K)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":s.push(e.pattern);break;case"home":r.length>0&&s.push((0,o.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${t}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:s,writeProtectionMapping:Z(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(a),l={},u=[s,n,i],d=["perUser","perRepo","teamAdmin","hardcoded"],p=(e,t)=>{r&&(l[e]=d[t]??"unknown")},f=lt(s?.disableTmpWrite,n?.disableTmpWrite,i?.disableTmpWrite);for(let e=u.length-1;e>=0;e--)if(!0===u[e]?.disableTmpWrite){p("disableTmpWrite",e);break}const m=lt(s?.networkPolicyStrict,n?.networkPolicyStrict,i?.networkPolicyStrict,c.networkPolicyStrict);c.networkPolicyStrict&&p("networkPolicyStrict",3);const g=yt(s?.readBoundary,n?.readBoundary,i?.readBoundary)??"system",w=yt(s?.additionalReadPaths,n?.additionalReadPaths),y=!1===i?.allowUserOverrideReadPaths?ut(i.additionalReadPaths):ut(w,i?.additionalReadPaths),v="workspace"===g?y:void 0,b=ut(s?.additionalReadonlyPaths,n?.additionalReadonlyPaths,i?.additionalReadonlyPaths,c.additionalReadonlyPaths),S=b.length>0?b:void 0;let k=gt(s?.networkPolicy,n?.networkPolicy,i?.networkPolicy,c.networkPolicy);const E=i?.networkPolicy?.allow;void 0!==E&&E.length>0&&void 0!==k&&(k={...k,allow:[...E]},r&&(l["networkPolicy.allow"]="teamAdmin (replace)"));const C=void 0!==(x=k)?x:{version:1,default:"deny"};var x;const _=yt(s?.debugOutputDir,n?.debugOutputDir,i?.debugOutputDir),P=lt(s?.captureDenies,n?.captureDenies,i?.captureDenies),R=yt(s?.enableSharedBuildCache,n?.enableSharedBuildCache,i?.enableSharedBuildCache),I=wt(s?.ignoreMapping,n?.ignoreMapping,i?.ignoreMapping,c.ignoreMapping),T=function(e){const t=K.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??a);return{disableTmpWrite:f||void 0,networkPolicyStrict:m,readBoundary:g,additionalReadPaths:v,additionalReadonlyPaths:S,networkPolicy:C,debugOutputDir:_,captureDenies:P||void 0,enableSharedBuildCache:R,ignoreMapping:I,writeProtectionMapping:wt(s?.writeProtectionMapping,n?.writeProtectionMapping,i?.writeProtectionMapping,c.writeProtectionMapping,T),fieldSources:l}}function kt(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function Et(e,t){const{perUser:r,perRepo:o,teamAdmin:s}=e,n=t?.debug,i=St(e,t),a=ut(r?.additionalReadwritePaths,o?.additionalReadwritePaths,s?.additionalReadwritePaths),c={policy:kt({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 n&&(c.debug={fieldSources:i.fieldSources}),c}const Ct="win32"===process.platform;function xt(e){return!Ct&&!!e?.SUDO_ASKPASS}function _t(e){return xt(e)?"alias sudo='sudo -A'; ":""}function Pt(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],s=Math.max(0,r-10),n=e.slice(s,r),i=/(?:&&|\|\||[|;])\s*$/.test(n)||0===r&&/^\s*$/.test(n);if((o||i)&&"sudo"===e.slice(r,r+4)){const o=r+4;if(o>=e.length||/\s/.test(e[o])){let s=o;for(;s<e.length&&/\s/.test(e[s]);)s++;let n=!1;if(s<e.length&&"-"===e[s]){let t=s+1;for(;t<e.length&&/[^\s]/.test(e[t]);)t++;const r=e.slice(s,t);n=/^-[a-zA-Z]*A[a-zA-Z]*$/.test(r)}n?(t.push("sudo"),r=o):(t.push("sudo -A"),r=o);continue}}t.push(e[r]),r++}return t.join("")}var Rt=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function It(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=u("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:u("bash",[]).cmd}function Tt(e){if("win32"!==process.platform)return e;const t=o.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===o.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}class At{cwd;state;userTerminalHint;useFileStateTransport;constructor(e,t,r,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=o}async getCwd(){return this.cwd}clone(e){return new At(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport)}async*execute(e,t,r){const s={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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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}(s,(0,p.VI)(e.withName("BashState.execute")),!1),i=r?.pipeStdin??!1,a=(0,f.Jt)(),c=r?.workingDirectory??this.cwd,l={...process.env,...Ve,...r?.env};let u='builtin eval "$1"';i||(u+=" < /dev/null");const m=_t(l),g=this.useFileStateTransport;let w,y,v;if(g){w=await(0,d.mkdtemp)(o.join(h.tmpdir(),"cursor-bash-state-")),o.basename(w),y=o.join(w,"state-in"),v=o.join(w,"state-out"),await(0,d.writeFile)(y,this.state,"utf8"),await(0,d.writeFile)(v,"","utf8").catch((()=>{}));const e=Tt(y),t=Tt(v);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const b=["-O","extglob","-c",(g?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)")+' && builtin shopt -s extglob && builtin eval -- "$snap" && { builtin set +u 2>/dev/null || true; builtin eval "${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; '+M+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${m}${u}; }; `+`COMMAND_EXIT_CODE=$?; ${g?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4"}; builtin exit $COMMAND_EXIT_CODE`,"--",t],S=It(this.userTerminalHint);if(!S)throw new Error("Can't find Bash");const k=r?.sandboxWorkspaceRoot??c,E=(await vt(k,r?.sandboxPolicy)).policy,C="insecure_none"!==E.type?{...E,sandboxWorkspaceRoot:k}:E;let x="";const _=async()=>{if(g){if(!v)return void(x=this.state);try{x=await(0,d.readFile)(v,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),x=this.state}}},P=async()=>{if(w)try{await(0,d.rm)(w,{recursive:!0,force:!0})}catch{}};let R;try{R=Ke(S,b,{env:l,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:c,detached:!0},C,r?.signal)}catch(e){throw await P(),e}R.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:R.stdin??void 0,pid:R.pid})}catch(e){}}));const I=it({stdout:R.stdout,stderr:R.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});R.on("error",(async e=>{await P(),a.throw(e)}));let T=null,A=null,D=!1;const O=async e=>{if(!D){if(D=!0,A&&(clearTimeout(A),A=null),(0,p.HF)(n.ctx,"exit"),e)try{await I.waitForOutput()}catch(e){return await P(),void a.throw(e instanceof Error?e:new Error(String(e)))}if(await I.flush(),!r?.signal?.aborted){await _();const e=`${tt}\n`,t=`${rt}\n`;if(x.startsWith(e)&&x.endsWith(t)){let t=x.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:o}=Ye(t);this.state=o,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(C.captureDenies)try{const e=await He(R);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:T,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch{a.close()}await P()}};R.on("exit",((e,t)=>{T=e;const o=r?.closeTimeout??5e3;o>0&&(A=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),O(!1)}),o))})),R.on("close",(async()=>{await O(!0)}));const N=R.stdio[3],j=R.stdio[4];g||(Qe(N,this.state),Xe(j,(e=>{x+=e}))),yield*a}catch(e){s.error=e,s.hasError=!0}finally{Rt(s)}}}var Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Dt{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 Dt((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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,p.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const s=await this.getExecutor();for await(const o of s.execute(e,t,r))yield o}catch(e){o.error=e,o.hasError=!0}finally{Mt(o)}}}var Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Nt(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=u("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=u("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=o.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,s.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}class jt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new jt(e??this.cwd,this.state)}async*execute(e,t,r){const s={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,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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}(s,(0,p.VI)(e.withName("PowerShellState.execute")),!1),i=r?.pipeStdin??!1,a=r?.workingDirectory??this.cwd,c=(0,f.Jt)(),l={...process.env,...Ve,...r?.env},u=xt(l)?Pt(t):t,m=h.tmpdir(),g=o.join(m,`ps-state-out-${(0,P.randomUUID)()}.txt`),w=((e,t,r,o)=>`\n${e}\n\nSet-Location '${t}'\n\n# Execute user command\n${r}\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n\n\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n\n Emit $PWD.Path\n #Log-Timing "working_dir"\n\n 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`)(this.state,a,u,g),y=o.join(m,`ps-script-${(0,P.randomUUID)()}.ps1`);await async function(e,t){await d.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(y,w);const v=["-ExecutionPolicy","Bypass"];i||v.push("-NonInteractive"),v.push("-File",y);const b=Nt(),S="win32"===process.platform,k=r?.sandboxWorkspaceRoot??a,E=(await vt(k,r?.sandboxPolicy)).policy,C=Ke(b,v,{env:l,stdio:[i?"pipe":"ignore","pipe","pipe"],cwd:a,detached:!S},"insecure_none"!==E.type?{...E,sandboxWorkspaceRoot:k}:E,r?.signal);C.on("spawn",(async()=>{try{await c.write({type:"stdin_ready",stdin:C.stdin??void 0,pid:C.pid})}catch(e){}}));const x=it({stdout:C.stdout,stderr:C.stderr,writable:c,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),_=async()=>{try{const e=await d.readFile(g,"utf8"),{cwd:t,rest:r}=Ye(e);this.state=r,this.cwd=t.trim(),await(0,d.rm)(g).catch((()=>{}))}catch(e){}await(0,d.rm)(y).catch((()=>{}))};let R=null,I=null,T=!1;const A=async e=>{if(!T){if(T=!0,I&&(clearTimeout(I),I=null),(0,p.HF)(n.ctx,"exit"),e)try{await x.waitForOutput()}catch(e){return await _(),void c.throw(e instanceof Error?e:new Error(String(e)))}await x.flush();try{await c.write({type:"exit",code:R,data:"",aborted:r?.signal?.aborted??!1}),await _(),c.close()}catch(e){c.close()}}};C.on("exit",((e,t)=>{R=e;const o=r?.closeTimeout??5e3;o>0&&(I=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))})),C.on("close",(async()=>{await A(!0)})),C.on("error",(e=>{_().catch((()=>{})),c.throw(e)})),yield*c}catch(e){s.error=e,s.hasError=!0}finally{Ot(s)}}}var $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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Ft{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new Ft(e??this.cwd,this.options)}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,p.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),n=(0,f.Jt)(),i=r?.pipeStdin??!1,a={...process.env,...Ve,...r?.env},c=xt(a)?Pt(t):t,l=r?.workingDirectory??this.cwd,u=r?.sandboxWorkspaceRoot??l,d=(await vt(u,r?.sandboxPolicy)).policy,h="insecure_none"!==d.type?{...d,sandboxWorkspaceRoot:u}:d,m="win32"===process.platform,g=Ke(this.options?.shell||process.env.SHELL||"/bin/sh",[...this.options?.shellArgs??[],"-c",c],{env:a,cwd:l,stdio:[i?"pipe":"ignore","pipe","pipe"],detached:!m},h,r?.signal);g.on("spawn",(async()=>{try{await n.write({type:"stdin_ready",stdin:g.stdin??void 0,pid:g.pid})}catch(e){}}));const w=it({stdout:g.stdout,stderr:g.stderr,writable:n,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});g.on("error",(e=>{n.throw(e)})),g.on("exit",(async e=>{if((0,p.HF)(s.ctx,"exit"),await w.flush(),h.captureDenies)try{const e=await He(g);e&&e.length>0&&await n.write({type:"sandbox_denies",events:e})}catch{}try{await n.write({type:"exit",code:e,data:"",aborted:r?.signal?.aborted??!1}),n.close()}catch(e){n.close()}})),yield*n}catch(e){o.error=e,o.hasError=!0}finally{$t(o)}}}const Lt="__CURSOR_ZSH_STATE_START__",Ut="__CURSOR_ZSH_STATE_END__";var Bt=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 zt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class Wt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Wt(e??this.cwd,this.state)}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,p.VI)(e.withName("ZshState.execute")),!1),n=r?.pipeStdin??!1,i=(0,f.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...Ve,...r?.env};let l='builtin eval "$1"';n||(l+=" < /dev/null");const u=_t(c),d=["-c",'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; builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; '+M+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${u}${l}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],h=r?.sandboxWorkspaceRoot??a,m=(await vt(h,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,w=Ke(zt(),d,{env:c,stdio:[n?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:a,detached:!0},g,r?.signal);let y="";w.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:w.stdin??void 0,pid:w.pid})}catch(e){}}));const v=it({stdout:w.stdout,stderr:w.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});w.on("error",(e=>{i.throw(e)}));let b=null,S=null,k=!1;const E=async e=>{if(!k){if(k=!0,S&&(clearTimeout(S),S=null),(0,p.HF)(s.ctx,"exit"),e)try{await v.waitForOutput()}catch(e){return void i.throw(e instanceof Error?e:new Error(String(e)))}if(await v.flush(),!r?.signal?.aborted){const e=`${Lt}\n`,t=`${Ut}\n`;if(y.startsWith(e)&&y.endsWith(t)){let t=y.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:o}=Ye(t);r?.startsWith("/")&&(this.state=o,this.cwd=r)}}if(g.captureDenies)try{const e=await He(w);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:b,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}}};w.on("exit",((e,t)=>{b=e;const o=r?.closeTimeout??5e3;o>0&&(S=setTimeout((()=>{k||(console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Killing detached process group.`),function(e,t){if(e)try{process.kill(-e,t)}catch{return}}(w.pid,"SIGKILL"),E(!1))}),o))})),w.on("close",(async()=>{await E(!0)}));const C=w.stdio[3],x=w.stdio[4];Qe(C,this.state),Xe(x,(e=>{y+=e})),yield*i}catch(e){o.error=e,o.hasError=!0}finally{Bt(o)}}}const Ht="__CURSOR_ZSH_STATE_LIGHT_VALID__",qt='#!/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 # 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 Gt,Vt,Jt=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,s=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===s)return s=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var n=o.dispose.call(o.value);if(o.async)return s|=2,Promise.resolve(n).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)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 Kt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class Zt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Zt(e??this.cwd,this.state)}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,s;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&&(s=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");s&&(o=function(){try{s.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,p.VI)(e.withName("ZshLightState.execute")),!1),n=r?.pipeStdin??!1,i=(0,f.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...Ve,...r?.env};let l='builtin eval "$1"';n||(l+=" < /dev/null");const u=_t(c),d=["-c",`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; ${qt} builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+M+`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`,"--",t],h=r?.sandboxWorkspaceRoot??a,m=(await vt(h,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,w=Ke(Kt(),d,{env:c,stdio:[n?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:a,detached:!0},g,r?.signal);let y="";w.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:w.stdin??void 0,pid:w.pid})}catch(e){}}));const v=it({stdout:w.stdout,stderr:w.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});w.on("error",(e=>{i.throw(e)}));let b=null,S=null,k=!1;const E=async e=>{if(!k){if(k=!0,S&&(clearTimeout(S),S=null),(0,p.HF)(s.ctx,"exit"),e)try{await v.waitForOutput()}catch(e){return void i.throw(e instanceof Error?e:new Error(String(e)))}if(await v.flush(),!r?.signal?.aborted){const e=`${Ht}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:o}=Ye(t);r?.startsWith("/")&&(this.state=o,this.cwd=r)}}if(g.captureDenies)try{const e=await He(w);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:b,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}}};w.on("exit",((e,t)=>{b=e;const o=r?.closeTimeout??5e3;o>0&&(S=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),E(!1)}),o))})),w.on("close",(async()=>{await E(!0)}));const C=w.stdio[3],x=w.stdio[4];Qe(C,this.state),Xe(x,(e=>{y+=e})),yield*i}catch(e){o.error=e,o.hasError=!0}finally{Jt(o)}}}r("node:perf_hooks"),function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}(Gt||(Gt={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(Vt||(Vt={}));const Qt="\n[This shell is producing too much output to stream. The command will still run.]\n";var Xt=r("../utils/dist/path-utils.js");function Yt(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 er(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 s={...r,networkAccess:e.networkAccess,networkPolicy:Yt(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",...s}:{type:"workspace_readwrite",...s,additionalReadwritePaths:e.additionalReadwritePaths}}async function tr(e,t){const r=await async function(e,t){try{const r=await(0,d.readFile)(e,"utf-8"),o=JSON.parse(r),s=function(e){if("object"!=typeof e||null===e)return"Expected an object";const t=e;if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const o=["debugOutputDir"];for(const e of o)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const s=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of s)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=t.networkPolicy;if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}(o);if(s)return{success:!1,error:`Invalid sandbox policy: ${s}`};let n=er(o);return t&&(n=rr(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 rr(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Xt.o1)(e,t))),o=e.additionalReadPaths?.map((e=>(0,Xt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:o};const s=e.additionalReadwritePaths?.map((e=>(0,Xt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:o,additionalReadwritePaths:s}}function or(e){try{return u(e,[]).cmd!==e}catch(e){return!1}}function sr(){if("win32"!==process.platform)return;if(!process.env.MSYSTEM)return;const e=process.env.EXEPATH;if(e)return function(e){const t=e.replace(/[\\/]+$/,""),r=o.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?o.win32.join(t,"bash.exe"):o.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(u(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function nr(e){if(e===Ge.ZshLight)return Ge.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,o=r&&!e?sr():void 0,s=void 0!==o||/git.*bash\.exe$/i.test(t)||/program.*git.*bin.*bash\.exe$/i.test(t),n=!r||s;return t.includes("zsh")?Ge.Zsh:t.includes("bash")&&n?Ge.Bash:t.includes("pwsh")||t.includes("powershell")?Ge.PowerShell:o?Ge.Bash:r&&(or("pwsh")||or("powershell"))?Ge.PowerShell:or("zsh")?Ge.Zsh:or("bash")&&n?Ge.Bash:or("pwsh")||or("powershell")?Ge.PowerShell:Ge.Naive}function ir(e){let t=e;if(!e?.userTerminalHint){const r=sr();r&&(t={...e,userTerminalHint:r})}switch(nr(t?.userTerminalHint??"")){case Ge.Zsh:return new Dt((()=>async function(e){const t={...process.env,...Ve,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-o","extendedglob","-ilc",`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state.zsh\n# dump_zsh_state\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state.zsh\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:functions p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # 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 # 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 {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_zsh_state`],s=Ke(zt(),o,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let n="";s.stdout?.on("data",(e=>{n+=e.toString()})),s.on("error",(e=>{console.warn(`[shell-exec] zsh state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const i=et(n,r),a=`${Lt}\n`,c=`${Ut}\n`;let l;i.startsWith(a)&&i.endsWith(c)?(l=i.slice(a.length),l=l.slice(0,-25)):l=`${process.cwd()}\n`;const{cwd:u,rest:d}=Ye(l);return new Wt(u,d)}(t)));case Ge.Bash:return new Dt((()=>async function(e){const t={...process.env,...Ve,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Require base64 for safe encoding of emitted sections\n if ! command -v base64 >/dev/null 2>&1; then\n echo "Error: base64 command is required" >&2\n return 1\n fi\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Builtin printf, 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 # 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 # 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' || 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 "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)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS_B64"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS_B64"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS_B64"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(builtin alias -p 2>/dev/null || true)\n _emit_encoded "$aliases" "ALIASES_B64"\n _log_timing "aliases"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],s=It(e?.userTerminalHint);if(!s)throw new Error("Can't find Bash");const n=Ke(s,o,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal);let i="";n.stdout?.on("data",(e=>{i+=e.toString()})),n.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=>{n.on("close",(()=>{e(void 0)}))}));const a=et(i,r),c=`${tt}\n`,l=`${rt}\n`;let u;a.startsWith(c)&&a.endsWith(l)?(u=a.slice(c.length),u=u.slice(0,-26)):u=`${process.cwd()}\n`;const{cwd:d,rest:h}=Ye(u),p="win32"===process.platform,f="win32"===process.platform?process.cwd():d;return new At(f,h,e?.userTerminalHint,p)}(t)));case Ge.PowerShell:return new Dt((()=>async function(){return new jt(process.cwd(),"")}()));case Ge.ZshLight:return new Dt((()=>async function(e){const t={...process.env,...Ve,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-o","extendedglob","-ilc",`${qt} builtin printf '${r}\\n'; dump_zsh_state_light`],s=Ke(Kt(),o,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let n="";s.stdout?.on("data",(e=>{n+=e.toString()})),s.on("error",(e=>{console.warn(`[shell-exec] zsh-light state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const i=et(n,r),a=`${Ht}\n`,c=i.startsWith(a)?i.slice(a.length):`${process.cwd()}\n`,{cwd:l,rest:u}=Ye(c);return new Zt(l,u)}(t)));default:return function(e){const t="win32"===process.platform,r=e?.shell??(t?Nt():void 0),o=process.cwd();return new Ft(o,{...e,shell:r})}(t)}}const ar={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){"use strict";r.d(t,{q:()=>ue});var o,s,n,i,a,c,l,u,d,h,p,f,m,g,w,y,v,b,S,k,E,C,x,_,P,R,I,T,A,M,D,O,N,j,$,F,L,U,B,z,W,H,q,G,V,J,K,Z,Q,X=function(e,t,r,o,s){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?s.call(e,r):s?s.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 se=globalThis.AbortController,ne=globalThis.AbortSignal;if(void 0===se){ne=class{constructor(){this._onabort=[],this.aborted=!1}addEventListener(e,t){this._onabort.push(t)}},se=class{constructor(){this.signal=new ne,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[];X(o,o,!0,"f",s);const r=new o(e,t);return X(o,o,!1,"f",s),r}constructor(e,t){if(!Y(o,o,"f",s))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,s={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,n,"m",G).call(e,t),backgroundFetch:(t,r,o,s)=>Y(e,n,"m",q).call(e,t,r,o,s),moveToTail:t=>Y(e,n,"m",J).call(e,t),indexes:t=>Y(e,n,"m",B).call(e,t),rindexes:t=>Y(e,n,"m",z).call(e,t),isStale:t=>Y(e,j,"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){n.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),R.set(this,void 0),I.set(this,void 0),T.set(this,void 0),A.set(this,void 0),D.set(this,(()=>{})),O.set(this,(()=>{})),N.set(this,(()=>{})),j.set(this,(()=>!1)),F.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[Q]="LRUCache";const{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:B,updateAgeOnHas:z,allowStale:W,dispose:H,onInsert:q,disposeAfter:G,noDisposeOnSet:V,noUpdateTTL:J,maxSize:K=0,maxEntrySize:Z=0,sizeCalculation:re,fetchMethod:se,memoMethod:ne,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(X(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(X(this,i,t,"f"),X(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!==ne&&"function"!=typeof ne)throw new TypeError("memoMethod must be a function if defined");if(X(this,h,ne,"f"),void 0!==se&&"function"!=typeof se)throw new TypeError("fetchMethod must be a function if specified");if(X(this,d,se,"f"),X(this,I,!!se,"f"),X(this,g,new Map,"f"),X(this,w,new Array(t).fill(void 0),"f"),X(this,y,new Array(t).fill(void 0),"f"),X(this,v,new ge(t),"f"),X(this,b,new ge(t),"f"),X(this,S,0,"f"),X(this,k,0,"f"),X(this,E,le.create(t),"f"),X(this,f,0,"f"),X(this,m,0,"f"),"function"==typeof H&&X(this,c,H,"f"),"function"==typeof q&&X(this,l,q,"f"),"function"==typeof G?(X(this,u,G,"f"),X(this,C,[],"f")):(X(this,u,void 0,"f"),X(this,C,void 0,"f")),X(this,R,!!Y(this,c,"f"),"f"),X(this,A,!!Y(this,l,"f"),"f"),X(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,n,"m",$).call(this)}if(this.allowStale=!!W,this.noDeleteOnStaleGet=!!de,this.updateAgeOnGet=!!B,this.updateAgeOnHas=!!z,this.ttlResolution=ie(o)||0===o?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!ie(this.ttl))throw new TypeError("ttl must be a positive integer if specified");Y(this,n,"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,n,"m",B).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,n,"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,n,"m",z).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,n,"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,n,"m",B).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,n,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*rkeys(){for(const e of Y(this,n,"m",z).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,n,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*values(){for(const e of Y(this,n,"m",B).call(this))void 0===Y(this,y,"f")[e]||Y(this,n,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}*rvalues(){for(const e of Y(this,n,"m",z).call(this))void 0===Y(this,y,"f")[e]||Y(this,n,"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,R=new WeakMap,I=new WeakMap,T=new WeakMap,A=new WeakMap,D=new WeakMap,O=new WeakMap,N=new WeakMap,j=new WeakMap,F=new WeakMap,L=new WeakMap,U=new WeakMap,n=new WeakSet,M=function(){const e=new ce(Y(this,i,"f")),t=new ce(Y(this,i,"f"));X(this,P,e,"f"),X(this,_,t,"f"),X(this,N,((r,o,s=Y(this,p,"f").now())=>{if(t[r]=0!==o?s:0,e[r]=o,0!==o&&this.ttlAutopurge){const e=setTimeout((()=>{Y(this,j,"f").call(this,r)&&Y(this,n,"m",K).call(this,Y(this,w,"f")[r],"expire")}),o+1);e.unref&&e.unref()}}),"f"),X(this,D,(r=>{t[r]=0!==e[r]?Y(this,p,"f").now():0}),"f"),X(this,O,((s,n)=>{if(e[n]){const i=e[n],a=t[n];if(!i||!a)return;s.ttl=i,s.start=a,s.now=r||o();const c=s.now-a;s.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=s=>{const n=Y(this,g,"f").get(s);if(void 0===n)return 0;const i=e[n],a=t[n];return i&&a?i-((r||o())-a):1/0},X(this,j,(s=>{const n=t[s],i=e[s];return!!i&&!!n&&(r||o())-n>i}),"f")},$=function(){const e=new ce(Y(this,i,"f"));X(this,m,0,"f"),X(this,x,e,"f"),X(this,F,(t=>{X(this,m,Y(this,m,"f")-e[t],"f"),e[t]=0}),"f"),X(this,U,((e,t,r,o)=>{if(Y(this,n,"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"),X(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,n,"m",H).call(this,!0)}X(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,n,"m",W).call(this,t)&&(!e&&Y(this,j,"f").call(this,t)||(yield t),t!==Y(this,S,"f"));)t=Y(this,b,"f")[t]},z=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,S,"f");Y(this,n,"m",W).call(this,t)&&(!e&&Y(this,j,"f").call(this,t)||(yield t),t!==Y(this,k,"f"));)t=Y(this,v,"f")[t]},W=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,n,"m",B).call(this)){const o=Y(this,y,"f")[r],s=Y(this,n,"m",G).call(this,o)?o.__staleWhileFetching:o;if(void 0!==s&&e(s,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,n,"m",B).call(this)){const o=Y(this,y,"f")[r],s=Y(this,n,"m",G).call(this,o)?o.__staleWhileFetching:o;void 0!==s&&e.call(t,s,Y(this,w,"f")[r],this)}}rforEach(e,t=this){for(const r of Y(this,n,"m",z).call(this)){const o=Y(this,y,"f")[r],s=Y(this,n,"m",G).call(this,o)?o.__staleWhileFetching:o;void 0!==s&&e.call(t,s,Y(this,w,"f")[r],this)}}purgeStale(){let e=!1;for(const t of Y(this,n,"m",z).call(this,{allowStale:!0}))Y(this,j,"f").call(this,t)&&(Y(this,n,"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,n,"m",G).call(this,r)?r.__staleWhileFetching:r;if(void 0===o)return;const s={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);s.ttl=t,s.start=Date.now()}}return Y(this,x,"f")&&(s.size=Y(this,x,"f")[t]),s}dump(){const e=[];for(const t of Y(this,n,"m",B).call(this,{allowStale:!0})){const r=Y(this,w,"f")[t],o=Y(this,y,"f")[t],s=Y(this,n,"m",G).call(this,o)?o.__staleWhileFetching:o;if(void 0===s||void 0===r)continue;const i={value:s};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:s=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,n,"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,n,"m",H).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"),X(this,k,x,"f"),X(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,n,"m",J).call(this,x);const r=Y(this,y,"f")[x];if(t!==r){if(Y(this,I,"f")&&Y(this,n,"m",G).call(this,r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||d||(Y(this,R,"f")&&Y(this,c,"f")?.call(this,t,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([t,e,"set"]))}else d||(Y(this,R,"f")&&Y(this,c,"f")?.call(this,r,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([r,e,"set"]));if(Y(this,F,"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,n,"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===s||Y(this,P,"f")||Y(this,n,"m",M).call(this),Y(this,P,"f")&&(m||Y(this,N,"f").call(this,x,s,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,n,"m",H).call(this,!0),Y(this,n,"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,s=Y(this,g,"f").get(e);if(void 0!==s){const e=Y(this,y,"f")[s];if(Y(this,n,"m",G).call(this,e)&&void 0===e.__staleWhileFetching)return!1;if(!Y(this,j,"f").call(this,s))return r&&Y(this,D,"f").call(this,s),o&&(o.has="hit",Y(this,O,"f").call(this,o,s)),!0;o&&(o.has="stale",Y(this,O,"f").call(this,o,s))}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,j,"f").call(this,o))return;const s=Y(this,y,"f")[o];return Y(this,n,"m",G).call(this,s)?s.__staleWhileFetching:s}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:m,forceRefresh:w=!1,status:v,signal:b}=t;if(!Y(this,I,"f"))return v&&(v.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:v});const S={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,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,n,"m",q).call(this,e,k,S,m);return t.__returned=t}{const t=Y(this,y,"f")[k];if(Y(this,n,"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 s=Y(this,j,"f").call(this,k);if(!w&&!s)return v&&(v.fetch="hit"),Y(this,n,"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,n,"m",q).call(this,e,k,S,m),a=void 0!==i.__staleWhileFetching&&r;return v&&(v.fetch=s?"stale":"refresh",a&&s&&(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:s,...n}=t,i=this.get(e,n);if(!s&&void 0!==i)return i;const a=r(e,i,{options:n,context:o});return this.set(e,a,n),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=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,n,"m",G).call(this,t);return i&&Y(this,O,"f").call(this,i,a),Y(this,j,"f").call(this,a)?(i&&(i.get="stale"),c?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(s||Y(this,n,"m",K).call(this,e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),c?t.__staleWhileFetching:(Y(this,n,"m",J).call(this,a),o&&Y(this,D,"f").call(this,a),t))}i&&(i.get="miss")}delete(e){return Y(this,n,"m",K).call(this,e,"delete")}clear(){Y(this,n,"m",Z).call(this,"delete")}}Q=Symbol.toStringTag,H=function(e){var t;const r=Y(this,S,"f"),o=Y(this,w,"f")[r],s=Y(this,y,"f")[r];return Y(this,I,"f")&&Y(this,n,"m",G).call(this,s)?s.__abortController.abort(new Error("evicted")):(Y(this,R,"f")||Y(this,T,"f"))&&(Y(this,R,"f")&&Y(this,c,"f")?.call(this,s,o,"evict"),Y(this,T,"f")&&Y(this,C,"f")?.push([s,o,"evict"])),Y(this,F,"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")?(X(this,S,X(this,k,0,"f"),"f"),Y(this,E,"f").length=0):X(this,S,Y(this,v,"f")[r],"f"),Y(this,g,"f").delete(o),X(this,f,(t=Y(this,f,"f"),--t),"f"),r},q=function(e,t,r,o){const s=void 0===t?void 0:Y(this,y,"f")[t];if(Y(this,n,"m",G).call(this,s))return s;const i=new se,{signal:a}=r;a?.addEventListener("abort",(()=>i.abort(a.reason)),{signal:i.signal});const c={signal:i.signal,options:r,context:o},l=(o,s=!1)=>{const{aborted:a}=i.signal,l=r.ignoreFetchAbort&&void 0!==o;if(r.status&&(a&&!s?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,l&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),a&&!l&&!s)return u(i.signal.reason);const d=h,p=Y(this,y,"f")[t];return(p===h||l&&s&&void 0===p)&&(void 0===o?void 0!==d.__staleWhileFetching?Y(this,y,"f")[t]=d.__staleWhileFetching:Y(this,n,"m",K).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,o,c.options))),o},u=o=>{const{aborted:s}=i.signal,a=s&&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,n,"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 n=Y(this,d,"f")?.call(this,e,s,c);n&&n instanceof Promise&&n.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:s,__returned:void 0});return void 0===t?(this.set(e,p,{...c.options,status:void 0}),t=Y(this,g,"f").get(e)):Y(this,y,"f")[t]=p,p},G=function(e){if(!Y(this,I,"f"))return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof se},V=function(e,t){Y(this,b,"f")[t]=e,Y(this,v,"f")[e]=t},J=function(e){e!==Y(this,k,"f")&&(e===Y(this,S,"f")?X(this,S,Y(this,v,"f")[e],"f"):Y(this,n,"m",V).call(this,Y(this,b,"f")[e],Y(this,v,"f")[e]),Y(this,n,"m",V).call(this,Y(this,k,"f"),e),X(this,k,e,"f"))},K=function(e,t){var r;let o=!1;if(0!==Y(this,f,"f")){const s=Y(this,g,"f").get(e);if(void 0!==s)if(o=!0,1===Y(this,f,"f"))Y(this,n,"m",Z).call(this,t);else{Y(this,F,"f").call(this,s);const o=Y(this,y,"f")[s];if(Y(this,n,"m",G).call(this,o)?o.__abortController.abort(new Error("deleted")):(Y(this,R,"f")||Y(this,T,"f"))&&(Y(this,R,"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")[s]=void 0,Y(this,y,"f")[s]=void 0,s===Y(this,k,"f"))X(this,k,Y(this,b,"f")[s],"f");else if(s===Y(this,S,"f"))X(this,S,Y(this,v,"f")[s],"f");else{const e=Y(this,b,"f")[s];Y(this,v,"f")[e]=Y(this,v,"f")[s];const t=Y(this,v,"f")[s];Y(this,b,"f")[t]=Y(this,b,"f")[s]}X(this,f,(r=Y(this,f,"f"),--r),"f"),Y(this,E,"f").push(s)}}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,n,"m",z).call(this,{allowStale:!0})){const r=Y(this,y,"f")[t];if(Y(this,n,"m",G).call(this,r))r.__abortController.abort(new Error("deleted"));else{const o=Y(this,w,"f")[t];Y(this,R,"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),X(this,S,0,"f"),X(this,k,0,"f"),Y(this,E,"f").length=0,X(this,m,0,"f"),X(this,f,0,"f"),Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){"use strict";r.d(t,{BJ:()=>p,DN:()=>u,PS:()=>m,ZU:()=>d,fl:()=>g,jl:()=>a,o1:()=>l,oL:()=>f,yn:()=>c});var o=r("node:fs/promises"),s=r("node:os"),n=r("node:path"),i=r("node:url");function a(e){return e.replace(/^~(?=$|\/|\\)/,(0,s.homedir)())}function c(e,t){return void 0!==e&&("win32"===process.platform?(0,n.normalize)(e).toLowerCase()===(0,n.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,n.isAbsolute)(r)?(0,n.resolve)(t,r):(0,n.resolve)(r)}async function u(e,t){const r=l(e,t);let s=r;for(;;)try{const e=await(0,o.realpath)(s);return(0,n.resolve)(e,(0,n.relative)(s,r))}catch(e){if("ENOENT"!==e.code)return null;const t=(0,n.dirname)(s);if(t===s)return r;s=t}}function d({basePath:e,targetPath:t}){const r=(0,n.resolve)(e),o=(0,n.resolve)(e,t);return r===(0,n.parse)(r).root?(0,n.parse)(o).root===r&&(o===r||o.length>r.length):o===r||o.startsWith(r+n.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,s=r?t.toLowerCase():t;if(o===s)return!0;const i=s.endsWith(n.sep)?s:s+n.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 s=(0,n.isAbsolute)(t)?[(0,n.resolve)(t)]:r.map((e=>(0,n.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 s=o[0]??"";return 0!==s.length?t.slice(0,r+19+s.length):void 0}(e))).filter((e=>void 0!==e));return!!(i.length>0&&s.some((e=>h(e,i))))||!(void 0===o||!s.some((e=>h(e,[o]))))}},"../utils/dist/workload-spawn.js"(e,t,r){"use strict";r.d(t,{D9:()=>l});var o=r("node:fs");function s(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,o.writeFileSync)(`/proc/${e}/oom_score_adj`,"0")}catch{}}const n=/^\/sys\/fs\/cgroup\/[A-Za-z0-9_/.-]+$/,i=Object.freeze({kind:"direct"});function a(e){return`echo $$ 2>/dev/null > '${e}/cgroup.procs'; echo 0 2>/dev/null > /proc/$$/oom_score_adj; exec "$0" "$@"`}function c(e){try{return!!(0,o.statSync)(e).isDirectory()&&((0,o.accessSync)(`${e}/cgroup.procs`,o.constants.W_OK),!0)}catch{return!1}}const l=function(e,t=s){return function(r,o,s,...n){const i="direct"===e.kind?r(o,[...s],...n):r(e.executable,[...e.argumentPrefix,o,...s],...n);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)}(i,t),i}}(function(e,t,r=c){return"linux"===e&&void 0!==t&&n.test(t)&&!t.includes("..")&&r(t)?Object.freeze({kind:"armed",workloadCgroupDir:t,executable:"/bin/sh",argumentPrefix:Object.freeze(["-c",a(t)])}):i}(process.platform,process.env.CURSOR_WORKLOAD_CGROUP))},"../utils/dist/writable-iterable.js"(e,t,r){"use strict";r.d(t,{F8:()=>s,Jt:()=>n,W2:()=>o});class o extends Error{constructor(e){super(e),this.name="WriteIterableClosedError"}}class s{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 n(){const e=[],t=[];let r,s=!1,n=()=>{},i=()=>{};const a=()=>{const e=new Promise(((e,t)=>{n=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(n){if(s)throw r??new o("WritableIterable is closed");const i=e.shift();if(i){if(i.resolve({done:!1,value:n}),e.length>0)return}else t.push(n);const a=t.length+1;for(let e=0;e<a;e++)await c},throw(e){s||(s=!0,r=e,u(e),l({done:!0,value:void 0},e))},close(){s||(s=!0,t.length=0,n(),c=Promise.reject(new o("WritableIterable is closed")),c.catch((()=>{})),l({done:!0,value:void 0}))},[Symbol.asyncIterator]:()=>({next(){n(),c=a();const o=t.shift();return void 0!==o?Promise.resolve({done:!1,value:o}):s?r?Promise.reject(r):Promise.resolve({done:!0,value:void 0}):new Promise(((t,r)=>{e.push({resolve:t,reject:r})}))},throw:e=>(s=!0,r=e,t.length=0,u(e),l({done:!0,value:void 0},e),Promise.resolve({done:!0,value:void 0})),return:()=>(s=!0,t.length=0,n(),c=Promise.reject(new Error("Iterator was closed")),c.catch((()=>{})),l({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))})}}}};