@cursor/sdk 1.0.25 → 1.0.27-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/417.js +1 -0
- package/dist/cjs/642.js +1 -1
- package/dist/cjs/856.js +1 -1
- package/dist/cjs/agent/options.d.ts +90 -1
- package/dist/cjs/agent/options.d.ts.map +1 -1
- package/dist/cjs/agent/store/local-agent-store.d.ts.map +1 -1
- package/dist/cjs/agent/usage-types.d.ts +12 -3
- package/dist/cjs/agent/usage-types.d.ts.map +1 -1
- package/dist/cjs/agent.d.ts +11 -5
- package/dist/cjs/agent.d.ts.map +1 -1
- package/dist/cjs/analytics.d.ts.map +1 -1
- package/dist/cjs/auth/credential-store.d.ts +56 -0
- package/dist/cjs/auth/credential-store.d.ts.map +1 -0
- package/dist/cjs/auth/login-flow.d.ts +72 -0
- package/dist/cjs/auth/login-flow.d.ts.map +1 -0
- package/dist/cjs/auth/login.d.ts +86 -0
- package/dist/cjs/auth/login.d.ts.map +1 -0
- package/dist/cjs/auth/mint-api-key.d.ts +29 -0
- package/dist/cjs/auth/mint-api-key.d.ts.map +1 -0
- package/dist/cjs/auth/open-browser.d.ts +12 -0
- package/dist/cjs/auth/open-browser.d.ts.map +1 -0
- package/dist/cjs/auth/stored-credentials.d.ts +20 -0
- package/dist/cjs/auth/stored-credentials.d.ts.map +1 -0
- package/dist/cjs/cloud-agent.d.ts +1 -3
- package/dist/cjs/cloud-agent.d.ts.map +1 -1
- package/dist/cjs/cloud-api-client.d.ts +4 -0
- package/dist/cjs/cloud-api-client.d.ts.map +1 -1
- package/dist/cjs/cloud-executor.d.ts.map +1 -1
- package/dist/cjs/executor-common.d.ts.map +1 -1
- package/dist/cjs/executor-types.d.ts +23 -0
- package/dist/cjs/executor-types.d.ts.map +1 -1
- package/dist/cjs/index.d.ts +2 -2
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/local-executor.d.ts +7 -0
- package/dist/cjs/local-executor.d.ts.map +1 -1
- package/dist/cjs/native/vendored-tree-sitter.d.ts +19 -0
- package/dist/cjs/native/vendored-tree-sitter.d.ts.map +1 -0
- package/dist/cjs/options.d.ts +90 -1
- package/dist/cjs/options.d.ts.map +1 -1
- package/dist/cjs/platform-package-locator.d.ts +23 -0
- package/dist/cjs/platform-package-locator.d.ts.map +1 -0
- package/dist/cjs/platform.d.ts +9 -2
- package/dist/cjs/platform.d.ts.map +1 -1
- package/dist/cjs/public-api.d.ts +5 -1
- package/dist/cjs/public-api.d.ts.map +1 -1
- package/dist/cjs/sqlite.js +1 -1
- package/dist/cjs/store/local-agent-store.d.ts.map +1 -1
- package/dist/cjs/stubs.d.ts +14 -2
- package/dist/cjs/stubs.d.ts.map +1 -1
- package/dist/cjs/tools-option.d.ts +31 -0
- package/dist/cjs/tools-option.d.ts.map +1 -0
- package/dist/cjs/usage-types.d.ts +12 -3
- package/dist/cjs/usage-types.d.ts.map +1 -1
- package/dist/esm/357.js +1 -1
- package/dist/esm/642.js +1 -1
- package/dist/esm/856.js +1 -1
- package/dist/esm/agent/options.d.ts +90 -1
- package/dist/esm/agent/options.d.ts.map +1 -1
- package/dist/esm/agent/store/local-agent-store.d.ts.map +1 -1
- package/dist/esm/agent/usage-types.d.ts +12 -3
- package/dist/esm/agent/usage-types.d.ts.map +1 -1
- package/dist/esm/agent.d.ts +11 -5
- package/dist/esm/agent.d.ts.map +1 -1
- package/dist/esm/analytics.d.ts.map +1 -1
- package/dist/esm/auth/credential-store.d.ts +56 -0
- package/dist/esm/auth/credential-store.d.ts.map +1 -0
- package/dist/esm/auth/login-flow.d.ts +72 -0
- package/dist/esm/auth/login-flow.d.ts.map +1 -0
- package/dist/esm/auth/login.d.ts +86 -0
- package/dist/esm/auth/login.d.ts.map +1 -0
- package/dist/esm/auth/mint-api-key.d.ts +29 -0
- package/dist/esm/auth/mint-api-key.d.ts.map +1 -0
- package/dist/esm/auth/open-browser.d.ts +12 -0
- package/dist/esm/auth/open-browser.d.ts.map +1 -0
- package/dist/esm/auth/stored-credentials.d.ts +20 -0
- package/dist/esm/auth/stored-credentials.d.ts.map +1 -0
- package/dist/esm/cloud-agent.d.ts +1 -3
- package/dist/esm/cloud-agent.d.ts.map +1 -1
- package/dist/esm/cloud-api-client.d.ts +4 -0
- package/dist/esm/cloud-api-client.d.ts.map +1 -1
- package/dist/esm/cloud-executor.d.ts.map +1 -1
- package/dist/esm/executor-common.d.ts.map +1 -1
- package/dist/esm/executor-types.d.ts +23 -0
- package/dist/esm/executor-types.d.ts.map +1 -1
- package/dist/esm/index.d.ts +2 -2
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/local-executor.d.ts +7 -0
- package/dist/esm/local-executor.d.ts.map +1 -1
- package/dist/esm/native/vendored-tree-sitter.d.ts +19 -0
- package/dist/esm/native/vendored-tree-sitter.d.ts.map +1 -0
- package/dist/esm/options.d.ts +90 -1
- package/dist/esm/options.d.ts.map +1 -1
- package/dist/esm/platform-package-locator.d.ts +23 -0
- package/dist/esm/platform-package-locator.d.ts.map +1 -0
- package/dist/esm/platform.d.ts +9 -2
- package/dist/esm/platform.d.ts.map +1 -1
- package/dist/esm/public-api.d.ts +5 -1
- package/dist/esm/public-api.d.ts.map +1 -1
- package/dist/esm/sqlite.js +1 -1
- package/dist/esm/store/local-agent-store.d.ts.map +1 -1
- package/dist/esm/stubs.d.ts +14 -2
- package/dist/esm/stubs.d.ts.map +1 -1
- package/dist/esm/tools-option.d.ts +31 -0
- package/dist/esm/tools-option.d.ts.map +1 -0
- package/dist/esm/usage-types.d.ts +12 -3
- package/dist/esm/usage-types.d.ts.map +1 -1
- package/package.json +13 -14
- package/dist/cjs/880.js +0 -1
package/dist/cjs/880.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";exports.id=880,exports.ids=[880],exports.modules={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>Sx});var n=r("node:buffer"),o=r("node:crypto"),i=r("node:fs"),s=r("node:os"),a=r("node:path"),l=r.t(a,2),c=r("../context/dist/otel.js"),u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class d{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}run(){return e=this,t=void 0,n=function*(){var e,t,r,n;const o={stack:[],error:void 0,hasError:!1};try{const l=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,c.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,u=[];try{for(var i,s=!0,a=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.checkpointStream);!(e=(i=yield a.next()).done);s=!0){n=i.value,s=!1;const e=n;u.push(this.checkpointHandler.handleCheckpoint(l,e.checkpoint,e.metadata))}}catch(e){t={error:e}}finally{try{s||e||!(r=a.return)||(yield r.call(a))}finally{if(t)throw t.error}}yield Promise.all(u)}catch(e){o.error=e,o.hasError=!0}finally{u(o)}},new((r=void 0)||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}));var e,t,r,n}}var h=r("../context/dist/logger.js"),p=r("../metrics/dist/index.js"),f=r("../proto/dist/generated/agent/v1/exec_pb.js"),m=r("../utils/dist/writable-iterable.js");const g=/https?:\/\/\S+/gi,v=/[)"'<>,.;:\]}]$/;function y(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&v.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),i=o.indexOf("//")+2,s=o.slice(i).search(/[/?#]/),a=-1===s?o.length:i+s,l=o.lastIndexOf("@",a-1);return l<i?o+r:o.slice(0,i)+o.slice(l+1)+r}const w=/ \[git: ([^\]]*)\]/;function b(e,t,r){if("object"!=typeof t||null===t)return e;if(w.test(e))return e;const n=t,o=[];if("string"==typeof n.gitErrorCode&&n.gitErrorCode.length>0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let i=`${e} [git: ${o.join(" ")}]`;var s,a;return!0===(null==r?void 0:r.includeStderr)&&"string"==typeof n.stderr&&n.stderr.length>0&&(i+=`\n--- git stderr ---\n${a=n.stderr,s=a.replace(g,y),s.length<=2048?s:`${s.slice(0,2048)}… [truncated to 2048 chars]`}`),i}var S=function(e){return this instanceof S?(this.v=e,this):new S(e)},k=function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof S?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},E=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}};const x=(0,h.h)("SimpleControlledExecManager"),C=(0,p.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),_=(0,p.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,p.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]});class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class R{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return function(r){return k(this,arguments,(function*(){const i=performance.now(),s=[],a=yield S(r.exec.execute(e,o,{execId:t.execId,hookContextCollector:s,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts})),l=r.serializeResult(n,a);l.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-i)),s.length>0&&(l.hookAdditionalContexts=s),yield yield S(l)}))}(this)}}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return function(r){return k(this,arguments,(function*(){var i,s,a,l;const c=performance.now(),u=[],d=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:u,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{try{for(var h,p=!0,m=E(d);!(i=(h=yield S(m.next())).done);p=!0){l=h.value,p=!1;const e=l,t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-c)),yield yield S(t)}}catch(e){s={error:e}}finally{try{p||i||!(a=m.return)||(yield S(a.call(m)))}finally{if(s)throw s.error}}}finally{const e=u.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield yield S(new f.yT({id:n,hookAdditionalContexts:e})))}}))}(this)}}class O{constructor(e){var t;this.handlers=[],this.runningExecs=new Map;const r=null!==(t=null==e?void 0:e.includeGitStderrInThrows)&&void 0!==t&&t;this.includeGitStderrInThrows="function"==typeof r?r:()=>r}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){var r;const[n,o]=e.withCancel();this.runningExecs.set(t.id,o);const i=null!==(r=t.message.case)&&void 0!==r?r:"unknown";for(const e of this.handlers){const r=e.handle(n,t);if(void 0===r)continue;const o=r,s=(0,m.Jt)();let a;const l=()=>{a=setTimeout((()=>{s.write(new f.$Y({message:{case:"heartbeat",value:new f.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const c=performance.now(),u=()=>{return e=this,r=void 0,u=function*(){var e,r,l,u;try{try{for(var d,h=!0,p=E(o);!(e=(d=yield p.next()).done);h=!0){u=d.value,h=!1;const e=u;yield s.write(e)}}catch(e){r={error:e}}finally{try{h||e||!(l=p.return)||(yield l.call(p))}finally{if(r)throw r.error}}yield s.write(new f.$Y({message:{case:"streamClose",value:new f.D9({id:t.id})}})),_.increment(n,1,{exec_case:i})}catch(e){if(e instanceof m.W2)return;P.increment(n,1,{exec_case:i}),yield s.write(new f.$Y({message:{case:"throw",value:new f.Fu({id:t.id,error:e instanceof Error?b(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{const e=performance.now()-c;C.histogram(n,e,{exec_case:i}),clearTimeout(a),s.close(),this.runningExecs.delete(t.id)}},new((l=void 0)||(l=Promise))((function(t,n){function o(e){try{s(u.next(e))}catch(e){n(e)}}function i(e){try{s(u.throw(e))}catch(e){n(e)}}function s(e){var r;e.done?t(e.value):(r=e.value,r instanceof l?r:new l((function(e){e(r)}))).then(o,i)}s((u=u.apply(e,r||[])).next())}));var e,r,l,u};return u(),s}this.runningExecs.delete(t.id);const s=`No handler found for server message of type ${t.message.case}`;return x.error(e,s,{messageCase:t.message.case}),P.increment(e,1,{exec_case:i}),function(){return k(this,arguments,(function*(){yield yield S(new f.$Y({message:{case:"throw",value:new f.Fu({id:t.id,error:s})}})),yield yield S(new f.$Y({message:{case:"streamClose",value:new f.D9({id:t.id})}}))}))}()}static fromResources(e,t){const r=new O(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var M=function(e){return this instanceof M?(this.v=e,this):new M(e)};function j(e){return t=this,r=void 0,o=function*(){const t=e[Symbol.asyncIterator](),r=yield t.next();if(r.done)return;const n={[Symbol.asyncIterator](){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof M?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(){for(;;){const e=yield M(t.next());if(e.done)return yield M(void 0);yield yield M(e.value)}}))}};return{firstItem:r.value,rest:n}},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}var D=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n}),L=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}},F=function(e){return this instanceof F?(this.v=e,this):new F(e)};const U=(0,h.h)("ExecutorResource"),B=(0,p.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class z{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}execute(e,t,r){return D(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,c.VI)(e.withName("ExecutorResource.execute")),!1),i=o.ctx;void 0!==(null==r?void 0:r.execId)&&o.span.setAttribute("exec.id",r.execId);const s=(0,c.mJ)(i),a=s?new f.Kg(s):void 0,l=this.execManager.createExecInstance(i,(e=>{const n=this.serializeArgs(e,t);return new f.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,spanContext:a,acceptHookAdditionalContexts:void 0!==(null==r?void 0:r.hookContextCollector)})})),u=yield j(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const p=e=>{if(void 0!==(null==r?void 0:r.hookContextCollector)&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)B.increment(i,1,{hook_event_name:t.hookEventName})}};p(d);let m=this.deserializeResult(d);for(;void 0===m;){const e=yield j(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,p(d),m=this.deserializeResult(d)}return(()=>D(this,void 0,void 0,(function*(){var e,t,r,n;try{try{for(var o,s=!0,a=L(h);!(e=(o=yield a.next()).done);s=!0)n=o.value,s=!1,p(n)}catch(e){t={error:e}}finally{try{s||e||!(r=a.return)||(yield r.call(a))}finally{if(t)throw t.error}}}catch(e){U.info(i,"Ignoring exec stream shutdown during detached drain",{error:e})}})))().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{$(n)}}))}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}execute(e,t,r){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof F?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(){var n,o,i,s;const a={stack:[],error:void 0,hasError:!1};try{const h=N(a,(0,c.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,p=(0,c.mJ)(h),m=p?new f.Kg(p):void 0,g=this.execManager.createExecInstance(h,(e=>{const n=this.serializeArgs(e,t);return new f.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,spanContext:m,acceptHookAdditionalContexts:void 0!==(null==r?void 0:r.hookContextCollector)||!0===(null==r?void 0:r.deliverAgentStoreConflictNotices)})}));try{for(var l,u=!0,d=L(g);!(n=(l=yield F(d.next())).done);u=!0){s=l.value,u=!1;const e=s;void 0!==(null==r?void 0:r.hookContextCollector)&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield yield F(t))}}catch(e){o={error:e}}finally{try{u||n||!(i=d.return)||(yield F(i.call(d)))}finally{if(o)throw o.error}}}catch(e){a.error=e,a.hasError=!0}finally{$(a)}}))}}function H(e,t){return{symbol:Symbol(),remoteImplementation:e,registerControlledImplementation:t}}class q{constructor(e,t){this.resource=e,this.value=t}}class G{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new q(e,t))}get(e){var t;return null===(t=this.resources.get(e.symbol))||void 0===t?void 0:t.value}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class V{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?t.implementation:this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function J(e){return function(t,r){return new f.Ye({id:t,message:{case:e,value:r}})}}function K(e){return t=>{if(t.message.case===e)return t.message.value}}function Z(e){return function(t,r){const n={case:e,value:r};return new f.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const X=H((e=>new z(e,J("agentStoreConflictArgs"),K("agentStoreConflictResult"))),((e,t)=>{t.register(new R(e,Y("agentStoreConflictArgs"),Z("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","gap"]);class Q{execute(e,t){return r=this,n=void 0,i=function*(){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"}},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{l(i.next(e))}catch(e){t(e)}}function a(e){try{l(i.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,a)}l((i=i.apply(r,n||[])).next())}));var r,n,o,i}}H((e=>new Q),((e,t)=>{}));const ee=H((e=>new z(e,J("backgroundShellSpawnArgs"),K("backgroundShellSpawnResult"))),((e,t)=>{t.register(new R(e,Y("backgroundShellSpawnArgs"),Z("backgroundShellSpawnResult")))})),te=H((e=>new z(e,J("writeShellStdinArgs"),K("writeShellStdinResult"))),((e,t)=>{t.register(new R(e,Y("writeShellStdinArgs"),Z("writeShellStdinResult")))}));function re(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}const ne="local",oe=H((e=>new z(e,J("canvasDiagnosticsArgs"),K("canvasDiagnosticsResult"))),((e,t)=>{t.register(new R(e,Y("canvasDiagnosticsArgs"),Z("canvasDiagnosticsResult")))}));Error;const ie=H((e=>new z(e,J("computerUseArgs"),K("computerUseResult"))),((e,t)=>{t.register(new R(e,Y("computerUseArgs"),Z("computerUseResult")))})),se=(H((e=>new z(e,J("conversationSearchArgs"),K("conversationSearchResult"))),((e,t)=>{t.register(new R(e,Y("conversationSearchArgs"),Z("conversationSearchResult")))})),H((e=>new z(e,J("deleteArgs"),K("deleteResult"))),((e,t)=>{t.register(new R(e,Y("deleteArgs"),Z("deleteResult")))}))),ae=H((e=>new z(e,J("diagnosticsArgs"),K("diagnosticsResult"))),((e,t)=>{t.register(new R(e,Y("diagnosticsArgs"),Z("diagnosticsResult")))})),le=H((e=>new z(e,J("fetchArgs"),K("fetchResult"))),((e,t)=>{t.register(new R(e,Y("fetchArgs"),Z("fetchResult")))})),ce=H((e=>new z(e,J("gitDiffRequest"),K("gitDiffResponse"))),((e,t)=>{t.register(new R(e,Y("gitDiffRequest"),Z("gitDiffResponse")))})),ue=H((e=>new z(e,J("grepArgs"),K("grepResult"))),((e,t)=>{t.register(new R(e,Y("grepArgs"),Z("grepResult")))})),de={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"},he={PreToolUse:de.preToolUse,PermissionRequest:null,PostToolUse:de.postToolUse,UserPromptSubmit:de.beforeSubmitPrompt,Stop:de.stop,SubagentStop:de.subagentStop,SessionStart:de.sessionStart,SessionEnd:de.sessionEnd,PreCompact:de.preCompact,Notification:null},pe=Object.fromEntries(Object.entries(he).filter((e=>null!==e[1])).map((([e,t])=>[t,e]))),fe={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},me=["Glob"],ge=["Notification","PermissionRequest"],ve={warn:()=>{},info:()=>{}};function ye(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?Object.assign({type:"prompt",prompt:e.prompt},r):null:e.command?Object.assign({type:"command",command:e.command},r):null}function we(e,t,r=ve){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=ve){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=fe[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):me.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=ye(t,o);e&&n.push(e)}return n}function be(e,t=ve){const r={};for(const[n,o]of Object.entries(e)){const e=n;if(ge.includes(e)){t.warn(`Claude Code event "${e}" is not supported in Cursor and will be ignored`);continue}const i=he[e];if(!i){t.warn(`Unknown Claude Code event "${e}", skipping`);continue}const s=[];if(Array.isArray(o))for(const r of o){const n=we(r,e,t);s.push(...n)}else void 0!==o&&t.warn(`Claude Code event "${e}" has invalid value (expected array), skipping`);if(s.length>0){const e=r[i]||[];r[i]=[...e,...s]}}return{version:1,hooks:r}}function Se(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch(e){return!0}}(e,t)))}const ke=e=>"string"==typeof e,Ee=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),xe=(e,t=[])=>({isValid:e,errors:t});function Ce(e,t,r){void 0===e||ke(e)||r.push(`${t} must be a string if provided`)}const _e=e=>{const t=[];return Ee(e)?xe(!0):(t.push("Expected an object"),xe(!1,t))},Pe=e=>{const t=[],r=_e(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"),xe(0===t.length,t)};function Ie(e){const t=e.modelId,r=e.modelParams;return Object.assign(Object.assign({},void 0!==t&&{model_id:t}),void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{})}const Te=new Set([de.sessionStart,de.beforeSubmitPrompt,de.preToolUse,de.postToolUse,de.postToolUseFailure]);function Re(e){return"prompt"===e.type}const Ae={[de.beforeShellExecution]:Pe,[de.beforeMCPExecution]:Pe,[de.afterShellExecution]:e=>{const t=_e(e);return t.isValid,t},[de.afterMCPExecution]:e=>{const t=_e(e);return t.isValid,t},[de.beforeReadFile]:e=>{const t=[],r=_e(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"),xe(0===t.length,t)},[de.afterFileEdit]:e=>{const t=_e(e);return t.isValid,t},[de.beforeTabFileRead]:e=>{const t=[],r=_e(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"),xe(0===t.length,t)},[de.afterTabFileEdit]:e=>_e(e),[de.beforeSubmitPrompt]:e=>{const t=_e(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||ke(e.additional_context)||r.push("additional_context must be a string if provided"),xe(0===r.length,r)},[de.stop]:e=>{const t=_e(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"),xe(0===r.length,r)},[de.afterAgentResponse]:e=>{const t=_e(e);return t.isValid,t},[de.afterAgentThought]:e=>{const t=_e(e);return t.isValid,t},[de.sessionStart]:e=>{const t=_e(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Ee(e.env))for(const[t,n]of Object.entries(e.env))ke(t)||r.push(`env key "${t}" must be a string`),ke(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||ke(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||ke(e.user_message)||r.push("user_message must be a string if provided"),xe(0===r.length,r)},[de.sessionEnd]:e=>{const t=_e(e);return t.isValid?xe(!0,[]):t},[de.preCompact]:e=>{const t=_e(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return xe(!0,[]);const r=[];if(!Ee(e))return r.push("PreCompact response must be an object"),xe(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),xe(0===r.length,r)},[de.subagentStart]:e=>{const t=_e(e);if(!t.isValid)return t;const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||ke(n.user_message)||r.push("user_message must be a string if provided"),xe(0===r.length,r)},[de.subagentStop]:e=>{const t=_e(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"),xe(0===r.length,r)},[de.preToolUse]:e=>{const t=[],r=_e(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"),Ce(e.additional_context,"additional_context",t),xe(0===t.length,t)},[de.postToolUse]:e=>{const t=[],r=_e(e);return r.isValid?(Ce(e.additional_context,"additional_context",t),xe(0===t.length,t)):r},[de.postToolUseFailure]:e=>{const t=_e(e);if(!t.isValid)return t;const r=[];return Ce(e.additional_context,"additional_context",r),xe(0===r.length,r)},[de.workspaceOpen]:e=>{const t=_e(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{ke(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")),xe(0===r.length,r)}},Oe=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===de.preToolUse?function(e,t){if(!ze(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!Be(t))return r;const n=We(e);if(!He(n,"PreToolUse"))return r;const o=Object.assign({},r);let i=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,i=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,i=!0),ze(n.updatedInput)&&(o.updated_input=n.updatedInput,i=!0),i?o:r}(t,r):e===de.stop?qe(t,r,"Stop"):e===de.subagentStop?qe(t,r,"SubagentStop"):t,function(e,t,r,n){var o;if(!Te.has(e)||!ze(r)||void 0!==r.additional_context)return r;const i=ze(t)?null!==(o=function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t))&&void 0!==o?o:function(e,t,r){if(!Be(r))return;const n=pe[e];if(void 0===n)return;const o=We(t);return He(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===i?r:Object.assign(Object.assign({},r),{additional_context:i})}(e,t,n,r)}(e,t,r),o=(0,Ae[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},Me=[de.beforeShellExecution,de.beforeMCPExecution,de.beforeReadFile,de.beforeTabFileRead,de.subagentStart,de.preToolUse],je=[de.workspaceOpen];function De(e,t){const r=[];return(null==e?void 0:e.trim())&&r.push(e.trim()),(null==t?void 0:t.trim())&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function Ne(e,t){if(e||t)return Object.assign(Object.assign({},e||{}),t||{})}function $e(e){return Me.includes(e)}function Le({step:e,command:t,failClosed:r,kind:n}){const o=$e(e);if(!r&&!o)return{shouldNotifyUser:!1};const i=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:Fe(e,i),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:i,shouldNotifyUser:o&&!r}}function Fe(e,t){return $e(e)?{permission:"deny",user_message:t}:e===de.beforeSubmitPrompt||e===de.sessionStart?{continue:!1,user_message:t}:e===de.stop?{}:void 0}function Ue(e){try{return{value:JSON.parse(e)}}catch(e){return}}function Be(e){var t;return null!==(t=null==e?void 0:e.enableClaudeNestedHookSpecificOutputCompatibility)&&void 0!==t&&t}function ze(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function We(e){if(!ze(e))return;const t=e.hookSpecificOutput;return ze(t)?t:void 0}function He(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function qe(e,t,r){if(!ze(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return Object.assign(Object.assign({},n),{followup_message:n.reason.trim()});if(!Be(t))return n;const o=We(e),i=He(o,r)?o:void 0,s=void 0!==i?Object.assign(Object.assign({},n),i):n;return"block"===s.decision&&"string"==typeof s.reason&&s.reason.trim().length>0?Object.assign(Object.assign({},s),{followup_message:s.reason.trim()}):n}const Ge=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"],Ve=e=>{const t=[];if(!Ee(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)"),xe(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{ke(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&&(ke(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)=>{ke(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{var r;if(void 0!==e.matcher)if(ke(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(n){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${null!==(r=null==n?void 0:n.message)&&void 0!==r?r:String(n)}`)}}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),xe(0===t.length,t)},Je=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),xe(!1,r);for(let n=0;n<e.length;n++){const o=Ve(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return xe(0===r.length,r)},Ke=e=>{const t=[];if(!Ee(e))return t.push("Hooks config must be an object"),xe(!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"),!Ee(e.hooks))return t.push("Config hooks must be an object"),xe(!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(de),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Je(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return xe(0===t.length,t)};var Ze=r("../proto/dist/generated/agent/v1/agent_pb.js");const Ye=H((e=>new z(e,J("executeHookArgs"),K("executeHookResult"))),((e,t)=>{t.register(new R(e,Y("executeHookArgs"),Z("executeHookResult")))}));class Xe{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){var r,n,o;return null!==(o=null===(n=(r=this.hookExecutor).hasFailClosedHooksForStep)||void 0===n?void 0:n.call(r,e,t))&&void 0!==o&&o}execute(e,t){return r=this,n=void 0,i=function*(){var e,r,n,o,i,s,a,l,c,u,d,h,p,m,g,v,y,w,b,S,k,E,x,C,_,P,I,T,R,A,O;const M=t.request;if(!M)return new f.S1({response:void 0});switch(M.request.case){case"preCompact":{const t=M.request.value,o=Object.assign(Object.assign({conversation_id:null!==(e=t.conversationId)&&void 0!==e?e:"",generation_id:null!==(r=t.generationId)&&void 0!==r?r:"",model:null!==(n=t.model)&&void 0!==n?n:""},Ie(t)),{trigger:"manual"===t.trigger?"manual":"auto",context_usage_percent:t.contextUsagePercent,context_tokens:Number(t.contextTokens),context_window_size:Number(t.contextWindowSize),message_count:t.messageCount,messages_to_compact:t.messagesToCompact,is_first_compaction:t.isFirstCompaction}),i=yield this.hookExecutor.executeHookForStep(de.preCompact,o);return new f.S1({response:new f.w5({response:{case:"preCompact",value:new Ze.$__({userMessage:null==i?void 0:i.user_message})}})})}case"subagentStart":{const e=M.request.value,t=Object.assign(Object.assign({conversation_id:null!==(o=e.conversationId)&&void 0!==o?o:"",generation_id:null!==(i=e.generationId)&&void 0!==i?i:"",model:null!==(s=e.model)&&void 0!==s?s:""},Ie(e)),{subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch}),r=yield this.hookExecutor.executeHookForStep(de.subagentStart,t);return new f.S1({response:new f.w5({response:{case:"subagentStart",value:new Ze.W0W({permission:null==r?void 0:r.permission,userMessage:null==r?void 0:r.user_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"subagentStop":{const e=M.request.value,t=Object.assign(Object.assign({conversation_id:null!==(a=e.conversationId)&&void 0!==a?a:"",generation_id:null!==(l=e.generationId)&&void 0!==l?l:"",model:null!==(c=e.model)&&void 0!==c?c:""},Ie(e)),{subagent_id:e.subagentId,subagent_type:e.subagentType,status:e.status,duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:null!==(u=e.loopCount)&&void 0!==u?u:0,task:e.task,description:e.description}),r=yield this.hookExecutor.executeHookForStep(de.subagentStop,t);return new f.S1({response:new f.w5({response:{case:"subagentStop",value:new Ze.AHw({followupMessage:null==r?void 0:r.followup_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"beforeSubmitPrompt":{const e=M.request.value,t=yield this.hookExecutor.executeHookForStep(de.beforeSubmitPrompt,Object.assign(Object.assign({conversation_id:null!==(d=e.conversationId)&&void 0!==d?d:"",generation_id:null!==(h=e.generationId)&&void 0!==h?h:"",model:null!==(p=e.model)&&void 0!==p?p:""},Ie(e)),{prompt:e.prompt,attachments:(j=e.attachments,j.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode}));return new f.S1({response:new f.w5({response:{case:"beforeSubmitPrompt",value:new Ze.u1V({continue:null==t?void 0:t.continue,userMessage:null==t?void 0:t.user_message,additionalContext:null==t?void 0:t.additional_context})}})})}case"afterAgentResponse":{const e=M.request.value;return yield this.hookExecutor.executeHookForStep(de.afterAgentResponse,Object.assign(Object.assign({conversation_id:null!==(m=e.conversationId)&&void 0!==m?m:"",generation_id:null!==(g=e.generationId)&&void 0!==g?g:"",model:null!==(v=e.model)&&void 0!==v?v:""},Ie(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 f.S1({response:new f.w5({response:{case:"afterAgentResponse",value:new Ze.FW9}})})}case"afterAgentThought":{const e=M.request.value;return yield this.hookExecutor.executeHookForStep(de.afterAgentThought,Object.assign(Object.assign({conversation_id:null!==(y=e.conversationId)&&void 0!==y?y:"",generation_id:null!==(w=e.generationId)&&void 0!==w?w:"",model:null!==(b=e.model)&&void 0!==b?b:""},Ie(e)),{text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0})),new f.S1({response:new f.w5({response:{case:"afterAgentThought",value:new Ze.HaO}})})}case"stop":{const e=M.request.value,t=yield this.hookExecutor.executeHookForStep(de.stop,Object.assign(Object.assign({conversation_id:null!==(S=e.conversationId)&&void 0!==S?S:"",generation_id:null!==(k=e.generationId)&&void 0!==k?k:"",model:null!==(E=e.model)&&void 0!==E?E:""},Ie(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 f.S1({response:new f.w5({response:{case:"stop",value:new Ze.rTS({followupMessage:null==t?void 0:t.followup_message})}})})}case"preToolUse":{const e=M.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(x=e.conversationId)&&void 0!==x?x:"",generation_id:null!==(C=e.generationId)&&void 0!==C?C:"",model:null!==(_=e.model)&&void 0!==_?_:""},Ie(e)),{tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd}),n=yield this.hookExecutor.executeHookForStep(de.preToolUse,r);return new f.S1({response:new f.w5({response:{case:"preToolUse",value:new Ze.D2O({permission:null==n?void 0:n.permission,userMessage:null==n?void 0:n.user_message,agentMessage:null==n?void 0:n.agent_message,updatedInput:(null==n?void 0:n.updated_input)?JSON.stringify(n.updated_input):void 0,additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUse":{const e=M.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(P=e.conversationId)&&void 0!==P?P:"",generation_id:null!==(I=e.generationId)&&void 0!==I?I:"",model:null!==(T=e.model)&&void 0!==T?T:""},Ie(e)),{tool_name:e.toolName,tool_input:t,tool_output:e.toolOutput,duration:Number(e.durationMs),tool_use_id:e.toolUseId,cwd:e.cwd}),n=yield this.hookExecutor.executeHookForStep(de.postToolUse,r);return new f.S1({response:new f.w5({response:{case:"postToolUse",value:new Ze.uB8({additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUseFailure":{const e=M.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(R=e.conversationId)&&void 0!==R?R:"",generation_id:null!==(A=e.generationId)&&void 0!==A?A:"",model:null!==(O=e.model)&&void 0!==O?O:""},Ie(e)),{tool_name:e.toolName,tool_input:t,error_message:e.errorMessage,failure_type:e.failureType,duration:Number(e.durationMs),tool_use_id:e.toolUseId,is_interrupt:e.isInterrupt}),n=yield this.hookExecutor.executeHookForStep(de.postToolUseFailure,r);return new f.S1({response:new f.w5({response:{case:"postToolUseFailure",value:new Ze.U15({additionalContext:null==n?void 0:n.additional_context})}})})}default:return new f.S1({response:void 0})}var j},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{l(i.next(e))}catch(e){t(e)}}function a(e){try{l(i.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,a)}l((i=i.apply(r,n||[])).next())}));var r,n,o,i}}var Qe=r("../context/dist/core.js");(0,Qe.cF)(Symbol("execHookConversationId"),void 0),(0,Qe.cF)(Symbol("execHookGenerationId"),void 0),(0,Qe.cF)(Symbol("execHookModel"),void 0);const et=(0,Qe.cF)(Symbol("execHookWorkspaceRoots"),void 0),tt=H((e=>new z(e,J("lsArgs"),K("lsResult"))),((e,t)=>{t.register(new R(e,Y("lsArgs"),Z("lsResult")))})),rt="custom-user-tools",nt=new Set(["cursor-dev-control","cursor-ide-browser"]);function ot(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 st(e){return void 0===e||void 0===e.serverIdentifiers}!function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(it||(it={}));const at=H((e=>new z(e,J("mcpArgs"),K("mcpResult"))),((e,t)=>{t.register(new R(e,Y("mcpArgs"),Z("mcpResult")))})),lt=H((e=>new z(e,J("listMcpResourcesExecArgs"),K("listMcpResourcesExecResult"))),((e,t)=>{t.register(new R(e,Y("listMcpResourcesExecArgs"),Z("listMcpResourcesExecResult")))})),ct=H((e=>new z(e,J("readMcpResourceExecArgs"),K("readMcpResourceExecResult"))),((e,t)=>{t.register(new R(e,Y("readMcpResourceExecArgs"),Z("readMcpResourceExecResult")))})),ut=H((e=>new z(e,J("mcpStateExecArgs"),K("mcpStateExecResult"))),((e,t)=>{t.register(new R(e,Y("mcpStateExecArgs"),Z("mcpStateExecResult")))})),dt=H((e=>new z(e,J("mcpAllowlistPrecheckArgs"),K("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Y("mcpAllowlistPrecheckArgs"),Z("mcpAllowlistPrecheckResult")))})),ht=H((e=>new z(e,J("miniSweAgentBashArgs"),K("miniSweAgentBashResult"))),((e,t)=>{t.register(new R(e,Y("miniSweAgentBashArgs"),Z("miniSweAgentBashResult")))})),pt=H((e=>new z(e,J("piBashArgs"),K("piBashResult"))),((e,t)=>{t.register(new R(e,Y("piBashArgs"),Z("piBashResult")))})),ft=H((e=>new z(e,J("piEditArgs"),K("piEditResult"))),((e,t)=>{t.register(new R(e,Y("piEditArgs"),Z("piEditResult")))})),mt=H((e=>new z(e,J("piFindArgs"),K("piFindResult"))),((e,t)=>{t.register(new R(e,Y("piFindArgs"),Z("piFindResult")))})),gt=H((e=>new z(e,J("piGrepArgs"),K("piGrepResult"))),((e,t)=>{t.register(new R(e,Y("piGrepArgs"),Z("piGrepResult")))})),vt=H((e=>new z(e,J("piLsArgs"),K("piLsResult"))),((e,t)=>{t.register(new R(e,Y("piLsArgs"),Z("piLsResult")))})),yt=H((e=>new z(e,J("piReadArgs"),K("piReadResult"))),((e,t)=>{t.register(new R(e,Y("piReadArgs"),Z("piReadResult")))})),wt=H((e=>new z(e,J("piWriteArgs"),K("piWriteResult"))),((e,t)=>{t.register(new R(e,Y("piWriteArgs"),Z("piWriteResult")))})),bt=H((e=>new z(e,J("readArgs"),K("readResult"))),((e,t)=>{t.register(new R(e,Y("readArgs"),Z("readResult")))})),St=H((e=>new z(e,J("redactedReadArgs"),K("redactedReadResult"))),((e,t)=>{t.register(new R(e,Y("redactedReadArgs"),Z("redactedReadResult")))}));var kt=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Et=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),xt=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),Ct=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),_t=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Pt=H((e=>new z(e,J("shellArgs"),K("shellResult"))),((e,t)=>{t.register(new R(e,Y("shellArgs"),Z("shellResult")))})),It=H((e=>new W(e,J("shellStreamArgs"),K("shellStream"))),((e,t)=>{t.register(new A(e,Y("shellStreamArgs"),Z("shellStream")))})),Tt=H((e=>new z(e,J("writeArgs"),K("writeResult"))),((e,t)=>{t.register(new R(e,Y("writeArgs"),Z("writeResult")))}));var Rt=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},At=function(e){return this instanceof At?(this.v=e,this):new At(e)};function Ot(e,t){var r,n;return new Ct.jn({command:null!==(r=t.command)&&void 0!==r?r:"",workingDirectory:null!==(n=t.workingDirectory)&&void 0!==n?n:"",error:e,isReadonly:!0})}function Mt(e){return{execute(t,r){return Rt(this,void 0,void 0,(function*(){return new Ct.W4({result:{case:"permissionDenied",value:Ot(e,r)}})}))}}}function jt(e){return{execute(t,r){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof At?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(){yield yield At(new Ct.FI({event:{case:"permissionDenied",value:Ot(e,r)}}))}))}}}function Dt(e){return{execute(t,r){return Rt(this,void 0,void 0,(function*(){return new kt.Lt({result:{case:"permissionDenied",value:Ot(e,r)}})}))}}}function Nt(e){return{execute(t,r){return Rt(this,void 0,void 0,(function*(){return new Et.Pi({result:{case:"permissionDenied",value:new Et.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}))}}}function $t(e){return{execute(t,r){return Rt(this,void 0,void 0,(function*(){return new xt.iz({result:{case:"permissionDenied",value:new xt.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}))}}}function Lt(e){return{execute(t,r){return Rt(this,void 0,void 0,(function*(){return new kt.nt({result:{case:"error",value:new kt.Gv({error:e})}})}))}}}const Ft=H((e=>new z(e,J("recordScreenArgs"),K("recordScreenResult"))),((e,t)=>{t.register(new R(e,Y("recordScreenArgs"),Z("recordScreenResult")))})),Ut=H((e=>new z(e,J("requestContextArgs"),K("requestContextResult"))),((e,t)=>{t.register(new R(e,Y("requestContextArgs"),Z("requestContextResult")))}));var Bt=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const zt=H((e=>new z(e,J("shellAllowlistPrecheckArgs"),K("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Y("shellAllowlistPrecheckArgs"),Z("shellAllowlistPrecheckResult")))})),Wt=H((e=>new z(e,J("forceBackgroundShellArgs"),K("forceBackgroundShellResult"))),((e,t)=>{t.register(new R(e,Y("forceBackgroundShellArgs"),Z("forceBackgroundShellResult")))}));function Ht(e,t){e.hookApprovalRequirement=void 0!==t?new Ct.In(t):void 0}function qt(e){return e.hookApprovalRequirement}function Gt(e){return(null==e?void 0:e.kind)===Ct.b.FORCE_PROMPT}H((e=>new z(e,J("smartModeClassifierArgs"),K("smartModeClassifierResult"))),((e,t)=>{t.register(new R(e,Y("smartModeClassifierArgs"),Z("smartModeClassifierResult")))}));var Vt=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");class Jt extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=null==t?void 0:t.agentId,this.cause=null==t?void 0:t.cause}}function Kt(e){const t=new Map,r=new Map;function n(t,r,n){return o=this,i=void 0,a=function*(){var o,i,s,a;let l;try{l=yield e.createOrResumeSession(t,r);const a=yield e.runSession(t,l,r,{execId:null==n?void 0:n.execId});return"error"===a.status?new Vt.vS({result:{case:"error",value:new Vt.od({agentId:l,error:a.error})}}):"aborted"===a.status?new Vt.vS({result:{case:"error",value:new Vt.od({agentId:l,error:null!==(o=a.error)&&void 0!==o?o:"Subagent was aborted by the user"})}}):"background"===a.status?new Vt.vS({result:{case:"success",value:new Vt.HJ({agentId:l,finalMessage:a.finalMessage,toolCallCount:null!==(i=a.toolCallCount)&&void 0!==i?i:0,backgroundReason:a.backgroundReason,transcriptPath:a.transcriptPath})}}):new Vt.vS({result:{case:"success",value:new Vt.HJ({agentId:l,finalMessage:a.finalMessage,toolCallCount:null!==(s=a.toolCallCount)&&void 0!==s?s:0})}})}catch(t){l&&e.releaseSession&&e.releaseSession(l);const n=t instanceof Error?t.message:String(t),o=null!==(a=null!=l?l:function(e){if(e instanceof Jt&&e.agentId)return e.agentId;if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.agentId?t.agentId:void 0}(t))&&void 0!==a?a:r.resumeAgentId;return new Vt.vS({result:{case:"error",value:new Vt.od(Object.assign(Object.assign({},o?{agentId:o}:{}),{error:n}))}})}},new((s=void 0)||(s=Promise))((function(e,t){function r(e){try{l(a.next(e))}catch(e){t(e)}}function n(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s((function(e){e(o)}))).then(r,n)}l((a=a.apply(o,i||[])).next())}));var o,i,s,a}return{execute(e,o,i){const s=function(e){var t,r;if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,null!==(t=e.resumeAgentId)&&void 0!==t?t:"",null!==(r=e.forkAgentId)&&void 0!==r?r:""].join("\0")}(o);if(void 0===s)return n(e,o,i);const a=r.get(s);if(void 0!==a)return Promise.resolve(a);const l=t.get(s);if(void 0!==l)return l;const c=n(e,o,i).then((e=>("success"===e.result.case&&(r.set(s,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(s)}));return t.set(s,c),c}}}const Zt=H((e=>new z(e,J("subagentArgs"),K("subagentResult"))),((e,t)=>{t.register(new R(e,Y("subagentArgs"),Z("subagentResult")))}));H((e=>new z(e,J("subagentAwaitArgs"),K("subagentAwaitResult"))),((e,t)=>{t.register(new R(e,Y("subagentAwaitArgs"),Z("subagentAwaitResult")))})),H((e=>new z(e,J("forceBackgroundSubagentArgs"),K("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new R(e,Y("forceBackgroundSubagentArgs"),Z("forceBackgroundSubagentResult")))}));class Yt{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){var t;return null!==(t=this.states.get(e))&&void 0!==t?t:{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:null==t?void 0:t.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){var t;const r=(null!==(t=this.runCounterBySession.get(e))&&void 0!==t?t:0)+1;return this.runCounterBySession.set(e,r),r}enqueueEvent(e,t){var r;const n=null!==(r=this.dispatchQueueBySession.get(e))&&void 0!==r?r:[];n.push(t),this.dispatchQueueBySession.set(e,n),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){null!=t||(t=e)}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){var r,n,o,i,s;const a=this.getState(e),{nextState:l,effects:c}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:Object.assign(Object.assign({},e),{queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)}),effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(a,t);this.states.set(e,l),null===(n=(r=this.options).onStateChange)||void 0===n||n.call(r,{sessionId:e,previousState:a,nextState:l});for(const t of c)switch(t.type){case"abortActiveRun":null===(o=t.abort)||void 0===o||o.call(t);break;case"startQueuedRun":null===(s=(i=this.options).onQueuedRunReady)||void 0===s||s.call(i,{sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const u=this.getState(e);"release"===t.type&&"idle"!==u.status&&this.releaseRequestedBySession.add(e),"idle"!==u.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function Xt(e){return"string"==typeof e&&e.trim().length>0}const Qt=H((e=>new z(e,J("webFetchAllowlistPrecheckArgs"),K("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Y("webFetchAllowlistPrecheckArgs"),Z("webFetchAllowlistPrecheckResult")))})),er=e=>String(e).replace(/[\r\n]/g,""),tr="x-inference-authentication-jwt",rr={textDelta:e=>new Ze.Uq({message:{case:"textDelta",value:new Ze.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new Ze.Uq({message:{case:"toolCallStarted",value:new Ze.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new Ze.Uq({message:{case:"toolCallCompleted",value:new Ze.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r)=>new Ze.Uq({message:{case:"toolCallDelta",value:new Ze.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t)=>new Ze.Uq({message:{case:"thinkingDelta",value:new Ze.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:e=>new Ze.Uq({message:{case:"thinkingCompleted",value:new Ze.tr3({thinkingDurationMs:e})}}),userMessageAppended:e=>new Ze.Uq({message:{case:"userMessageAppended",value:new Ze.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new Ze.Uq({message:{case:"partialToolCall",value:new Ze.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new Ze.Uq({message:{case:"tokenDelta",value:new Ze.Fyz({tokens:e})}}),summary:e=>new Ze.Uq({message:{case:"summary",value:new Ze.ECk({summary:e})}}),summaryStarted:()=>new Ze.Uq({message:{case:"summaryStarted",value:new Ze.lWT}}),heartbeat:()=>new Ze.Uq({message:{case:"heartbeat",value:new Ze.ih1}}),summaryCompleted:e=>new Ze.Uq({message:{case:"summaryCompleted",value:new Ze.ZM9({hookMessage:e})}}),shellOutputDelta:e=>new Ze.Uq({message:{case:"shellOutputDelta",value:new Ze.Nn_({event:e})}}),turnEnded(e){var t;return new Ze.Uq({message:{case:"turnEnded",value:new Ze.lJj(e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(null!==(t=e.reasoningTokens)&&void 0!==t?t:0)}:{})}})},stepStarted:e=>new Ze.Uq({message:{case:"stepStarted",value:new Ze.dwJ({stepId:BigInt(e)})}}),stepCompleted:(e,t)=>new Ze.Uq({message:{case:"stepCompleted",value:new Ze.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),promptSuggestion:e=>new Ze.Uq({message:{case:"promptSuggestion",value:new Ze.yfd({suggestion:e})}}),activeBranchChange:(e,t)=>new Ze.Uq({message:{case:"activeBranchChange",value:new Ze.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new Ze.Uq({message:{case:"feedbackRequest",value:new Ze.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};var nr=r("../agent-kv/dist/index.js");function or(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 ir=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_pb.js"),ar=r("@bufbuild/protobuf"),lr=r("@connectrpc/connect"),cr=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_ef7275568c8b1f1f499006dc986c70d2/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ur=r("../proto/dist/generated/aiserver/v1/utils_pb.js");class dr 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 hr extends dr{get kind(){return"RetriableError"}}class pr extends dr{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class fr extends dr{get kind(){return"NonRetriableError"}}class mr extends dr{get kind(){return"CancelledError"}}const gr=new Set([ur.yM.NOT_LOGGED_IN,ur.yM.AGENT_REQUIRES_LOGIN,ur.yM.AUTH_TOKEN_NOT_FOUND,ur.yM.AUTH_TOKEN_EXPIRED,ur.yM.INVALID_AUTH_ID,ur.yM.UNAUTHORIZED,ur.yM.GITHUB_NO_USER_CREDENTIALS,ur.yM.GITHUB_USER_NO_ACCESS]),vr=new Set([ur.yM.FREE_USER_USAGE_LIMIT,ur.yM.FREE_USER_RATE_LIMIT_EXCEEDED,ur.yM.PRO_USER_ONLY,ur.yM.PRO_USER_USAGE_LIMIT,ur.yM.PRO_USER_RATE_LIMIT_EXCEEDED,ur.yM.RATE_LIMITED,ur.yM.RATE_LIMITED_CHANGEABLE,ur.yM.GENERIC_RATE_LIMIT_EXCEEDED]),yr=new Set([ur.yM.USAGE_PRICING_REQUIRED,ur.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),wr=new Set([ur.yM.BAD_API_KEY,ur.yM.BAD_USER_API_KEY,ur.yM.OUTDATED_CLIENT]),br=new Set([ur.yM.USER_ABORTED_REQUEST,ur.yM.DEBOUNCED]),Sr=new Set([ur.yM.CUSTOM_MESSAGE]),kr=["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"],Er=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH"]),xr=new RegExp(`\\b(${[...Er].join("|")})\\b`),Cr=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"];function _r(e,t={}){const{requestId:r}=t;if(e instanceof dr)return e;if(function(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}(e))return function(e,t){var r,n,o,i,s,a,l,c;const u=function(e){var t,r;const n=e.findDetails(ur.vj);if(n.length>0)return n[0];try{const n=null===(r=null===(t=e.cause)||void 0===t?void 0:t.findDetails)||void 0===r?void 0:r.call(t,ur.vj);return null==n?void 0:n[0]}catch(e){return}}(e),d={title:null===(r=null==u?void 0:u.details)||void 0===r?void 0:r.title,detail:null===(n=null==u?void 0:u.details)||void 0===n?void 0:n.detail,isRetryable:null===(o=null==u?void 0:u.details)||void 0===o?void 0:o.isRetryable,connectCode:e.code,errorCode:null==u?void 0:u.error,inferenceRequestErrorType:null!==(c=e.metadata.get("x-cursor-inference-request-error-type"))&&void 0!==c?c:void 0,errorDetails:u},h={cause:e,requestId:t,displayInfo:d};if(e.code===lr.Code.Canceled||e.code===lr.Code.Aborted)return Ir(e)?new hr(e.message,h):new mr(e.message,h);if(void 0!==(null==u?void 0:u.error)){const t=u.error;if(br.has(t))return new mr(Pr(e,u),h);const r=null===(s=null===(i=u.details)||void 0===i?void 0:i.analyticsMetadata)||void 0===s?void 0:s.actionRequired;if(void 0!==r&&""!==r)return new pr(Pr(e,u),r,h);if(gr.has(t))return new pr(Pr(e,u),"login",h);if(vr.has(t))return new pr(Pr(e,u),"upgrade",h);if(yr.has(t))return new pr(Pr(e,u),"payment",h);if(wr.has(t))return new pr(Pr(e,u),"config",h);if(Sr.has(t)&&!0!==(null===(a=u.details)||void 0===a?void 0:a.isRetryable))return new fr(Pr(e,u),h);if(!1===(null===(l=u.details)||void 0===l?void 0:l.isRetryable))return new fr(Pr(e,u),h)}return e.code===lr.Code.Unauthenticated?new pr(e.message,"login",h):new hr(e.message,h)}(e,r);const n=(0,nr.y_)(e);if(void 0!==n)return new fr(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new mr(e.message,{cause:e,requestId:r});if(Ir(e))return new hr(e.message,{cause:e,requestId:r})}const o=e instanceof Error?e.message:String(e);return new hr(o,{cause:e instanceof Error?e:void 0,requestId:r})}function Pr(e,t){if(null==t?void 0:t.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}function Ir(e){let t=e;for(;t instanceof Error;){const e=`${t.name}: ${t.message}`;if(kr.some((t=>e.includes(t)))||xr.test(e))return!0;const r=t.code;if("string"==typeof r&&(kr.some((e=>r.includes(e)))||Er.has(r)))return!0;t=t.cause}return!1}function Tr(e){return!0===e.isTransport||(e.cause instanceof Error?Ir(e.cause):kr.some((t=>e.message.includes(t)))||xr.test(e.message))}var Rr=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},Ar=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Or=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n}),Mr=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}};class jr extends Error{constructor(e){super(e),this.name="LostConnection"}}class Dr{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}run(e){return Rr(this,void 0,void 0,(function*(){var t,r,n,o;const i={stack:[],error:void 0,hasError:!1};try{Ar(i,(0,c.VI)(e.withName("ClientExecController.run")),!1);const u=[];try{try{for(var s,a=!0,l=Mr(this.serverStream);!(t=(s=yield l.next()).done);a=!0){o=s.value,a=!1;const t=o;if((0,ar.isMessage)(t,ir.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const r=(()=>Rr(this,void 0,void 0,(function*(){var r,n,o,i,s;const a={stack:[],error:void 0,hasError:!1};try{let h,p;if(t.spanContext){const r=t.spanContext;h=(0,c.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:null!==(s=r.traceFlags)&&void 0!==s?s:1},"exec.handle",e),p=(0,c.fU)(h)}else h=e;Ar(a,p?new c.r2(h,p):void 0,!1);const f=this.controlledExecManager.handle(h,t);try{for(var l,u=!0,d=Mr(f);!(r=(l=yield d.next()).done);u=!0){i=l.value,u=!1;const e=i;yield this.clientStream.write(e)}}catch(e){n={error:e}}finally{try{u||r||!(o=d.return)||(yield o.call(d))}finally{if(n)throw n.error}}}catch(e){a.error=e,a.hasError=!0}finally{Or(a)}})))();u.push(r)}}catch(e){r={error:e}}finally{try{a||t||!(n=l.return)||(yield n.call(l))}finally{if(r)throw r.error}}yield Promise.all(u)}catch(e){if(e instanceof lr.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new jr(e.message);if(e instanceof lr.ConnectError&&e.code===lr.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 jr(e.message)}else{if(e instanceof m.W2)throw new jr(e.message);if(e instanceof lr.ConnectError&&e.code===lr.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new jr(e.message)}}throw e}}catch(e){i.error=e,i.hasError=!0}finally{Or(i)}}))}}var Nr=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},$r=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Lr=(0,h.h)("ClientInteractionController"),Fr=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Ur{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}run(e){return Nr(this,void 0,void 0,(function*(){var t,r,n,o;const i={stack:[],error:void 0,hasError:!1};try{const u=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(i,(0,c.VI)(e.withName("ClientInteractionController.run")),!1);e=u.ctx;let d,h=Promise.resolve();try{for(var s,a=!0,l=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.interactionStream);!(t=(s=yield l.next()).done);a=!0){o=s.value,a=!1;const t=o;"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):"interactionUpdate"===t.case&&(h=h.then((()=>this.handleInteractionUpdate(e,t.value))).catch((t=>{Lr.error(e,"Error handling interaction update",t),null!=d||(d=t)})))}}catch(e){r={error:e}}finally{try{a||t||!(n=l.return)||(yield n.call(l))}finally{if(r)throw r.error}}if(yield h,void 0!==d)throw d}catch(e){i.error=e,i.hasError=!0}finally{$r(i)}}))}handleInteractionUpdate(e,t){return Nr(this,void 0,void 0,(function*(){yield this.interactionListener.sendUpdate(e,t)}))}handleInteractionQuery(e,t){var r;const n=void 0!==t.query.case&&Fr.has(t.query.case);let o=!1;const i=()=>{var e;n&&!o&&(o=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&(null===(e=this.stallSuspender)||void 0===e||e.setPaused(!1)))};n&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&(null===(r=this.stallSuspender)||void 0===r||r.setPaused(!0))),this.interactionListener.query(e,t).then((e=>(i(),this.queryResponseStream.write(e)))).catch((t=>{Lr.error(e,"Error handling interaction query",t)})).finally(i)}}var Br=r("../utils/dist/promise-extras.js");function zr(e){return t=this,r=arguments,o=function*({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){var t,r,n;const o=e.clone();return o.rules=[],o.nonFileRules=[],o.cloudRule=void 0,o.agentSkills=[],o.skillOptions=void 0,o.customSubagents=[],o.tools=[],o.mcpInstructions=[],o.mcpFileSystemOptions=void 0,o.mcpMetaToolOptions=void 0,{dynamicContext:o,rules:new Bt.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Bt.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:null===(t=e.skillOptions)||void 0===t?void 0:t.clone()}),subagents:new Bt.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Bt.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:null===(r=e.mcpFileSystemOptions)||void 0===r?void 0:r.clone(),mcpMetaToolOptions:null===(n=e.mcpMetaToolOptions)||void 0===n?void 0:n.clone()})}}(e);if("ref_only"===t&&o.dynamicContext.toBinary().byteLength>n)return;const i=o.rules.toBinary(),s=o.skills.toBinary(),a=o.subagents.toBinary(),l=o.mcps.toBinary(),c=i.byteLength+s.byteLength+a.byteLength+l.byteLength;if(c>r)return;const[u,d,h,p]=yield Promise.all([(0,nr.Bk)(i),(0,nr.Bk)(s),(0,nr.Bk)(a),(0,nr.Bk)(l)]),f=[{blobId:u,blobData:i},{blobId:d,blobData:s},{blobId:h,blobData:a},{blobId:p,blobData:l}],m=new Bt.sG({rulesBlobId:u,rulesByteLength:i.byteLength,skillsBlobId:d,skillsByteLength:s.byteLength,subagentsBlobId:h,subagentsByteLength:a.byteLength,mcpsBlobId:p,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});return"dual"===t?{kind:"dual",inlineContext:e,byteLength:c,parts:m}:{kind:"ref_only",stagedBlobs:f,byteLength:c,parts:m}},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}var Wr=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Hr=15728640,qr=(0,p.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Gr=(0,p.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Vr=(0,p.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});class Jr{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){var t,r;const n=new Map;for(const{blobId:t,blobData:r}of e)n.set((0,nr.nj)(t),r.byteLength);let o=this.transientBytes;for(const[e,i]of n)o-=null!==(r=null===(t=this.transientBlobs.get(e))||void 0===t?void 0:t.byteLength)&&void 0!==r?r:0,o+=i;if(o>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,nr.nj)(t),r);return this.transientBytes=o,!0}has(e){return this.transientBlobs.has((0,nr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}getBlob(e,t){return Wr(this,void 0,void 0,(function*(){const r=(0,nr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?yield this.parent.getBlob(e,t):n}))}persistForRemoteRead(e,t){return Wr(this,void 0,void 0,(function*(){const r=(0,nr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(yield(0,Br.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}))}setBlob(e,t,r){return Wr(this,void 0,void 0,(function*(){yield this.parent.setBlob(e,t,r)}))}setBlobLocallyOnly(e,t,r){return Wr(this,void 0,void 0,(function*(){yield this.parent.setBlobLocallyOnly(e,t,r)}))}flush(e){return Wr(this,void 0,void 0,(function*(){yield this.parent.flush(e)}))}}function Kr(e){const t=void 0===(null==(r=e.tokenDetails)?void 0:r.promptContextUsageTree)?r:new Ze.VNy(Object.assign(Object.assign({},r),{promptContextUsageTree:void 0}));var r;const n=t!==e.tokenDetails;let o=!1,i=e.subagentStates;for(const[t,r]of Object.entries(e.subagentStates)){const n=r.conversationState;if(void 0===n)continue;const s=Kr(n);s!==n&&(o||(i=Object.assign({},e.subagentStates),o=!0),i[t]=new Ze.aK_(Object.assign(Object.assign({},r),{conversationState:s})))}return n||o?new Ze.Y9z(Object.assign(Object.assign({},e),{tokenDetails:t,subagentStates:i})):e}const Zr=(0,h.h)("@anysphere/agent-client:stall-detector"),Yr=(0,p.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type"]}),Xr=(0,p.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type"]}),Qr=(0,p.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall"}),en=(0,p.Pu)("agent_client.stream.total",{description:"Total number of streams monitored"});class tn{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(){var e;const t=Date.now(),r={};for(const[n,o]of this.handlers)r[n]={state:o.state,durationMs:(null!==(e=o.endedAt)&&void 0!==e?e:t)-o.startedAt,error:o.error};return r}}class rn{constructor(e,t,r){var n;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.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=null!==(n=t.heartbeatOnlyThresholdMs)&&void 0!==n?n:3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker),this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),en.increment(this.ctx,1),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog("[NAL client stall detector] Stream aborted while stall detector active","aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}trackActivity(e,t){var r;const n={type:e,messageType:t};this.lastActivity=n,"inbound_message"===e?this.lastInboundMessage=n:"outbound_write"===e&&(this.lastOutboundMessage=n);const o=this.activityHistory.at(-1);(null==o?void 0:o.type)===e&&o.messageType===t?o.repeat=(null!==(r=o.repeat)&&void 0!==r?r:1)+1:(this.activityHistory.push(n),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=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){var t;const r=this.ctx.get(un),n=Object.assign({},e);(null===(t=null==r?void 0:r.modelDetails)||void 0===t?void 0:t.displayName)&&(n.model_name=r.modelDetails.displayName),this.abortedAt&&(n.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(n.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(n.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(n.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(n.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(n.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(n.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let i;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];i!==t&&(i?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),i=t),o.push(`${r}${n?` (x${n})`:""}`)}return n.activities=o.join("\n"),{reqId:null==r?void 0:r.requestId,stall:n}}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"});Zr.warn(this.ctx,"[NAL client stall detector] Advisory stall detected - no activity for advisory threshold period",r)}catch(e){console.error("Error logging advisory stall:",e)}}onStallDetected(e){if("heartbeat_only"===e){const t=Date.now(),r=t-this.lastActivityTime,n=t-this.lastMeaningfulActivityTime;if(r<this.thresholdMs&&n>=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){var r,n,o,i,s;const a=this.lastActivity,l=this.lastInboundMessage,c=this.lastOutboundMessage,u=this.ctx.get(un);try{const o=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),d="heartbeat_only"===e?"[NAL client stall detector] Stream receiving heartbeats only - no meaningful data for threshold period":"[NAL client stall detector] Bidirectional stream stall detected - no activity for threshold period";if(Zr.warn(this.ctx,d,o),Yr.increment(this.ctx,1,{activity_type:null!==(i=null==a?void 0:a.type)&&void 0!==i?i:"unknown",message_type:null!==(s=null==a?void 0:a.messageType)&&void 0!==s?s:"unknown"}),this.hasEverStalled||(this.hasEverStalled=!0,Qr.increment(this.ctx,1)),this.onStallCallback){const t=Date.now(),o={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:null==a?void 0:a.messageType,lastInboundMessageType:null==l?void 0:l.messageType,lastOutboundMessageType:null==c?void 0:c.messageType,requestId:null==u?void 0:u.requestId,modelName:null===(r=null==u?void 0:u.modelDetails)||void 0===r?void 0:r.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:null===(n=this.handlerTracker)||void 0===n?void 0:n.getHandlerStates()};try{this.onStallCallback(o)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{null===(o=this.onStall)||void 0===o||o.call(this)}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Zr.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){var e,t;const r=Date.now()-this.lastActivityTime;this.emitLifecycleLog("[NAL client stall detector] Stream activity resumed after stall","recovered"),Xr.histogram(this.ctx,r,{activity_type:null!==(t=null===(e=this.lastActivity)||void 0===e?void 0:e.type)&&void 0!==t?t:"unknown"})}[Symbol.dispose](){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("[NAL client stall detector] Stream stall detector disposed","disposed")}}var nn=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const on=(0,h.h)("@anysphere/agent-client:turn-runner");var sn=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},an=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ln=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n}),cn=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}};const un=(0,Qe.cF)(Symbol("agentStreamMetadata"),void 0),dn=(0,h.h)("@anysphere/agent-client:abort"),hn=(0,h.h)("@anysphere/agent-client:retry"),pn=(0,h.h)("@anysphere/agent-client:request-context-blob");function fn(e){return sn(this,arguments,void 0,(function*({ctx:e,action:t,resources:r,blobStore:n,options:o,source:i,transportMode:s}){var a,l,c;try{yield function(e){return Wr(this,arguments,void 0,(function*({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:i,maxInlineDynamicBytes:s=1048576,notesSessionId:a}){var l;const c=performance.now(),u=function(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}(t);if(void 0===u)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(d=t.requestContextParts)?[]:[d.rulesBlobId,d.skillsBlobId,d.subagentsBlobId,d.mcpsBlobId];if(void 0!==u.requestContext||e.length>0&&n.hasAll(e))return{kind:"already_prepared"}}var d;t.requestContextParts=void 0;const h=void 0===u.requestContext,p=null!==(l=u.requestContext)&&void 0!==l?l:yield function(e){return Wr(this,arguments,void 0,(function*({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Ut),o=yield n.execute(e,new Bt._K({notesSessionId:r})),i="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===i)throw new Error(`Failed to compute request context: ${o.result.case}`);return i}))}({ctx:e,resources:r,notesSessionId:a}),f=Math.min(Math.max(0,i),Hr),m=yield zr({requestContext:p,mode:o,maxBlobBytes:f,maxInlineDynamicBytes:Math.min(Math.max(0,s),f)});if(void 0===m)return u.requestContext=p,t.requestContextParts=void 0,qr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===m.kind&&!n.seedAll(m.stagedBlobs))return u.requestContext=p,t.requestContextParts=void 0,qr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};u.requestContext="dual"===m.kind?m.inlineContext:void 0,t.requestContextParts=m.parts;const g=m.byteLength;return qr.increment(e,1,{mode:o,outcome:h?"hydrated":"inline"}),Gr.histogram(e,g,{mode:o}),Vr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:g,hydrated:h}}))}({ctx:e,action:t,resources:r,blobStore:n,mode:null!==(a=null!=s?s:o.requestContextBlobTransportMode)&&void 0!==a?a:"legacy",maxBlobBytes:null!==(l=o.requestContextBlobMaxBytes)&&void 0!==l?l:Hr,maxInlineDynamicBytes:null!==(c=o.requestContextDynamicInlineMaxBytes)&&void 0!==c?c:1048576,notesSessionId:o.conversationId})}catch(r){t.requestContextParts=void 0,pn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:i})}}))}const mn=e=>{var t,r;const n=[];switch(n.push(e.message.case),e.message.case){case"conversationAction":n.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":n.push(e.message.value.message.case);break;case"interactionResponse":n.push(e.message.value.result.case);break;case"interactionUpdate":switch(n.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":n.push(null===(t=e.message.value.message.value.toolCall)||void 0===t?void 0:t.tool.case);break;case"toolCallDelta":n.push(null===(r=e.message.value.message.value.toolCallDelta)||void 0===r?void 0:r.delta.case)}break;case"interactionQuery":n.push(e.message.value.query.case)}return n.filter((e=>void 0!==e)).join(":")};function gn(e,t,r){return sn(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c;try{for(n=!0,o=cn(t);!(s=(i=yield o.next()).done);n=!0){c=i.value,n=!1;const t=c;switch(t.event.case){case"stdout":yield r.sendUpdate(e,rr.shellOutputDelta({case:"stdout",value:new Ct.o0({data:t.event.value.data})}));break;case"stderr":yield r.sendUpdate(e,rr.shellOutputDelta({case:"stderr",value:new Ct.Db({data:t.event.value.data})}));break;case"exit":yield r.sendUpdate(e,rr.shellOutputDelta({case:"exit",value:new Ct.vb({code:t.event.value.code,aborted:t.event.value.aborted})}))}}}catch(e){a={error:e}}finally{try{n||s||!(l=o.return)||(yield l.call(o))}finally{if(a)throw a.error}}}))}const vn=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0;function yn(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function wn(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}function bn(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}function Sn(e){return e instanceof Error?e.name:void 0}function kn(e){const t={errorName:Sn(e)};let r=e;for(let e=0;e<10&&void 0!==r;e++){if(yn(r)){const e=wn(r),n=bn(e),o=Sn(e);return Object.assign(Object.assign({},t),{underlyingConnectError:{code:r.code,codeName:lr.Code[r.code],cause:void 0!==n||void 0!==o?{code:n,name:o}:void 0}})}r=wn(r)}return t}class En{constructor(e,t){this.client=e,this.endpointUrl=t,this.hasStartedStream=!1}run(e,t,r,n,o,i,s,a,l,u,d){return sn(this,void 0,void 0,(function*(){var h,p;const f={stack:[],error:void 0,hasError:!1};try{const m=new Jr(s),g=null!==(p=d.generationUUID)&&void 0!==p?p:crypto.randomUUID(),v={value:!1},y={sources:[],abortReasonName:void 0,abortReasonMessage:void 0};let w=0,b=0;try{null===(h=d.onNetworkPhaseStart)||void 0===h||h.call(d)}catch(t){hn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const S=an(f,(0,c.VI)(e.withName("networkPhase")),!1);e=S.ctx,yield function(e){return nn(this,void 0,void 0,(function*(){var t,r,n,o,i,s,a,l,c,u,d,h,p,f,m,g,v,y;const{ctx:w,checkpointHandler:b,runOptions:S,requestId:k,hooks:E,cancellation:x}=e,C=k,_=null!==(f=e.backoff)&&void 0!==f?f:(e,t)=>function(e,t,r,n){return nn(this,void 0,void 0,(function*(){const o=r?100:1e3,i=null!=n?n:Math.min(o*Math.pow(2,e),6e4),s=void 0!==n?0:.2*i*Math.random();yield new Promise(((e,r)=>{if(null==t?void 0:t.aborted)return void r(new mr("Cancelled during backoff"));const n=setTimeout((()=>{null==t||t.removeEventListener("abort",o),e()}),i+s);function o(){clearTimeout(n),r(new mr("Cancelled during backoff"))}null==t||t.addEventListener("abort",o,{once:!0})}))}))}(e,t,S.isRunningInTest,S.fixedRetryDelayMs);let P,I,T=e.state,R=e.action,A=0,O=k,M=0,j=0,D=!1;const N=()=>{var e;D&&(null===(e=S.onConnectionStateChange)||void 0===e||e.call(S,{state:"connected"}),D=!1)},$={handleCheckpoint:(e,t,r)=>nn(this,void 0,void 0,(function*(){var n;yield b.handleCheckpoint(e,t,r),P=t,I=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible",N()})),getLatestCheckpoint:()=>b.getLatestCheckpoint()};for(;;){if(w.canceled)throw x.toCancelledError(void 0,O);if(P=void 0,I=void 0,null===(t=E.beginAttempt)||void 0===t||t.call(E,{attempt:A,originalRequestId:C}),A>0?(O=crypto.randomUUID(),yield null===(r=S.onRetryStarting)||void 0===r?void 0:r.call(S,A,{actionCase:R.action.case,conversationState:T,isResume:"resumeAction"===R.action.case,attemptRequestId:O}),e.logging&&on.info(w,`[${e.logging.tag}] Retrying attempt ${A}`,{attempt:A,actionCase:R.action.case,requestId:O,originalRequestId:C}),"resumeAction"===R.action.case&&(yield null===(n=S.onRetryResuming)||void 0===n?void 0:n.call(S,{checkpointState:T,nextAttempt:A,reason:"resume_action"}),e.logging&&on.info(w,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:A,reason:"resume_action"}))):(e.logging&&on.info(w,`[${e.logging.tag}] Initial request`,{attempt:A,actionCase:R.action.case,requestId:O}),!0===e.notifyInitialResume&&"resumeAction"===R.action.case&&(yield null===(o=S.onRetryResuming)||void 0===o?void 0:o.call(S,{checkpointState:T,nextAttempt:A,reason:"resume_action"}),e.logging&&on.info(w,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:A,reason:"resume_action"}))),w.canceled)throw x.toCancelledError(void 0,O);try{return yield E.runAttempt({state:T,action:R,checkpointHandler:$,attempt:A,attemptRequestId:O,notifyConnected:N}),N(),void(e.logging&&on.info(w,`[${e.logging.tag}] Request successful`,{attempt:A,actionCase:R.action.case,requestId:O,originalRequestId:C}))}catch(t){if(!0===(null===(i=x.shortCircuit)||void 0===i?void 0:i.call(x,t)))throw x.toCancelledError(t,O);const r=!0===(null===(s=S.endlessRetries)||void 0===s?void 0:s.call(S)),n=E.classify(t,{attempt:A,attemptRequestId:O,originalRequestId:C,serverErrorRetries:M,transportErrorRetries:j,endlessRetries:r});if(e.logging){const o="retry"===n.action?`RETRY (countAsServerError=${n.countAsServerError}, countAsTransportError=${n.countAsTransportError})`:`THROW ${n.error.kind}`;on.warn(w,`[AGENT_ERROR_DIAGNOSTICS] requestId=${O} originalRequestId=${C} decision=${o}`,Object.assign({decision:o,willRetry:"retry"===n.action,enableAgentRetries:null!==(m=S.enableAgentRetries)&&void 0!==m&&m,endlessRetries:r,isRunningInTest:null!==(g=S.isRunningInTest)&&void 0!==g&&g,serverErrorRetries:M,transportErrorRetries:j,attempt:A,requestId:O,originalRequestId:C},null===(l=(a=e.logging).diagnostics)||void 0===l?void 0:l.call(a,t)))}if("throw"===n.action){if(0===A){const t={attempt:0,actionCase:R.action.case,error:n.error,requestId:O,originalRequestId:C,enableAgentRetries:!0===S.enableAgentRetries,endlessRetries:r,stallAborted:!1,abortSources:[]};try{yield null===(c=S.onErrorNotRetried)||void 0===c?void 0:c.call(S,null!==(v=null===(u=E.buildNonRetriedErrorInfo)||void 0===u?void 0:u.call(E,t))&&void 0!==v?v:t)}catch(t){e.logging&&on.warn(w,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(t),requestId:O,originalRequestId:C})}}throw e.logging&&on.warn(w,`[${e.logging.tag}] Error not retryable`,Object.assign(Object.assign({attempt:A,actionCase:R.action.case},!0===e.logging.includeErrorObjects?{error:n.error}:{errorName:n.error.name}),{serverErrorRetries:M,transportErrorRetries:j})),n.error}const o=A+1;if("ineligible_terminal_turn"===I)return void(e.logging&&on.warn(w,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:t instanceof Error?t.name:typeof t,errorMessage:t instanceof Error?t.message:String(t)}));null===(d=S.onConnectionStateChange)||void 0===d||d.call(S,{state:"reconnecting",attempt:o,trigger:null!==(y=null===(h=E.reconnectTrigger)||void 0===h?void 0:h.call(E,t,n,{originalRequestId:C,failedAttemptRequestId:O,nextAttempt:o}))&&void 0!==y?y:{originatingRequestId:C,attemptRequestId:O}}),D=!0,n.countAsServerError&&M++,n.countAsTransportError&&j++,A=o,void 0!==P&&(T=P,R=new Ze.QFf({action:{case:"resumeAction",value:new Ze.qKo}}),null===(p=E.onResumeFromCheckpoint)||void 0===p||p.call(E)),yield _(A,w.signal)}}}))}({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:g,notifyInitialResume:!0,logging:{tag:"nal_agent_retries",includeErrorObjects:!0,diagnostics:e=>Object.assign({stallAborted:v.value,abortSources:[...y.sources],abortReasonName:y.abortReasonName},kn(e))},cancellation:{toCancelledError:()=>new mr("Request cancelled")},hooks:{beginAttempt:()=>{v.value=!1,y.sources=[],y.abortReasonName=void 0,y.abortReasonMessage=void 0,b=++w},runAttempt:t=>sn(this,[t],void 0,(function*({state:t,action:r,checkpointHandler:s,attempt:l,attemptRequestId:c,notifyConnected:h}){const p=function(e,t,r){return{sendUpdate:(n,o)=>sn(this,void 0,void 0,(function*(){var i;if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===(null===(i=o.message)||void 0===i?void 0:i.case)&&hn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})})),query:(n,o)=>sn(this,void 0,void 0,(function*(){if(t!==r())throw new mr("Stale query from previous attempt");return e.query(n,o)})),enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(o,b,(()=>w));yield this.runInternal(e,t,r,n,p,i,m,a,s,u,d,c,g,v,y,h,l)})),classify:(e,t)=>{var r,n;return function(e,t,r,n,o,i,s,a,l,c){const u=i||s,d=c?2:10,h=e instanceof dr?e:_r(e,{requestId:o});return t?u?!s&&n>=d?{action:"throw",error:new hr("Connection stalled repeatedly",{cause:h.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:new hr("Connection stalled",{cause:h.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0}})}:h instanceof mr&&!l&&function(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(yn(t)&&(t.code===lr.Code.Canceled||t.code===lr.Code.Aborted))return!0;t=wn(t)}return!1}(h)?u?!s&&n>=d?{action:"throw",error:new hr("Connection failed repeatedly",{cause:h.cause,requestId:o,displayInfo:{title:"Connection failed",detail:`The connection failed ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:h}:a&&(h instanceof pr||h instanceof fr)&&function(e){var t;const r=null===(t=e.displayInfo)||void 0===t?void 0:t.inferenceRequestErrorType;return void 0!==r&&!Cr.some((e=>e===r))}(h)?!s&&r>=3?{action:"throw",error:h}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:h instanceof mr||h instanceof pr||h instanceof fr?{action:"throw",error:h}:h instanceof hr&&Tr(h)?u?!s&&n>=d?{action:"throw",error:new hr("Connection failed repeatedly",{cause:h.cause,requestId:o,displayInfo:{title:"Connection failed",detail:`The connection failed ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:h}:u?!s&&r>=3?{action:"throw",error:h}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:{action:"throw",error:h}}(e,v.value,t.serverErrorRetries,t.transportErrorRetries,t.attemptRequestId,null!==(r=d.enableAgentRetries)&&void 0!==r&&r,t.endlessRetries,null!==(n=d.retryAllInferenceErrors)&&void 0!==n&&n,y.sources.length>0,d.isRunningInTest)},buildNonRetriedErrorInfo:e=>{var t;return Object.assign(Object.assign({},e),{enableAgentRetries:null!==(t=d.enableAgentRetries)&&void 0!==t&&t,stallAborted:v.value,abortSources:[...y.sources],abortReasonName:y.abortReasonName,abortReasonMessage:y.abortReasonMessage})},reconnectTrigger:(e,t,r)=>{var n,o,i;const s=kn(e),a=e instanceof dr?e:_r(e,{requestId:r.failedAttemptRequestId});return{errorClass:a.name,connectCode:null===(n=s.underlyingConnectError)||void 0===n?void 0:n.code,connectCodeName:null===(o=s.underlyingConnectError)||void 0===o?void 0:o.codeName,errorCode:null===(i=a.displayInfo)||void 0===i?void 0:i.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:v.value,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,endpointUrl:this.endpointUrl}},onResumeFromCheckpoint:()=>a.resetStream()}})}catch(e){f.error=e,f.hasError=!0}finally{ln(f)}}))}runInternal(e,t,r,n,o,i,s,a,l,u,h,p,g,v,y,w,b){return sn(this,arguments,void 0,(function*(e,t,r,n,o,i,s,a,l,u,h,p,g,v,y,w,b,S="agent.request.attempt"){var k,E,x,C,_,P,I;const T={stack:[],error:void 0,hasError:!1};try{const R=e,A=an(T,(0,c.VI)(e.withName(S)),!1);A.span.setAttribute("agent.attempt",b),A.span.setAttribute("agent.request_id",p),A.span.setAttribute("agent.original_request_id",g),e=A.ctx,e=(0,c.Mf)(e,"agent.request_id",p),e=(e=(0,c.Mf)(e,"agent.original_request_id",g)).with(un,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const M=new Set(y.sources);let j=void 0!==y.abortReasonName||void 0!==y.abortReasonMessage;const D=(t,r)=>{if(M.has(t))return;M.add(t),y.sources=[...M];const n=(e=>{const t="string"==typeof(null==e?void 0:e.abortReasonName)?e.abortReasonName:void 0,r="string"==typeof(null==e?void 0:e.abortReasonMessage)?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);j||void 0===n||(j=!0,y.abortReasonName=n.abortReasonName,y.abortReasonMessage=n.abortReasonMessage),dn.error(e,"Agent client stream abort",new Error(t),Object.assign({abortSource:t,requestId:p,conversationId:h.conversationId},null!=r?r:{}))};if(e.signal.aborted){const t=e.signal.reason;D("ctx_signal_abort",or(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;D("ctx_signal_abort",or(t))}),{once:!0});const[N,$]=e.withCancel();if(null===(k=a.signal)||void 0===k?void 0:k.aborted){const e=null===(x=a.signal)||void 0===x?void 0:x.reason;D("conversation_action_abort",or(e)),$()}else null===(E=a.signal)||void 0===E||E.addEventListener("abort",(()=>{var e;const t=null===(e=a.signal)||void 0===e?void 0:e.reason;D("conversation_action_abort",or(t)),$()}),{once:!0});if(e.canceled||N.canceled){const t={ctxCanceled:e.canceled,softCancel:N.canceled};throw D("pre_run_cancel",t),new mr("User aborted request")}const L=(0,c.VI)(e.withName("createControlledExecManager")),F=O.fromResources(i);L[Symbol.dispose]();const[U,B]=e.withCancel(),z=new tn,{failThresholdMs:W,advisoryThresholdMs:H}=(e=>{var t;const r=null!==(t=vn(null==e?void 0:e.failTimeoutMs))&&void 0!==t?t:3e4,n=vn(null==e?void 0:e.advisoryTimeoutMs);return{failThresholdMs:r,advisoryThresholdMs:void 0!==n&&n>0&&(r<=0||n<r)?n:void 0}})(h.stallDetectorConfig),q=an(T,new rn(U,{thresholdMs:W,advisoryThresholdMs:H,onStall:()=>{v.value=!0,D("stall_detector",{thresholdMs:W,advisoryThresholdMs:H}),B()},onStallCallback:h.onStall,handlerTracker:z}),!1);let G,V;const J=(0,cr.Jt)(),K=new m.F8(J,(e=>(q.reset("outbound_write",mn(e)),e))),Z=an(T,(0,c.VI)(e.withName("writeInitialRequest")),!1);let Y;const X=u.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0}))),Q=null!==(_=h.requestContextBlobTransportMode)&&void 0!==_?_:"legacy",ee=0===b&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Q&&ee?"dual":Q;yield fn({ctx:e,action:r,resources:i,blobStore:s,options:h,source:"run_request",transportMode:te});const re=new Ze.Mpn({conversationState:Kr(t),action:r,modelDetails:n,requestedModel:h.requestedModel,mcpTools:new sr.Or({mcpTools:X}),conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,suggestNextPrompt:h.suggestNextPrompt,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:null!==(P=h.subagentModelOverrides)&&void 0!==P?P:[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsSendToUser:h.clientSupportsSendToUser,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,runId:g});if(Y=K.write(new ir.KS({message:{case:"runRequest",value:re}})),N.canceled){const t={ctxCanceled:e.canceled,softCancel:N.canceled};throw D("post_write_cancel",t),Z[Symbol.dispose](),new mr("User aborted request")}const ne=Object.assign(Object.assign(Object.assign({"x-request-id":p,"x-original-request-id":g},function(e){return Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.parentRequestId?{"x-parent-request-id":er(e.parentRequestId)}:{}),void 0!==e.rootParentRequestId?{"x-root-parent-request-id":er(e.rootParentRequestId)}:{}),void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":er(e.parentAgentToolCallId)}:{}),!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{})}(h)),function(){var e,t;const r=null===(e=globalThis.process)||void 0===e?void 0:e.env,n=null===(t=null==r?void 0:r.INFERENCE_PROXY_JWT)||void 0===t?void 0:t.trim();return void 0===n||""===n||n.startsWith("$")?{}:{[tr]:n}}()),null!==(I=h.headers)&&void 0!==I?I:{});G=(0,c.VI)(e.withName("handshakeEstablishment")),G.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=this.client.run(G.ctx,J,{signal:U.signal,headers:ne,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===V&&(V=performance.now())}}),ie=performance.now(),se=e=>{var t,r;G&&(G.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==V&&G.span.setAttribute("handshake.preNetworkMs",V-ie),G[Symbol.dispose](),G=void 0),w();const n=performance.now();null===(t=h.onFirstMessage)||void 0===t||t.call(h,n-ie),void 0!==V&&(null===(r=h.onFirstMessageNetwork)||void 0===r||r.call(h,n-V))},ae=h.onFirstNonHeartbeatResponse?()=>{h.onFirstNonHeartbeatResponse(performance.now()-ie,b)}:void 0,le=h.onTtftBreakdown?e=>{h.onTtftBreakdown(e,b)}:void 0,{interactionStream:ce,execStream:ue,checkpointStream:de,kvStream:he,done:pe}=function(e,t,r,n,o,i,s,a){const l=(0,cr.Jt)(),c=(0,cr.Jt)(),u=(0,cr.Jt)(),d=(0,cr.Jt)();let h=!1,p=!1;return{interactionStream:l,execStream:c,checkpointStream:u,kvStream:d,done:function(){return sn(this,void 0,void 0,(function*(){var f,m,g,v;let y,w,b=!1,S=!1;try{try{for(var k,E=!0,x=cn(t);!(f=(k=yield x.next()).done);E=!0){v=k.value,E=!1;const t=v;if(void 0!==t.ttftBreakdown){const r=t.ttftBreakdown;try{null==a||a({serverFirstTokenMs:r.serverFirstTokenMs,preStreamSetupMs:r.preStreamSetupMs,waitForFirstEventMs:r.waitForFirstEventMs,providerTtftMs:r.providerTtftMs,slowPoolWaitMs:r.slowPoolWaitMs})}catch(t){hn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const o="interactionUpdate"===t.message.case&&"heartbeat"===t.message.value.message.case;if(h||(h=!0,n(o)),o)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{null==s||s()}catch(t){hn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",mn(t))}if("interactionUpdate"===t.message.case&&"turnEnded"===t.message.value.message.case&&(b=!0),"interactionUpdate"!==t.message.case&&"interactionQuery"!==t.message.case||(yield l.write(t.message).catch((()=>{}))),"execServerMessage"!==t.message.case&&"execServerControlMessage"!==t.message.case||(yield c.write(t.message.value)),"conversationCheckpointUpdate"===t.message.case){const e=b?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(S=!0),yield u.write({checkpoint:t.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===t.message.case&&(yield d.write(t.message.value))}}catch(e){m={error:e}}finally{try{E||f||!(g=x.return)||(yield g.call(x))}finally{if(m)throw m.error}}r.onStreamEnded()}catch(e){y=e}finally{if(w=y,b&&S&&void 0!==y&&!(null==o?void 0:o.aborted)&&!(null==i?void 0:i.aborted)&&function(e){const t=e instanceof dr?e:_r(e);return t instanceof hr&&Tr(t)}(y)&&(hn.warn(e,"Ignoring transport close after terminal agent stream",{caughtError:y instanceof Error?`${y.name}: ${y.message}`:String(y)}),r.onStreamEnded(),w=void 0),b||(null==o?void 0:o.aborted)||(null==i?void 0:i.aborted)){if(!b&&!(null==o?void 0:o.aborted)){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${null==o?void 0:o.aborted}, parentSignal.aborted=${null==i?void 0:i.aborted}; firstMessageFired=${h}`;hn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===y?(hn.warn(e,t),w=new hr(t,{isTransport:!0})):y instanceof Error&&"[aborted] aborted"===y.message?(hn.warn(e,`${t}; retrying caught [aborted] aborted error`),w=new hr(t,{cause:y,isTransport:!0})):hn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:y instanceof Error?`${y.name}: ${y.message}`:String(y)})}l.close(),c.close(),u.close(),d.close()}if(void 0!==w)throw w}))}()}}(e,oe,q,se,N.signal,e.signal,ae,le);let fe;const me={handleCheckpoint:(e,t,r)=>sn(this,void 0,void 0,(function*(){var n;yield l.handleCheckpoint(e,t,r),fe=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"})),getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ge=5e3;let ve;const ye=()=>{ve=setTimeout((()=>{K.write(new ir.KS({message:{case:"clientHeartbeat",value:new ir.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),ye()}),ge)},we=()=>{void 0!==ve&&(clearTimeout(ve),ve=void 0)};ye();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,s=new Ct.a({command:(null===(C=n.shellCommand)||void 0===C?void 0:C.command)||"",parsingResult:new Ct.HO,skipApproval:!0}),a=i.get(It).execute(e,s,{execId:n.execId}),l=new Ur(ce,o,new m.F8(K,(e=>new ir.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:e=>sn(this,void 0,void 0,(function*(){yield Promise.all([z.track("handleShellStream",gn(e,a,o)),z.track("interactionController",l.run(e))])}))}}else{const e=new Ur(ce,o,new m.F8(K,(e=>new ir.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:t=>sn(this,void 0,void 0,(function*(){yield z.track("interactionController",e.run(t))}))}}void 0!==Y&&(yield Promise.race([Y,pe.catch((()=>{}))]));const l=new m.F8(K,(e=>{if((0,ar.isMessage)(e,f.yT))return new ir.KS({message:{case:"execClientMessage",value:e}});if((0,ar.isMessage)(e,f.$Y))return new ir.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ar.isMessage)(e)?e.getType().typeName:typeof e})`)})),c=new Dr(ue,l,F),b=new nr.hC(he,new m.F8(K,(e=>new ir.KS({message:{case:"kvClientMessage",value:e}}))),s,{beforeGetBlob:(e,t)=>sn(this,void 0,void 0,(function*(){return s.persistForRemoteRead(e,t)}))}),S=new d(de,me,e);let k,E;const x={promise:new Promise(((e,t)=>{k=e,E=t})),resolve:k,reject:E};N.canceled?(x.resolve(),ce.close()):N.signal.addEventListener("abort",(()=>{x.resolve(),ce.close()}),{once:!0}),c.run(N).then(x.resolve).catch(x.reject);const _=Promise.allSettled([z.track("streamSplitter",pe.finally((()=>{we(),a.close(),l.close()}))),z.track("execHandler",x.promise),t.run(e),z.track("checkpointController",S.run()),z.track("kvHandler",b.run(e)),z.track("conversationActionManager",a.run(e,{write:t=>sn(this,void 0,void 0,(function*(){yield fn({ctx:e,action:t,resources:i,blobStore:s,options:h,source:"queued_action"}),yield K.write(new ir.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 mr("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new mr("User aborted request"))),{once:!0}),N.canceled?(B(),T.reject(new mr("User aborted request"))):N.signal.addEventListener("abort",(()=>{B(),T.reject(new mr("User aborted request"))}),{once:!0});const A=yield T.promise,O=A[0],M=A[1],j=A[3],D=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===j.status)throw new fr("Checkpoint persistence failed",{cause:j.reason instanceof Error?j.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:D(j),isRetryable:!1}});const $="ineligible_terminal_turn"===fe;if($){const t=Object.assign(Object.assign({},"rejected"===O.status?{streamSplitter:D(O)}:{}),"rejected"===M.status?{execHandler:D(M)}:{});Object.keys(t).length>0&&hn.warn(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===O.status&&!$)throw O.reason;if("rejected"===M.status&&!$)throw M.reason;N.canceled||(yield this.processUnprocessedMessages(R,a,me,n,o,i,s,u,h,p,g,v,y,q,w))}finally{we(),G&&(G[Symbol.dispose](),G=void 0)}}catch(e){T.error=e,T.hasError=!0}finally{ln(T)}}))}processUnprocessedMessages(e,t,r,n,o,i,s,a,l,c,u,d,h,p,f){return sn(this,void 0,void 0,(function*(){if(!t.hasUnprocessedMessages())return;const m=t.getUnprocessedUserMessages(),g=r.getLatestCheckpoint();if(!g||0===m.length)return;const v=m[0];t.markMessageAsProcessed(v),t.resetStream(),p[Symbol.dispose]();const y=r.getLatestCheckpoint();try{yield this.runInternal(e,g,new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:v})}}),n,o,i,s,t,r,a,l,c,u,d,h,f,0,"agent.request.queuedMessage")}catch(e){throw y===r.getLatestCheckpoint()&&t.requeueMessage(v),e}}))}}var xn=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Cn=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),_n=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Pn=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),In=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Tn=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Rn=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");Error;const An=e=>new Ze.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Rn.lI({result:{case:"approved",value:new Rn.XJ}})}}),On=(e,t)=>new Ze.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Rn.lI({result:{case:"rejected",value:new Rn.yc({reason:null!=t?t:""})}})}}),Mn=e=>new Ze.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Tn.fS({result:{case:"approved",value:new Tn.Hs}})}}),jn=(e,t)=>new Ze.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Tn.fS({result:{case:"rejected",value:new Tn.m$({reason:null!=t?t:""})}})}}),Dn=(e,t)=>new Ze.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new Ze.zT({result:t})}}),Nn=e=>new Ze.Y5({id:e,result:{case:"switchModeRequestResponse",value:new In.w$({result:{case:"approved",value:new In.q5}})}}),$n=(e,t)=>new Ze.Y5({id:e,result:{case:"switchModeRequestResponse",value:new In.w$({result:{case:"rejected",value:new In.rA({reason:null!=t?t:""})}})}}),Ln=(e,t)=>new Ze.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Cn.gz({result:t})}}),Fn=(e,t)=>new Ze.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Un=(e,t)=>new Ze.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),Bn=(e,t)=>new Ze.Y5({id:e,result:{case:"prManagementResult",value:t}}),zn=(e,t)=>new Ze.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Pn.h({result:{case:"rejected",value:new Pn.OI({reason:null!=t?t:"Authentication was rejected"})}})}}),Wn=(e,t)=>new Ze.Y5({id:e,result:{case:"connectScmRequestResponse",value:new xn.qG({result:{case:"rejected",value:new xn.lB({reason:null!=t?t:"Connecting GitHub was skipped"})}})}}),Hn=(e,t)=>new Ze.Y5({id:e,result:{case:"generateImageRequestResponse",value:new _n.vW({result:{case:"approved",value:new _n.l3({description:null!=t?t:""})}})}});var qn=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js");Error;var Gn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),Vn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),Jn=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Kn=(0,lr.createContextKey)(void 0,{description:"anysphere.callerContext"});function Zn(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function Yn(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const i=e=>{o||(o=!0,e?(null==t||t.recordException(e instanceof Error?e:new Error(String(e))),null==t||t.setStatus({code:Gn.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):null==t||t.setStatus({code:Gn.s.OK}),null==t||t.end(),null==r||r())};return{next(){return Jn(this,void 0,void 0,(function*(){try{const e=yield n.next();return e.done&&i(),e}catch(e){throw i(e),e}}))},return(e){return Jn(this,void 0,void 0,(function*(){return i(),n.return?n.return(e):{done:!0,value:void 0}}))},throw(e){return Jn(this,void 0,void 0,(function*(){if(i(e),n.throw)return n.throw(e);throw e}))}}}}}function Xn(...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 Qn(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const i=e[o];return"function"!=typeof i?i:(s,a,l={})=>{var u;const d=(0,c.fR)(s.withName(`rpc.${String(o)}`),{kind:Vn.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),h=(0,c.fU)(d);let p;try{let o;if(r&&(o=function(e){var t,r;const n=new Headers;try{const o=(0,c.fU)(e),i=null===(t=null==o?void 0:o.spanContext)||void 0===t?void 0:t.call(o);if((null==i?void 0:i.traceId)&&i.spanId){const e=null!==(r=i.traceFlags)&&void 0!==r?r:0,t=`00-${i.traceId}-${i.spanId}-${e.toString(16).padStart(2,"0")}`;if(n.set("traceparent",t),n.set("backend-traceparent",t),i.traceState){const e="function"==typeof i.traceState.serialize?i.traceState.serialize():String(i.traceState);n.set("tracestate",e)}}}catch(e){}return n}(d)),n){const e=n(d);e&&(o=Xn(o,e))}const s=Xn(l.headers,o),{signal:m,cleanup:g}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(d.signal,l.signal):{signal:l.signal,cleanup:void 0};p=g;const v=(null!==(u=l.contextValues)&&void 0!==u?u:(0,lr.createContextValues)()).set(Kn,d),y=Object.assign(Object.assign({},l),{headers:s,signal:m,contextValues:v}),w=i.call(e,a,y);return Zn(w)?Yn(w,h,p):null!==(f=w)&&"object"==typeof f&&"then"in f&&"function"==typeof f.then?w.then((e=>Zn(e)?Yn(e,h,p):(null==h||h.setStatus({code:Gn.s.OK}),null==h||h.end(),null==p||p(),e))).catch((e=>{throw null==h||h.recordException(e instanceof Error?e:new Error(String(e))),null==h||h.setStatus({code:Gn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e})):(null==h||h.setStatus({code:Gn.s.OK}),null==h||h.end(),null==p||p(),w)}catch(e){throw null==h||h.recordException(e instanceof Error?e:new Error(String(e))),null==h||h.setStatus({code:Gn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e}var f}}})}var eo=r("../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/index.js");const to=process.env.HTTPS_PROXY||process.env.https_proxy||void 0;let ro;try{ro=void 0!==to&&to.length>0?new eo.kT(to):void 0}catch(hk){ro=void 0}Error,r("@connectrpc/connect-node"),new Ze.Gmx({modelId:"gpt-5",displayModelId:"gpt-5",displayName:"GPT-5",displayNameShort:"GPT-5",aliases:["gpt-5"]});var no=r("node:fs/promises"),oo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),io=r("../shell-exec/dist/index.js"),so=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),ao=r("../utils/dist/path-utils.js");const lo="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",co="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",uo=/\$\(|`|<\(|>\(/,ho=/[;&|]/;let po,fo,mo,go;function vo(){if(void 0===po){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();po=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return po}function yo(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 wo(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function bo(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function So(){if(void 0===go){const e=(process.env[lo]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${lo} (expected "allow" or "deny"); using "deny".`);const r=wo("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[co]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=wo(co)),go={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:wo("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:bo("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return go}function ko(e,t,r={}){const n=[yo(e),yo(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),i=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(i,"i")}function Eo(e,t){const r=function(){const e=So();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===fo&&(fo=ko("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),fo);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(uo.test(e))return r;const i=(void 0===mo&&(mo=ko("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),mo);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||i?.test(t)||ho.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=So();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 xo=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Co(e){if(!e)return;let t;return"allow"===e.default?t=xo.h1.ALLOW:"deny"===e.default&&(t=xo.h1.DENY),new xo.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new xo.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function _o(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 xo.h1.ALLOW:t.default="allow";break;case xo.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,io.networkAllowAllPolicy)():(0,io.networkDisabledPolicy)())}function Po(e){if(!e)return{type:"insecure_none"};switch(e.type){case xo.vc.INSECURE_NONE:case xo.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case xo.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:_o(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};case xo.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:_o(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};default:return{type:"insecure_none"}}}function Io(e){if(e)return"insecure_none"===e.type?new xo.Mw({type:xo.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new xo.Mw({type:xo.vc.WORKSPACE_READWRITE,networkAccess:(0,io.isNetworkEnabledByPolicy)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Co(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):"workspace_readonly"===e.type?new xo.Mw({type:xo.vc.WORKSPACE_READONLY,networkAccess:(0,io.isNetworkEnabledByPolicy)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Co(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):new xo.Mw({type:xo.vc.INSECURE_NONE})}async function To(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Ro(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}var Ao=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Oo=(0,h.h)("local-exec:background-shell");function Mo(e,t,r){return"permissionsConfig"===r.type&&r.isReadonly?new kt.Lt({result:{case:"permissionDenied",value:new Ct.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new kt.Lt({result:{case:"rejected",value:new Ct.pZ({command:e,workingDirectory:t,reason:Ro(r)})}})}class jo{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 Do(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function No(e){e().catch((()=>{}))}const $o=65536;class Lo{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=so.L3.compile(e.config.pattern,so.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>$o){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=$o)this.observe(e.slice(t,t+$o));return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrences<this.limit&&n.find();){const e=n.group()??"";n.end()>t&&this.queueMatch(e)}this.carryover=r.slice(-1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer())}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,i=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;var s;this.args.registry.enqueue({conversationId:this.args.conversationId,id:i,source:"shell",payload:{taskId:i,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(s=t,s.length<=500?s:`${s.slice(0,500)}...`),detail:o,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"}})}}class Fo{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=a.join(this.projectDir,"terminals",`${t}.txt`);try{return new Lo({shellId:t,outputPath:i,config:o,conversationId:r??ne,toolCallId:n,registry:this.backgroundWorkRegistry})}catch(r){return void(void 0!==e&&Oo.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class Uo{async spawn(e,t){const r=new AbortController,n=new jo(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof io.SandboxUnsupportedError)throw e}return No((()=>Do(n,o))),n}async adopt(e){const t=new jo(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,No((()=>Do(t,e.eventIterator))),t}}function Bo(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function zo(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${Bo(e.cwd)}\n`,n+=`command: ${Bo(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${Bo(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}class Wo{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=a.join(this.projectDir,"terminals");await(0,no.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,s){let l,c,u,d=!1,h=!1;const p=Date.now(),f=new Date(p).toISOString();let m,g="running",v=!1,y=Promise.resolve();const w=async e=>{if(c)try{await c.write(e)}catch(e){}},b=t.shellId,S=a.join(r,`${b}.txt`),k=async()=>{if(!l)return;const e=Date.now()-p,r=zo({pid:m,cwd:t.workingDirectory,command:t.command,title:t.description,status:g,startedAt:f,runningForMs:e});try{await l.write(r,0,"utf8")}catch(e){}},E=()=>(y=y.then(k).catch((()=>{})),y),x=()=>{void 0!==u&&(clearInterval(u),u=void 0)},C=async e=>{if(h)return;h=!0,m=e;const r=Date.now()-p,n=zo({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:g,startedAt:f,runningForMs:r});await(0,no.writeFile)(S,n,"utf8"),u=setInterval((()=>{E()}),5e3)},_=async()=>{l||(l=await i.promises.open(S,"r+")),c||(c=await i.promises.open(S,"a"))},P=async(e,t)=>{if(!v){if(v=!0,x(),h||await C(),await _(),void 0!==t){const e=Date.now()-p,r=`\n---\n${t}\n`+(s.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await w(r)}g=e,await E()}};try{for await(const t of o(e,s)){if("stdout"===t.type)h||(await C(),await _()),await w(t.data);else if("stderr"===t.type)h||(await C(),await _()),await w(t.data);else if("stdin_ready"!==t.type||d)"exit"===t.type&&await P(t.aborted?"aborted":0===t.code?"succeeded":"failed",`exit_code: ${t.code??"unknown"}`);else{d=!0,h||(await C(t.pid),await _());const e=t.stdin;if(e){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)?e.toString():String(e);if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;w(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}yield t}if(!v){const e=s.signal?.aborted??!1;await P(e?"aborted":"failed")}}catch(e){const t=s.signal?.aborted??!1,r=Bo(e instanceof Error?e.message:"Unknown error");if(await P(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await y,l)try{await l.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=a.join(this.projectDir,"terminals");await(0,no.mkdir)(t,{recursive:!0});const r=a.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let s="running";const l=Date.now()-n,c=zo({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:s,startedAt:o,runningForMs:l})+(e.initialOutput??"");await(0,no.writeFile)(r,c,"utf8");const u=await i.promises.open(r,"r+");let d;try{d=await i.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=Promise.resolve();const m=async()=>{const t=Date.now()-n,r=zo({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:s,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},g=()=>(f=f.then(m).catch((()=>{})),f);let v=setInterval((()=>{g()}),5e3);const y=()=>{void 0!==v&&(clearInterval(v),v=void 0)},w=async()=>{if(!h){h=!0,y(),await f;try{await u.close()}catch{}try{await d.close()}catch{}}},b=async e=>{try{await d.write(e)}catch(e){}},S=async(t,r)=>{if(!p){if(p=!0,y(),void 0!==r){const t=Date.now()-n,o=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(o)}s=t,await g()}},k={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await S(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await b(e.data):"exit"===e.type&&(await S(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await w())}return t.done&&await w(),t}catch(t){const r=e.abortController.signal.aborted;throw await S(r?"aborted":"failed"),await w(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await S(t?"aborted":"failed")}return await w(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:k})}}class Ho{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:re(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o){if(!this.backgroundWorkRegistry)return;const i=o.aborted?"aborted":0===o.code?"success":"error",s=o.aborted||null===o.code||0===o.code?void 0:`exit_code=${o.code}`,a=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??ne,id:a,source:"shell",payload:{taskId:a,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n,...s?{detail:s}:{},...o.outputPath?{outputPath:o.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 n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}class qo{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){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 Go{constructor(e,t,r,n,o,i,s){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=i&&void 0!==s?new qo(i,s):i,l=o??function(e){const t=new Uo;return new Wo(t,e)}(n),c=new Fo(l,n,a);this.backgroundShellManager=new Ho(c,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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Po(t.sandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(),s=(0,ao.o1)(i);if(!t.parsingResult)return new kt.Lt({result:{case:"error",value:new kt.Of({command:n,workingDirectory:s,error:"Parsing result is required"})}});let a=o;if(Oo.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:t.parsingResult.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:s},o);if("block"===r.kind)return Oo.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),Mo(n,s,r.reason);Oo.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:s,timeout:0,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:qt(t)},o);if("block"===r.kind)return Oo.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),Mo(n,s,r.reason);a=r.policy,Oo.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:a.type})}if(vo()&&(a=Eo(n,t.parsingResult),"insecure_none"!==a.type)){const e=await this.ignoreService.getCursorIgnoreMapping();a={...a,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=a?{perRepo:a}:void 0,i={ctx:e,command:n,workingDirectory:s,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,description:t.description,outputNotification:t.outputNotification},l=await this.backgroundShellManager.spawn(i,this.coreExecutor);return new kt.Lt({result:{case:"success",value:new kt.Po({shellId:r,command:n,workingDirectory:s,pid:l.pid})}})}catch(r){if(r instanceof io.SandboxUnsupportedError){const o=a?.type??"unknown";return Oo.warn(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new kt.Lt({result:{case:"sandboxUnsupported",value:new Ct.rI({command:n,workingDirectory:s,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new kt.Lt({result:{case:"error",value:new kt.Of({command:n,workingDirectory:s,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Ao(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var Vo=r("node:async_hooks"),Jo=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),Ko=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js"),Zo=r("node:util"),Yo=r("zod");const Xo={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Qo=Yo.z.object({command:Yo.z.string().optional(),args:Yo.z.array(Yo.z.string()).optional(),env:Yo.z.record(Yo.z.string(),Yo.z.string()).optional(),url:Yo.z.string().optional(),headers:Yo.z.record(Yo.z.string(),Yo.z.string()).optional(),cwd:Yo.z.string().optional(),envFile:Yo.z.string().optional(),auth:Yo.z.object({CLIENT_ID:Yo.z.string(),CLIENT_SECRET:Yo.z.string().optional(),scopes:Yo.z.array(Yo.z.string()).optional()}).optional(),enabledTools:Yo.z.array(Yo.z.string()).optional()}),ei=Yo.z.object({mcpServers:Yo.z.record(Yo.z.string(),Qo).optional()}),ti=Yo.z.enum(["canvas"]),ri=Yo.z.array(ti).transform((e=>[...new Set(e)].sort()));class ni extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function oi(e){const t=e.trim();if(!t)throw new ni("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new ni("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new ni("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new ni("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),i=t.slice(n+1).trim();if(!o)throw new ni("Missing plugin name before @",e);if(!i)throw new ni("Missing source after @",e);if(!r.test(o))throw new ni("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new ni("Plugin name must be 100 characters or less",e);if(i.startsWith("github:")){const t=i.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new ni("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(i.startsWith("local:")){const t=i.slice(6).trim();if(!t)throw new ni("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(i.startsWith("url:")){const t=i.slice(4).trim();if(!t)throw new ni("Missing Git URL after 'url:'",e);try{new URL(t)}catch(t){throw new ni("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const s=i.indexOf("#");let a,l;if(-1!==s?(a=i.slice(0,s).trim(),l=i.slice(s+1).trim()):a=i,!a)throw new ni("Missing marketplace name",e);if(!r.test(a))throw new ni("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:l,raw:e}}function ii(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 si(e){return e.sourceInfo.name}function ai(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function li(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function ci(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}var ui=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const di=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),hi=/^v?(\d+\.\d+(?:\.\d+)?)$/;function pi(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 fi(e){let t;try{t=new URL(e).pathname.split("/")}catch(r){t=e.split("/")}for(const e of t){const t=hi.exec(e);if(null!==t)return t[1]}}function mi(e){var t;return void 0===e?{kind:"absent"}:di.has(e)?{kind:"supported",id:e,version:null!==(t=fi(e))&&void 0!==t?t:e}:{kind:"unsupported",id:e}}const gi=10485760,vi=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,yi=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],wi=[".cursor-plugin",".claude-plugin"],bi=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Si=Yo.z.object({source:Yo.z.literal("github"),repo:Yo.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Yo.z.string().optional(),sha:Yo.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ki=Yo.z.object({source:Yo.z.literal("url"),url:Yo.z.string().url().endsWith(".git","URL must end with .git"),ref:Yo.z.string().optional(),sha:Yo.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Ei=Yo.z.object({source:Yo.z.literal("git-subdir"),url:Yo.z.string().url().endsWith(".git","URL must end with .git"),path:Yo.z.string().min(1),ref:Yo.z.string().optional(),sha:Yo.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),xi=Yo.z.union([Yo.z.string(),Si,ki,Ei]),Ci=Yo.z.object({name:Yo.z.string().min(1,"Author name is required"),email:Yo.z.string().email().optional()}),_i=Yo.z.enum(["string","number","integer","boolean","object","array","null"]),Pi=Yo.z.union([_i,Yo.z.array(_i).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Yo.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function Ii(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Yo.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:Yo.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:Yo.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:Yo.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:Yo.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:Yo.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:Yo.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const Ti=Yo.z.lazy((()=>Yo.z.object({type:Pi.optional(),title:Yo.z.string().optional(),description:Yo.z.string().optional(),format:Yo.z.string().optional(),writeOnly:Yo.z.boolean().optional(),default:Yo.z.unknown().optional(),enum:Yo.z.array(Yo.z.any()).nonempty().optional(),const:Yo.z.unknown().optional(),properties:Yo.z.record(Yo.z.string(),Ti).optional(),required:Yo.z.array(Yo.z.string()).optional(),additionalProperties:Yo.z.union([Yo.z.boolean(),Ti]).optional(),items:Yo.z.union([Ti,Yo.z.array(Ti)]).optional(),minLength:Yo.z.number().int().nonnegative().optional(),maxLength:Yo.z.number().int().nonnegative().optional(),minimum:Yo.z.number().optional(),maximum:Yo.z.number().optional(),exclusiveMinimum:Yo.z.number().optional(),exclusiveMaximum:Yo.z.number().optional(),multipleOf:Yo.z.number().positive().optional(),minItems:Yo.z.number().int().nonnegative().optional(),maxItems:Yo.z.number().int().nonnegative().optional(),uniqueItems:Yo.z.boolean().optional(),minProperties:Yo.z.number().int().nonnegative().optional(),maxProperties:Yo.z.number().int().nonnegative().optional()}).strict().superRefine(Ii)));function Ri(e){const t=Ti.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:Yo.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 Ai=Yo.z.unknown().superRefine(((e,t)=>{const r=Ri(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),Oi=(Yo.z.object({name:Yo.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>vi.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Yo.z.string().optional(),source:xi,description:Yo.z.string().optional(),version:Yo.z.string().optional(),author:Ci.optional(),publisher:Yo.z.string().min(1).optional(),homepage:Yo.z.string().url().optional(),repository:Yo.z.string().url().optional(),license:Yo.z.string().optional(),keywords:Yo.z.array(Yo.z.string()).optional(),capabilities:ri.optional(),logo:Yo.z.string().optional(),category:Yo.z.string().optional(),tags:Yo.z.array(Yo.z.string()).optional(),strict:Yo.z.boolean().default(!0),commands:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),agents:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),skills:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),rules:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),hooks:Yo.z.union([Yo.z.string(),Yo.z.record(Yo.z.unknown())]).optional(),variables:Ai.optional(),mcpServers:Yo.z.union([Yo.z.string(),Yo.z.record(Yo.z.unknown()),Yo.z.array(Yo.z.union([Yo.z.string(),Yo.z.record(Yo.z.unknown())]))]).optional()}),Yo.z.object({description:Yo.z.string().optional(),version:Yo.z.string().optional(),pluginRoot:Yo.z.string().optional()}),Yo.z.object({name:Yo.z.string().min(1).regex(vi,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Yo.z.string().optional(),description:Yo.z.string().optional(),version:Yo.z.string().optional(),author:Ci.optional(),publisher:Yo.z.string().min(1).optional(),homepage:Yo.z.string().url().optional(),repository:Yo.z.string().url().optional(),license:Yo.z.string().optional(),logo:Yo.z.string().optional(),keywords:Yo.z.array(Yo.z.string()).optional(),capabilities:ri.optional(),commands:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),agents:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),skills:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),rules:Yo.z.union([Yo.z.string(),Yo.z.array(Yo.z.string())]).optional(),hooks:Yo.z.union([Yo.z.string(),Yo.z.record(Yo.z.unknown())]).optional(),variables:Ai.optional(),mcpServers:Yo.z.union([Yo.z.string(),Yo.z.record(Yo.z.unknown()),Yo.z.array(Yo.z.union([Yo.z.string(),Yo.z.record(Yo.z.unknown())]))]).optional()}));function Mi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ji(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Di(e,t){if(Mi(e)&&"string"==typeof e.name){const t=ji(e.name);if(t.length>0)return t}return function(e){var t;const r=void 0!==e.repoName?ji(e.repoName):"";return r.length>0?r:`cursor-marketplace-${null!==(t=e.fallbackId)&&void 0!==t?t:(0,o.randomUUID)()}`}(t)}function Ni(e){if(Mi(e)&&Mi(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return Object.assign({name:t},void 0!==r?{email:r}:{})}return{name:"Unknown"}}function $i(e){return"string"==typeof e?e:void 0}function Li(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Fi(e){return"string"==typeof e?e:Li(e)}function Ui(e){if(!Mi(e)||!Mi(e.metadata))return;const t={description:$i(e.metadata.description),version:$i(e.metadata.version),pluginRoot:$i(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Bi(e){if(!Mi(e))return;const t=$i(e.name);if(void 0===t||0===t.length)return;const r=$i(e.email);return Object.assign({name:t},void 0!==r?{email:r}:{})}function zi(e){if("string"==typeof e||Mi(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Mi(e)));return t.length>0?t:void 0}}function Wi(e){if("string"==typeof e||Mi(e))return e}function Hi(e){if(void 0===e)return;const t=Ri(e);return t.success?t.data:void 0}function qi(e,t={}){if(e.length>gi)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(!Mi(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!Mi(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:Mi(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:$i(n.ref),sha:$i(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:$i(n.ref),sha:$i(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:$i(n.ref),sha:$i(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:$i(n.ref),sha:$i(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=$i(e.name);return{skippedEntry:Object.assign(Object.assign({index:t},void 0!==r&&r.length>0?{name:r}:{}),{error:`Plugin entry at index ${t} has no usable source`})}}const o=("string"==typeof e.name?ji(e.name):"")||function(e){var t;if("string"==typeof e){const t=ji((0,a.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const r=ji(null!==(t=e.repo.split("/").at(-1))&&void 0!==t?t:"");return r.length>0?r:void 0}if("git-subdir"===e.source){const t=ji((0,a.basename)(e.path));return t.length>0?t:void 0}let r=e.url;try{r=new URL(e.url).pathname}catch(e){}for(;r.endsWith("/");)r=r.slice(0,-1);r.toLowerCase().endsWith(".git")&&(r=r.slice(0,-4));const n=ji((0,a.basename)(r));return n.length>0?n:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=ri.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const s=i.success?i.data:void 0;return{entry:Object.assign({name:o,displayName:$i(e.displayName),source:r,description:$i(e.description),version:$i(e.version),author:Bi(e.author),publisher:$i(e.publisher),homepage:$i(e.homepage),repository:$i(e.repository),license:$i(e.license),keywords:Li(e.keywords),logo:$i(e.logo),category:$i(e.category),tags:Li(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Fi(e.commands),agents:Fi(e.agents),skills:Fi(e.skills),rules:Fi(e.rules),hooks:Wi(e.hooks),variables:Hi(e.variables),mcpServers:zi(e.mcpServers)},void 0!==s&&{capabilities:s})}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:Di(r,t),owner:Ni(r),description:$i(r.description),plugins:n,metadata:Ui(r),skippedPluginEntries:o}}}function Gi(e){if(e.length>gi)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=mi(pi(t));if("unsupported"===r.kind)return{success:!1,error:`Unsupported plugin manifest $schema version: ${r.id}`,unsupportedSchema:!0};const n=Oi.safeParse(t);return n.success?{success:!0,data:n.data}:{success:!1,error:`Invalid plugin manifest: ${n.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Vi(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 Ji(e){return!e.includes("..")&&!(0,a.isAbsolute)(e)&&!e.includes("://")}new ui.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Ki=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Zi=/\$\{([^:}]+)(?::-([^}]*))?\}/g;function Yi(e,t){const r="function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>{var n;return null!==(n=e[r])&&void 0!==n?n:t.get(r.toLowerCase())}}(t);return Xi(e,r)}function Xi(e,t){if("string"==typeof e)return e.replace(Zi,((e,r,n)=>{const o=t(r);return void 0!==o?o:void 0!==n?n:e}));if(Array.isArray(e))return e.map((e=>Xi(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Xi(o,t);return r}return e}function Qi(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}var es=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const ts=[".mcp.json","mcp.json"],rs=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function ns(e,t){if(!function(e){return rs.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 os(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function is(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return ts.map((e=>void 0!==t?`${t}/${e}`:e))}function ss(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e=Object.assign({},o);if("string"==typeof o.command&&(e.command=Qi(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Qi(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Qi(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Qi(o.cwd,t)),n[r]=e}return function(e,t){const r=null==t?void 0:t.cloudAgentEnvLookup,n=null==t?void 0:t.configuredVariables;return Yi(e,void 0!==r?r:e=>{const t=process.env[e];if(void 0!==t)return t;const r=null==n?void 0:n[e];return null!=r?"string"==typeof r?r:String(r):void 0})}(Object.assign(Object.assign({},e),{mcpServers:n}),r)}function as(e,t,r){try{const n=(0,Ki.qg)(e),o=pi(n);if(void 0!==o){if("unsupported"===mi(o).kind)return null;if(function(e,t){if(void 0===e||void 0===t)return!1;const r=fi(e),n=fi(t);return void 0!==r&&void 0!==n&&r!==n}(null==r?void 0:r.pluginSchemaId,o))return null}const i=ei.safeParse(n),s=!0===(null==r?void 0:r.skipExpansion);if(i.success&&i.data.mcpServers&&Object.keys(i.data.mcpServers).length>0)return s?i.data:ss(i.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!ns(e,t)&&os(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=ei.safeParse({mcpServers:a});if(e.success)return s?e.data:ss(e.data,t,r)}return null}catch(e){return null}}function ls(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}function cs(e,t,r){return es(this,arguments,void 0,(function*(e,t,r,n={}){var o,i,s,a;const l=null!==(o=n.toSourcePath)&&void 0!==o?o:e=>e,c=null!==(i=n.installPathForExpansion)&&void 0!==i?i:"",u=null!==(s=n.fallbackFileNames)&&void 0!==s?s:ts,d=null!==(a=n.manifestPrecedence)&&void 0!==a?a:"override",h={},p={};for(const t of u){const r=yield e(t);if(null===r)continue;const o=as(r,c,n.parserOptions);if(null==o?void 0:o.mcpServers)for(const[e,r]of Object.entries(o.mcpServers))void 0===h[e]&&(h[e]=r,p[e]=l(t))}if(void 0!==t){const o=yield function(e,t){return es(this,arguments,void 0,(function*(e,t,r={}){var n,o;const i=null!==(n=r.toSourcePath)&&void 0!==n?n:e=>e,s=null!==(o=r.installPathForExpansion)&&void 0!==o?o:"",a={mcpServers:{},mcpServerSourcePaths:{}},l=e=>es(this,void 0,void 0,(function*(){const n=e.replace(/^\.\//,"");if(!Ji(n))return;const o=yield t(n);if(null===o)return;const l=as(o,s,r.parserOptions);(null==l?void 0:l.mcpServers)&&Object.keys(l.mcpServers).length>0&&ls(a,l.mcpServers,i(n))})),c=e=>{var t;const n=as(JSON.stringify(e),s,r.parserOptions);(null==n?void 0:n.mcpServers)&&Object.keys(n.mcpServers).length>0&&ls(a,n.mcpServers,null!==(t=r.manifestSourcePath)&&void 0!==t?t:"manifest")};if("string"==typeof e)yield l(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?yield l(t):"object"==typeof t&&null!==t&&c(t);else"object"==typeof e&&null!==e&&c(e);return a}))}(t,e,{toSourcePath:l,manifestSourcePath:r,installPathForExpansion:c,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(o.mcpServers))"fill"===d&&void 0!==h[e]||(h[e]=t,p[e]=o.mcpServerSourcePaths[e])}return 0===Object.keys(h).length?null:Object.assign({mcpServers:h},Object.keys(p).length>0&&{mcpServerSourcePaths:p})}))}function us(e,t,r,n,o,i){var s,a;const l=[],c=e.mcpServers;if(!c)return l;for(const[e,u]of Object.entries(c)){const c=u,d=`plugin-${n}-${e}`,h=e;c.url?l.push({identifier:d,name:h,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:i,type:"streamableHttp",url:c.url,headers:c.headers,auth:c.auth,enabledTools:c.enabledTools,projectManaged:!1,pluginManaged:!0}):c.command&&l.push({identifier:d,name:h,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:i,type:"stdio",command:c.command,args:null!==(s=c.args)&&void 0!==s?s:[],env:null!==(a=c.env)&&void 0!==a?a:{},cwd:c.cwd,envFile:c.envFile,enabledTools:c.enabledTools,projectManaged:!1,pluginManaged:!0})}return l}var ds=r("node:stream"),hs=r("node:stream/promises"),ps=r("node:zlib");function fs(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 ms(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var gs=r("../../node_modules/.pnpm/tar@7.5.7/node_modules/tar/dist/esm/index.js"),vs=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const ys=".cache-complete";function ws(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function bs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function Ss(e){return ms(e)}function ks(e,t){return function(e,t,r,n){const o=[e,t,r];return void 0!==n&&o.push(n),(0,a.join)(...o)}(e,ws(t.marketplaceSlug),bs(t.pluginId),void 0!==t.version?Ss(t.version):void 0)}class Es{constructor(e,t){var r,n;const o=null!==(r=null!=e?e:process.env.HOME)&&void 0!==r?r:"";this.cacheRoot=null!==(n=null==t?void 0:t.cacheRoot)&&void 0!==n?n:(0,a.join)(o,".cursor","plugins/cache")}getCacheDir(e){return ks(this.cacheRoot,e)}isCached(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{const e=(0,a.join)(t,ys);return(yield(0,no.stat)(e)).isFile()}catch(e){return!1}}))}extractToCache(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,no.mkdir)(t,{recursive:!0});const r=ds.Readable.from(e.tarball);return yield(0,hs.pipeline)(r,(0,ps.createGunzip)(),(0,gs.o6)({cwd:t,strip:1})),yield this.markCacheComplete(e),t}))}listCachedVersions(e){return vs(this,void 0,void 0,(function*(){const t=ws(e.marketplaceSlug),r=bs(e.pluginId),n=(0,a.join)(this.cacheRoot,t,r);try{return(yield(0,no.readdir)(n,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(e){return[]}}))}removeVersion(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{yield(0,no.rm)(t,{recursive:!0,force:!0})}catch(e){}}))}removeAllVersions(e){return vs(this,void 0,void 0,(function*(){const t=ks(this.cacheRoot,e);yield(0,no.rm)(t,{recursive:!0,force:!0})}))}pruneOldVersions(e){return vs(this,void 0,void 0,(function*(){const t=yield this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>Ss(e))));for(const n of t)r.has(n)||(yield this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n}))}))}markCacheComplete(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,no.writeFile)((0,a.join)(t,ys),"")}))}}function xs(e,t){var r;const n=null!==(r=e.releaseTag)&&void 0!==r?r:t;if(e.releaseRepo&&e.releaseAsset&&n)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:n}}var Cs=r("node:child_process");const _s="safe.bareRepository",Ps="explicit";var Is=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r};const Ts=(0,Zo.promisify)(Cs.execFile);function Rs(e){const t=new Set(["-c","-C","--git-dir","--work-tree"]);for(let r=0;r<e.length;r++){const n=e[r];if(t.has(n))r++;else if(!n.startsWith("-"))return n}}function As(e,t){return function(e){const t=Object.assign(Object.assign(Object.assign(Object.assign({},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){const t=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),r=Object.assign({},e);let n=!1;for(let e=0;e<t;e++)r[`GIT_CONFIG_KEY_${e}`]===_s&&(r[`GIT_CONFIG_VALUE_${e}`]=Ps,n=!0);return n||(r.GIT_CONFIG_COUNT=String(t+1),r[`GIT_CONFIG_KEY_${t}`]=_s,r[`GIT_CONFIG_VALUE_${t}`]=Ps),r}(t)}({command:Rs(e),optionsEnv:t})}function Os(e,t,r){return n=this,o=void 0,s=function*(){const n=null!=r?r:{},{env:o,encoding:i="utf8"}=n,s=Is(n,["env","encoding"]),a=yield Ts(e,t,Object.assign(Object.assign({},s),{encoding:i,env:As(t,o)}));return{stdout:String(a.stdout),stderr:String(a.stderr)}},new((i=void 0)||(i=Promise))((function(e,t){function r(e){try{l(s.next(e))}catch(e){t(e)}}function a(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i((function(e){e(n)}))).then(r,a)}l((s=s.apply(n,o||[])).next())}));var n,o,i,s}function Ms(e,t,r){const n=null!=r?r:{},{env:o}=n,i=Is(n,["env"]);return(0,Cs.spawn)(e,t,Object.assign(Object.assign({},i),{env:As(t,o)}))}function js(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Ds(e){return"function"==typeof e?e():e}function Ns(e,t){return r=this,n=void 0,i=function*(){const r=function(e){var t;const r=Object.assign(Object.assign({},process.env),{GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"});if(r.GIT_CONFIG_NOSYSTEM=void 0,!0===(null==e?void 0:e.sshBatchMode)){const e=(null===(t=process.env.GIT_SSH_COMMAND)||void 0===t?void 0:t.trim())||"ssh";r.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==(null==e?void 0:e.extraGitConfig)){const t=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));r.GIT_CONFIG_COUNT=String(t.length);for(const[e,[n,o]]of t.entries())r[`GIT_CONFIG_KEY_${e}`]=n,r[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:null==e?void 0:e.cwd,env:r}}({cwd:null==t?void 0:t.cwd,sshBatchMode:null==t?void 0:t.sshBatchMode,extraGitConfig:null==t?void 0:t.extraGitConfig});return Os("git",[...js(),...e],Object.assign(Object.assign({},r),void 0!==(null==t?void 0:t.timeoutMs)&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}))},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{l(i.next(e))}catch(e){t(e)}}function a(e){try{l(i.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,a)}l((i=i.apply(r,n||[])).next())}));var r,n,o,i}var $s=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Ls=/^[0-9a-f]{7,40}$/i,Fs=/^[0-9a-f]{40}$/i;function Us(e){var t,r;if(void 0===e||""===e)return;const n=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!==n.length?null!==(r=null===(t=n.find((e=>e.refName.endsWith("^{}"))))||void 0===t?void 0:t.sha)&&void 0!==r?r:n[0].sha:void 0}function Bs(e,t,r){return $s(this,void 0,void 0,(function*(){const n=t.trim();if(Fs.test(n))return{fullSha:n.toLowerCase()};if(Ls.test(n)){try{const t=yield function(e,t,r){return $s(this,void 0,void 0,(function*(){var n;const{stdout:o}=yield Ns(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig,timeoutMs:null==r?void 0:r.timeoutMs});return null===(n=Us(o))||void 0===n?void 0:n.toLowerCase()}))}(e,n,r);if(t)return{fullSha:t}}catch(e){}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=yield Ns(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig,timeoutMs:null==r?void 0:r.timeoutMs}),n=Us(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(yield Ns(["ls-remote",e,n],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig,timeoutMs:null==r?void 0:r.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const i=Us(o);if(!i)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:i.toLowerCase()}}))}var zs=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Ws=bi.map((e=>e.split("/")[0]));let Hs;function qs(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 Gs(e){const t=[];for(const r of e){const e=qs(r);if(null===e)return"all";t.push(e)}return t}function Vs(e,t){return zs(this,void 0,void 0,(function*(){const r="all"===e?"all":Gs(e),n=t&&"all"!==r&&(yield function(){return process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(null!=Hs||(Hs=(()=>zs(this,void 0,void 0,(function*(){try{const{stdout:e}=yield Ns(["--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>=26)}catch(e){return!1}})))()),Hs)}());return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Ws,...o])]):[]};var o}))}function Js(e){return e.toLowerCase().includes("filtering not recognized by server")}function Ks(e,t,r){return zs(this,void 0,void 0,(function*(){yield Ns(["sparse-checkout","set","--cone","--",...t],Object.assign(Object.assign({},r),{cwd:e}))}))}function Zs(e){return zs(this,void 0,void 0,(function*(){try{yield(0,no.access)((0,a.join)(e,".git","info","sparse-checkout"))}catch(e){return!1}try{const{stdout:t}=yield Ns(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch(e){return!1}}))}function Ys(e,t,r){return zs(this,void 0,void 0,(function*(){if("all"!==t&&0===t.length)return;if(!(yield Zs(e)))return;const n=Object.assign(Object.assign({},r),{cwd:e,sshBatchMode:!0});if("all"===t)return void(yield Ns(["sparse-checkout","disable"],n));const o=Gs(t);"all"!==o?yield Ns(["sparse-checkout","add","--",...o],n):yield Ns(["sparse-checkout","disable"],n)}))}const Xs=/\.git$/i,Qs=new Set(["account","dashboard"]);function ea(e){return e.replace(Xs,"")}function ta(e){let t;try{t=decodeURIComponent(e)}catch(e){return}return t.length>0&&!t.includes("/")?t:void 0}function ra(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function na(e){return e.toLowerCase().split(".").includes("gitlab")}function oa(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function ia(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}function sa(e){return void 0!==function(e){var t;const r=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(e){return}}}(e):void 0;if(void 0===r||!ia(r.hostname))return;const n=function(e){const t=e.replace(/\/+$/,"").replace(/\.git$/i,"");return t&&"/"!==t?t.startsWith("/")?t:`/${t}`:""}(r.pathname).split("/").filter(Boolean);if(3!==n.length||"git"!==(null===(t=n[0])||void 0===t?void 0:t.toLowerCase()))return;const o=n[1],i=n[2];return o&&i?{owner:o,name:i}:void 0}(e)}function aa(e){const t=e.toLowerCase();return na(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function la(e){return ra(e)?"github":na(e)?"gitlab":oa(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function ca(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch(e){return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);ia(r)&&"git"===n[0]&&(n=n.slice(1)),n.length>=3&&"scm"===n[0].toLowerCase()&&(n=n.slice(1));const o=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=ea(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===o?null:{provider:la(r),owner:o.owner,repo:o.repo,host:r}}function ua(e){const t=da(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean);return r.length>=3&&"scm"===r[0].toLowerCase()}function da(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch(e){return null}}function ha(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=ca(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(na(r.host)){const e=da(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=ea(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,"");return{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:r.repositorySegments[0],repo:r.repositorySegments[r.repositorySegments.length-1],host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=da(e.trim());if(null!==t&&oa(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=ta(t),o=ta(r);if(void 0===n||void 0===o||Qs.has(n.toLowerCase()))return;const i=ea(o);return i?{workspace:encodeURIComponent(n),repo:encodeURIComponent(i),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=da(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=ea(n);if(!o)return;const i=2===t?e[1]:o;return i?{organization:r,project:i,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!ia(e.host)&&null===aa(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=fa(r.host.replace(/^www\./i,""));return{url:`https://${e}/${ua(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=aa(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function pa(e){const t=ha(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(e){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 fa(e){return ra(e)?"github.com":e}new Map;function ma(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,s.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function ga(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function va(e,t){const r=(0,a.resolve)(e),n=(0,a.resolve)(e,t),o=(0,a.relative)(r,n);if(o.startsWith("..")||(0,a.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}var ya=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const wa=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 ba(e){const t=ms(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":wa.has(t.toLowerCase())?`_${t}`:t}const Sa=18e5,ka=6e5,Ea=["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"],xa=["enotempty: directory not empty, rename","/_staging/"],Ca=["upload-pack: not our ref","server does not allow request for unadvertised object"];function _a(e){const t=String(e).toLowerCase().replaceAll("\\","/");return Ea.some((e=>t.includes(e)))?"user_git_access":xa.every((e=>t.includes(e)))?"local_cache_race":Ca.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function Pa(e){return"object"==typeof e&&null!==e&&(!0===e.killed||Pa(e.cause))}function Ia(e){return Pa(e)?"killed_by_budget":_a(e)}function Ta(e){const t=ha(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch(t){throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=ca(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:fa(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const Ra=new Map;class Aa{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){var e,t;return null!==(t=null===(e=this.options)||void 0===e?void 0:e.sparsePluginClones)&&void 0!==t&&t}remoteTimeoutMs(){return this.sparsePluginClones?Sa:void 0}localTimeoutMs(){return this.sparsePluginClones?ka:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}cloneResolvedRef(e,t,r,n){return ya(this,void 0,void 0,(function*(){var o,i,s;const a={cwd:e,sshBatchMode:null==n?void 0:n.sshBatchMode,extraGitConfig:Object.assign(Object.assign({},Ds(null===(o=this.options)||void 0===o?void 0:o.extraGitConfig)),{"safe.directory":e})},{sparse:l,sparseDirs:c}=yield Vs(null!==(s=null==n?void 0:n.materialize)&&void 0!==s?s:"all",this.sparsePluginClones);yield Ns(["init"],Object.assign(Object.assign({},a),{timeoutMs:this.localTimeoutMs()})),l&&(yield Ks(e,c,{sshBatchMode:null==n?void 0:n.sshBatchMode,extraGitConfig:Ds(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.localTimeoutMs()}));const{stderr:u}=yield Ns(["fetch","--depth","1",...l?["--filter=blob:none"]:[],t,r],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()}));return yield Ns(["checkout","FETCH_HEAD"],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()})),{strategy:l?"sparse":"full",filterIgnoredByServer:l&&Js(null!=u?u:"")}}))}createStagingDir(){return ya(this,void 0,void 0,(function*(){const e=(0,a.join)(this.cacheRoot,"_staging",(0,o.randomUUID)());return yield(0,no.mkdir)(e,{recursive:!0}),e}))}moveToCanonicalDir(e,t){return ya(this,void 0,void 0,(function*(){return yield(0,no.mkdir)((0,a.dirname)(t),{recursive:!0}),yield(0,no.rm)(t,{recursive:!0,force:!0}),yield(0,no.rename)(e,t),t}))}cleanStaleStagingDirs(){return ya(this,void 0,void 0,(function*(){const e=(0,a.join)(this.cacheRoot,"_staging");try{const t=yield(0,no.readdir)(e,{withFileTypes:!0}),r=Date.now();yield Promise.all(t.filter((e=>e.isDirectory())).map((t=>ya(this,void 0,void 0,(function*(){try{const n=(0,a.join)(e,t.name),o=yield(0,no.stat)(n);r-o.mtimeMs>Aa.STALE_STAGING_THRESHOLD_MS&&(yield(0,no.rm)(n,{recursive:!0,force:!0}))}catch(e){}})))))}catch(e){}}))}getLegacyCloneDir(e,t){return(0,a.join)(this.cacheRoot,ba(e),ba(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=Ta(e);return(0,a.join)(this.cacheRoot,ba(r),...n.map(ba),ba(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=Ta(e);return(0,a.join)(this.cacheRoot,ba(t),...r.map(ba))}pruneSiblingCloneDirs(e,t,r){return ya(this,void 0,void 0,(function*(){const n=this.getCanonicalRepoRootDir(e),o=ba(t);try{const e=yield(0,no.readdir)(n,{withFileTypes:!0});yield Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,no.rm)((0,a.join)(n,e.name),{recursive:!0,force:!0}))))}catch(e){}if(void 0!==r)try{yield(0,no.rm)(r,{recursive:!0,force:!0})}catch(e){}}))}ensureCloned(e,t,r){return ya(this,arguments,void 0,(function*(e,t,r,n=Xo,o){const i=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>{var i;return this.ensureClonedImpl(e,t,r,n,null!==(i=null==o?void 0:o.materialize)&&void 0!==i?i:"all")}));return this.sparsePluginClones?i:(0,Br.wj)(i,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}))}ensureMaterialized(e,t){return ya(this,arguments,void 0,(function*(e,t,r=Xo){const n=this.serializedOnRepo((0,a.dirname)(e),(()=>ya(this,void 0,void 0,(function*(){var n;const o=performance.now();try{yield Ys(e,t,{extraGitConfig:Ds(null===(n=this.options)||void 0===n?void 0:n.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o)}catch(n){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(n),errorCategory:Ia(n)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:Ia(n)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o,{outcome:"error"}),n}}))));return this.sparsePluginClones?n:(0,Br.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}))}serializedOnRepo(e,t){return ya(this,void 0,void 0,(function*(){const r=`${this.cacheRoot}:${e}`,n=Ra.get(r),o=(null!=n?n:Promise.resolve()).catch((()=>{})).then(t);Ra.set(r,o);try{return yield o}finally{Ra.get(r)===o&&Ra.delete(r)}}))}ensureClonedImpl(e,t,r,n,o){return ya(this,void 0,void 0,(function*(){var i,s,a,l;n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const c=r.trim();let u,d=t.startsWith("git@")||t.startsWith("ssh://")?null:pa(t);if(null!==d)try{u=(yield Bs(d,c,{sshBatchMode:!0,extraGitConfig:Ds(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&Pa(e))throw e;n.log("error","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:_a(e)}),d=null,u=(yield Bs(t,c,{extraGitConfig:Ds(null===(s=this.options)||void 0===s?void 0:s.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else u=(yield Bs(t,c,{extraGitConfig:Ds(null===(a=this.options)||void 0===a?void 0:a.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const h=this.getCanonicalCloneDir(t,u),p=this.getLegacyCloneDir(e,c);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${h}`,{marketplaceId:e,resolvedRef:u,originalRef:c});const f=performance.now(),m=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-f,t)};if(yield this.isCloneComplete(h)){yield this.pruneSiblingCloneDirs(t,u,p);const e=yield Zs(h);return e&&(yield Ys(h,o,{extraGitConfig:Ds(null===(l=this.options)||void 0===l?void 0:l.extraGitConfig),timeoutMs:this.remoteTimeoutMs()})),m("cache_hit",{strategy:e?"sparse":"full"}),h}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(h,t,d,u,p,r,n,m,o)}))}cloneViaStaging(e,t,r,n,o,i,s,a,l){return ya(this,void 0,void 0,(function*(){var c;yield this.cleanStaleStagingDirs();const u=yield this.createStagingDir();s.log("info",`MarketplaceCacheManager: Cloning ${t}@${i} into staging directory: ${u}`,{gitUrl:t,ref:i,cloneDir:e});const d=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,no.utimes)(u,e,e).catch((()=>{}))}),Aa.STAGING_HEARTBEAT_INTERVAL_MS):void 0;null===(c=null==d?void 0:d.unref)||void 0===c||c.call(d);try{let c;if(null!==r)try{c=yield this.cloneResolvedRef(u,r,n,{sshBatchMode:!0,materialize:l})}catch(e){if(this.sparsePluginClones&&Pa(e))throw e;s.log("error","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:i,error:String(e),errorCategory:Ia(e)}),yield(0,no.rm)(u,{recursive:!0,force:!0}),yield(0,no.mkdir)(u,{recursive:!0}),c=yield this.cloneResolvedRef(u,t,n,{materialize:l})}else c=yield this.cloneResolvedRef(u,t,n,{materialize:l});c.filterIgnoredByServer&&(s.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:i}),s.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=yield this.moveToCanonicalDir(u,e);return yield this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:c.strategy}),d}catch(e){const r=Ia(e);throw a("error",{error_category:r}),s.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:i,error:String(e),errorCategory:r}),s.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==d&&clearInterval(d);try{yield(0,no.rm)(u,{recursive:!0,force:!0})}catch(e){}}}))}isCloneComplete(e){return ya(this,void 0,void 0,(function*(){try{if(!(yield(0,no.stat)(e)).isDirectory())return!1;const t=yield(0,no.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(yield(0,no.stat)((0,a.join)(e,".git","info","sparse-checkout"))).isFile()}catch(e){return!1}}catch(e){return!1}}))}getPluginDir(e,t){return va(e,t)}copyPluginToDir(e,t){return ya(this,void 0,void 0,(function*(){yield(0,no.mkdir)(t,{recursive:!0}),yield(0,no.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}))}readManifest(e){return ya(this,arguments,void 0,(function*(e,t={}){var r;const n=function(e,t){var r,n;return JSON.stringify({clonePath:e,repoName:null!==(r=t.repoName)&&void 0!==r?r:null,fallbackId:null!==(n=t.fallbackId)&&void 0!==n?n:null})}(e,t);if(this.manifestCache.has(n))return null!==(r=this.manifestCache.get(n))&&void 0!==r?r:null;const o=yield function(e){return ya(this,arguments,void 0,(function*(e,t={}){for(const r of bi){const n=(0,a.join)(e,r);let o;try{o=yield(0,no.readFile)(n,"utf-8")}catch(e){continue}const i=qi(o,t);if(i.success)return i.data}return null}))}(e,t);return this.manifestCache.set(n,o),o}))}resolvePluginPath(e,t){return ya(this,void 0,void 0,(function*(){var r;const n=yield this.readManifest(e);if(!n)return null;const o=n.plugins.find((e=>e.name===t.toLowerCase()));if(!o)return null;const i=Vi(o.source,null===(r=n.metadata)||void 0===r?void 0:r.pluginRoot);return i&&Ji(i)?i:null}))}discoverPlugins(e){return ya(this,void 0,void 0,(function*(){const t=yield this.readManifest(e);return t?function(e){var t;const r=[],n=function(e,t){var r,n,o;const i=[];for(const s of e){const e=s.source;if("string"!=typeof e)switch(e.source){case"github":i.push({entry:s,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(r=e.sha)&&void 0!==r?r:e.ref});break;case"url":i.push({entry:s,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(n=e.sha)&&void 0!==n?n:e.ref});break;case"git-subdir":i.push({entry:s,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(o=e.sha)&&void 0!==o?o:e.ref,subdirPath:e.path})}else{const r=Vi(e,t);null!==r?i.push({entry:s,kind:"local",localPath:r}):i.push({entry:s,kind:"unresolvable",rawSource:e})}}return i}(e.plugins,null===(t=e.metadata)||void 0===t?void 0:t.pluginRoot);for(const e of n){const{name:t,displayName:n,description:o,version:i}=e.entry,s={name:t,displayName:n,description:o,version:i};switch(e.kind){case"local":Ji(e.localPath)&&r.push(Object.assign(Object.assign({},s),{sourceType:"local",gitPath:e.localPath}));break;case"external-github":r.push(Object.assign(Object.assign({},s),{sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha}));break;case"external-url":r.push(Object.assign(Object.assign({},s),{sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha}));break;case"external-git-subdir":r.push(Object.assign(Object.assign({},s),{sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath}))}}return r}(t):[]}))}}Aa.STALE_STAGING_THRESHOLD_MS=3e5,Aa.STAGING_HEARTBEAT_INTERVAL_MS=6e4;var Oa=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Ma=(0,Zo.debuglog)("cursor-plugins");function ja(e){var t;const r=null===(t=e.name)||void 0===t?void 0:t.trim();return void 0!==r&&r.length>0?r:e.pluginId}function Da(e,t){return void 0!==(null==e?void 0:e.marketplace)?e.marketplace:void 0!==(null==e?void 0:e.marketplaceId)?(null!=t?t:[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function Na(e,t){var r;const n=null===(r=null==t?void 0:t.distributionGitUrl)||void 0===r?void 0:r.trim();return n?(null==t?void 0:t.gitUrl)&&!Va(e,t.gitUrl)?e:n:e}function $a(e){var t;return(null===(t=null==e?void 0:e.distributionGitUrl)||void 0===t?void 0:t.trim())||(null==e?void 0:e.gitUrl)}function La(e,t){var r,n;if(e.pinnedGitRef)return e.pinnedGitRef;if(null===(r=e.plugin)||void 0===r?void 0:r.gitRef)return e.plugin.gitRef;const o=Da(e.plugin,t),i=null===(n=e.plugin)||void 0===n?void 0:n.gitUrl,s=null==o?void 0:o.gitUrl;return i&&s&&i!==s||!(null==o?void 0:o.gitRef)?"main":o.gitRef}const Fa="backend-git://";function Ua(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Fa}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Ba(e){if(!e.startsWith(Fa))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,i=n.lastIndexOf("@");return i<0?null:{gitUrl:decodeURIComponent(n.slice(0,i)),ref:decodeURIComponent(n.slice(i+1)),gitPath:o?decodeURIComponent(o):void 0}}const za="backend-release://";function Wa(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${za}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Ha(e){if(!e.startsWith(za))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),i=o.lastIndexOf("@");return{repo:n,asset:i>=0?decodeURIComponent(o.slice(0,i)):decodeURIComponent(o),tag:i>=0?decodeURIComponent(o.slice(i+1)):void 0}}const qa=/^[0-9a-f]{7,40}$/i;function Ga(e){let t;try{t=Ta(e)}catch(e){return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Va(e,t){if(e.trim()===t.trim())return!0;const r=Ga(e),n=Ga(t);return null!==r&&r===n}const Ja=104857600;function Ka(e,t,r,n,i,l){return Oa(this,void 0,void 0,(function*(){const c=yield function(e){return Oa(this,void 0,void 0,(function*(){const{repo:t,asset:r,tag:n}=e,{apiBase:i,ownerRepo:s,host:a}=function(e){const t=e.split("/");if(3===t.length)return{apiBase:`https://${t[0]}/api/v3`,ownerRepo:`${t[1]}/${t[2]}`,host:t[0]};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),l="github.com"===a&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${i}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${i}/repos/${s}/releases/latest`,u=yield fetch(c,{headers:Object.assign({Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller"},l)});if(!u.ok)throw new Error(`Failed to fetch release from ${c}: ${u.status} ${u.statusText}`);const d=yield u.json(),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>Ja)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||!Za(p.hostname,a))throw new Error(`Refusing to download release asset from untrusted host: ${p.hostname}`);const f=yield fetch(h.browser_download_url,{headers:Object.assign({"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream"},l)});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||!Za(e.hostname,a))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const m=Buffer.from(yield f.arrayBuffer());if(m.byteLength>Ja)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${m.byteLength})`);if(e.expectedSha256){const t=(0,o.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:i,githubToken:l}),u=c.byteLength;yield(0,no.mkdir)(n,{recursive:!0});const d=yield(0,no.mkdtemp)((0,a.join)((0,s.tmpdir)(),"release-asset-")),h=(0,a.join)(d,"asset.tar.gz"),p=(0,a.join)(d,"extracted");try{yield(0,no.writeFile)(h,c),yield(0,no.mkdir)(p,{recursive:!0});let e=0,t=0;yield gs.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=yield(0,no.readdir)(p,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let s=p;if(1===o.length&&0===i.length){const e=(0,a.join)(p,o[0].name);(yield(0,no.readdir)(e)).some((e=>wi.includes(e)))&&(s=e)}const l=yield(0,no.readdir)(s);yield Promise.all(l.map((e=>(0,no.cp)((0,a.join)(s,e),(0,a.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{yield(0,no.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}))}function Za(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Ya{constructor(e,t,r,n,o){var i,s,a,l,c,u,d;this.getEffectiveUserPlugins=e;const h="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,p=null!==(i=h.marketplaceCacheOptions)&&void 0!==i?i:n;this.pluginLogger=null!==(a=null!==(s=h.pluginLogger)&&void 0!==s?s:r)&&void 0!==a?a:Xo,this.extraGitConfig=h.extraGitConfig,this.githubToken=h.githubToken,this.sparsePluginClones=null!==(l=h.sparsePluginClones)&&void 0!==l&&l,this.marketplaceCache=h.marketplaceCacheRoot?new Aa(h.marketplaceCacheRoot,Object.assign(Object.assign({},p),{extraGitConfig:null!==(c=null==p?void 0:p.extraGitConfig)&&void 0!==c?c:h.extraGitConfig,sparsePluginClones:this.sparsePluginClones})):void 0;const f=null!==(u=h.listOptions)&&void 0!==u?u:o;this.allowedMarketplaceNames=(null==f?void 0:f.allowedMarketplaceNames)?new Set(f.allowedMarketplaceNames):void 0,this.enableInlinePlugins=null!==(d=null==f?void 0:f.enableInlinePlugins)&&void 0!==d&&d}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==(null==e?void 0:e.name)&&this.allowedMarketplaceNames.has(e.name)}listEnabledPlugins(e,t){return Oa(this,void 0,void 0,(function*(){var e,t,r,n,i,s,a,l,c,u,d,h,p,f,m;const g=yield this.getEffectiveUserPlugins(),v=null!==(t=g.plugins)&&void 0!==t?t:[],y=null!==(r=g.marketplaces)&&void 0!==r?r:[],w=[],b=[],S=new Map,k=(e,t)=>Oa(this,void 0,void 0,(function*(){const r=`${e}\0${t}`;let n=S.get(r);if(!n){const o=Ds(this.extraGitConfig),i=this.sparsePluginClones?3e4:void 0,s=e.startsWith("git@")||e.startsWith("ssh://")?null:pa(e),a=(e,r)=>Oa(this,void 0,void 0,(function*(){const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==i&&(n.timeoutMs=i),(Object.keys(n).length>0?yield Bs(e,t,n):yield Bs(e,t)).fullSha}));if(null!==s)try{n=yield a(s,!0)}catch(t){if(this.sparsePluginClones&&Pa(t))throw t;n=yield a(e,!1)}else n=yield a(e,!1);S.set(r,n)}return n})),E=e=>Oa(this,void 0,void 0,(function*(){const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){const e=`${t}\0${n}`,i=!S.has(e);let s;i&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{s={sha:yield k(t,n),gitUrl:t}}catch(e){i&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==s){if(i)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch(e){}return s}}return{sha:yield k(r,n),gitUrl:r}}));for(const t of v){if(!t.isEnabled||!(null===(e=t.plugin)||void 0===e?void 0:e.name))continue;const r=t.plugin,g=Da(r,y);if(!this.isMarketplaceAllowed(g)){this.pluginLogger.log("info",`Skipping plugin ${r.name} because marketplace ${null!==(n=null==g?void 0:g.name)&&void 0!==n?n:"<none>"} is not allowed`,{pluginId:r.name,marketplaceName:null==g?void 0:g.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const v=ja({name:r.name,pluginId:void 0!==r.id?String(r.id):null!==(i=r.name)&&void 0!==i?i:""}),S=v;if(!r.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${v} without gitUrl (enableInlinePlugins=false)`,{pluginId:S});continue}const e=t.inlineContentJson;if(!e){this.pluginLogger.log("info",`Skipping DB-inline plugin ${v}: no inline content provided`,{pluginId:S});continue}const n=(0,o.createHash)("sha256").update(`${null!==(s=r.id)&&void 0!==s?s:"0"}:${null!==(a=r.updatedAt)&&void 0!==a?a:"0"}`).digest("hex").slice(0,40),i=(null==g?void 0:g.name)?{id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-inline`,name:g.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${S}`,{pluginId:S,marketplaceId:null!==(l=null==i?void 0:i.id)&&void 0!==l?l:"unknown",version:n}),w.push({pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:v,version:n,downloadUrl:`inline://${null!==(c=r.id)&&void 0!==c?c:S}`,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:i,inlineContentJson:e});continue}const k=r.gitUrl,x=Na(k,g),C=La(t,y),_=xs(r,C),P=null!==(u=null==g?void 0:g.gitRef)&&void 0!==u?u:C;let I,T,R=x;try{if(void 0!==_)I=`release/${_.releaseTag}`;else{const e=yield E({preferredGitUrl:x,sourceGitUrl:k,gitRef:C,pluginId:S});I=e.sha,R=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${v}@${C}, skipping plugin`,{pluginId:S,ref:C,error:String(e)});const t=e instanceof Error?e.message:String(e);b.push({pluginName:v,pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,marketplaceName:null==g?void 0:g.name,errorMessage:t,errorType:/timed?\s*out/i.test(t)?"timeout":"clone"});continue}T=void 0!==_?Wa({repo:_.releaseRepo,asset:_.releaseAsset,tag:_.releaseTag}):Ua(R,C,null!==(d=r.gitPath)&&void 0!==d?d:void 0);const A=$a(g);let O=A,M=P;if((null==g?void 0:g.gitUrl)&&A){const e=Va(k,g.gitUrl),t=e?R:A,r=e?k:g.gitUrl,n=e?C:P;try{const e=yield E({preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:S});M=e.sha,O=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 ${v} from ${t}@${n}, falling back to raw ref`,{pluginId:S,cacheRepoUrl:t,cacheRef:n,error:String(e)}),O=r}}const j=(null==g?void 0:g.name)?Object.assign({id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-${encodeURIComponent(null!==(h=g.gitUrl)&&void 0!==h?h:"project")}`,name:g.name},O&&{gitUrl:O,gitRef:M}):void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${S} from ${M} at ${r.gitPath}`,{pluginId:S,marketplaceId:null!==(p=null==j?void 0:j.id)&&void 0!==p?p:"unknown",gitPath:null!==(f=r.gitPath)&&void 0!==f?f:void 0,gitRef:M}),w.push({pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:v,version:I,downloadUrl:T,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:j,gitPath:null!==(m=r.gitPath)&&void 0!==m?m:void 0,isOriginBacked:void 0===_&&R!==k||void 0})}return{plugins:w,listFailures:b}}))}isDirectInstallSameFetch(e){const t=e.marketplace;if(!(null==t?void 0:t.gitUrl)||!t.gitRef)return!1;const r=Ba(e.downloadUrl);return!(!r||!Va(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}installPlugin(e,t){return Oa(this,void 0,void 0,(function*(){if(e.inlineContentJson)yield function(e){return t=this,r=void 0,o=function*(){var t,r;const{targetDir:n,inlineContentJson:o,pluginName:i}=e,s=JSON.parse(o);yield(0,no.mkdir)(n,{recursive:!0});const l={};if(s.rules&&s.rules.length>0){const e=(0,a.join)(n,"rules");yield(0,no.mkdir)(e,{recursive:!0});const t=[];for(const r of s.rules){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${ms(r.name)}.md`,o=[];o.push(`description: ${ga(r.name)}`),r.globs&&r.globs.length>0&&o.push(`globs: ${ga(r.globs.join(", "))}`),o.push(`alwaysApply: ${!0===r.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;yield(0,no.writeFile)((0,a.join)(e,n),i+r.content,"utf-8"),t.push(`rules/${n}`)}t.length>0&&(l.rules=t)}if(s.commands&&s.commands.length>0){const e=(0,a.join)(n,"commands");yield(0,no.mkdir)(e,{recursive:!0});const t=[];for(const r of s.commands){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${ms(r.name)}.md`,o=r.description?`---\ndescription: ${ga(r.description)}\n---\n\n`:"";yield(0,no.writeFile)((0,a.join)(e,n),o+r.content,"utf-8"),t.push(`commands/${n}`)}t.length>0&&(l.commands=t)}if(s.hooks&&s.hooks.length>0){const e=(0,a.join)(n,"hooks");yield(0,no.mkdir)(e,{recursive:!0});const o={};for(const e of s.hooks){const n=e.hookStep;n&&!1!==e.isActive&&ma(e)&&(o[n]||(o[n]=[]),"prompt"===e.hookType?o[n].push(Object.assign({type:"prompt",prompt:null!==(t=e.promptContent)&&void 0!==t?t:""},e.promptModel?{model:e.promptModel}:{})):o[n].push({type:"command",command:null!==(r=e.scriptContent)&&void 0!==r?r:""}))}yield(0,no.writeFile)((0,a.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:o},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&&(yield(0,no.writeFile)((0,a.join)(n,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8"))}const c=Object.assign({name:i},l),u=(0,a.join)(n,".cursor-plugin");yield(0,no.mkdir)(u,{recursive:!0}),yield(0,no.writeFile)((0,a.join)(u,"plugin.json"),JSON.stringify(c,null,2),"utf-8")},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{if(null===Ha(e.downloadUrl))try{if(yield 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)&&Pa(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)})}yield function(e,t){return Oa(this,arguments,void 0,(function*(e,t,r=Xo,n,o){var i;const l=null!==(i=null==o?void 0:o.sparsePluginClones)&&void 0!==i&&i,c=l?Sa:void 0,u=Ha(e.downloadUrl);if(u){if(e.gitPath){const r=yield(0,no.mkdtemp)((0,a.join)((0,s.tmpdir)(),"release-plugin-"));try{yield Ka(u.repo,u.asset,u.tag,r,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);const n=va(r,e.gitPath);yield(0,no.mkdir)(t,{recursive:!0}),yield(0,no.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,no.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else yield Ka(u.repo,u.asset,u.tag,t,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);return}const d=Ba(e.downloadUrl);if(!d)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const h=yield(0,no.mkdtemp)((0,a.join)((0,s.tmpdir)(),"backend-plugin-"));try{let o;if(yield function(e,t,r){return Oa(this,arguments,void 0,(function*(e,t,r,n=Xo,o,i="all",s=!1){const a=performance.now(),l=qa.test(t),c="HEAD"===t.toUpperCase(),u=Object.assign(Object.assign({},o),{"safe.directory":r}),d=s?Sa:void 0,h=s?ka:void 0,{sparse:p,sparseDirs:f}=yield Vs(i,s),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,v=e=>Oa(this,void 0,void 0,(function*(){p&&(yield Ks(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0}))})),y=(e,n)=>Oa(this,void 0,void 0,(function*(){let o="";return c?(({stderr:o}=yield Ns(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield v(d)):l?(yield Ns(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield Ns(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield v(h),({stderr:o}=yield Ns(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield Ns(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=yield Ns(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield v(d)),o})),w=e.startsWith("git@")||e.startsWith("ssh://")?null:pa(e);let b="";if(null!==w)try{b=yield y(w,!0)}catch(t){if(s&&Pa(t))throw t;yield(0,no.rm)(r,{recursive:!0,force:!0}),yield(0,no.mkdir)(r,{recursive:!0}),b=yield y(e,g)}else b=yield y(e,g);p&&Js(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);Ma("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}))}(d.gitUrl,d.ref,h,r,n,d.gitPath?Gs([d.gitPath]):[],l),d.gitPath)o=va(h,d.gitPath);else{const t=yield function(e,t){return Oa(this,void 0,void 0,(function*(){var r;for(const n of bi){const o=(0,a.join)(e,n);let i;try{i=yield(0,no.readFile)(o,"utf-8")}catch(e){continue}const s=qi(i);if(!s.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${n}: ${s.error}`};const l=s.data,c=l.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${n}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const u=Vi(c.source,null===(r=l.metadata)||void 0===r?void 0:r.pluginRoot);return u&&Ji(u)?{type:"resolved",gitPath:u}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}))}(h,e.name);if("resolved"===t.type)yield Ys(h,Gs([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=va(h,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);yield Ys(h,"all",{extraGitConfig:n,timeoutMs:c}),o=h}}yield(0,no.mkdir)(t,{recursive:!0}),yield(0,no.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,no.rm)(h,{recursive:!0,force:!0}).catch((()=>{}))}}))}(e,t,this.pluginLogger,Ds(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(e){}}tryInstallFromMarketplaceCache(e,t){return Oa(this,void 0,void 0,(function*(){var r,n,o,i;const s=this.marketplaceCache,a=e.marketplace;if(!s||!a||!a.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:null===(r=e.marketplace)||void 0===r?void 0:r.id}),!1;const l=yield s.ensureCloned(a.id,a.gitUrl,null!==(o=a.gitRef)&&void 0!==o?o:"main",this.pluginLogger,{materialize:e.gitPath?Gs([e.gitPath]):[]}),c=null!==(i=e.gitPath)&&void 0!==i?i:yield s.resolvePluginPath(l,e.name);if(!c)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:null===(n=e.marketplace)||void 0===n?void 0:n.id}),!1;void 0===e.gitPath&&(yield s.ensureMaterialized(l,Gs([c]),this.pluginLogger));const u=s.getPluginDir(l,c);return yield s.copyPluginToDir(u,t),!0}))}discoverMarketplacePlugins(e,t,r){return Oa(this,void 0,void 0,(function*(){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=yield n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}))}}function Xa(e,t,r,n,o){return new Ya(e,t,r,n,o)}var Qa=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const el=()=>({});function tl(e,t){return Qa(e,Object.assign(Object.assign({},t),{engines:Object.assign(Object.assign({},null==t?void 0:t.engines),{js:el,javascript:el})}))}function rl(e,t,r){return Qa.stringify({content:e,data:{}},t,r)}function nl(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}var ol=r("../../node_modules/.pnpm/js-yaml@4.1.0/node_modules/js-yaml/dist/js-yaml.mjs"),il=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const sl=[".md",".mdc",".markdown"],al=[...sl,".txt"],ll=/^---\s*\n([\s\S]*?)\n---/,cl="";function ul(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function dl(e){var t,r;const n=e.match(ll);if(!n)return{};try{const e=ol.Ay.load(n[1],{schema:ol.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const o=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,i=hl(null!==(t=e.environments)&&void 0!==t?t:null==o?void 0:o.environments);return{disabledEnvironments:hl(null!==(r=e["disabled-environments"])&&void 0!==r?r:null==o?void 0:o.disabledEnvironments),environments:i,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch(e){const t=n[1],r=t.match(/^name:\s*(.+)$/m),o=t.match(/^description:\s*(.+)$/m);return r||o?{name:r?r[1].trim():void 0,description:o?o[1].trim():void 0}:{}}}function hl(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 pl(e){return ul((0,a.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function fl(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class ml{constructor(e){this.fetcher=e}discoverComponents(){return il(this,arguments,void 0,(function*(e={}){var t,r;const n=null!==(t=e.basePath)&&void 0!==t?t:"",o=n?`${n}/`:"",i=null!==(r=e.metadataOnly)&&void 0!==r&&r,s=e.manifest;let a;try{a=yield this.fetcher.listDirectory(n)}catch(e){a=[]}const l=new Set(a.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),c=ts.filter((e=>a.some((t=>"file"===t.type&&t.name===e)))),u=a.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[d,h,p,f,m,g,v]=yield Promise.all([u&&void 0===(null==s?void 0:s.skills)?this.discoverRootSkill(o,i):Promise.resolve(null),void 0!==(null==s?void 0:s.skills)?this.discoverFromManifestPaths(o,s.skills,!0,sl,i):l.has("skills")?this.discoverSkills(`${o}skills`,i):Promise.resolve([]),void 0!==(null==s?void 0:s.agents)?this.discoverFromManifestPaths(o,s.agents,!1,sl,i):l.has("agents")?this.discoverMarkdownComponents(`${o}agents`,sl,i):Promise.resolve([]),void 0!==(null==s?void 0:s.hooks)?this.discoverHooksFromManifest(o,s.hooks,i):l.has("hooks")?this.discoverHooksFromJson(`${o}hooks/hooks.json`,i):Promise.resolve([]),void 0!==(null==s?void 0:s.commands)?this.discoverFromManifestPaths(o,s.commands,!1,al,i):l.has("commands")?this.discoverMarkdownComponents(`${o}commands`,al,i):Promise.resolve([]),void 0!==(null==s?void 0:s.rules)?this.discoverFromManifestPaths(o,s.rules,!1,sl,i):l.has("rules")?this.discoverMarkdownComponents(`${o}rules`,sl,i):Promise.resolve([]),this.discoverMcpServers(o,null==s?void 0:s.mcpServers,c)]);return{skills:fl(d?[d,...h]:h),agents:fl(p),hooks:f,commands:fl(m),rules:fl(g),mcpServers:v}}))}discoverHooksFromJson(e){return il(this,arguments,void 0,(function*(e,t=!1){try{if(!(yield this.fetcher.fileExists(e)))return[];const{content:r}=yield this.fetcher.fetchFile(e),n=JSON.parse(r);return!n.hooks||"object"!=typeof n.hooks||Array.isArray(n.hooks)?[]:Object.keys(n.hooks).map((r=>({name:ul(r),path:e,description:t?cl:`Hook: ${r}`})))}catch(e){return[]}}))}discoverHooksFromManifest(e,t){return il(this,arguments,void 0,(function*(e,t,r=!1){var n;if("string"==typeof t){if(!Ji(t))return[];const n=`${e}${t.replace(/^\.\//,"")}`;return n.endsWith(".json")?this.discoverHooksFromJson(n,r):this.discoverHooksFromJson(`${n}/hooks.json`,r)}const o=null!==(n=t.hooks)&&void 0!==n?n:t;return!o||"object"!=typeof o||Array.isArray(o)?[]:Object.keys(o).map((e=>({name:ul(e),path:"manifest",description:r?cl:`Hook: ${e}`})))}))}discoverFromManifestPaths(e,t){return il(this,arguments,void 0,(function*(e,t,r=!1,n=sl,o=!1){var i,s;if("string"==typeof t){if(!Ji(t))return[];const i=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(i,o):this.discoverMarkdownComponents(i,n,o)}const a=[];for(const n of t)try{if(!Ji(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!(yield this.fetcher.fileExists(e))){const e=t.replace(/\/$/,""),r=yield this.discoverSkills(e,o);a.push(...r);continue}let r=pl(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t),n=o?cl:void 0;if(!o){const{content:t}=yield this.fetcher.fetchFile(e),o=dl(t);if(r=null!==(i=o.name)&&void 0!==i?i:r,n=o.description,r){const t={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:ul(r),path:e};void 0!==n&&(t.description=n),a.push(t)}continue}if(r){const t={name:ul(r),path:e};void 0!==n&&(t.description=n),a.push(t)}}else{if(!(yield this.fetcher.fileExists(t)))continue;let e=pl(t),r=o?cl:void 0;if(!o){const{content:n}=yield this.fetcher.fetchFile(t),o=dl(n);e=null!==(s=o.name)&&void 0!==s?s:e,r=o.description}if(e){const n={name:ul(e),path:t};void 0!==r&&(n.description=r),a.push(n)}}}catch(e){}return a}))}discoverMarkdownComponents(e){return il(this,arguments,void 0,(function*(e,t=sl,r=!1,n=new Set){let o;try{o=yield this.fetcher.listDirectory(e,n)}catch(e){return[]}const i=o.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=o.filter((e=>"dir"===e.type)),[a,l]=yield Promise.all([Promise.all(i.map((e=>il(this,void 0,void 0,(function*(){try{let t=pl(e.name),n=r?cl:void 0;if(!r){const{content:r}=yield this.fetcher.fetchFile(e.path),o=dl(r);t=o.name?ul(o.name):t,n=o.description}if(!t)return null;const o={name:t,path:e.path};return void 0!==n&&(o.description=n),o}catch(e){return null}}))))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r,n))))]);return[...a.filter((e=>null!==e)),...l.flat()]}))}discoverRootSkill(e){return il(this,arguments,void 0,(function*(e,t=!1){try{const r=`${e}SKILL.md`,n=(0,a.basename)(e.replace(/[\\/]+$/,""));let o=ul(t?n||pl(r):n),i=t?cl:void 0;if(!t){const{content:e}=yield this.fetcher.fetchFile(r),t=dl(e);if(o=t.name?ul(t.name):o,i=t.description,!o)return null;const n={disabledEnvironments:t.disabledEnvironments,environments:t.environments,name:o,path:r};return void 0!==i&&(n.description=i),n}return o?Object.assign({name:o,path:r},void 0!==i?{description:i}:{}):null}catch(e){return null}}))}discoverSkills(e){return il(this,arguments,void 0,(function*(e,t=!1){let r;try{r=yield this.fetcher.listDirectory(e)}catch(e){return[]}const n=r.filter((e=>"dir"===e.type));return(yield Promise.all(n.map((e=>il(this,void 0,void 0,(function*(){try{const r=`${e.path}/SKILL.md`;if(!(yield this.fetcher.fileExists(r)))return null;if(t){const t=ul(e.name);return t?{name:t,path:r,description:cl}:null}const{content:n}=yield this.fetcher.fetchFile(r),o=dl(n),i=o.name?ul(o.name):ul(e.name);if(!i)return null;const s={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:i,path:r};return void 0!==o.description&&(s.description=o.description),s}catch(e){return null}})))))).filter((e=>null!==e))}))}discoverMcpServers(e,t,r){return il(this,void 0,void 0,(function*(){const n=yield cs((t=>il(this,void 0,void 0,(function*(){try{const{content:r}=yield this.fetcher.fetchFile(`${e}${t}`);return r}catch(e){return null}}))),t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:"fill",toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}});return void 0===(null==n?void 0:n.mcpServers)?[]:Object.keys(n.mcpServers).map((e=>{var t,r;return{name:ul(e),path:null!==(r=null===(t=n.mcpServerSourcePaths)||void 0===t?void 0:t[e])&&void 0!==r?r:"manifest"}}))}))}}var gl=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function vl(e){var t;const r=null!==(t=null!=e?e:process.env.HOME)&&void 0!==t?t:"";return(0,a.join)(r,".claude")}var yl=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function wl(e){return yl(this,void 0,void 0,(function*(){try{return(yield(0,no.lstat)(e)).isSymbolicLink()}catch(e){return!1}}))}function bl(e){return yl(this,void 0,void 0,(function*(){if(yield wl(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,no.readFile)(e,"utf-8")}))}function Sl(e){return yl(this,void 0,void 0,(function*(){if((yield(0,no.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}))}function kl(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}function El(e){return yl(this,void 0,void 0,(function*(){var t;for(const r of yi){const n=(0,a.join)(e,r);let o;try{if(yield wl(n))continue;if(!(yield(0,no.stat)(n)).isFile())continue;yield Sl(n),o=yield bl(n)}catch(e){continue}const i=Gi(o);if(!i.success){if(i.unsupportedSchema)throw new Error(i.error);continue}const s=i.data,l=s.commands,c=s.agents,u=s.skills,d=s.rules,h=s.hooks,p=s.mcpServers,f=void 0!==l||void 0!==c||void 0!==u||void 0!==d||void 0!==h||void 0!==p,m="string"==typeof s.displayName?s.displayName:void 0,g="string"==typeof s.description?s.description:void 0,v=null===(t=s.author)||void 0===t?void 0:t.name,y=s.variables,w=s.capabilities,b=void 0!==m||void 0!==g||void 0!==v||void 0!==y||void 0!==w;if(f||b)return Object.assign(Object.assign({manifestFilePath:n},f&&{manifestOptions:{commands:l,agents:c,skills:u,rules:d,hooks:h,mcpServers:p}}),b&&{metadata:{displayName:m,description:g,authorName:v,variables:y,capabilities:w}})}}))}function xl(e,t){return yl(this,void 0,void 0,(function*(){const r=function(e,t){var r;const n=new Map,o=(0,a.resolve)(e),i=(0,a.resolve)(null!==(r=null==t?void 0:t.symlinkTargetRoot)&&void 0!==r?r:o),s=(0,no.realpath)(i).catch((()=>i));function l(e){const t=(0,a.resolve)(e);try{return va(o,t)}catch(t){throw new Error(`Path escapes plugin directory: ${e}`)}}function c(e){return yl(this,void 0,void 0,(function*(){const t=l(e),r=yield s,n=yield(0,no.realpath)(t);try{return va(r,n)}catch(t){throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}))}return{listDirectory(t,r){return yl(this,void 0,void 0,(function*(){const n=l(t?(0,a.join)(e,t):e);try{const e=yield c(n);if(null==r?void 0:r.has(e))return[];null==r||r.add(e);const o=yield(0,no.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,a.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=yield c(r);o=(yield(0,no.stat)(e)).isDirectory()?"dir":"file"}catch(e){continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch(e){return[]}}))},fetchFile(t){return yl(this,void 0,void 0,(function*(){const r=n.get(t);if(void 0!==r)return{content:r};const o=l((0,a.join)(e,t)),i=yield c(o);yield Sl(i);const s=yield(0,no.readFile)(i,"utf-8");return n.set(t,s),{content:s}}))},fileExists(t){return yl(this,void 0,void 0,(function*(){try{const r=l((0,a.join)(e,t)),n=yield c(r);return(yield(0,no.stat)(n)).isFile()}catch(e){return!1}}))}}}(e),n=new ml(r),o=yield n.discoverComponents({manifest:t}),[i,s,l,c]=yield Promise.all([Cl(r,o.skills,e),Pl(r,o.agents,e),Il(r,o.commands,e),_l(r,o.rules,e)]);return{skills:i,agents:s,commands:l,rules:c}}))}function Cl(e,t,r){return yl(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=Rl({content:Qi(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function _l(e,t,r){return yl(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=Rl({content:Qi(t,r),relativePath:o.path});i&&n.push(Object.assign(Object.assign({},i),{name:o.name}))}catch(e){}return n}))}function Pl(e,t,r){return yl(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=Al({content:Qi(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function Il(e,t,r){return yl(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=Ol({content:Qi(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function Tl(e){if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Rl({content:e,relativePath:t}){var r,n,o,i,s;try{const a=tl(e),l=t.replace(/\\/g,"/"),c=l.split("/").filter((e=>e.length>0)),u=c.length>=2?c[c.length-2]:void 0,d=null!==(o=c[c.length-1])&&void 0!==o?o:l,h=null!=u?u:d.replace(/\.md$/i,""),p="string"==typeof a.data.name?a.data.name.trim():void 0,f=hl(null!==(i=a.data.environments)&&void 0!==i?i:null===(r=a.data.metadata)||void 0===r?void 0:r.environments),m=hl(null!==(s=a.data["disabled-environments"])&&void 0!==s?s:null===(n=a.data.metadata)||void 0===n?void 0:n.disabledEnvironments);return{path:t,name:p&&p.length>0?p:h,description:"string"==typeof a.data.description?a.data.description:void 0,globs:Tl(a.data.globs),alwaysApply:!0===a.data.alwaysApply,content:e,environments:f,disabledEnvironments:m}}catch(e){return null}}function Al({content:e,relativePath:t}){var r,n;try{const o=tl(e),i=o.content.trim();if(!i)return null;let s;"string"==typeof o.data.tools?s=o.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(o.data.tools)&&(s=o.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const l=null!==(r=o.data.permissionMode)&&void 0!==r?r:o.data.permissionmode,c=(0,a.basename)(t);return{path:t,name:"string"==typeof o.data.name?o.data.name:(0,a.basename)(c,(0,a.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof o.data.description?o.data.description:void 0,tools:s,model:"string"==typeof o.data.model?o.data.model:"inherit",prompt:i,permissionMode:(n=l,"readonly"===(null!=n?n:"").trim().toLowerCase()?"readonly":"default")}}catch(e){return null}}function Ol({content:e,relativePath:t}){try{const r=tl(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,a.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,a.basename)(i,(0,a.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch(e){return null}}function Ml(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}function jl(e,t,r){return yl(this,void 0,void 0,(function*(){const n=null!=r?r:Ml(t);return function(e){return es(this,arguments,void 0,(function*(e,t={}){var r;const n=null!==(r=t.toSourcePath)&&void 0!==r?r:e=>e;let o,i,s;for(const t of yi){const r=yield e(t);if(null===r)continue;let a;try{a=JSON.parse(r)}catch(e){continue}s=pi(a);const l=Gi(r);if(l.success){void 0!==l.data.mcpServers&&(o=l.data.mcpServers,i=n(t));break}}return cs(e,o,i,void 0===s?t:Object.assign(Object.assign({},t),{parserOptions:Object.assign(Object.assign({},t.parserOptions),{pluginSchemaId:s})}))}))}(function(e){return t=>yl(this,void 0,void 0,(function*(){if(!Ji(t))return null;const r=(0,a.join)(e,t);try{return(yield wl(r))?null:(yield(0,no.stat)(r)).isFile()?(yield Sl(r),yield bl(r)):null}catch(e){return null}}))}(e),{fallbackFileNames:is(),manifestPrecedence:"override",toSourcePath:t=>(0,a.join)(e,t),installPathForExpansion:e,parserOptions:n})}))}function Dl(e,t){return yl(this,void 0,void 0,(function*(){var r;const n=yield jl(e);if(n)return n;for(const n of bi){const o=(0,a.join)(e,n);try{if(!(yield(0,no.stat)(o)).isFile())continue;const n=yield(0,no.readFile)(o,"utf-8"),i=JSON.parse(n).plugins;if(!Array.isArray(i))continue;const s=t.name,l=i.find((e=>e.name===s));if(!(null===(r=null==l?void 0:l.mcpServers)||void 0===r?void 0:r.length))continue;for(const t of l.mcpServers){const r=t.replace(/^\.\//,"");if(!Ji(r))continue;const n=(0,a.join)(e,r);try{yield Sl(n);const t=as(yield bl(n),e);if((null==t?void 0:t.mcpServers)&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,n])));return Object.assign(Object.assign({},t),{mcpServerSourcePaths:e})}}catch(e){}}return null}catch(e){}}return null}))}function Nl(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?Object.assign(Object.assign({},e),{command:Qi(e.command,t)}):"prompt"in e&&"string"==typeof e.prompt?Object.assign(Object.assign({},e),{prompt:Qi(e.prompt,t)}):e)));return Object.assign(Object.assign({},e),{hooks:r})}function $l(e,t,r,n){return yl(this,void 0,void 0,(function*(){if("object"==typeof r){const o=Ll(r,t);return o&&"config"in o?Object.assign({config:Nl(o.config,e)},void 0!==n&&{sourcePath:n}):o}let o,i,s;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Ji(t))return;o=t.endsWith(".json")?(0,a.join)(e,t):(0,a.join)(e,t,"hooks.json")}else o=(0,a.join)(e,"hooks","hooks.json");try{if(yield wl(o))return;if(!(yield(0,no.stat)(o)).isFile())return}catch(e){return}try{yield Sl(o),i=yield(0,no.readFile)(o,"utf-8")}catch(e){return}try{s=JSON.parse(i)}catch(e){return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const l=Ll(s,t);return l&&"config"in l?{config:Nl(l.config,e),sourcePath:o}:l}))}function Ll(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,n=Ke(r);return n.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${n.errors.join("; ")}`}}}if("claude-code"===r){const r=null==e?void 0:e.hooks;if(!r||0===Object.keys(r).length)return;const n=be(r),o=Ke(n);return o.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}}function Fl(e,t,r,n){return yl(this,void 0,void 0,(function*(){var o,i,s,a,l,c,u,d;const h=yield El(e),p=null!==(u=Ml(r))&&void 0!==u?u:(null==n?void 0:n.configuredVariables)?{configuredVariables:n.configuredVariables}:void 0,[f,m,g]=yield Promise.all([xl(e,null==h?void 0:h.manifestOptions),jl(e,r,p),$l(e,t,null===(o=null==h?void 0:h.manifestOptions)||void 0===o?void 0:o.hooks,null==h?void 0:h.manifestFilePath)]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},f),void 0!==(null===(i=null==h?void 0:h.metadata)||void 0===i?void 0:i.displayName)&&{displayName:h.metadata.displayName}),void 0!==(null===(s=null==h?void 0:h.metadata)||void 0===s?void 0:s.description)&&{description:h.metadata.description}),void 0!==(null===(a=null==h?void 0:h.metadata)||void 0===a?void 0:a.authorName)&&{authorName:h.metadata.authorName}),{variablesSchema:null===(l=null==h?void 0:h.metadata)||void 0===l?void 0:l.variables,mcpConfig:m,capabilities:null!==(d=null===(c=null==h?void 0:h.metadata)||void 0===c?void 0:c.capabilities)&&void 0!==d?d:[],hooks:g})}))}function Ul(e,t){return yl(this,void 0,void 0,(function*(){var r,n,o,i,s,a;const l=yield El(e),[c,u,d]=yield Promise.all([xl(e,null==l?void 0:l.manifestOptions),Dl(e,t),$l(e,t.raw,null===(r=null==l?void 0:l.manifestOptions)||void 0===r?void 0:r.hooks,null==l?void 0:l.manifestFilePath)]),h={source:"claude-plugin",sourceInfo:t};return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:h,installPath:e},void 0!==(null===(n=null==l?void 0:l.metadata)||void 0===n?void 0:n.displayName)&&{displayName:l.metadata.displayName}),void 0!==(null===(o=null==l?void 0:l.metadata)||void 0===o?void 0:o.description)&&{description:l.metadata.description}),void 0!==(null===(i=null==l?void 0:l.metadata)||void 0===i?void 0:i.authorName)&&{authorName:l.metadata.authorName}),c),{mcpConfig:null!=u?u:void 0,capabilities:null!==(a=null===(s=null==l?void 0:l.metadata)||void 0===s?void 0:s.capabilities)&&void 0!==a?a:[],hooks:d})}))}function Bl(e,t,r){return yl(this,void 0,void 0,(function*(){const n=`${r.name}@${r.version}`,{displayName:o,description:i,authorName:s,variablesSchema:a,skills:l,rules:c,agents:u,commands:d,mcpConfig:h,capabilities:p,hooks:f}=yield Fl(e,n,r),m={source:t,sourceInfo:r};return Object.assign(Object.assign(Object.assign(Object.assign({identifier:m,installPath:e},void 0!==o&&{displayName:o}),void 0!==i&&{description:i}),void 0!==s&&{authorName:s}),{variablesSchema:a,skills:l,rules:c,agents:u,commands:d,mcpConfig:null!=h?h:void 0,capabilities:p,hooks:f})}))}function zl(e,t){return yl(this,arguments,void 0,(function*(e,t,r={}){var n,o;const i=null!==(n=r.log)&&void 0!==n?n:Xo,s=performance.now(),l=yield function(e){return gl(this,void 0,void 0,(function*(){const t=vl(e),r=(0,a.join)(t,"plugins","installed_plugins.json");try{const e=yield(0,no.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir);if(!(null==l?void 0:l.plugins))return i.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-s).toFixed(1)}ms)`),[];const c=yield function(e){return gl(this,void 0,void 0,(function*(){const t=vl(e),r=(0,a.join)(t,"settings.json");try{const e=yield(0,no.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir),u=e?(0,a.resolve)(e):void 0,d=function(e,t,r,n){var o;const i=null==e?void 0:e.plugins;if(!i||"object"!=typeof i)return[];const s=null!==(o=null==t?void 0:t.enabledPlugins)&&void 0!==o?o:{},a={};(null==r?void 0:r.enabledPlugins)&&Object.assign(a,r.enabledPlugins);const l=void 0!==n?nl(n):void 0,c=new Set,u=[];for(const[e,t]of Object.entries(i)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==l&&!1===a[e])continue;let r;void 0!==l&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&nl(t.projectPath)===l&&!0===a[e]))),r||!0!==s[e]||(r=t.find((e=>"user"===e.scope))),(null==r?void 0:r.installPath)&&!c.has(e)&&(u.push({pluginId:e,installPath:r.installPath}),c.add(e))}return u}(l,c,u?yield function(e){return gl(this,void 0,void 0,(function*(){const t={enabledPlugins:{}};let r=!1;const n=(0,a.join)(e,".claude","settings.json");try{const e=yield(0,no.readFile)(n,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch(e){}const o=(0,a.join)(e,".claude","settings.local.json");try{const e=yield(0,no.readFile)(o,"utf-8"),n=JSON.parse(e);n.enabledPlugins&&(Object.assign(t.enabledPlugins,n.enabledPlugins),r=!0)}catch(e){}return r?t:null}))}(u):null,u),h=[],p=r.onError;for(const{pluginId:e,installPath:t}of d)try{const r=performance.now(),n=oi(e),o=yield Ul(t,n);h.push(o),i.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(p)try{p(oi(e),r)}catch(t){p({name:null!==(o=e.split("@")[0])&&void 0!==o?o:e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return i.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-s).toFixed(1)}ms (${d.length} resolved, ${h.length} loaded)`),h}))}Error;function Wl(e){return yl(this,void 0,void 0,(function*(){var t,r,n,o,i,s,a,l;const c=null!==(a=e.log)&&void 0!==a?a:Xo,u=performance.now(),{client:d,userId:h,teamId:p,onCursorError:f,pruneOldVersions:m,pluginFilter:g}=e,v=[],y=null!==(l=e.cacheManager)&&void 0!==l?l:new Es(e.userHomeDir),w=performance.now(),b=yield d.listEnabledPlugins(h,p);c.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-w).toFixed(1)}ms (${b.plugins.length} plugins)`);const S=[];if(b.listFailures){v.push(...b.listFailures);for(const e of b.listFailures)S.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:Object.assign(Object.assign({name:e.pluginName,version:""},void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId}),{marketplace:e.marketplaceName})},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const k=new Map;for(const e of b.plugins)if(!g||g(e))try{const i=null===(t=e.marketplace)||void 0===t?void 0:t.name;if(!i){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);v.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),f&&f(e,t);continue}const s=`${i}/${e.pluginId}`;let a,l=k.get(s);if(l||(l={slug:i,pluginId:e.pluginId,versions:[]},k.set(s,l)),l.versions.push(e.version),yield y.isCached({marketplaceSlug:i,pluginId:e.pluginId,version:e.version}))a=y.getCacheDir({marketplaceSlug:i,pluginId:e.pluginId,version:e.version}),c.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${a}`,{marketplaceSlug:i,pluginId:e.pluginId,gitRef:e.version,marketplaceId:null===(r=e.marketplace)||void 0===r?void 0:r.id});else{const t=y.getCacheDir({marketplaceSlug:i,pluginId:e.pluginId,version:e.version});c.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${t}`,{marketplaceSlug:i,pluginId:e.pluginId,gitRef:e.version,marketplaceId:null===(n=e.marketplace)||void 0===n?void 0:n.id}),yield(0,no.mkdir)(t,{recursive:!0});try{yield d.installPlugin(e,t),yield y.markCacheComplete({marketplaceSlug:i,pluginId:e.pluginId,version:e.version})}catch(e){try{yield(0,no.rm)(t,{recursive:!0,force:!0})}catch(e){}throw e}a=t}const u=null===(o=e.marketplace)||void 0===o?void 0:o.name,h=void 0!==u&&"cursor-public"!==u&&u.length>0?"cursor-third-party":"cursor-first-party",p={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:u,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},m=yield Bl(a,h,p);S.push(m);try{yield y.pruneOldVersions({marketplaceSlug:i,pluginId:e.pluginId,keepVersions:[e.version]})}catch(e){}}catch(t){c.captureException(t,{error_type:"load_plugin_from_marketplace"});const r=t instanceof Error?t:new Error(String(t));v.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:null===(i=e.marketplace)||void 0===i?void 0:i.name,errorMessage:r.message,errorType:kl(r)});const n=null===(s=e.marketplace)||void 0===s?void 0:s.name,o=void 0!==n&&"cursor-public"!==n&&n.length>0;S.push({identifier:{source:o?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:n,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:r.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),f&&f(e,r)}if(m)for(const{slug:e,pluginId:t,versions:r}of k.values())try{yield y.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch(e){}return c.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-u).toFixed(1)}ms (${S.length} plugins loaded, ${v.length} failures)`),{plugins:S,failures:v}}))}function Hl(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 ql(e,t={}){return Object.assign(Object.assign({},e),{model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools})}(0,a.join)((0,s.homedir)(),".claude","plugins","marketplaces");var Gl=r("node:url");function Vl(e,t){const r=[];for(const o of e){const e=ii(o.identifier),i=`plugin:${e}`,s=si(o.identifier),l=ai(o.identifier),c=li(o.identifier),u=ci(o.identifier);for(const d of t(o)){const t=(0,a.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:s,marketplace:l,pluginId:c,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}const Jl=Yo.z.object({path:Yo.z.string(),name:Yo.z.string().optional(),description:Yo.z.string().optional(),globs:Yo.z.array(Yo.z.string()).optional(),alwaysApply:Yo.z.boolean().optional(),content:Yo.z.string(),environments:Yo.z.array(Yo.z.string()).optional(),disabledEnvironments:Yo.z.array(Yo.z.string()).optional()}),Kl=Jl.extend({name:Yo.z.string()}),Zl=Yo.z.object({path:Yo.z.string(),name:Yo.z.string(),description:Yo.z.string().optional(),tools:Yo.z.array(Yo.z.string()).optional(),model:Yo.z.string().optional(),prompt:Yo.z.string(),permissionMode:Yo.z.enum(["default","readonly"]).optional()}),Yl=Yo.z.object({path:Yo.z.string(),name:Yo.z.string(),description:Yo.z.string().optional(),argumentHint:Yo.z.string().optional(),content:Yo.z.string()}),Xl=Yo.z.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),Ql=Yo.z.object({config:Xl,sourcePath:Yo.z.string().optional()}),ec=Yo.z.custom((e=>"object"==typeof e&&null!==e));Yo.z.object({schemaVersion:Yo.z.number().int(),displayName:Yo.z.string().optional(),description:Yo.z.string().optional(),authorName:Yo.z.string().optional(),skills:Yo.z.array(Jl),rules:Yo.z.array(Kl),agents:Yo.z.array(Zl),commands:Yo.z.array(Yl),mcpConfig:ei.extend({mcpServerSourcePaths:Yo.z.record(Yo.z.string(),Yo.z.string()).optional()}).optional(),hooks:Ql.optional(),hooksError:Yo.z.string().optional(),capabilities:Yo.z.array(Yo.z.string()),variablesSchema:ec.optional()}),Error;var tc=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function rc(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch(e){return!1}}class nc extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function oc(e){return tc(this,void 0,void 0,(function*(){try{return yield(0,no.readFile)(function(e){return(0,a.join)(e,".cursor","settings.json")}(e),"utf-8")}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}))}function ic(e){return tc(this,void 0,void 0,(function*(){const t=yield oc(e);return void 0===t?{}:function(e){const t=[],r=(0,Ki.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,Ki._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new nc(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const n=r;return void 0===n.plugins||"object"==typeof n.plugins&&null!==n.plugins&&!Array.isArray(n.plugins)?n:{}}(t)}))}function sc(e){return tc(this,void 0,void 0,(function*(){const t=yield ic(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||rc(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}))}function ac(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var lc=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),cc=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),uc=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),dc=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");const hc="utf8",pc="utf8bom",fc="latin1",mc={"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 gc(e){const t=e.toLowerCase();return"latin-1"===t?fc:"utf-8"===t?hc:"utf-8-bom"===t||"utf-8 bom"===t?pc:t}var vc,yc=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},wc=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}},bc=function(e){return this instanceof bc?(this.v=e,this):new bc(e)},Sc=function(e){var t,r;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,o){t[n]=e[n]?function(t){return(r=!r)?{value:bc(e[n](t)),done:!1}:o?o(t):t}:o}};!function(e){e.CRLF="CRLF",e.LF="LF"}(vc||(vc={}));const kc=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Ec=new Set(kc),xc=new Zo.TextDecoder("utf-8",{fatal:!0}),Cc=new Zo.TextDecoder("latin1"),_c=Buffer.from([239,187,191]),Pc=new Map,Ic=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...kc]),Tc=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i;function Rc(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ac(e){const t=Rc(e);return Ec.has(t)}function Oc(e){const t=Rc(e);return{encoding:"binary",lineEnding:vc.LF,isBinaryFile:!0,isImageFile:Tc.test(t),isVideoFile:Ec.has(t)}}function Mc(e,t){return yc(this,void 0,void 0,(function*(){const r=yield(0,no.readFile)(e),n=$c(r);if(n.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const o=Pc.get(e);let i;i=t||o||n.encoding;const{text:s,encoding:a}=function(e,t){const r=gc(t);if(r===hc||r===pc||"ascii"===r){const t=Wc(e);return r===pc&&t.encoding===hc?{text:t.text,encoding:pc}:t}if(r===fc)return{text:Cc.decode(e),encoding:fc};try{const t=function(e){return mc[e]||e}(r);if(uc.encodingExists(t))return{text:uc.decode(e,t),encoding:r}}catch(e){}return Wc(e)}(r,i),l=function(e){return e.startsWith("\ufeff")?e.slice(1):e}(s);return zc(e,a===hc&&Hc(r)?pc:a),n.lineEnding===vc.CRLF?l.replaceAll("\r\n","\n"):l}))}function jc(e,t,r,n){return yc(this,void 0,void 0,(function*(){let o;try{o=r?yield function(e,t){return yc(this,void 0,void 0,(function*(){try{return yield Dc(e)}catch(e){}const r=Rc(e);if(Ic.has(r))return Oc(e);try{return yield function(e){return yc(this,void 0,void 0,(function*(){var t,r,n,o;const i=new Map;let s=0;try{for(var a,l=!0,c=wc(Uc(e));!(t=(a=yield c.next()).done);l=!0){o=a.value,l=!1;const e=o;if(s>=100)break;try{const t=yield Dc(e);if(!t.isBinaryFile){const e=`${t.encoding}:${t.lineEnding}`,r=i.get(e);if(r){if(r.count++,r.count>=3)return r.format}else i.set(e,{format:t,count:1})}s++}catch(e){}}}catch(e){r={error:e}}finally{try{l||t||!(n=c.return)||(yield n.call(c))}finally{if(r)throw r.error}}let u;for(const e of i.values())(!u||e.count>u.count)&&(u=e);return u?u.format:Bc()}))}(t)}catch(e){return Bc()}}))}(e,r):yield Dc(e)}catch(t){const r=Rc(e);o=Ic.has(r)?Oc(e):Bc()}const i=Pc.get(e);if(!o.isBinaryFile){let t;t=gc(n||i||o.encoding);const r=t===pc||t===hc&&!n&&(yield function(e){return yc(this,void 0,void 0,(function*(){try{return Hc(yield Fc(e))}catch(e){return!1}}))}(e));o=Object.assign(Object.assign({},o),{encoding:r?pc:t}),zc(e,o.encoding)}const s=Nc(t);if(o.lineEnding===vc.CRLF&&(t=t.replaceAll("\n","\r\n")),"binary"===o.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(e){}return Buffer.from(e,"latin1")}(t);return{lines:s,buffer:e,format:o}}return{lines:s,buffer:o.encoding===pc?Buffer.concat([_c,uc.encode(t,hc,{defaultEncoding:hc})]):uc.encode(t,o.encoding,{defaultEncoding:hc}),format:o}}))}function Dc(e){return yc(this,void 0,void 0,(function*(){const t=$c(yield Fc(e));return t.isBinaryFile?Object.assign(Object.assign({},t),{isVideoFile:Ac(e)}):Object.assign(Object.assign({},t),{isVideoFile:!1})}))}function Nc(e){if(""===e)return 1;let t=1;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}function $c(e){if(0===e.length)return Bc();const t=function(e){if(e.length<4)return null;if(255===e[0]&&254===e[1]&&(0!==e[2]||0!==e[3]))return"UTF-16LE";if(254===e[0]&&255===e[1])return"UTF-16BE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/2));for(let o=0;o<2*n&&!(o+1>=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e);if(t)return{encoding:t,lineEnding:Lc(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 n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(r)return{encoding:r,lineEnding:Lc(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 n=0;n<t;n++){const t=e[n];t<32&&9!==t&&10!==t&&13!==t&&r++}return r/t*100<5}(e))return{encoding:"binary",lineEnding:vc.LF,isBinaryFile:!0,isImageFile:(o=e,!(o.length<4)&&(o.length>=8&&137===o[0]&&80===o[1]&&78===o[2]&&71===o[3]&&13===o[4]&&10===o[5]&&26===o[6]&&10===o[7]||255===o[0]&&216===o[1]&&255===o[2]||o.length>=12&&82===o[0]&&73===o[1]&&70===o[2]&&70===o[3]&&87===o[8]&&69===o[9]&&66===o[10]&&80===o[11]||o.length>=6&&71===o[0]&&73===o[1]&&70===o[2]&&56===o[3]&&(55===o[4]||57===o[4])&&97===o[5])),isVideoFile:!1};var o;if((0,n.isUtf8)(e)&&!e.includes(27))return{encoding:"UTF-8",lineEnding:Lc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=dc.detect(e);let s=i.confidence>.7?i.encoding:"utf-8";return"ascii"===s&&(s="utf-8"),{encoding:null!=s?s:"utf-8",lineEnding:Lc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Lc(e){let t=0,r=0;for(let n=0;n<e.length;n++)10===e[n]&&(n>0&&13===e[n-1]?t++:r++);return 0===t&&0===r?vc.LF:t/(t+r)*100>=5?vc.CRLF:vc.LF}function Fc(e){return yc(this,void 0,void 0,(function*(){const t=yield(0,no.open)(e,"r");try{const e=Buffer.allocUnsafe(8192),{bytesRead:r}=yield t.read(e,0,8192,0);return e.subarray(0,r)}finally{yield t.close()}}))}function Uc(e){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof bc?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=yield bc((0,no.readdir)(e,{withFileTypes:!0}));for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,a.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield bc(yield*Sc(wc(Uc(r))))):n.isFile()&&(yield yield bc(r))}}catch(e){return yield bc(void 0)}}))}function Bc(){return{encoding:hc,lineEnding:"win32"===process.platform?vc.CRLF:vc.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zc(e,t){if(Pc.has(e)&&Pc.delete(e),Pc.set(e,t),Pc.size<=100)return;const r=Pc.keys().next().value;void 0!==r&&Pc.delete(r)}function Wc(e){try{return{text:xc.decode(e),encoding:hc}}catch(t){return{text:Cc.decode(e),encoding:fc}}}function Hc(e){return e.length>=_c.length&&e[0]===_c[0]&&e[1]===_c[1]&&e[2]===_c[2]}class qc{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.ttlMs="function"==typeof e?e:qc.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 Gc=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Vc(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:o=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:l={type:"insecure_none"},noIgnoreVcs:c=!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,s.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),c&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of a)h.push("--cursor-ignore",e);for(const e of n)h.push("--iglob",e);for(const e of o)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 n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,io.spawnInSandbox)((0,io.getRipgrepBinaryPath)(),t,{cwd:r},n),i=[];o.stderr?.on("data",(e=>{i.push(e)}));const s=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(!o.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:o.stdout,processExit:s,stderr:()=>Buffer.concat(i).toString(),aborted:a,[Symbol.dispose](){o.kill()}}}(e,h,t,l),!1);let o=0;const i=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)}(n.stdout)[Symbol.asyncIterator]();for(;;){const e=await Promise.race([i.next(),n.aborted]);if("aborted"===e){m=!0,f(!0);break}if(e.done)break;o++,yield e.value}if(o>0);else if(!m){const e=await n.processExit;if(0!==e&&1!==e){const t=n.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{Gc(r)}}(),didTimeout:g}}let Jc;function Kc({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:i=[],sandboxPolicy:s={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:l=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:i,sandboxPolicy:s,noIgnoreVcs:a,followSymlinks:l})}class Zc{constructor(e=()=>function(e=process.env){if(void 0!==Jc)return Jc;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 qc({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(Kc(e))}walk(e,t){const r=Kc(t);let n,o=!1,i=!1;const s=new Promise((e=>{n=e})),a=e=>{i||(i=!0,n(e))},l=(c=e.signal,new Promise((e=>{c.aborted?e("aborted"):c.addEventListener("abort",(()=>e("aborted")),{once:!0})})));var c;return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const e=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),l.then((()=>({type:"aborted"})))]);if("aborted"===e.type)return o=!0,void a(!0);if("lines"===e.type)return a(!1),void(yield*e.lines);this.cache.get(r)===n&&this.cache.delete(r)}let i,s;const c={linesPromise:new Promise(((e,t)=>{i=e,s=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const u=[];let d,h=!1;try{const r=Vc(e,t);for await(const e of r.lines)u.push(e),yield e;if(await r.didTimeout)return o=!0,d=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);h=!0}catch(e){throw d=e,e}finally{h?i?.(u):(this.cache.get(r)===c&&this.cache.delete(r),s?.(d??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:s}}}async function Yc(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}async function Xc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Qc(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 eu(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 tu=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];var ru=r("../utils/dist/lru-cache.js"),nu=r("../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js");const ou=[".gitignore",".cursorignore"];async function iu(e){if(!(0,a.isAbsolute)(e))return null;const t=await(0,ao.DN)(e);return null===t?null:t}class su{constructor(e,t,r){this.ignoreServicePromise=lu.init((0,Qe.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e){return this.ignoreServicePromise.then((t=>t.isCursorIgnored(e)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}}const au=Math.min(8,Math.max(1,Math.floor(s.availableParallelism()/2)));class lu{constructor(e,t,r,n,o){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.gitIgnoreCache=new ru.q({max:2e3}),this.cursorIgnoreCache=new ru.q({max:2e3}),this.gitRootCache=new ru.q({max:1e3}),this.gitRemoteUrlCache=new ru.q({max:200}),this.hasGitDirCache=new ru.q({max:1e3}),this.gitParsedIgnoreCache=new Map,this.cursorParsedIgnoreCache=new Map}static getRipwalkCache(){return lu.ripwalkCache??=new Zc,lu.ripwalkCache}getIgnoreInstance(e,t,r){let n=r.get(e);return n||(n=Jo().add(t),r.set(e,n)),n}hasNoWorkspaceFolders(){return 0===Object.keys(this.gitIgnoreMapping).length&&0===Object.keys(this.cursorIgnoreMapping).length}async resolveLookupRoot(e){return await(0,ao.DN)(e)??(0,ao.o1)(e)}static async init(e,t,r,n){const o=await(0,Br.PH)(r,(async e=>{const t=await(0,ao.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),i={},s={},a=(await(0,Br.PH)(o,(r=>Yc(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([lu.initializeIgnoreMapping(a,".gitignore",i),lu.initializeIgnoreMapping(o,".cursorignore",s)]),new lu(t,i,s,n,o)}static async preloadHierarchy(e,t,r,n){let o=(0,ao.o1)(e);const i=(0,a.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,a.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await lu.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,a.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,a.join)(e,t);try{await(0,no.access)(n,no.constants.F_OK);const t=await Mc(n),o=lu.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===o.code||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r){try{const n=lu.deduplicateRootDirectories(e),o=await lu.promiseQueue.enqueueList(n,(e=>lu.findFilesWithRipgrep(e,t))),i=Array.from(o.values()).flat();await Promise.all(i.map((async e=>{try{const t=await Mc(e),n=lu.parseIgnoreRules(t),o=(0,a.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const s=new Set;for(const e of n)await lu.preloadHierarchy(e,t,r,s)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t){const r=(0,Qe.q6)(),n=[],o={root:e,includeGlobs:ou.map((e=>`**/${e}`)),excludeGlobs:tu,source:"ignore_scan"},i=lu.getRipwalkCache().walk(r,o);for await(const r of i.lines)(0,a.basename)(r)===t&&n.push((0,a.join)(e,r));return n}async handleManualLookupWhenNoWorkspaceDirs(e,t){const r={};let n=(0,a.dirname)(e);const o=(0,a.parse)(n).root;for(;;){const e=(0,a.join)(n,t);try{const t=await Mc(e),o=lu.parseIgnoreRules(t);o.length>0&&(r[n]=o)}catch{}if(n===o)break;n=(0,a.dirname)(n)}return this.testIgnored(e,r,((e,t)=>Jo().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e){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 n=(0,a.dirname)((0,ao.o1)(e));const o=[],i=(0,a.parse)(n).root;for(;n!==i;){if(this.rootDirectories.some((e=>(0,ao.ZU)({basePath:e,targetPath:n})))){n=(0,a.dirname)(n);continue}if(void 0!==r[n])break;o.push(n);const e=(0,a.dirname)(n);if(e===n)break;n=e}o.length>0&&(await lu.promiseQueue.enqueueList(o,(e=>lu.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ao.ZU)({basePath:n,targetPath:e}))continue;const t=(0,a.relative)(n,e);if(""===t)continue;const i=r(n,o),s=(0,ao.oL)(t),l=i.test(s);if(l.ignored&&!l.unignored)return!0;const c=i.test(`${s}/`);if(c.ignored&&!c.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>this.getIgnoreInstance(e,t,r)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ao.ZU)({basePath:t,targetPath:e}))continue;const o=(0,a.join)(e,".cursorignore");try{await(0,no.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ao.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear()}async handleCursorIgnoreCreated(e){const t=(0,a.dirname)(e),r=await Mc(e),n=lu.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,a.dirname)(e),r=await Mc(e),n=lu.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,a.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ao.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let s=t;const l=(0,a.parse)(s).root;for(;s!==l;){o.push(s),void 0===this.hasGitDirCache.get(s)&&i.push(s);const e=(0,a.dirname)(s);if(e===s)break;s=e}if(i.length>0){const e=i.map((e=>(0,no.access)((0,a.join)(e,".git"),no.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=await this.findGitRootsForFile(e);if(0===t.length)return!1;const r=await(this.teamSettingsService?.getTeamRepos());if(!r||!r.repos)return!1;for(const n of t){let t;this.gitRemoteUrlCache.has(n)?t=this.gitRemoteUrlCache.get(n):(t=await Xc((0,Qe.q6)(),this.gitExecutor,n),void 0!==t&&this.gitRemoteUrlCache.set(n,t));const o=r.repos.filter((e=>void 0!==t&&this.doesRepoUrlMatch(e.url,t)));if(0===o.length)continue;const i=(0,a.relative)(n,e)||".";for(const e of o)for(const t of e.patterns||[])if(this.matchGlob(t.pattern,i))return!0}return!1}doesRepoUrlMatch(e,t){if(e.trim().toLowerCase().replace(/\.git$/i,""),e.includes("*")){if("*"===e.trim())return!0;const r=eu(e).toLowerCase(),n=eu(t).toLowerCase();return this.matchRepoUrlGlob(r,n)}return eu(e).toLowerCase()===eu(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return nu(r)(t)}catch{return r===t}}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),s=this.normalizePathForComparison(r);let l=!1,c="";if(s.startsWith(n)?(l=!0,c=""):n.startsWith(s)&&(l=!0,c=(0,a.relative)(r,e)),!l)continue;const u=t.repos.filter((e=>this.doesRepoUrlMatch(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=c?(0,a.join)(c,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],n=(0,Qe.q6)();for(const e of this.rootDirectories){const o=(0,ao.o1)(e);try{await(0,no.access)((0,a.join)(o,".git"),no.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,a.dirname)(o);const s=(0,a.parse)(i).root;for(;i!==s&&""!==i;){try{await(0,no.access)((0,a.join)(i,".git"),no.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,a.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:r,noIgnoreVcs:!0,source:"ignore_scan"},i=lu.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,a.join)(o,e),n=(0,a.dirname)(r),i=(0,a.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Xc(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}lu.promiseQueue=new Br.TJ({max:au});var cu=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const uu=[{pattern:/[/\\]\.cursor[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.agents[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.codex[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.cursor[/\\]skills-cursor[/\\]/i,requiresThirdParty:!1}],du=/[/\\]\.cursor[/\\]rules[/\\]/i,hu=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],pu=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function fu(e,t){const r=e.replace(/\\/g,"/"),n=(0,a.basename)(r);if(pu.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(du.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of uu)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of hu)if(e.test(r)){if(n&&!t)continue;return"agents"}}class mu{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return mu.ripwalkCache??=new Zc,mu.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,c.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]};if((0,a.resolve)(this.root)===(0,a.resolve)(this.userHomeDirectory))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Yc(e,this.gitExecutor,(0,a.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const o=this.getThirdPartyExtensibilityEnabled(),i=this.buildIncludeGlobs(o),s={root:this.root,includeGlobs:i,excludeGlobs:tu,followSymlinks:!0,source:"nested_extensibility"},l={rules:[],skills:[],markdown:[],agents:[]},u=mu.getRipwalkCache();try{const e=u.walk(r.ctx,s);try{for await(const t of e.lines){const e=fu(t,o);e&&l[e].push((0,a.resolve)(this.root,t))}}finally{u.delete(s)}}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{cu(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const gu=new Set(["node_modules",".git",".svn",".hg","__pycache__",".cache","dist","build",".next",".nuxt"]);async function vu({rootDir:e,includeFile:t,maxDepth:r=10,skipDirectories:n=gu,containmentRootDir:o}){const i=[],s=[{dir:e,depth:0}],l=new Set,c=void 0!==o?await(0,no.realpath)(o):null,u=e=>{if(null===c)return!0;const t=(0,a.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,a.isAbsolute)(t)};for(;s.length>0;){const e=s.pop();if(void 0===e)continue;const{dir:o,depth:c}=e;if(c>r)continue;try{const e=await(0,no.realpath)(o);if(!u(e))continue;if(l.has(e))continue;l.add(e)}catch{continue}const d=await(0,no.readdir)(o,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,a.join)(o,e.name);let l=e.isDirectory(),u=e.isFile();if(e.isSymbolicLink())try{const e=await(0,no.stat)(r);l=e.isDirectory(),u=e.isFile()}catch{continue}if(l){if(n.has(e.name))continue;s.push({dir:r,depth:c+1})}else u&&t(e.name)&&i.push(r)}}return i.sort(((e,t)=>e.localeCompare(t))),i}const yu=new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]);function wu(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean),r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&yu.has(o)}function bu(e){return{dirPath:(0,a.join)(e,".cursor","skills-cursor"),scope:"builtin",source:"builtin"}}function Su(e,t){const r=[];return t&&r.push({dirPath:(0,a.join)(e,".claude","skills"),scope:"project",source:"workspace"},{dirPath:(0,a.join)(e,".codex","skills"),scope:"project",source:"workspace"}),r.push({dirPath:(0,a.join)(e,".agents","skills"),scope:"project",source:"workspace"},{dirPath:(0,a.join)(e,".cursor","skills"),scope:"project",source:"workspace"}),r}function ku(e,t){const r=[];return t&&r.push({dirPath:(0,a.join)(e,".claude","skills"),scope:"user",source:"user"},{dirPath:(0,a.join)(e,".codex","skills"),scope:"user",source:"user"}),r.push({dirPath:(0,a.join)(e,".agents","skills"),scope:"user",source:"user"},{dirPath:(0,a.join)(e,".cursor","skills"),scope:"user",source:"user"}),r}var Eu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},xu=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Cu=(0,h.h)("local-exec:cursor-rules");function _u(e){return Tu(e.data?.environments??e.data?.metadata?.environments)??[]}function Pu(e){return Tu(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Iu(e){return Tu(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Tu(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 Ru(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 Au(e){return e.slice(0,1536)}async function Ou(e){const t=await Mc(e);return{skillFilePath:e,content:t,parsed:tl(t)}}function Mu(e){return!0===e.data?.alwaysApply}function ju({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){var t,r,n;const o=(null!==(r=e.matter)&&void 0!==r?r:"").trim(),i=null===(t=e.language)||void 0===t?void 0:t.toLowerCase();return o.length>0&&"js"!==i&&"javascript"!==i?`---\n${o}\n---`:rl("",null!==(n=e.data)&&void 0!==n?n:{}).trim()}(e)}(r);if(Mu(r))return new cc.DX({fullPath:e,content:t,frontmatter:n,type:new cc.f5({type:{case:"global",value:new cc.i9}}),environments:_u(r),disabledEnvironments:Pu(r),scopedTo:Iu(r)});const o="string"==typeof r.data?.description?Au(r.data.description):void 0;return o?new cc.DX({fullPath:e,content:t,frontmatter:n,type:new cc.f5({type:{case:"agentFetched",value:new cc.Xo({description:o})}}),environments:_u(r),disabledEnvironments:Pu(r),scopedTo:Iu(r)}):new cc.DX({fullPath:e,parseError:"Description is required",frontmatter:n,scopedTo:Iu(r),type:new cc.f5({type:{case:"agentFetched",value:new cc.Xo}})})}function Du({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?Au(r.data.description):"",o=Tl(r.data?.paths??r.data?.globs);return new lc.N({fullPath:e,content:t,description:n,globs:o??[],parseError:n?void 0:"Description is required",environments:_u(r),disabledEnvironments:Pu(r),scopedTo:Iu(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function Nu({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new cc.DX({fullPath:e,parseError:t,type:new cc.f5({type:{case:"agentFetched",value:new cc.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new lc.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`}))}function $u(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),i=r.indexOf("/.codex/"),s=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+8)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+9)}`:e}function Lu(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Fu(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),i={};let s=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=i[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(s&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=e.slice(r+1).trim(),l=Lu(o),c=`${s}.${n}`;""===o?(i[c]=[],a=c):"metadata.environments"===c||"metadata.disabledEnvironments"===c||"metadata.scopedTo"===c?(i[c]=String(l).split(",").map((e=>e.trim())).filter(Boolean),a=null):(i[c]=l,a=null);continue}s=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const l=t.slice(0,o).trim(),c=t.slice(o+1).trim();if(""===c&&"metadata"===l){s=l;continue}if("globs"===l&&""===c){i.globs=[],a="globs";continue}const u=Lu(c);i[l]="metadata.environments"!==l&&"metadata.disabledEnvironments"!==l&&"metadata.scopedTo"!==l?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:i,rawFrontmatter:`---\n${n}\n---`,body:o}}class Uu{constructor(e){this.cursorRulesServices=e,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Eu(t,(0,c.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Zo.debuglog)("Failed to load cursor rules from service:",e),[]))))),o=(await Promise.all(n)).flat(),i=new Set,s=[];for(const e of o){const t=$u(e.fullPath);i.has(t)||(i.add(t),s.push(e))}return s}catch(e){t.error=e,t.hasError=!0}finally{xu(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()}),Uu.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()}}Uu.CHANGE_COALESCE_MS=1e3;class Bu{constructor(e,t,r,n,o,i,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=o,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new mu(r,t,(0,s.homedir)(),o),this.ignoreService=l??new su(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{Cu.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Zo.debuglog)("Failed to load cursor rules:",e),[]))),i){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=i.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,Qe.q6)(),n=Eu(t,(0,c.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,a.basename)(e))return Bu.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{xu(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Zo.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return Bu.ripwalkCache??=new Zc,Bu.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1),o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Zo.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{xu(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 n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,a.basename)(t);if(".cursorrules"===o){const e=(0,a.resolve)(this.rootDirectory),t=await Yc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=Fu(await Mc(t));if(e)return[{filename:(0,a.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,a.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,a.resolve)(this.rootDirectory),i=await Yc(n.ctx,this.gitExecutor,o)||o,s=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,o);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const h=(await Promise.all([s,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{xu(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,a.join)(t,".cursorrules");if((await(0,no.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Mc(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Eu(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{xu(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new cc.i9};else{const r=Tl(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new cc.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new cc.Xo({description:Au(e.frontmatter.description)})}:{case:"manuallyAttached",value:new cc._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],i=Array.isArray(o)?o:[],s=e.frontmatter["metadata.scopedTo"],a=Array.isArray(s)?s:[];return new cc.DX({fullPath:e.path,content:e.body,type:new cc.f5({type:t}),environments:n,disabledEnvironments:i,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 n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const s=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,a.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];s&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const l=(0,a.dirname)(i);if(l===i)break;i=l}const l=(await Promise.all(o)).flat();return n.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Eu(n,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,a.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,no.stat)(e)).isFile()){const t=await Mc(e);return[{filename:(0,a.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{xu(n)}}async isCursorIgnored(e){try{const t=await iu((0,a.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=Fu(await Mc(e));if(t)return{filename:(0,a.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,a.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,a.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,a.join)(t,".cursorignore");const e={root:(0,a.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=Bu.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,a.join)(e.root,t);o.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Eu(r,(0,c.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,no.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}}class zu{constructor(e,t,r,n,o,i,s=()=>!0,a=Promise.resolve(),l="ide",c){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.surface=l,this.fileWatcher=i,this.getThirdPartyExtensibilityEnabled=s,void 0!==c&&c.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${c.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new mu(e,n,r,s))):[],this.foldersToWatch=this.computeFoldersToWatch();const u=performance.now(),d=this.loadAll(e,c).then((t=>{try{Cu.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,Zo.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=d.then((e=>e.rules)),this._agentSkills=d.then((e=>e.agentSkills)),this.setupWatchers(this.foldersToWatch)}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,a.join)(r,".cursor","rules"));for(const n of Su(r,e))t.add(n.dirPath)}for(const r of ku(this.userHomeDirectory,e))t.add(r.dirPath);return t.add(bu(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,Qe.q6)(),n=Eu(t,(0,c.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{xu(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){return await this._rules}reload(e){const t=this.computeFoldersToWatch(),r=new Set(this.foldersToWatch),n=new Set(t),o=this.foldersToWatch.filter((e=>!n.has(e)));this.removeWatchers(o);const i=t.filter((e=>!r.has(e)));this.setupWatchers(i),this.foldersToWatch=t;const s=this.loadAll(e).catch((e=>((0,Zo.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=s.then((e=>e.rules)),this._agentSkills=s.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{Eu(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1);const n=t.endsWith("SKILL.md")?t:(0,a.join)(t,"SKILL.md"),o=Ou(n);o.catch((()=>{}));const i=async(e,t)=>{const r=(await e).filter((e=>e.fullPath!==n));if(wu(n))return r;try{await(0,no.stat)(n);const e=await o;if(Ru(e.parsed,this.surface))return r;const i=t(e);return void 0===i?r:[...r,i]}catch{return r}};this._rules=i(this._rules,(e=>ju(e))).catch((e=>((0,Zo.debuglog)("Failed to load Agent Skills at path:",e),[]))),this._agentSkills=i(this._agentSkills,(e=>Mu(e.parsed)?void 0:Du(e))).catch((e=>((0,Zo.debuglog)("Failed to load Agent Skills (proto) at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}async getAllAgentSkills(e){return await this._agentSkills}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],i=[],s=new Set,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{(0,Zo.debuglog)("cursor-rules-service")("Failed to discover nested agent skills: %O",e)}))))),l=await Promise.all(this.foldersToWatch.map((async e=>{const t=(await async function(e){return await vu({rootDir:e,includeFile:e=>"SKILL.md"===e})}(e)).filter((e=>!wu(e)));return Promise.all(t.map((async e=>{try{return await Ou(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})))})));for(const e of l)for(const t of e)if(s.add(t.skillFilePath),"error"in t)Nu({rules:o,agentSkills:i,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ru(t.parsed,this.surface))continue;o.push(ju(t)),Mu(t.parsed)||i.push(Du(t))}const u=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wu(e))),d=[],h=new Set;for(const e of u)s.has(e)||h.has(e)||(h.add(e),d.push(e));const p=await Promise.all(d.map((async e=>{try{return await Ou(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})));for(const e of p)if(s.add(e.skillFilePath),"error"in e)Nu({rules:o,agentSkills:i,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ru(e.parsed,this.surface))continue;o.push(ju(e)),Mu(e.parsed)||i.push(Du(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}}function Wu(e){let t;switch(e.type){case"global":t=new cc.f5({type:{case:"global",value:new cc.i9}});break;case"fileGlobbed":t=new cc.f5({type:{case:"fileGlobbed",value:new cc.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new cc.f5({type:{case:"agentFetched",value:new cc.Xo({description:Au(e.description??"")})}});break;case"manuallyAttached":t=new cc.f5({type:{case:"manuallyAttached",value:new cc._u}});break;default:e.type,t=new cc.f5({type:{case:"manuallyAttached",value:new cc._u}})}return new cc.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 Hu{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now(),i=this.loadAll(e).then((t=>{try{Cu.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,Zo.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]})));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t;const r=this.loadAll(e,!0).catch((e=>((0,Zo.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]})));this._rules=r.then((e=>e.rules)),this._agentSkills=r.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Eu(r,(0,c.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return Vl(e,(e=>e.skills))}(e),s=function(e){return Vl(e,(e=>e.rules))}(e);for(const e of[...r,...s])o.push(Wu(e));for(const t of e){const e=`plugin:${ii(t.identifier)}`,r=si(t.identifier),n=ai(t.identifier),o=li(t.identifier),s=ci(t.identifier);for(const l of t.skills){if(!0===l.alwaysApply)continue;let c=!1;if(l.content?.includes("disable-model-invocation"))try{c=!0===tl(l.content).data?.["disable-model-invocation"]}catch{}i.push(new lc.N({fullPath:(0,a.join)(t.installPath,l.path),content:l.content,description:Au(l.description??""),environments:l.environments??[],disabledEnvironments:l.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:s,disableModelInvocation:c}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{xu(r)}}}var qu=r("../proto/dist/generated/agent/v1/subagents_pb.js");const Gu=(0,Zo.debuglog)("local-subagents");class Vu{async getAllSubagents(){return[]}async reload(){return[]}}function Ju(e){return"true"===(e??"").trim().toLowerCase()}function Ku(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),i=t.slice(r+1).trim();0!==n.length&&(o[n]=i)}const i=o.name??"",s=o.description,a=o.model,l=Ju(o["force-default-model"]),c="true"===(o.readonly??"").trim().toLowerCase()?qu.b$.READONLY:qu.b$.DEFAULT,u=Ju(o.background??o.is_background),d=o.tools;return{name:i,description:s,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:l,prompt:n,permissionMode:c,isBackground:u}}function Zu(e){const t=(0,a.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Yu(e){return(0,a.basename)(e,(0,a.extname)(e)).replace(/[\s_]+/g,"-")}async function Xu(e,t){return await vu({rootDir:e,includeFile:Zu,containmentRootDir:t})}class Qu{constructor(e,t,r="workspace",n=!1){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(Gu("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(Gu("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,a.resolve)(this.workspacePath),t=[{dirPath:(0,a.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&t.push({dirPath:(0,a.join)(e,".claude","agents"),source:"claude"}),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Xu(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,a.basename)(r);try{if(!(await(0,no.stat)(r)).isFile())continue}catch(e){Gu("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Ku(await Mc(r));if(!o)continue;t.push(new qu.zz({fullPath:r,name:o.name||Yu(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){Gu("Failed to parse subagent file %s: %o",r,e)}}}return t}}const ed=new Set(["claude-code-tutor"]);class td{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(Gu("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)ed.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 rd{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&&(Gu("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){var r;const n=[];for(const o of e){const e=si(o.identifier),i=ai(o.identifier),s=li(o.identifier),l=ci(o.identifier);for(const c of o.agents){const u=ql(c,t),d=(0,a.join)(o.installPath,u.path);n.push({name:u.name,description:null!==(r=u.description)&&void 0!==r?r:"",prompt:u.prompt,fullPath:d,permissionMode:"readonly"===u.permissionMode?"readonly":"default",plugin:e,marketplace:i,pluginId:s,marketplaceId:l})}}return n}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?qu.b$.READONLY:qu.b$.DEFAULT;t.push(new qu.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 nd=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");function od(e,t,r){return new Promise(((n,o)=>{const i={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0};(0,Cs.execFile)(e,t.map(String),{...i,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}nd.w3.UNSPECIFIED,nd.w3.LEFT,nd.w3.MIDDLE,nd.w3.RIGHT,nd.w3.BACK,nd.w3.FORWARD,nd.Dh.UNSPECIFIED,nd.Dh.UP,nd.Dh.DOWN,nd.Dh.LEFT,nd.Dh.RIGHT,(0,p.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,p.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,p.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.h)("computer-use");const id=(0,Zo.promisify)(Cs.execFile);function sd(e,t){const r=e/t;return{display:{width:e,height:t},api:{width:1280,height:Math.round(1280/r)}}}async function ad(e){const{stdout:t}=await id("xrandr",["--display",e],{timeout:5e3}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const i=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(i){const e=parseFloat(i[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:sd(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}var ld,cd,ud,dd,hd;!function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ARROW=1]="ARROW",e[e.POINTER=2]="POINTER",e[e.TEXT=3]="TEXT",e[e.WAIT=4]="WAIT",e[e.CROSSHAIR=5]="CROSSHAIR",e[e.MOVE=6]="MOVE",e[e.RESIZE_NS=7]="RESIZE_NS",e[e.RESIZE_EW=8]="RESIZE_EW",e[e.RESIZE_NWSE=9]="RESIZE_NWSE",e[e.RESIZE_NESW=10]="RESIZE_NESW",e[e.NOT_ALLOWED=11]="NOT_ALLOWED",e[e.GRAB=12]="GRAB",e[e.GRABBING=13]="GRABBING"}(ld||(ld={})),ar.proto3.util.setEnumType(ld,"agent.v1.CursorType",[{no:0,name:"CURSOR_TYPE_UNSPECIFIED"},{no:1,name:"CURSOR_TYPE_ARROW"},{no:2,name:"CURSOR_TYPE_POINTER"},{no:3,name:"CURSOR_TYPE_TEXT"},{no:4,name:"CURSOR_TYPE_WAIT"},{no:5,name:"CURSOR_TYPE_CROSSHAIR"},{no:6,name:"CURSOR_TYPE_MOVE"},{no:7,name:"CURSOR_TYPE_RESIZE_NS"},{no:8,name:"CURSOR_TYPE_RESIZE_EW"},{no:9,name:"CURSOR_TYPE_RESIZE_NWSE"},{no:10,name:"CURSOR_TYPE_RESIZE_NESW"},{no:11,name:"CURSOR_TYPE_NOT_ALLOWED"},{no:12,name:"CURSOR_TYPE_GRAB"},{no:13,name:"CURSOR_TYPE_GRABBING"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SLOW=1]="SLOW",e[e.MELLOW=2]="MELLOW",e[e.QUICK=3]="QUICK",e[e.RAPID=4]="RAPID"}(cd||(cd={})),ar.proto3.util.setEnumType(cd,"agent.v1.MotionStyle",[{no:0,name:"MOTION_STYLE_UNSPECIFIED"},{no:1,name:"MOTION_STYLE_SLOW"},{no:2,name:"MOTION_STYLE_MELLOW"},{no:3,name:"MOTION_STYLE_QUICK"},{no:4,name:"MOTION_STYLE_RAPID"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LOADING_WAIT=1]="LOADING_WAIT",e[e.VIEWING_RESULT=2]="VIEWING_RESULT",e[e.THINKING_PAUSE=3]="THINKING_PAUSE",e[e.LONG_OPERATION=4]="LONG_OPERATION"}(ud||(ud={})),ar.proto3.util.setEnumType(ud,"agent.v1.IdleClassification",[{no:0,name:"IDLE_CLASSIFICATION_UNSPECIFIED"},{no:1,name:"IDLE_CLASSIFICATION_LOADING_WAIT"},{no:2,name:"IDLE_CLASSIFICATION_VIEWING_RESULT"},{no:3,name:"IDLE_CLASSIFICATION_THINKING_PAUSE"},{no:4,name:"IDLE_CLASSIFICATION_LONG_OPERATION"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SINGLE=1]="SINGLE",e[e.DOUBLE=2]="DOUBLE",e[e.TRIPLE=3]="TRIPLE",e[e.RIGHT=4]="RIGHT",e[e.MIDDLE=5]="MIDDLE"}(dd||(dd={})),ar.proto3.util.setEnumType(dd,"agent.v1.ClickType",[{no:0,name:"CLICK_TYPE_UNSPECIFIED"},{no:1,name:"CLICK_TYPE_SINGLE"},{no:2,name:"CLICK_TYPE_DOUBLE"},{no:3,name:"CLICK_TYPE_TRIPLE"},{no:4,name:"CLICK_TYPE_RIGHT"},{no:5,name:"CLICK_TYPE_MIDDLE"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.KEY_COMBO=1]="KEY_COMBO",e[e.KEY_SINGLE=2]="KEY_SINGLE",e[e.TEXT_TYPED=3]="TEXT_TYPED"}(hd||(hd={})),ar.proto3.util.setEnumType(hd,"agent.v1.KeystrokeEventType",[{no:0,name:"KEYSTROKE_EVENT_TYPE_UNSPECIFIED"},{no:1,name:"KEYSTROKE_EVENT_TYPE_KEY_COMBO"},{no:2,name:"KEYSTROKE_EVENT_TYPE_KEY_SINGLE"},{no:3,name:"KEYSTROKE_EVENT_TYPE_TEXT_TYPED"}]);class pd extends ar.Message{constructor(e){super(),this.executionTimestampMs=ar.protoInt64.zero,this.commandDurationMs=ar.protoInt64.zero,this.cursorTypeAfter=ld.UNSPECIFIED,ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new pd).fromBinary(e,t)}static fromJson(e,t){return(new pd).fromJson(e,t)}static fromJsonString(e,t){return(new pd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(pd,e,t)}}pd.runtime=ar.proto3,pd.typeName="agent.v1.InputEvent",pd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"execution_timestamp_ms",kind:"scalar",T:3},{no:2,name:"action",kind:"message",T:nd.ho},{no:3,name:"command_duration_ms",kind:"scalar",T:3},{no:4,name:"position_before",kind:"message",T:nd.xp},{no:5,name:"position_after",kind:"message",T:nd.xp},{no:6,name:"cursor_type_after",kind:"enum",T:ar.proto3.getEnumType(ld)}]));class fd extends ar.Message{constructor(e){super(),this.videoTimestampMs=ar.protoInt64.zero,this.x=0,this.y=0,this.cursorType=ld.UNSPECIFIED,this.velocity=0,ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new fd).fromBinary(e,t)}static fromJson(e,t){return(new fd).fromJson(e,t)}static fromJsonString(e,t){return(new fd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(fd,e,t)}}fd.runtime=ar.proto3,fd.typeName="agent.v1.CursorPathKeyframe",fd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"x",kind:"scalar",T:5},{no:3,name:"y",kind:"scalar",T:5},{no:4,name:"cursor_type",kind:"enum",T:ar.proto3.getEnumType(ld)},{no:5,name:"velocity",kind:"scalar",T:2}]));class md extends ar.Message{constructor(e){super(),this.style=cd.UNSPECIFIED,this.keyframes=[],ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new md).fromBinary(e,t)}static fromJson(e,t){return(new md).fromJson(e,t)}static fromJsonString(e,t){return(new md).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(md,e,t)}}md.runtime=ar.proto3,md.typeName="agent.v1.CursorPath",md.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"style",kind:"enum",T:ar.proto3.getEnumType(cd)},{no:2,name:"keyframes",kind:"message",T:fd,repeated:!0}]));class gd extends ar.Message{constructor(e){super(),this.startMs=ar.protoInt64.zero,this.endMs=ar.protoInt64.zero,this.centerX=0,this.centerY=0,this.suggestedZoom=0,this.actionType="",this.actionIndex=0,this.importanceScore=0,this.context="",ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new gd).fromBinary(e,t)}static fromJson(e,t){return(new gd).fromJson(e,t)}static fromJsonString(e,t){return(new gd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(gd,e,t)}}gd.runtime=ar.proto3,gd.typeName="agent.v1.ZoomCandidate",gd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"center_x",kind:"scalar",T:5},{no:4,name:"center_y",kind:"scalar",T:5},{no:5,name:"suggested_zoom",kind:"scalar",T:2},{no:6,name:"action_type",kind:"scalar",T:9},{no:7,name:"action_index",kind:"scalar",T:5},{no:8,name:"importance_score",kind:"scalar",T:5},{no:9,name:"context",kind:"scalar",T:9}]));class vd extends ar.Message{constructor(e){super(),this.startMs=ar.protoInt64.zero,this.endMs=ar.protoInt64.zero,this.durationMs=ar.protoInt64.zero,this.classification=ud.UNSPECIFIED,this.suggestedSpeed=0,this.precedingActionType="",this.followingActionType="",ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new vd).fromBinary(e,t)}static fromJson(e,t){return(new vd).fromJson(e,t)}static fromJsonString(e,t){return(new vd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(vd,e,t)}}vd.runtime=ar.proto3,vd.typeName="agent.v1.IdlePeriod",vd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"duration_ms",kind:"scalar",T:3},{no:4,name:"classification",kind:"enum",T:ar.proto3.getEnumType(ud)},{no:5,name:"suggested_speed",kind:"scalar",T:2},{no:6,name:"preceding_action_type",kind:"scalar",T:9},{no:7,name:"following_action_type",kind:"scalar",T:9}]));class yd extends ar.Message{constructor(e){super(),this.videoTimestampMs=ar.protoInt64.zero,this.x=0,this.y=0,this.clickType=dd.UNSPECIFIED,this.actionIndex=0,this.hasModifiers=!1,ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new yd).fromBinary(e,t)}static fromJson(e,t){return(new yd).fromJson(e,t)}static fromJsonString(e,t){return(new yd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(yd,e,t)}}yd.runtime=ar.proto3,yd.typeName="agent.v1.ClickEffectKeyframe",yd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"x",kind:"scalar",T:5},{no:3,name:"y",kind:"scalar",T:5},{no:4,name:"click_type",kind:"enum",T:ar.proto3.getEnumType(dd)},{no:5,name:"action_index",kind:"scalar",T:5},{no:6,name:"has_modifiers",kind:"scalar",T:8}]));class wd extends ar.Message{constructor(e){super(),this.videoTimestampMs=ar.protoInt64.zero,this.displayText="",this.eventType=hd.UNSPECIFIED,this.displayDurationMs=ar.protoInt64.zero,this.actionIndex=0,ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new wd).fromBinary(e,t)}static fromJson(e,t){return(new wd).fromJson(e,t)}static fromJsonString(e,t){return(new wd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(wd,e,t)}}wd.runtime=ar.proto3,wd.typeName="agent.v1.KeystrokeEvent",wd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"display_text",kind:"scalar",T:9},{no:3,name:"event_type",kind:"enum",T:ar.proto3.getEnumType(hd)},{no:4,name:"display_duration_ms",kind:"scalar",T:3},{no:5,name:"action_index",kind:"scalar",T:5}]));class bd extends ar.Message{constructor(e){super(),this.videoPath="",this.videoDurationMs=ar.protoInt64.zero,this.videoWidth=0,this.videoHeight=0,this.actionCount=0,this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.cursorPaths=[],ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new bd).fromBinary(e,t)}static fromJson(e,t){return(new bd).fromJson(e,t)}static fromJsonString(e,t){return(new bd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(bd,e,t)}}bd.runtime=ar.proto3,bd.typeName="agent.v1.DecisionInput",bd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"video_path",kind:"scalar",T:9},{no:2,name:"video_duration_ms",kind:"scalar",T:3},{no:3,name:"video_width",kind:"scalar",T:5},{no:4,name:"video_height",kind:"scalar",T:5},{no:5,name:"action_count",kind:"scalar",T:5},{no:10,name:"zoom_candidates",kind:"message",T:gd,repeated:!0},{no:11,name:"idle_periods",kind:"message",T:vd,repeated:!0},{no:12,name:"click_effects",kind:"message",T:yd,repeated:!0},{no:13,name:"keystroke_events",kind:"message",T:wd,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:md,repeated:!0}]));class Sd extends ar.Message{constructor(e){super(),this.candidateIndex=0,ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Sd).fromBinary(e,t)}static fromJson(e,t){return(new Sd).fromJson(e,t)}static fromJsonString(e,t){return(new Sd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(Sd,e,t)}}Sd.runtime=ar.proto3,Sd.typeName="agent.v1.ZoomSelection",Sd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"zoom_override",kind:"scalar",T:2,opt:!0},{no:3,name:"start_ms_override",kind:"scalar",T:3,opt:!0},{no:4,name:"end_ms_override",kind:"scalar",T:3,opt:!0}]));class kd extends ar.Message{constructor(e){super(),this.candidateIndex=0,ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new kd).fromBinary(e,t)}static fromJson(e,t){return(new kd).fromJson(e,t)}static fromJsonString(e,t){return(new kd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(kd,e,t)}}kd.runtime=ar.proto3,kd.typeName="agent.v1.SpeedupSelection",kd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"speed_override",kind:"scalar",T:2,opt:!0}]));class Ed extends ar.Message{constructor(e){super(),this.cursorStyle=cd.UNSPECIFIED,this.selectedZooms=[],this.selectedSpeedups=[],this.showClickEffects=!1,this.selectedClickEffects=[],this.showKeystrokes=!1,this.cuts=[],ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ed).fromBinary(e,t)}static fromJson(e,t){return(new Ed).fromJson(e,t)}static fromJsonString(e,t){return(new Ed).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(Ed,e,t)}}Ed.runtime=ar.proto3,Ed.typeName="agent.v1.DecisionOutput",Ed.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"cursor_style",kind:"enum",T:ar.proto3.getEnumType(cd)},{no:2,name:"selected_zooms",kind:"message",T:Sd,repeated:!0},{no:3,name:"selected_speedups",kind:"message",T:kd,repeated:!0},{no:4,name:"show_click_effects",kind:"scalar",T:8},{no:5,name:"selected_click_effects",kind:"scalar",T:5,repeated:!0},{no:6,name:"show_keystrokes",kind:"scalar",T:8},{no:7,name:"cuts",kind:"message",T:xd,repeated:!0}]));class xd extends ar.Message{constructor(e){super(),this.startMs=ar.protoInt64.zero,this.endMs=ar.protoInt64.zero,this.reason="",ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new xd).fromBinary(e,t)}static fromJson(e,t){return(new xd).fromJson(e,t)}static fromJsonString(e,t){return(new xd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(xd,e,t)}}xd.runtime=ar.proto3,xd.typeName="agent.v1.VideoCut",xd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"reason",kind:"scalar",T:9}]));class Cd extends ar.Message{constructor(e){super(),this.rawVideoPath="",this.durationMs=ar.protoInt64.zero,this.displayWidth=0,this.displayHeight=0,this.apiWidth=0,this.apiHeight=0,this.recordingStartEpochMs=ar.protoInt64.zero,this.inputEvents=[],this.cursorPaths=[],this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.polishedVideoPath="",ar.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Cd).fromBinary(e,t)}static fromJson(e,t){return(new Cd).fromJson(e,t)}static fromJsonString(e,t){return(new Cd).fromJsonString(e,t)}static equals(e,t){return ar.proto3.util.equals(Cd,e,t)}}Cd.runtime=ar.proto3,Cd.typeName="agent.v1.RecordingDataPackage",Cd.fields=ar.proto3.util.newFieldList((()=>[{no:1,name:"raw_video_path",kind:"scalar",T:9},{no:2,name:"duration_ms",kind:"scalar",T:3},{no:3,name:"display_width",kind:"scalar",T:5},{no:4,name:"display_height",kind:"scalar",T:5},{no:5,name:"api_width",kind:"scalar",T:5},{no:6,name:"api_height",kind:"scalar",T:5},{no:7,name:"recording_start_epoch_ms",kind:"scalar",T:3},{no:10,name:"input_events",kind:"message",T:pd,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:md,repeated:!0},{no:30,name:"zoom_candidates",kind:"message",T:gd,repeated:!0},{no:31,name:"idle_periods",kind:"message",T:vd,repeated:!0},{no:32,name:"click_effects",kind:"message",T:yd,repeated:!0},{no:33,name:"keystroke_events",kind:"message",T:wd,repeated:!0},{no:40,name:"decision_input",kind:"message",T:bd},{no:41,name:"decision_output",kind:"message",T:Ed},{no:50,name:"polished_video_path",kind:"scalar",T:9}]));class _d{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 Pd={left_ptr:ld.ARROW,arrow:ld.ARROW,default:ld.ARROW,top_left_arrow:ld.ARROW,hand:ld.POINTER,hand1:ld.POINTER,hand2:ld.POINTER,pointer:ld.POINTER,pointing_hand:ld.POINTER,xterm:ld.TEXT,ibeam:ld.TEXT,text:ld.TEXT,watch:ld.WAIT,wait:ld.WAIT,progress:ld.WAIT,left_ptr_watch:ld.WAIT,crosshair:ld.CROSSHAIR,cross:ld.CROSSHAIR,tcross:ld.CROSSHAIR,move:ld.MOVE,fleur:ld.MOVE,size_all:ld.MOVE,sb_v_double_arrow:ld.RESIZE_NS,v_double_arrow:ld.RESIZE_NS,ns_resize:ld.RESIZE_NS,row_resize:ld.RESIZE_NS,top_side:ld.RESIZE_NS,bottom_side:ld.RESIZE_NS,sb_h_double_arrow:ld.RESIZE_EW,h_double_arrow:ld.RESIZE_EW,ew_resize:ld.RESIZE_EW,col_resize:ld.RESIZE_EW,left_side:ld.RESIZE_EW,right_side:ld.RESIZE_EW,top_left_corner:ld.RESIZE_NWSE,bottom_right_corner:ld.RESIZE_NWSE,nwse_resize:ld.RESIZE_NWSE,size_fdiag:ld.RESIZE_NWSE,top_right_corner:ld.RESIZE_NESW,bottom_left_corner:ld.RESIZE_NESW,nesw_resize:ld.RESIZE_NESW,size_bdiag:ld.RESIZE_NESW,not_allowed:ld.NOT_ALLOWED,no_drop:ld.NOT_ALLOWED,forbidden:ld.NOT_ALLOWED,circle:ld.NOT_ALLOWED,grab:ld.GRAB,openhand:ld.GRAB,grabbing:ld.GRABBING,closedhand:ld.GRABBING};class Id{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 _d(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const i=async()=>{let i,s;try{[i,s]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=i}catch{i=o,s=ld.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:i,cursorTypeAfter:s};this.events.push(a)};this.pending=this.pending.then((()=>i())).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 od("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await od("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Pd[t]??ld.ARROW}try{const e=await od("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Pd))if(e.toLowerCase().includes(t))return r}catch{}return ld.ARROW}catch{return ld.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,h.h)("computer-use-lazy");const Td=1048576,Rd=52428800;var Ad;!function(e){e.Write="write",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Ad||(Ad={}));var Od=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Md{constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path,o=(0,ao.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await To(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Et.Pi({result:{case:"rejected",value:new Et.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Et.Pi({result:{case:"permissionDenied",value:new Et.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const s=await this.pendingDecisionProvider.requestApproval({type:Ad.Delete,details:{path:o},toolCallId:t.toolCallId});if(!s.approved)return new Et.Pi({result:{case:"rejected",value:new Et.iq({path:o,reason:s.reason||""})}});let a;try{a=await(0,no.stat)(o)}catch(e){return"ENOENT"===e.code?new Et.Pi({result:{case:"fileNotFound",value:new Et.n0({path:o})}}):new Et.Pi({result:{case:"error",value:new Et.GU({path:o,error:e.message})}})}if(!a.isFile()){const e=a.isDirectory()?"directory":"other";return new Et.Pi({result:{case:"notFile",value:new Et.LX({path:o,actualType:e})}})}const l=a.size;let u;if(l<=Rd)try{u=await Mc(o)}catch{}const d=u??"";try{await(0,no.unlink)(o)}catch(e){return"EACCES"===e.code?new Et.Pi({result:{case:"permissionDenied",value:new Et.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new Et.Pi({result:{case:"fileBusy",value:new Et.vX({path:o})}}):new Et.Pi({result:{case:"error",value:new Et.GU({path:o,error:e.message})}})}if(this.fileChangeTracker&&void 0!==u){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(o,u,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Et.Pi({result:{case:"success",value:new Et.fl({path:o,deletedFile:o,fileSize:BigInt(l),prevContent:d})}})}catch(e){r.error=e,r.hasError=!0}finally{Od(r)}}}class jd{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===rt));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new sr.I0({serverIdentifier:rt,serverName:rt,instructions:`User-defined tools for this session (server "${rt}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Dd extends jd{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Nd=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),$d=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Ld{async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new Nd.uN({result:{case:"success",value:new Nd.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Nd.uN({result:{case:"error",value:new Nd.fk({url:n,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{$d(r)}}}class Fd{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n){const o=this.changes.get(e);if(o){const t=o.before,i=n||o.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:i};this.changes.set(e,n),this.notify(n)}}else{const o={path:e,before:t,after:r,metadata:n};this.changes.set(e,o),this.notify(o)}}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,no.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await function(e,t,r,n){return yc(this,void 0,void 0,(function*(){const{buffer:o}=yield jc(e,t,r,n);yield(0,no.writeFile)(e,o)}))}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}}var Ud=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Bd{async exec(e,t,r,n){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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(o,(0,c.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:s}=await Os("git",r,{cwd:t,timeout:n?.timeout});return{exitCode:0,stdout:i.toString(),stderr:s.toString()}}catch(e){o.error=e,o.hasError=!0}finally{Ud(o)}}}var zd=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const Wd=-(2**31),Hd=2**31-1;function qd(e){return Number.isNaN(e)?0:e<Wd?Wd:e>Hd?Hd:e}function Gd(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return qd(Math.trunc(e))}const Vd="agent-tools",Jd=52428800;var Kd=r("../mcp-core/dist/index.js"),Zd=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},Yd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Xd extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Qd extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class eh{constructor(e){this.disabledService=e}load(e,t,r,n,o){return Zd(this,void 0,void 0,(function*(){if(yield this.disabledService.isServerDisabled(t))throw new Xd(t);return yield o(e,r)}))}}class th{constructor(e){this.approvalService=e}load(e,t,r,n,o){return Zd(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(i,(0,c.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!(yield this.approvalService.isServerApproved(t,r,n)))throw new Qd(t);return yield o(e,r)}catch(e){i.error=e,i.hasError=!0}finally{Yd(i)}}))}}class rh{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}isServerApproved(e,t,r){return Zd(this,void 0,void 0,(function*(){const r=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,o.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(yield this.getApprovals()).includes(r)}))}loadApprovals(){return Zd(this,void 0,void 0,(function*(){try{const e=yield(0,no.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(yield this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}))}getApprovals(){return Zd(this,void 0,void 0,(function*(){return this.approvalsPromise}))}addApproval(e){return Zd(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise;t.includes(e)||(t.push(e),yield this.saveApprovals(t))}))}addApprovals(e){return Zd(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),yield this.saveApprovals(t))}))}removeApproval(e){return Zd(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&(yield this.saveApprovals(r))}))}clearApprovals(e){return Zd(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&(yield this.saveApprovals(r))}))}saveApprovalsToFile(e){return Zd(this,void 0,void 0,(function*(){yield(0,no.mkdir)(a.dirname(this.approvalsPath),{recursive:!0}),yield(0,no.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}))}saveApprovals(e){return Zd(this,void 0,void 0,(function*(){yield this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}))}}var nh=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},oh=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ih=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class sh{load(e,t,r,n,o){return nh(this,void 0,void 0,(function*(){const n=o(e,r);return new lh(e,t,n,r)}))}}function ah(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class lh{constructor(e,t,r,n){var o,i;this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=null===(i=null===(o=(0,c.fU)(e))||void 0===o?void 0:o.spanContext())||void 0===i?void 0:i.traceId,this.toolsPromise=this.clientPromise.then((t=>nh(this,void 0,void 0,(function*(){return null===t?[]:yield t.getTools(e)})))),this.resourcesPromise=this.clientPromise.then((t=>nh(this,void 0,void 0,(function*(){return null===t?[]:(yield t.listResources(e)).resources})))),this.promptsPromise=this.clientPromise.then((t=>nh(this,void 0,void 0,(function*(){return null===t?[]:yield t.listPrompts(e)})))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}getTools(e){return nh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=oh(r,(0,c.VI)(e.withName("CachedMcpClient.getTools")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=ah(this.toolsPromise);return void 0!==o?o:yield this.toolsPromise}catch(e){r.error=e,r.hasError=!0}finally{ih(r)}}))}callTool(e,t,r,n,o){return nh(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const s=oh(i,(0,c.VI)(e.withName("CachedMcpClient.callTool")),!1),a=yield this.getClient(s.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(s.ctx,t,r,n,o)}catch(e){i.error=e,i.hasError=!0}finally{ih(i)}}))}getInstructions(e){return nh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=oh(t,(0,c.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=yield this.getClient(r.ctx);if(null===n)return;return yield n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{ih(t)}}))}getClient(e){return nh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=oh(r,(0,c.VI)(e.withName("CachedMcpClient.getClient")),!1);return n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined"),yield this.clientPromise}catch(e){r.error=e,r.hasError=!0}finally{ih(r)}}))}listResources(e){return nh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=oh(r,(0,c.VI)(e.withName("CachedMcpClient.listResources")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=ah(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:yield this.resourcesPromise}}catch(e){r.error=e,r.hasError=!0}finally{ih(r)}}))}readResource(e,t){return nh(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=oh(r,(0,c.VI)(e.withName("CachedMcpClient.readResource")),!1),o=yield this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{ih(r)}}))}listPrompts(e){return nh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=oh(r,(0,c.VI)(e.withName("CachedMcpClient.listPrompts")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=ah(this.promptsPromise);return void 0!==o?o:yield this.promptsPromise}catch(e){r.error=e,r.hasError=!0}finally{ih(r)}}))}getPrompt(e,t,r){return nh(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=oh(n,(0,c.VI)(e.withName("CachedMcpClient.getPrompt")),!1),i=yield this.getClient(o.ctx);return null===i?{messages:[]}:i.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{ih(n)}}))}getState(e){return nh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=oh(t,(0,c.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=yield this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return yield n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{ih(t)}}))}close(){return nh(this,void 0,void 0,(function*(){var e;try{const t=yield this.clientPromise;yield null===(e=null==t?void 0:t.close)||void 0===e?void 0:e.call(t)}catch(e){}}))}}function ch(e){var t,r;const n=e;if(!n.resource||"object"!=typeof n.resource)return n.uri?`Resource: ${n.uri}${n.name?` (${n.name})`:""}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`;{const e=n.resource;if("string"==typeof e.text)return e.text;if("string"!=typeof e.blob)return`Resource: ${null!==(r=e.uri)&&void 0!==r?r:"unknown"}${e.name?` (${e.name})`:""}`;try{return Buffer.from(e.blob,"base64").toString("utf8")}catch(r){return`[Binary resource: ${null!==(t=e.uri)&&void 0!==t?t:"unknown"}]`}}}const uh=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function dh(e,t){if("string"==typeof e)return function(e,t){return e.replace(uh,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}const i=t(n);return void 0!==i?i:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>dh(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=dh(o,t);return r}return e}const hh=Yo.z.object({type:Yo.z.literal("stdio").optional(),command:Yo.z.string(),args:Yo.z.array(Yo.z.string()).optional(),env:Yo.z.record(Yo.z.string(),Yo.z.string()).optional(),cwd:Yo.z.string().optional()}),ph=Yo.z.object({CLIENT_ID:Yo.z.string(),CLIENT_SECRET:Yo.z.string().optional(),scopes:Yo.z.array(Yo.z.string()).optional()}),fh=Yo.z.object({caBundle:Yo.z.string().trim().min(1).max(131072)}).strict(),mh=Yo.z.object({type:Yo.z.enum(["http","sse"]).optional(),url:Yo.z.string(),headers:Yo.z.record(Yo.z.string(),Yo.z.string()).optional(),auth:ph.optional(),tls:fh.optional()}),gh=Yo.z.union([hh,mh]),vh=Yo.z.object({mcpServers:Yo.z.record(Yo.z.string(),gh)});function yh(e){return t=this,r=arguments,o=function*(e,t=e=>process.env[e]){try{const r=yield(0,no.readFile)(e,"utf8"),n=dh((0,Ki.qg)(r),t);return vh.parse(n)}catch(e){return{mcpServers:{}}}},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}var wh=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");const bh={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"consent"}},Sh=new Map([["gmailmcp.googleapis.com",Object.assign(Object.assign({},bh),{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",Object.assign(Object.assign({},bh),{scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]})],["calendarmcp.googleapis.com",Object.assign(Object.assign({},bh),{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",Object.assign(Object.assign({},bh),{scopes:["https://www.googleapis.com/auth/documents"]})],["sheetsmcp.googleapis.com",Object.assign(Object.assign({},bh),{scopes:["https://www.googleapis.com/auth/spreadsheets"]})],["slidesmcp.googleapis.com",Object.assign(Object.assign({},bh),{scopes:["https://www.googleapis.com/auth/presentations"]})]]);new Set([...Sh].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e)));const kh=["cursor"],Eh="http://localhost:8787/callback";function xh(e){return`${e}://anysphere.cursor-mcp/oauth/callback`}function Ch(e){const t=new Set,r=void 0!==e&&function(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch(e){return!1}}(e);e&&!r&&t.add(e);for(const e of Array.from(new Set([...kh])).map(xh))t.add(e);return t.add("https://www.cursor.com/agents/mcp/oauth/callback"),t.add(Eh),e&&r&&t.add(e),Array.from(t)}var _h=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),Ph=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Ih=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Th=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),Rh=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),Ah=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"),Oh=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},Mh=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jh=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dh=["authorization_code","refresh_token"],Nh=["code"];class $h{constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,o.randomUUID)(),this._oauthState=function(e,t,r){const n=Object.assign({id:e,owner:t},r?{attemptId:r}:{});return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}saveClientInformation(e){return Oh(this,void 0,void 0,(function*(){this._clientInformation=e,yield this._saveClientInformation(e)}))}tokens(){return this._tokens}saveTokens(e){return Oh(this,void 0,void 0,(function*(){this._tokens=e,yield this._saveTokens(e)}))}prepareForRefresh(){return Oh(this,void 0,void 0,(function*(){var e;yield null===(e=this._prepareForRefresh)||void 0===e?void 0:e.call(this)}))}releaseRefreshLeaseOnError(e){return Oh(this,void 0,void 0,(function*(){var t;yield null===(t=this._releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(this,e)}))}invalidateCredentials(e){return Oh(this,void 0,void 0,(function*(){var t;switch(e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0;break;default:return e}yield null===(t=this._invalidateCredentials)||void 0===t?void 0:t.call(this,e)}))}redirectToAuthorization(e){(0,Kd.E_S)(e,this._scopes),void 0!==this._serverUrl&&function(e,t){var r;let n;try{n=new URL(t).hostname}catch(e){return}const o=null===(r=function(e){return Sh.get(e.toLowerCase())}(n))||void 0===r?void 0:r.authorizationParams;if(void 0!==o)for(const[t,r]of Object.entries(o))e.searchParams.set(t,r)}(e,this._serverUrl),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}saveCodeVerifier(e){return Oh(this,void 0,void 0,(function*(){this._codeVerifier=e}))}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}function Lh(e){return Oh(this,void 0,void 0,(function*(){var t;const{serverName:r,config:n,tokenStorage:o,authRedirectUrl:i}=e,s=function(e,t){if(e)return Object.assign(Object.assign({client_id:e.CLIENT_ID},e.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{}),{redirect_uris:Ch(t),grant_types:[...Dh],response_types:[...Nh],token_endpoint_auth_method:"none"})}(n.auth,i),a=function({storedClientInformation:e,staticClientInformation:t}){var r,n,o,i;return t?e&&e.client_id===t.client_id?Object.assign(Object.assign(Object.assign({},t),e),{client_secret:null!==(r=t.client_secret)&&void 0!==r?r:e.client_secret,redirect_uris:t.redirect_uris,grant_types:null!==(n=e.grant_types)&&void 0!==n?n:t.grant_types,response_types:null!==(o=e.response_types)&&void 0!==o?o:t.response_types,token_endpoint_auth_method:null!==(i=e.token_endpoint_auth_method)&&void 0!==i?i:t.token_endpoint_auth_method}):t:e}({storedClientInformation:yield o.loadClientInformation(),staticClientInformation:s});return new $h({identifier:r,redirectUrl:i,serverUrl:n.url,clientMetadata:{redirect_uris:Ch(i),token_endpoint_auth_method:"none",grant_types:[...Dh],response_types:[...Nh],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:null===(t=n.auth)||void 0===t?void 0:t.scopes,tokens:yield o.loadTokens(),clientInformation:a,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>{var e,t;return null!==(t=null===(e=o.prepareForRefresh)||void 0===e?void 0:e.call(o))&&void 0!==t?t:Promise.resolve()},releaseRefreshLeaseOnError:e=>{var t,r;return null!==(r=null===(t=o.releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(o,e))&&void 0!==r?r:Promise.resolve()},invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e)})}))}const Fh=new Set;let Uh=!1;function Bh(){for(const e of Fh)try{process.kill(e,"SIGKILL")}catch(e){}}class zh{constructor(e,t,r){this._callToolLock=Promise.resolve(),this._stateEnteredAtMs=Date.now(),this.serverName=e,this.client=t,this.tools=new Kd.B1j,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._sessionId=r.sessionId,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,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),i=this._stateKindLabel(t);if(o===i)return;const s=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch(e){return}})();(0,Kd.VDJ)({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:Object.assign({identifier:this.serverName,from:o,to:i,cause:r,serverUrlHost:a,previousStateDurationMs:s},n)})}static createClient(){return new Ph.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}setupElicitationHandler(){this.client.setRequestHandler(Ah.$9,(e=>Oh(this,void 0,void 0,(function*(){if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=yield this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:e.params.requestedSchema});return{action:t.action,content:t.content}}catch(e){return{action:"decline"}}}))))}static fromStreamableHttp(e,t,r,n,o,i,s,a){return Oh(this,void 0,void 0,(function*(){const l=new URL(t.url);o=null!=o?o:Eh;const c=yield r.loadTokens(),u=yield Lh({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o}),d=null!=i?i:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=e=>void 0===d||void 0===s?d:(0,Kd.jIB)({fetch:d,logger:s.logger,metadata:Object.assign(Object.assign({},s.metadata),{transportType:e})}),p=zh.createClient(),f=r=>{var n,o,i;const s=null!==(i=null===(o=null===(n=u.lastRedirectUrl)||void 0===n?void 0:n.toString)||void 0===o?void 0:o.call(n))&&void 0!==i?i:"",c=new zh(e,p,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:s,callback:t=>Oh(this,void 0,void 0,(function*(){try{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.");yield(0,_h.j2)(u,Object.assign({serverUrl:l.toString(),authorizationCode:t},void 0!==d?{fetchFn:d}:{})),a&&(0,Kd.VDJ)({logger:a,event:"mcp_oauth_callback_completion",metadata:Object.assign(Object.assign({identifier:e},(0,Kd.q2e)(l.toString())),(0,Kd.tBH)(u.tokens(),{expiresInIsFresh:!0}))}),c.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}))},authProvider:u,sessionId:r,config:t});return c},m=()=>Oh(this,void 0,void 0,(function*(){const r=new Ih.A(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=n?n:{})},fetch:h("sse")});try{return yield p.connect(r),new zh(e,p,{initialState:{kind:"ready"},authProvider:u,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof _h.D_)return a&&(0,Kd.VDJ)({logger:a,event:"mcp_oauth_state_transition",metadata:Object.assign(Object.assign({identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(null==c?void 0:c.refresh_token)},(0,Kd.q2e)(l.toString())),(0,Kd.X5z)(t))}),f();throw t}}));if("sse"===t.type)return m();const g=new Rh.j(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=n?n:{})},fetch:h("streamableHttp")});try{return yield p.connect(g),new zh(e,p,{initialState:{kind:"ready"},authProvider:u,sessionId:g.sessionId,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof _h.D_)return a&&(0,Kd.VDJ)({logger:a,event:"mcp_oauth_state_transition",metadata:Object.assign(Object.assign({identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(null==c?void 0:c.refresh_token)},(0,Kd.q2e)(l.toString())),(0,Kd.X5z)(t))}),f(g.sessionId);if((0,Kd.PKk)(t))return m();throw t}}))}static fromCachedSession(e,t,r,n,o){return Oh(this,arguments,void 0,(function*(e,t,r,n,o,i=Eh,s,a,l){const c=new URL(t.url),u=yield Lh({serverName:e,config:t,tokenStorage:n,authRedirectUrl:i}),d=null!=s?s:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=new Rh.j(c,{authProvider:u,sessionId:r.sessionId,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:void 0!==d&&void 0!==a?(0,Kd.jIB)({fetch:d,logger:a.logger,metadata:Object.assign(Object.assign({},a.metadata),{transportType:"streamableHttp"})}):d}),p=zh.createClient();return yield p.connect(h),new zh(e,p,{initialState:{kind:"ready"},authProvider:u,sessionId:h.sessionId,config:t,oauthLifecycleLogger:l})}))}get sessionId(){return this._sessionId}static fromCommand(e,t,r,n,o){return Oh(this,void 0,void 0,(function*(){var i,s,a;const l={stack:[],error:void 0,hasError:!1};try{Mh(l,(0,c.VI)(e.withName("McpSdkClient.fromCommand")),!1);const d=new Th.oQ(Object.assign({command:r.command,args:null!==(i=r.args)&&void 0!==i?i:[],env:n,cwd:r.cwd,stderr:"ignore"},(null==o?void 0:o.spawn)&&{spawn:o.spawn})),h=zh.createClient(),p=h.connect(d),f=null!==(s=null==o?void 0:o.connectTimeoutMs)&&void 0!==s?s: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{yield Promise.race([p,g])}catch(e){throw p.catch((()=>{})),yield d.close().catch((()=>{})),e}finally{void 0!==m&&clearTimeout(m)}const v=null!==(a=d.pid)&&void 0!==a?a:void 0;return"number"==typeof v&&(u=v,Fh.add(u),Uh||(Uh=!0,process.on("exit",Bh))),new zh(t,h,{initialState:{kind:"ready"},config:r,stdioChildPid:v})}catch(e){l.error=e,l.hasError=!0}finally{jh(l)}var u}))}close(){return Oh(this,void 0,void 0,(function*(){var e;void 0!==this._stdioChildPid&&(e=this._stdioChildPid,Fh.delete(e)),yield this.client.close()}))}getTools(e){return Oh(this,void 0,void 0,(function*(){var t,r,n;const o={stack:[],error:void 0,hasError:!1};try{if(Mh(o,(0,c.VI)(e.withName("McpSdkClient.getTools")),!1),"requires_authentication"===this.stateValue.kind)return[];try{return yield this.tools.get((()=>Oh(this,void 0,void 0,(function*(){let e;const t=[];for(;;){const r=yield this.client.listTools({cursor:e});if(t.push(...r.tools.map((e=>Object.assign(Object.assign({},e),{inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),e=r.nextCursor,void 0===e)break}return t}))))}catch(e){if(e instanceof _h.D_&&"ready"===this.stateValue.kind){const o=this.stateValue,i=null!==(n=null===(r=null===(t=this._authProvider)||void 0===t?void 0:t.lastRedirectUrl)||void 0===r?void 0:r.toString())&&void 0!==n?n:"";this.stateValue={kind:"requires_authentication",url:i,callback:e=>Oh(this,void 0,void 0,(function*(){}))},this._logStateTransition(o,this.stateValue,"runtime_unauthorized",Object.assign({},(0,Kd.X5z)(e))),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){o.error=e,o.hasError=!0}finally{jh(o)}}))}callTool(e,t,r,n,o){return Oh(this,void 0,void 0,(function*(){var i,s,a;const l={stack:[],error:void 0,hasError:!1};try{Mh(l,(0,c.VI)(e.withName("McpSdkClient.callTool")),!1).span.setAttribute("toolName",t);const u=this._callToolLock;let d;this._callToolLock=new Promise((e=>{d=e}));try{yield u,this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;try{const e=yield this.client.callTool({name:t,arguments:r});return{content:e.content,isError:void 0!==e.error}}catch(e){if(e instanceof _h.D_&&"ready"===this.stateValue.kind){const t=this.stateValue,r=null!==(a=null===(s=null===(i=this._authProvider)||void 0===i?void 0:i.lastRedirectUrl)||void 0===s?void 0:s.toString())&&void 0!==a?a:"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>Oh(this,void 0,void 0,(function*(){}))},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",Object.assign({},(0,Kd.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){l.error=e,l.hasError=!0}finally{jh(l)}}))}getInstructions(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(Mh(t,(0,c.VI)(e.withName("McpSdkClient.getInstructions")),!1),"requires_authentication"===this.stateValue.kind)return;return yield this.client.getInstructions()}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}listResources(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(Mh(t,(0,c.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();if(!(null==r?void 0:r.resources))return{resources:[]};let n;const o=[];for(;;){const e=yield this.client.listResources({cursor:n});if(o.push(...e.resources),n=e.nextCursor,void 0===n)break}return{resources:o}}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}readResource(e,t){return Oh(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{return Mh(r,(0,c.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(yield this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{jh(r)}}))}listPrompts(e){return Oh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{if(Mh(r,(0,c.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind)return[];if(!(null!==(t=this.client.getServerCapabilities())&&void 0!==t?t:{prompts:!1}).prompts)return[];const n=yield this.client.listPrompts();return(null==n?void 0:n.prompts)?n.prompts.map((e=>{var t;return{name:e.name,description:e.description,arguments:null===(t=e.arguments)||void 0===t?void 0:t.map((e=>({name:e.name,description:e.description,required:e.required})))}})):[]}catch(e){r.error=e,r.hasError=!0}finally{jh(r)}}))}getPrompt(e,t,r){return Oh(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{return Mh(n,(0,c.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(yield this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{jh(n)}}))}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}getState(e){return Oh(this,void 0,void 0,(function*(){return this.stateValue}))}updateState(e,t){const r=this.stateValue;this.stateValue=e,this._logStateTransition(r,e,null!=t?t:"explicit_update"),this._stateEnteredAtMs=Date.now()}}class Wh extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}class Hh 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 qh{constructor(e){this.tools=e}execute(e,t,r,n){return Oh(this,void 0,void 0,(function*(){const o=this.tools[e];if(!o)throw new Wh(e,Object.keys(this.tools));return o.execute(t,r,n)}))}getTools(){return Object.entries(this.tools).map((([e,t])=>Object.assign(Object.assign({},t.definition),{name:e})))}}class Gh{getClients(e){return Oh(this,void 0,void 0,(function*(){return{}}))}getClient(e,t){return Oh(this,void 0,void 0,(function*(){}))}getInstructions(e){return Oh(this,void 0,void 0,(function*(){return[]}))}getToolSet(e){return Oh(this,void 0,void 0,(function*(){return new qh({})}))}getTools(e){return Oh(this,void 0,void 0,(function*(){return[]}))}getToolsForServers(e,t){return Oh(this,void 0,void 0,(function*(){return[]}))}}class Vh{constructor(e){this.manager=e}getClients(e){return Oh(this,void 0,void 0,(function*(){return this.manager.getClients()}))}getClient(e,t){return Oh(this,void 0,void 0,(function*(){return this.manager.getClient(t)}))}getInstructions(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Mh(t,(0,c.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return yield this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}getToolSet(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Mh(t,(0,c.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return yield this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}getTools(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Mh(t,(0,c.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(yield this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}getToolsForServers(e,t){return Oh(this,void 0,void 0,(function*(){const r=new Set(t);return(yield this.getTools(e)).filter((e=>r.has(e.clientKey)))}))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}reconcileSelection(e,t,r){return Oh(this,void 0,void 0,(function*(){var n;for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{yield null===(n=null==t?void 0:t.close)||void 0===n?void 0:n.call(t)}catch(e){}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=yield r(e,n);this.manager.setClient(n,t)}}))}}class Jh{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()}closeAllClients(){return Oh(this,void 0,void 0,(function*(){const e=Object.values(this.clients);yield Promise.all(e.map((e=>Oh(this,void 0,void 0,(function*(){var t;try{yield null===(t=e.close)||void 0===t?void 0:t.call(e)}catch(e){}})))))}))}getToolSet(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Mh(t,(0,c.VI)(e.withName("McpManager.getToolSet")),!1),n=yield(0,Br.PH)(Object.entries(this.clients),(([e,t])=>t.getTools(r.ctx).then((r=>r.map((r=>Object.assign(Object.assign({},r),{clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:4}),o=Array.from(n.values()).flat(),i={};for(const e of o)i[`${e.clientName}-${e.name}`]={definition:Object.assign(Object.assign({},e),{clientKey:e.clientKey,providerIdentifier:e.clientName,toolName:e.name}),execute:(t,n,o)=>Oh(this,void 0,void 0,(function*(){const i=null==o?void 0:o.createProvider(e.clientName,e.name,n);return yield e.client.callTool(r.ctx,e.name,t,n,i)}))};return new qh(i)}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}getInstructions(e){return Oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Mh(t,(0,c.VI)(e.withName("McpManager.getInstructions")),!1),n=yield(0,Br.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new sr.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:4});return Array.from(n.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{jh(t)}}))}}Error;var Kh=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function Zh(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}class Yh{constructor(e){this.options=e,(0,Kd.VDJ)({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return Object.assign({identifier:this.options.identifier},this.options.serverUrl?{serverUrl:(0,Kd.q2e)(this.options.serverUrl)}:{})}loadTokens(){return Kh(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadTokens();return(0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Kd.tBH)(e))}),e}))}saveTokens(e){return Kh(this,void 0,void 0,(function*(){yield this.options.inner.saveTokens(e),(0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Kd.tBH)(e,{expiresInIsFresh:!0}))})}))}prepareForRefresh(){return Kh(this,void 0,void 0,(function*(){var e,t;(0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),yield null===(t=(e=this.options.inner).prepareForRefresh)||void 0===t?void 0:t.call(e)}))}releaseRefreshLeaseOnError(e){return Kh(this,void 0,void 0,(function*(){var t,r;(0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Kd.X5z)(e))}),yield null===(r=(t=this.options.inner).releaseRefreshLeaseOnError)||void 0===r?void 0:r.call(t,e)}))}loadClientInformation(){return Kh(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadClientInformation();return(0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Kd.O3I)(e))}),e}))}saveClientInformation(e){return Kh(this,void 0,void 0,(function*(){yield this.options.inner.saveClientInformation(e),(0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Kd.O3I)(e))})}))}invalidateCredentials(e){return Kh(this,void 0,void 0,(function*(){void 0!==this.options.inner.invalidateCredentials&&((0,Kd.VDJ)({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:Object.assign(Object.assign({},this.baseMetadata),{scope:e})}),yield this.options.inner.invalidateCredentials(e))}))}}class Xh{constructor(e,t){this.storage=e,this.identifier=t}loadTokens(){return Kh(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.identifier)}))}saveTokens(e){return Kh(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.identifier,e)}))}loadClientInformation(){return Kh(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.identifier)}))}saveClientInformation(e){return Kh(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.identifier,e)}))}}class Qh{constructor(e){this.inner=e}loadTokens(){return Kh(this,void 0,void 0,(function*(){}))}loadClientInformation(){return Kh(this,void 0,void 0,(function*(){}))}saveTokens(e){return Kh(this,void 0,void 0,(function*(){return this.inner.saveTokens(e)}))}saveClientInformation(e){return Kh(this,void 0,void 0,(function*(){return this.inner.saveClientInformation(e)}))}invalidateCredentials(e){return Kh(this,void 0,void 0,(function*(){var t,r;yield null===(r=(t=this.inner).invalidateCredentials)||void 0===r?void 0:r.call(t,e)}))}}var ep=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},tp=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},rp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const np=(0,h.h)("DefinitionMcpLoader");function op(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?a.join(s.homedir(),t.slice(1)):t.startsWith("./")||"."===t?a.resolve(null!=r?r:process.cwd(),t):t}function ip(e){return"function"==typeof e.getMcpNetworkControlsConfig}function sp(e){var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0}function ap(e){if(void 0!==e)return(0,o.createHash)("sha256").update((0,Kd.Fmf)(e)).digest("hex")}class lp{constructor(e){this.configPath=e,this.configPromise=yh(e)}clearCache(){this.configPromise=yh(this.configPath)}getDefinitions(e){return ep(this,arguments,void 0,(function*(e,t=!0){const r=yield this.configPromise;return Object.entries(r.mcpServers).map((([e,t])=>({identifier:e,serverConfig:t,configPath:this.configPath})))}))}}class cp{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}load(e){return ep(this,arguments,void 0,(function*(e,t=!0){var r,n,o;const i={stack:[],error:void 0,hasError:!1};try{tp(i,(0,c.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(yield this.closeAllCachedClients(),null===(n=(r=this.source).clearCache)||void 0===n||n.call(r));const s=yield this.source.getDefinitions(e,t);yield this.evictClientsOnSandboxPolicyChange(e,s);const a={};return yield(0,Br.PH)([...s],(r=>ep(this,void 0,void 0,(function*(){try{const n=t?this.clientCache.get(r.identifier):void 0,o=null!=n?n:yield this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,o),a[r.identifier]=o}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r){np.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}(e,r,t)}}))),{max:null!==(o=this.options.maxConcurrency)&&void 0!==o?o:Math.max(s.length,1)}),new Jh(a,this.options.elicitationFactory)}catch(e){i.error=e,i.hasError=!0}finally{rp(i)}}))}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}evictClientsOnSandboxPolicyChange(e,t){return ep(this,void 0,void 0,(function*(){const r=this.middlewares.find(ip);if(!r)return;let n;try{n=JSON.stringify(yield Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((e=>ep(this,void 0,void 0,(function*(){var t,n;const o=null!==(n=yield null===(t=r.getMcpNetworkControlsConfig)||void 0===t?void 0:t.call(r,function(e){var t;return"url"in e?{url:e.url}:{command:[e.command,...null!==(t=e.args)&&void 0!==t?t:[]].join(" ")}}(e.serverConfig)))&&void 0!==n?n:{};return[e.identifier,(0,Kd.Fmf)(o)]}))))))}catch(e){return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(np.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),yield this.closeAllCachedClients())}))}closeAllCachedClients(){return ep(this,void 0,void 0,(function*(){const e=[...this.clientCache.values()];this.clientCache.clear(),yield(0,Br.PH)(e,(e=>ep(this,void 0,void 0,(function*(){var t;try{yield null===(t=e.close)||void 0===t?void 0:t.call(e)}catch(e){}}))),{max:Math.max(e.length,1)})}))}loadClient(e,t,r){return ep(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{tp(n,(0,c.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=yield this.source.getDefinitions(e);if(yield this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const i=o.find((e=>e.identifier===t));if(!i)throw new Error(`MCP server "${t}" not found in config`);let s;try{s=yield this.loadDefinitionClient(e,i,r)}catch(t){throw this.handleDefinitionLoadError(e,i,t),t}return r||this.clientCache.set(t,s),s}catch(e){n.error=e,n.hasError=!0}finally{rp(n)}}))}loadDefinitionClient(e,t,n){return ep(this,void 0,void 0,(function*(){var o,i;const s=null!==(o=t.authStorageKey)&&void 0!==o?o:t.identifier,a=new Xh(this.tokenStorage,s),l=Zh(e,np),u=new Yh({inner:a,logger:l,identifier:s,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),d=n?new Qh(u):u;return function(e,t,n,o){return ep(this,arguments,void 0,(function*(e,t,n,o,i={middlewares:[],configPath:""},s){const a={stack:[],error:void 0,hasError:!1};try{const{middlewares:l,configPath:u}=i,d=tp(a,(0,c.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let h=(e,n)=>ep(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const a=tp(i,(0,c.VI)(e.withName("loadServer.next")),!1);a.span.setAttribute("serverName",t);const u=a.ctx;if("command"in n){a.span.setAttribute("kind","command");const e=l.find(ip);return yield function(e,t,n,o){return ep(this,void 0,void 0,(function*(){var i,s,a;const l=n.cwd?op({filePath:n.cwd}):void 0;let c,u;if(n.args&&n.args.length>0)c=op({filePath:n.command,baseDir:l}),u=n.args.map((e=>op({filePath:e,baseDir:l})));else{const e=(0,wh.A)(n.command);c=op({filePath:e[0],baseDir:l}),u=e.slice(1).map((e=>op({filePath:e,baseDir:l})))}const d=null!==(s=n.env)&&void 0!==s?s:{},h=yield null===(i=null==o?void 0:o.getMcpNetworkControlsConfig)||void 0===i?void 0:i.call(o,{command:[n.command,...null!==(a=n.args)&&void 0!==a?a:[]].join(" ")}),p=(0,Kd.$HQ)(h);if(void 0!==p){const{buildMcpSandboxPolicy:n}=yield Promise.resolve().then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:i}=yield Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),s=null!=l?l:process.cwd(),a=yield n(p,s);np.info(e,function(e){var t,r,n,o,i,s,a;return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===(null===(t=e.networkControlsConfig)||void 0===t?void 0:t.enabled))}, mcpNetworkMode=${null!==(s=null===(r=e.networkControlsConfig)||void 0===r?void 0:r.mcpNetworkMode)&&void 0!==s?s:"unset"}, mcpNetworkAllowlistCount=${sp(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${sp(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${sp(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist)}, sandboxPolicyHash=${null!==(a=ap(e.sandboxNetworkControlsConfig))&&void 0!==a?a:"none"}`}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:p}),function(e){var t,r,n,o,i;return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===(null===(t=e.networkControlsConfig)||void 0===t?void 0:t.enabled),mcpNetworkMode:null===(r=e.networkControlsConfig)||void 0===r?void 0:r.mcpNetworkMode,mcpNetworkAllowlistCount:sp(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist),mcpNetworkDenylistCount:sp(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist),localAgentNetworkAllowlistCount:sp(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist),sandboxPolicyHash:ap(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:p}));try{return yield zh.fromCommand(e,t,{command:c,args:u,cwd:l},d,{spawn:(e,t,r)=>i(e,t,r,a)})}catch(e){if(e instanceof o)throw new Kd.c8u(t,e);throw e}}return!0===(null==h?void 0:h.enabled)&&"no_sandbox"===h.mcpNetworkMode&&np.info(e,`Starting local MCP server "${t}" without MCP sandboxing`),zh.fromCommand(e,t,{command:c,args:u,cwd:l},d)}))}(u,t,n,e)}if("url"in n){a.span.setAttribute("kind","url");const e=null==s?void 0:s(t);return yield function(e,t,r,n,o){return ep(this,void 0,void 0,(function*(){const i=Zh(e,np),s=function(e,t){return{logger:{debug:(t,r)=>np.debug(e,t,r),info:(t,r)=>np.info(e,t,r),warn:(t,r)=>np.warn(e,t,r),error:(t,r,n)=>np.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t);return zh.fromStreamableHttp(t,r,n,r.headers,o,void 0,s,i)}))}(u,t,n,o,e)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){i.error=e,i.hasError=!0}finally{rp(i)}}));for(const e of l){const r=h;h=(n,o)=>ep(this,void 0,void 0,(function*(){return yield e.load(n,t,o,u,r)}))}return yield h(d.ctx,n)}catch(e){a.error=e,a.hasError=!0}finally{rp(a)}}))}(e,t.identifier,t.serverConfig,d,{middlewares:this.middlewares,configPath:null!==(i=t.configPath)&&void 0!==i?i:""},this.options.authRedirectUrlGenerator)}))}handleDefinitionLoadError(e,t,r){var n,o;let i=!1;try{i="handled"===(null===(o=(n=this.options).onDefinitionLoadError)||void 0===o?void 0:o.call(n,e,t,r))}catch(r){np.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 i||function(e){return e instanceof Xd||e instanceof Qd||e instanceof up}(r)}}class up extends Error{constructor(e,t,r){super(null!=r?r:"teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}class dp{constructor(e){this.blockingService=e}getMcpNetworkControlsConfig(e){return ep(this,void 0,void 0,(function*(){var t,r,n;return null!==(n=yield null===(r=(t=this.blockingService).getMcpNetworkControlsConfig)||void 0===r?void 0:r.call(t,e))&&void 0!==n?n:{}}))}load(e,t,r,n,o){return ep(this,void 0,void 0,(function*(){var n,i,s,a,l;const c={command:"command"in r?[r.command,...null!==(s=r.args)&&void 0!==s?s:[]].join(" "):void 0,url:"url"in r?r.url:void 0},u=null!==(a=yield null===(i=(n=this.blockingService).getMcpServerBlockInfo)||void 0===i?void 0:i.call(n,c))&&void 0!==a?a:{blocked:yield this.blockingService.isServerBlocked(c)};if(u.blocked)throw new up(t,null!==(l=u.reason)&&void 0!==l?l:"teamPolicy",u.message);return o(e,r)}))}}class hp extends cp{constructor(e,t,r=[],n,o){super(new lp(e),t,r,{authRedirectUrlGenerator:n,elicitationFactory:o}),this.configPath=e,this.elicitationFactory=o}static init(e,t,r=[]){return new hp(t,e,r)}}function pp(e){var t;return"stdio"===e.type&&e.command?{command:e.command,args:null!==(t=e.args)&&void 0!==t?t:[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth}:void 0}r("../mcp-agent-exec/dist/mcp-sandbox-policy.js");var fp=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class mp{constructor(e){this.mcpAuthPath=e;const t=mp.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,mp.mcpAuthPromises.set(e,t),t.catch((()=>{mp.mcpAuthPromises.get(e)===t&&mp.mcpAuthPromises.delete(e)}))}mp.saveLocks.has(e)||mp.saveLocks.set(e,Promise.resolve())}loadMcpAuth(){return fp(this,void 0,void 0,(function*(){try{const e=yield(0,no.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t))e[r]={tokens:n};return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?n.tokens:void 0,clientInfo:"clientInfo"in n?n.clientInfo:void 0});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}))}loadTokens(e){return fp(this,void 0,void 0,(function*(){var t;return null===(t=(yield this.mcpAuthPromise)[e])||void 0===t?void 0:t.tokens}))}saveTokens(e,t){return fp(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>fp(this,void 0,void 0,(function*(){const r=yield this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,yield this.saveMcpAuth(r)}))))}))}loadClientInformation(e){return fp(this,void 0,void 0,(function*(){var t;return null===(t=(yield this.mcpAuthPromise)[e])||void 0===t?void 0:t.clientInfo}))}withSaveLock(e){return fp(this,void 0,void 0,(function*(){var t;const r=null!==(t=mp.saveLocks.get(this.mcpAuthPath))&&void 0!==t?t:Promise.resolve();let n;mp.saveLocks.set(this.mcpAuthPath,new Promise((e=>{n=e})));try{return yield r,yield e()}finally{n()}}))}saveClientInformation(e,t){return fp(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>fp(this,void 0,void 0,(function*(){const r=yield this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,yield this.saveMcpAuth(r)}))))}))}deleteCredentials(e){return fp(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>fp(this,void 0,void 0,(function*(){const t=yield this.mcpAuthPromise;e in t&&(delete t[e],yield this.saveMcpAuth(t))}))))}))}saveMcpAuth(e){return fp(this,void 0,void 0,(function*(){yield(0,no.mkdir)(a.dirname(this.mcpAuthPath),{recursive:!0}),yield(0,no.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}))}}mp.mcpAuthPromises=new Map,mp.saveLocks=new Map;var gp=r("../proto/dist/generated/agent/v1/utils_pb.js");let vp;function yp(){if(void 0===vp){const e=function(){return e=this,t=void 0,o=function*(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:i},{default:s},{default:a},{methods:l}]=yield Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,i,s,a],plugins:[l]})},new((n=void 0)||(n=Promise))((function(r,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}));var e,t,n,o}().catch((t=>{throw vp===e&&(vp=void 0),t}));vp=e}return vp}const wp=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bp=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sp=e=>wp().encode(e);var kp=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Ep=1048576,xp=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Cp=(e,t,r=1024)=>{let n=e,o=t;return e>t?e>r&&(n=r,o=Math.max(1,Math.round(t*r/e))):t>r&&(o=r,n=Math.max(1,Math.round(e*r/t))),{width:n,height:o,needsResize:n!==e||o!==t}},_p=e=>kp(void 0,void 0,void 0,(function*(){if(bp(e))return(e=>kp(void 0,void 0,void 0,(function*(){const t=(e=>{if(!bp(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(void 0!==t&&!Cp(t.width,t.height,1280).needsResize&&e.length<=Ep)return{data:xp(e),mimeType:"image/webp"};const r=yield(n=e,wp().decode(n));var n;const o=(yield yp()).fromBitmap({data:Buffer.from(r.data),width:r.width,height:r.height});let{width:i,height:s,needsResize:a}=Cp(o.bitmap.width,o.bitmap.height,1280);a&&o.resize({w:i,h:s});let l=yield Sp({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});for(;l.length>Ep&&i>1&&s>1;)i=Math.max(1,Math.round(.8*i)),s=Math.max(1,Math.round(.8*s)),o.resize({w:i,h:s}),l=yield Sp({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});return{data:xp(l),mimeType:"image/webp"}})))(e);const t=yield yp(),r=yield t.read(e),n=(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"}})(r),{width:o,height:i,needsResize:s}=Cp(r.width,r.height);if(!s&&e.length<=Ep)return{data:xp(e),mimeType:n};let a=o,l=i;s&&r.resize({w:a,h:l});let c=yield r.getBuffer(n);for(;c.length>Ep&&a>1&&l>1;)a=Math.max(1,Math.round(.8*a)),l=Math.max(1,Math.round(.8*l)),r.resize({w:a,h:l}),c=yield r.getBuffer(n);return{data:xp(c),mimeType:n}}));var Pp=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ip=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tp=(0,p.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),Rp=(0,p.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),Ap=(0,p.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),Op=(0,p.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),Mp=(0,p.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"]}),jp=(0,p.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"]}),Dp=(0,h.h)("McpFileSystemWriter"),Np="mcpFsStructuredLogOptIn";function $p(e,t){return t?.includeStructuredLogs?{...e??{},[Np]:!0}:e}const Lp={debug(e,t,r,n){Dp.debug(e,t,$p(r,n))},info(e,t,r,n){Dp.info(e,t,$p(r,n))},warn(e,t,r,n){Dp.warn(e,t,$p(r,n))},error(e,t,r,n,o){Dp.error(e,t,r,$p(n,o))}},Fp="mcps",Up="tools",Bp="~staging",zp="~prev",Wp="mcp_auth",Hp="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.",qp="# >>> CURSOR MANAGED BLOCK >>>",Gp="# <<< CURSOR MANAGED BLOCK <<<",Vp=["# 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 Jp(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function Kp(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function Zp(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function Yp(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 Xp(e){if(Array.isArray(e))return e.map((e=>Xp(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,Xp(t)]));return Object.fromEntries(t)}return e}function Qp(e){return JSON.stringify(Xp(e))}function ef(e){const t=e.map((e=>({value:e,key:Qp(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function tf(e){const t=ef(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=ef(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=ef(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return Qp({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class rf{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=>{Lp.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),Lp.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,a.join)(e,".gitignore"),r=`${qp}\n${Vp}\n${Gp}\n`;let n;await(0,no.mkdir)(e,{recursive:!0});try{n=await(0,no.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==e?.code)throw e}if(void 0===n)return void await(0,no.writeFile)(t,r);const o=n.indexOf(qp),i=n.indexOf(Gp,o+30);if(-1===o||-1===i)await(0,no.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,no.writeFile)(t,e)}})((0,a.join)((0,s.homedir)(),".cursor")).catch((e=>{Lp.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,a.join)(this.projectDir,Fp);try{const e=await(0,no.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(Bp))).map((e=>(0,no.rm)((0,a.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==e?.code&&Lp.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){var t,r,n,o,i;const[s,a]=e;return e.length<2?s:st(a)?{serverIdentifiers:void 0,reason:null!==(t=null==s?void 0:s.reason)&&void 0!==t?t:null==a?void 0:a.reason}:void 0===s?a:st(s)?{serverIdentifiers:void 0,reason:null!==(r=s.reason)&&void 0!==r?r:null==a?void 0:a.reason}:{serverIdentifiers:[...new Set([...null!==(n=s.serverIdentifiers)&&void 0!==n?n:[],...null!==(o=null==a?void 0:a.serverIdentifiers)&&void 0!==o?o:[]])],reason:null!==(i=s.reason)&&void 0!==i?i:null==a?void 0:a.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){Lp.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,Qe.q6)();return e&&(t=t.with(h._O,e)),t}getLogContext(e){return e.with(h._O,this.ctx.get(h._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return Zp(this.mcpAuthCopyOverrides?.authToolDescription)??Hp}shouldExposeVirtualMcpAuthToolForStatus(e){return this.exposeVirtualMcpAuthTool&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===e)}getErrorStatusMessage(){return Zp(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=Zp(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:Wp},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool?this.getNeedsAuthStatusMessage(e):Zp(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){Lp.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${n}`);const o=await this.mcpLease.getTools(e).catch((e=>(Lp.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),i=new Set(t);return o.filter((e=>i.has(e.clientKey)))}}async getEnabledToolsByServer(e){if(this.useDirectClientTools&&void 0!==this.enabledToolsByServerProvider)try{return await this.enabledToolsByServerProvider(e)}catch(t){return void Lp.warn(this.getLogContext(e),`getEnabledToolsByServer() threw, falling back to raw direct client tool lists: ${t}`)}}async fetchClientDataForServer(e,t,r,n){const o=this.getLogContext(e),i=await Jp(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||Lp.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===i.kind||"requires_authentication"===i.kind,[a,l,c,u]=await Promise.all([s&&this.useDirectClientTools?Jp(r.getTools(e),[]).then((e=>(0===e.length&&Lp.info(o,`Direct client getTools() returned 0 tools for "${t}" (state=${i.kind})`),e))):Promise.resolve([]),s?Jp(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?Jp(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?Jp(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:l.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:c.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:u,status:Yp(i)}}buildServerDataMap(e,t,r,n,o){const i=new Map(r.map((e=>[e.clientKey,e.clientTools]))),s=new Map;for(const e of r){const t=uf(e.clientKey);s.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,a.join)(this.projectDir,Fp,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const e of t){let t=s.get(e.clientKey);if(!t){const r=uf(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,a.join)(this.projectDir,Fp,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},s.set(e.clientKey,t)}t.tools.push(e)}for(const[t,r]of s)if(0===r.tools.length){const o=i.get(t);if(o&&o.length>0){const i=n?.[t],s=void 0!==i?o.filter((e=>i.includes(e.toolName))):o;if(void 0!==i&&0===s.length){Lp.info(e,`Skipping direct client tool fallback for "${t}": settings report 0 enabled tools`);continue}Lp.info(e,`Using direct client tool fallback for "${t}": lease had 0 tools, client has ${o.length}, writing ${s.length}`),r.tools=s}}if(void 0!==o)for(const e of o){const t=e.serverIdentifier?.trim();let r=t?Array.from(s.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(s.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of s.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.status)&&(e.tools.some((e=>e.toolName===Wp))||e.tools.push({clientKey:(l={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:l.serverName,plugin:l.plugin,marketplace:l.marketplace,pluginId:l.pluginId,marketplaceId:l.marketplaceId,toolName:Wp,name:Wp,description:l.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var l;return s}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,i="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||i?n.has(o.sanitizedId)?Lp.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):Lp.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.status)&&!r.some((e=>e.toolName===Wp))){const t=e.tools.find((e=>e.toolName===Wp));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];Lp.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),i=await this.mcpLease.getInstructions(e).catch((e=>(Lp.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),s=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return Lp.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${e}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=s.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let l=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{Lp.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(l=new Set(a.filter((e=>void 0===t[e]))))}const[c,u]=await Promise.all([Promise.all(s.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,o,c,u,i),p=new Set(n),f=new Set(s.filter((e=>"error"===e.kind||"missing"===e.kind&&!l.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=d.get(e),n=h.get(e);if(void 0===n)l.has(e)?d.delete(e):Lp.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,n)),Lp.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}d.set(e,n)}}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=uf(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{Pp(r,(0,c.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!st(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,i,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(Lp.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(Lp.warn(n,`getClients() threw, defaulting to {}: ${e}`),{}))),this.getEnabledToolsByServer(e)]),a=Object.keys(i);Lp.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${a.length} clients`);const l=Object.entries(i).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(l),u=this.buildServerDataMap(e,r,c,s,o),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){Lp.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{Ip(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,a.join)(e.folderPath,Up,`${Kp(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Pp(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,a.join)(this.projectDir,Fp);await(0,no.mkdir)(i,{recursive:!0});const s=new Map;for(const e of t)try{s.set(e.serverIdentifier,tf(e))}catch(t){Lp.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),s.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==s.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&Lp.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,no.stat)((0,a.join)(i,e.sanitizedId))}catch{Lp.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!s.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??uf(e);r.has(n)?(Lp.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),s.set(e,this.cachedFingerprints.get(e))):(Lp.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),u.add(n))}if(void 0===this.cachedServerData)try{const e=await(0,no.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(Bp)&&!e.endsWith(zp))));for(const r of e)if(r.endsWith(Bp))await(0,no.rm)((0,a.join)(i,r),{recursive:!0,force:!0});else if(r.endsWith(zp)){const e=r.slice(0,-5);if(t.has(e))await(0,no.rm)((0,a.join)(i,r),{recursive:!0,force:!0});else try{await(0,no.rename)((0,a.join)(i,r),(0,a.join)(i,e)),t.add(e)}catch{await(0,no.rm)((0,a.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);s.has(t)||s.set(t,`__preserved_${e}`)}else u.add(e)}catch(e){Lp.error(o,"Error clearing mcps directory",e)}const d=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));Lp.info(o,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-l.length,totalServerCount:t.length},{includeStructuredLogs:!0})}const h=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t<l.length;t++){const r=h[t];if("rejected"===r.status){const n=l[t],o=this.cachedFingerprints.get(n.serverIdentifier);void 0!==o?s.set(n.serverIdentifier,o):s.delete(n.serverIdentifier),Lp.error(e,"Error writing server directory",r.reason,{serverIdentifier:n.serverIdentifier,sanitizedId:n.sanitizedId},{includeStructuredLogs:!0})}}const p=await Promise.allSettled(d.map((e=>(0,no.rm)((0,a.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r<p.length;r++){const n=p[r];if("rejected"===n.status){const o=d[r];Lp.error(e,"Error removing server directory",n.reason,{sanitizedId:o,removalIndex:r,removalAttemptCount:p.length,removedServerCount:d.length,removedServerSanitizedIds:d,changedServerCount:l.length,unchangedServerCount:t.length-l.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=s}catch(e){n.error=e,n.hasError=!0}finally{Ip(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Pp(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=`${t.sanitizedId}${Bp}`,i=`${t.sanitizedId}${zp}`,s=(0,a.join)(r,o),l=(0,a.join)(r,i),u=(0,a.join)(r,t.sanitizedId);await(0,no.rm)(s,{recursive:!0,force:!0});try{await(0,no.rename)(l,u)}catch{await(0,no.rm)(l,{recursive:!0,force:!0})}await this.writeServerDirectory(e,t,{basePath:r,dirName:o});try{try{await(0,no.rename)(u,l)}catch{}await(0,no.rename)(s,u)}catch(r){Lp.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0});try{await(0,no.rename)(l,u)}catch{}throw await(0,no.rm)(s,{recursive:!0,force:!0}),r}await(0,no.rm)(l,{recursive:!0,force:!0}).catch((()=>{}))}catch(e){n.error=e,n.hasError=!0}finally{Ip(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Pp(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,a.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,no.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,a.join)(o,Up);await(0,no.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=Kp(r.toolName),n=(0,a.join)(e,`${t}.json`),o=ot(r);await(0,no.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,a.join)(o,"resources");await(0,no.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=Kp(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,a.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,no.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,a.join)(o,"prompts");await(0,no.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=Kp(r.name),n=(0,a.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,no.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,a.join)(o,"INSTRUCTIONS.md");await(0,no.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,a.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,no.writeFile)(e,r)}const i=(0,a.join)(o,"SERVER_METADATA.json"),s={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,no.writeFile)(i,JSON.stringify(s,null,2))}catch(e){n.error=e,n.hasError=!0}finally{Ip(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;Pp(r,(0,c.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&Lp.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=Kp(t.toolName),n=(0,a.join)(e.folderPath,Up,`${r}.json`);return new sr.E$({toolName:t.toolName,definitionPath:n})}));return new sr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new sr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{Ip(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&Lp.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){Lp.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&Lp.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){Lp.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{Pp(t,(0,c.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,a.join)(this.projectDir,Fp),s=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=uf(e.serverIdentifier),r=(0,a.join)(i,t),n=e.tools.map((e=>{const t=Kp(e.name);return new sr.E$({toolName:e.name,definitionPath:(0,a.join)(r,Up,`${t}.json`)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.status)&&!e.tools.some((e=>e.name===Wp))){const e=Kp(Wp);n.push(new sr.E$({toolName:Wp,definitionPath:(0,a.join)(r,Up,`${e}.json`)}))}return new sr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),l=s.reduce(((e,t)=>e+t.tools.length),0);return Lp.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${s.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,s,"snapshot"),new sr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:s})}catch(e){t.error=e,t.hasError=!0}finally{Ip(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs<rf.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{Lp.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,a.join)(this.projectDir,Fp),i=new Set,s=new Map;for(const e of t){const t=uf(e.serverIdentifier);i.add(t),s.set(t,e.tools.length)}let l=[];try{l=await(0,no.readdir)(o),l=l.filter((e=>!e.endsWith(Bp)&&!e.endsWith(zp)))}catch(e){if("ENOENT"!==e?.code)throw e}const c=new Set(l);let u=!0,d=0,h=0,p=0;const f=0===(m=i.size)?"0":m<=3?"1-3":m<=6?"4-6":m<=10?"7-10":"11+";var m;for(const t of i)c.has(t)||(u=!1,d++,Tp.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),Lp.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of c)i.has(t)||(u=!1,h++,Tp.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!c.has(t))continue;const l=s.get(t)??0,d=(0,a.join)(o,t,Up);let h=0;try{h=(await(0,no.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==l&&(u=!1,p++,Tp.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),Lp.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:l,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}Rp.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),Ap.gauge(e,i.size,this.getMetricTags({mcp_source:r})),Op.gauge(e,c.size,this.getMetricTags({mcp_source:r})),Mp.gauge(e,d,this.getMetricTags({mcp_source:r})),jp.gauge(e,p,this.getMetricTags({mcp_source:r})),Lp.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:c.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||Lp.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:c.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}rf.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var nf=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},of=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const sf=(0,h.h)("local-exec:mcp");function af(e,t){const r=a.relative(e,t);return""===r||!a.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${a.sep}`)}function lf(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function cf(e){return new xt._Z({content:{case:"text",value:new xt.zN({text:e})}})}function uf(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 df(e,t,r){const n=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t);if(n)return await To(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new xt.iz({result:{case:"error",value:new xt.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Ad.Mcp,details:{name:n.name,toolName:n.toolName,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId},toolCallId:t.toolCallId});return o.approved?t.smartModeApprovalOnly?new xt.iz({result:{case:"approved",value:new xt.Ke}}):null:new xt.iz({result:{case:"rejected",value:new xt.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new xt.iz({result:{case:"error",value:new xt.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new xt.iz({result:{case:"permissionDenied",value:new xt.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}})??void 0}class hf{constructor(e,t,r,n,o=4e4,i,s){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=i,this.ensureMcpServersLoaded=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=nf(r,(0,c.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(n,[i]));const s=await this.toolSet.getTools(n),l=Array.from(new Set(s.map((e=>e.clientKey)))).sort(),u=s.find((e=>e.providerIdentifier===t.providerIdentifier&&e.toolName===t.toolName)),d=await df(n,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u});if(void 0!==d)return d;const h=await this.toolSet.getToolSet(n);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(r instanceof Wh&&t.providerIdentifier.length>0&&!s.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new Hh(t.providerIdentifier,l)),r instanceof Hh)return new xt.iz({result:{case:"serverNotFound",value:new xt.JL({name:r.serverName,availableServers:r.availableServers})}});if(r instanceof Wh)return new xt.iz({result:{case:"toolNotFound",value:new xt.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(cf(t.text))}else if("resource"===t){const t=e;t.resource?.text&&f.push(cf(t.resource.text))}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),n=await _p(r);f.push(new xt._Z({content:{case:"image",value:new xt.do({data:n.data,mimeType:n.mimeType})}}))}else if("image"!==t){const t=ch(e);f.push(cf(t))}}const m=await function(e){return t=this,r=arguments,o=function*({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=yield r(n);if(void 0===o)return;const i=[];let s=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?s||(i.push(new xt._Z({content:{case:"text",value:new xt.zN({text:"",outputLocation:o})}})),s=!0):i.push(t);return i},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}({contentItems:f,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=a.join(t,Vd),n=a.join(r,`${(0,o.randomUUID)()}.txt`);await(0,no.mkdir)(a.dirname(n),{recursive:!0});const i=e.slice(0,Jd),s=i.split("\n").length,l=Buffer.byteLength(i,"utf8");return await(0,no.writeFile)(n,i,"utf8"),new gp.pV({filePath:n,sizeBytes:BigInt(l),lineCount:BigInt(s)})}(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)?ar.Struct.fromJson(p.structuredContent):void 0,v=new xt.QW({content:m,isError:p.isError,structuredContent:g});return new xt.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{of(r)}}}class pf{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=nf(r,(0,c.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new xt.kP({result:{case:"error",value:new xt.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new xt.kP({result:{case:"success",value:new xt.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const i=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);i.push(...e)}return new xt.kP({result:{case:"success",value:new xt.T2({resources:i})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new xt.kP({result:{case:"error",value:new xt.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{of(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const i=await t.listResources(e);return i&&i.resources?i.resources.map((e=>new xt.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class ff{constructor(e,t=".",r,n=[],o,i){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(et),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=nf(r,(0,c.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new xt.ZD({result:{case:"error",value:new xt.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Ad.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ar.Value.fromJson(t.server),uri:ar.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ar.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new xt.ZD({result:{case:"rejected",value:new xt.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),s=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!s)return new xt.ZD({result:{case:"error",value:new xt.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await s.getState(n)).kind)return new xt.ZD({result:{case:"error",value:new xt.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await s.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new xt.ZD({result:{case:"notFound",value:new xt.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=a.resolve(e),n=await(0,no.realpath)(r),o=a.resolve(r,t.replace(/^\/+/,""));if(!af(r,o))throw new Error("downloadPath must stay within the workspace");let i=a.dirname(o);for(;;)try{if(!af(n,await(0,no.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==lf(e))throw e;const t=a.dirname(i);if(t===i)throw e;i=t}if(await(0,no.mkdir)(a.dirname(o),{recursive:!0}),!af(n,await(0,no.realpath)(a.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,no.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==lf(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,no.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,no.writeFile)(e,t)}return new xt.ZD({result:{case:"success",value:new xt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType})}})}if(r.text)return new xt.ZD({result:{case:"success",value:new xt.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 xt.ZD({result:{case:"success",value:new xt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"blob",value:e}})}})}return new xt.ZD({result:{case:"error",value:new xt.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return sf.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new xt.ZD({result:{case:"error",value:new xt.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{of(r)}}}async function mf(e,t){const r=uf(t),n=(0,a.join)(e,"mcps",r,"tools");let o;try{o=await(0,no.readdir)(n)}catch(e){if("ENOENT"===e?.code)return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch(e){return}}(await(0,no.readFile)((0,a.join)(n,e),"utf8"))}catch{return}}))),s=new Set;for(const e of i)e&&s.add(e);return{toolNames:Array.from(s).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const gf=(0,h.h)("local-exec:mcp-disk-freshness-on-access"),vf="/mcps/",yf=(0,p.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),wf=(0,p.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),bf=(0,p.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Sf=(0,p.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),kf=new Map;function Ef(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function xf({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:i}){let s=i;if(void 0===s)try{s=await t.getState(e)}catch(t){return void gf.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=s.servers.find((e=>uf(e.serverIdentifier)===n));if(void 0===a)return;let l;try{l=await o(r,a.serverIdentifier)}catch(t){return void gf.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!l.toolsDirExists)return;const c=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),i=new Set(r),s=r.filter((e=>!o.has(e))),a=n.filter((e=>!i.has(e))),l=0===s.length&&0===a.length?"match":"mismatch",c={surface:"disk"};yf.increment(e,1,{...c,outcome:l}),wf.histogram(e,s.length,c),bf.histogram(e,a.length,c),Sf.histogram(e,s.length+a.length,c),"mismatch"===l&&gf.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:s.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:c,observedToolNames:l.toolNames})}function Cf(e,t,r,n=mf){if(void 0===r||(void 0===(o=r)||!Ef(o).includes(vf)))return;var o;const i=function(e){const t=Ef(e),r=t.indexOf(vf);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===i)return;let s,a;const l="mcps_root"===i.kind;"mcps_root"===i.kind?(s=`${i.projectDir}\0__mcps_root__`,a=void 0):(s=`${i.projectDir}\0${i.sanitizedServerFolder}`,a=i.sanitizedServerFolder);const c=kf.get(s);void 0!==c&&clearTimeout(c);const u=e,d=setTimeout((()=>{kf.delete(s),(async()=>{if(l){const e=await t.getState(u);for(const r of e.servers){const o=uf(r.serverIdentifier);await xf({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await xf({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{gf.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);kf.set(s,d)}var _f=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Pf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function If(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}function Tf(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ao.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,a.resolve)(e,t),r);return void 0===n||n===e}const Rf=(0,h.h)("local-exec/grep");function Af(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function Of(e){try{return(0,i.existsSync)(e)}catch{return"check_failed"}}function Mf(e,t,r,n){return{...Df(e),...n,cwd:t,cwdExists:Of(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function jf(e){return new Error(`Path does not exist: ${e}`)}function Df(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,i.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,i.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,a.dirname)(e);try{t.parentDirExists=(0,i.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,i.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,a.dirname)(r);try{t.grandparentDirExists=(0,i.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,i.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,i.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const e=r.concat("node_modules.asar");try{t.asarExists=(0,i.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,i.existsSync)(n),t.asarUnpackedDirExists){const e=(0,a.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,i.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class Nf{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor}computeRelativeTarget(e,t){const r=(0,ao.o1)(e,this.singleWorkspacePath);return r===t?".":(0,a.relative)(t,r)}async buildArgs(e,t,r){const n=[],o=await this.ignoreService.listCursorIgnoreFilesByRoot(e);for(const e of o)n.push("--cursor-ignore",e);if("content"===r)n.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&n.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&n.push("--after-context",String(t.contextAfter)),n.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&n.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)n.push("-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${r}`);n.push("-c","--with-filename")}!0===t.caseInsensitive?n.push("--ignore-case"):n.push("--case-sensitive"),t.type&&n.push("--type",t.type),t.glob&&n.push("--iglob",t.glob),t.multiline&&n.push("--multiline","--multiline-dotall");const i=t.sort??"modified";if("none"!==i){const e=!0===t.sortAscending?"--sort":"--sortr";n.push(e,i)}return n.push("--no-config","--color=never"),n.push("--hidden"),n.push("--follow"),n.push("--regexp",t.pattern),n.push("--"),n.push(t.path?this.computeRelativeTarget(t.path,e):"."),n}async filterBlockedFiles(e,t){const r=[];for(const n of e){const e=await iu((0,ao.o1)(n.file,t));null===e||await this.isPostRipgrepBlocked(e)||r.push(n)}return r}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,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=_f(i,(0,c.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),a=await this.buildArgs(t,r,"files_with_matches"),l=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{files:u,totalFiles:d,clientTruncated:h,ripgrepTruncated:p}=function(e,t,r){const n=e.trim(),o=""!==n?If(n):[],i=o.length,s=o.slice(0,t),a=o.length>t;return{files:s,totalFiles:qd(i),clientTruncated:a,ripgrepTruncated:i>=r}}(l.stdout,Nf.CLIENT_LIMIT_LINES,Nf.HARD_MAX_OUTPUT_LINES),f=[];for(const e of u){const r=await iu((0,ao.o1)(e,t));null===r||await this.isPostRipgrepBlocked(r)||f.push(e)}const m=u.length-f.length,g=new zd.T7({files:f,totalFiles:qd(d-m),clientTruncated:h,ripgrepTruncated:p});return new zd.vD({result:{case:"files",value:g}})}catch(e){i.error=e,i.hasError=!0}finally{Pf(i)}}async runCountMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=_f(i,(0,c.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),a=await this.buildArgs(t,r,"count"),l=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{counts:u,totalFiles:d,totalMatches:h,clientTruncated:p,ripgrepTruncated:f}=function(e,t,r){const n=e.trim(),o=""!==n?If(n):[],i=[];for(const e of o){if(""===e||void 0===e)continue;const t=e.lastIndexOf(":");if(t<=0)continue;const r=e.substring(t+1).trim(),n=parseInt(r,10);if(!Number.isFinite(n))continue;const o=e.substring(0,t);i.push({file:o,count:n})}const s=i.length,a=i.reduce(((e,t)=>e+t.count),0),l=i.slice(0,t),c=i.length>t;return{counts:l,totalFiles:qd(s),totalMatches:qd(a),clientTruncated:c,ripgrepTruncated:s>=r}}(l.stdout,Nf.CLIENT_LIMIT_LINES,Nf.HARD_MAX_OUTPUT_LINES),m=await this.filterBlockedFiles(u,t),g=m.reduce(((e,t)=>e+t.count),0),v=u.length-m.length,y=u.reduce(((e,t)=>e+t.count),0)-g,w=new zd.xA({counts:m.map((e=>new zd.sS({file:e.file,count:qd(e.count)}))),totalFiles:qd(d-v),totalMatches:qd(h-y),clientTruncated:p,ripgrepTruncated:f});return new zd.vD({result:{case:"count",value:w}})}catch(e){i.error=e,i.hasError=!0}finally{Pf(i)}}async runContentMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=_f(i,(0,c.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),a=await this.buildArgs(t,r,"content"),l=await this.executeRg(s.ctx,t,a,void 0,n,o);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,n){const o={stack:[],error:void 0,hasError:!1};try{_f(o,(0,c.VI)(n.withName("parseContentOutput")),!1);const i=""===e.trim()?[]:If(e);i.length>0&&""===i[i.length-1]&&i.pop();const s=new Map,a=new Set;let l=0,u=0;for(const e of i){if(void 0===e)continue;if("--"===e)continue;const[r,n]=e.split("\0",2);if(void 0===r||void 0===n)continue;const o=/^(\d+)([:-])(.*)$/.exec(n);if(!o)continue;const i=o[1],c=o[2],d=o[3]??"",h=parseInt(i,10);if(!Number.isFinite(h))continue;const p="-"===c;if(!1===p&&l++,a.has(r)||a.add(r),u>=t)continue;const f=s.get(r)??{file:r,matches:[]};f.matches.push({lineNumber:h,content:d,isContextLine:p}),s.set(r,f),u++}const d=a.size;return{byFile:s,totalLines:qd(i.length),totalMatchedLines:qd(l),totalFiles:qd(d),clientTruncated:u>=t,ripgrepTruncated:i.length>=r}}catch(e){o.error=e,o.hasError=!0}finally{Pf(o)}}(l.stdout,Nf.CLIENT_LIMIT_LINES,Nf.HARD_MAX_OUTPUT_LINES,s.ctx),m=Array.from(u.values()),g=await this.filterBlockedFiles(m,t),v=m.filter((e=>!g.includes(e))),y=v.reduce(((e,t)=>e+t.matches.length),0),w=v.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),b=new zd.Zp({matches:g.map((e=>new zd.uI({file:e.file,matches:e.matches.map((e=>new zd.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:qd(d-y),totalMatchedLines:qd(h-w),clientTruncated:p,ripgrepTruncated:f});return new zd.vD({result:{case:"content",value:b}})}catch(e){i.error=e,i.hasError=!0}finally{Pf(i)}}async executeIndexedGrepWithTimeout(e,t,r,n){if(void 0===this.grepProvider.executeIndexedGrep)return;const[o,i]=e.withTimeoutAndCancel(Nf.INDEXED_GREP_CONTEXT_TIMEOUT_MS),s={phase:"provider"},a=performance.now();try{return await(0,Br.wj)(this.grepProvider.executeIndexedGrep(o,t,r,s),Nf.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${Nf.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Br.MU)return void Rf.warn(e,"indexed_grep.timeout_fallback",{...n,totalMs:Math.round(performance.now()-a),...s});throw t}finally{i()}}async executeRg(e,t,r,n,o,i){const s=(0,c.VI)(e.withName("LocalGrepExecutor.executeRg")),a="utf8",l=8388608;return n=n??Nf.HARD_MAX_OUTPUT_LINES,new Promise(((c,u)=>{let d=!1,h=!1;const p=()=>{h||(h=!0,s.span.end())};let f,m;try{const e=o;f=(0,io.spawnInSandbox)((0,io.getRipgrepBinaryPath)(),r,{cwd:t},e),0}catch(r){if(p(),Af(r)){const n=r,o=(0,io.getRipgrepBinaryPath)();if(Rf.error(e,"rg_diagnostics.spawn_throw",void 0,Mf(o,t,n,i)),!1===Of(t))return u(jf(t))}return u(r)}const g=[],v=[];let y=0,w=0,b=0,S=!1;m=setTimeout((()=>{if(!d)try{p(),u(new Error(`Timed out after ${Nf.MAIN_TIMEOUT_MS/1e3}s`)),f.kill()}catch{}}),Nf.MAIN_TIMEOUT_MS),f.stdout?.on("data",(e=>{if(y+=e.length,void 0!==n&&!0!==S){let t=-1,r=0;for(let o=0;o<e.length;o++)if(10===e[o]&&(r++,b+r>=n)){t=o+1,S=!0;try{f.kill()}catch{}break}b+=r;const o=t>=0?e.subarray(0,t):e;y<=l&&g.push(o)}else!0!==S&&y<=l&&g.push(e)})),f.stderr?.on("data",(e=>{w+=e.length,w<=l&&v.push(e)})),f.on("error",(r=>{if(clearTimeout(m),p(),Af(r)){const n=(0,io.getRipgrepBinaryPath)(),o=r;if(Rf.error(e,"rg_diagnostics.spawn_enoent",void 0,Mf(n,t,o,i)),!1===Of(t))return void u(jf(t))}u(r)})),f.on("close",(e=>{d=!0,clearTimeout(m);const t=Buffer.concat(g).toString(a),r=Buffer.concat(v).toString(a);p(),c({stdout:t,stderr:r,exitCode:e??0})}))}))}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const i=_f(n,(0,c.VI)(e.withName("LocalGrepExecutor.execute")),!1),s=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content",u={toolCallId:t.toolCallId,execId:r?.execId,outputMode:l,targetPath:t.path,workspacePaths:s},d=Po(t.sandboxPolicy);try{const r=this.grepProvider.getWorktreeGuardInfo?.(s);if((0,ao.fl)({targetPath:t.path,workspacePaths:s,mainWorktreePath:r?.mainWorktreePath}))return new zd.Ud({result:{case:"error",value:new zd.ts({error:ao.PS})}});if(t.path){const r=await iu((0,ao.o1)(t.path,this.singleWorkspacePath));if(null===r)return new zd.Ud({result:{case:"error",value:new zd.ts({error:(o=t.path,`Path '${o}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`)})}});if(await this.ignoreService.isCursorIgnored(r))return new zd.Ud({result:{case:"error",value:new zd.ts({error:`Path '${t.path}' is filtered out by .cursorignore`})}});void 0!==this.mcpStateAccessor&&Cf(e,this.mcpStateAccessor,r)}let n={};const c=await this.executeIndexedGrepWithTimeout(i.ctx,s,t,u);if(void 0!==c)n=c;else for(const e of s){if(!1===Of(e))return new zd.Ud({result:{case:"error",value:new zd.ts({error:`Path does not exist: ${e}`})}});let r;if("content"===l)r=await this.runContentMode(i.ctx,e,t,d,u);else if("files_with_matches"===l)r=await this.runFilesMode(i.ctx,e,t,d,u);else{if("count"!==l)throw new Error(`Unknown output mode: ${l}`);r=await this.runCountMode(i.ctx,e,t,d,u)}n[e]=r}const h=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,a.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,a.resolve)(t),i=t=>Tf(e,t,r),s=o.result;switch(s.case){case"content":{const e=s.value,r=[];let o=0,a=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,a+=t.matches.filter((e=>!e.isContextLine)).length);n[t]=new zd.vD({result:{case:"content",value:new zd.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-o),totalMatchedLines:Math.max(0,e.totalMatchedLines-a)})}});break}case"files":{const e=s.value,r=e.files.filter((e=>i(e)));n[t]=new zd.vD({result:{case:"files",value:new zd.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=s.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;n[t]=new zd.vD({result:{case:"count",value:new zd.xA({...e,counts:r,totalFiles:Math.max(0,e.totalFiles-(e.counts.length-r.length)),totalMatches:Math.max(0,e.totalMatches-o)})}});break}default:n[t]=o}}return n}(n,s),p=new zd._0({pattern:t.pattern,path:t.path,outputMode:l,workspaceResults:h});return new zd.Ud({result:{case:"success",value:p}})}catch(e){if(t.path){const e=(0,ao.o1)(t.path,this.singleWorkspacePath);try{await(0,no.stat)(e)}catch(t){return new zd.Ud({result:{case:"error",value:new zd.ts({error:`Path does not exist: ${e}`})}})}}return new zd.Ud({result:{case:"error",value:new zd.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{Pf(n)}var o}}Nf.MAIN_TIMEOUT_MS=25e3,Nf.INDEXED_GREP_TIMEOUT_MS=25e3,Nf.INDEXED_GREP_CONTEXT_TIMEOUT_MS=Nf.INDEXED_GREP_TIMEOUT_MS+100,Nf.HARD_MAX_OUTPUT_LINES=1e4,Nf.CLIENT_LIMIT_LINES=2e3;var $f=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),Lf=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ff=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Uf{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{Lf(r,(0,c.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ao.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,no.stat)(n)}catch(e){return"ENOENT"===e.code?function(e){const t=fs(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new $f.fv({result:{case:"error",value:new $f.uj({path:n,error:"No active terminals."})}}):new $f.fv({result:{case:"error",value:new $f.uj({path:n,error:`Path does not exist: ${n}`})}}):new $f.fv({result:{case:"error",value:new $f.uj({path:n,error:e.message})}})}if(!r.isDirectory())return new $f.fv({result:{case:"error",value:new $f.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Po(t.sandboxPolicy),i=t.timeoutMs??5e3,s=e.withTimeout(i),{tree:a,didTimeout:l}=await this.getDirectoryTree(s,n,t.ignore,o);return l?new $f.fv({result:{case:"timeout",value:new $f.ze({directoryTreeRoot:a})}}):new $f.fv({result:{case:"success",value:new $f.PC({directoryTreeRoot:a})}})}catch(e){return new $f.fv({result:{case:"error",value:new $f.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Ff(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return Lf(o,(0,c.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{Ff(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{Lf(i,(0,c.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const s=(0,a.resolve)(t),l=new $f.vq({absPath:s,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(s,l);const d={charactersUsed:s.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=Vc(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:n,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,a.resolve)(t,e),n=await iu(r);null===n||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,s,u,d,o)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){i.error=e,i.hasError=!0}finally{Ff(i)}}addPathToTree(e,t,r,n,o){const i=(0,a.basename)(e),s=(0,a.dirname)(e);this.ensureDirectoryPath(s,t,r,n.budgetExceeded);const l=r.get(s);if(!l)return;const c=i.length;if(!n.budgetExceeded&&n.charactersUsed+c<=o){const e=new $f.ur({name:i});l.childrenFiles.push(e),n.charactersUsed+=c}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=s;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,a.dirname)(e);if(n===e)break;e=n}}const o=(0,a.extname)(e);let i=s;for(;i.startsWith(t);){const e=r.get(i);e&&(e.fullSubtreeExtensionCounts[o]??=0,e.fullSubtreeExtensionCounts[o]=qd(e.fullSubtreeExtensionCounts[o]+1),e.numFiles??=0,e.numFiles=qd(e.numFiles+1));const t=(0,a.dirname)(i);if(t===i)break;i=t}}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,a.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new $f.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const s=r.get(o);s&&s.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,a.basename)(e.absPath).localeCompare((0,a.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}var Bf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zf=1e4,Wf={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class Hf{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<zf){const r=Math.min(e.length,zf-t);this.fullOutput+=e.slice(0,r)}this.totalChars>zf&&(this.fullOutput="")}getOutput(){return this.totalChars<=zf?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=zf))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-zf}}}function qf(e,t){const r=Td-e.length;return r<=0?e:e+t.slice(0,r)}function Gf(e,t){return null!==e?e:null===t?-1:-s.constants.signals[t]}class Vf{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},i=r.exceptionInfo.length>0,s=0!==r.returncode||i?{case:"failure",value:new Ct.xC({...o,aborted:i,abortReason:r.abortReason})}:{case:"success",value:new Ct.QR(o)};return new Ct.W4({result:s,sandboxPolicy:Io(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const i=performance.now(),s=r,a=(await(0,io.resolveSandboxPolicyForWorkspace)(s,n?{perRepo:n}:void 0)).policy,l="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:s}:a;return await new Promise((n=>{const s=new Hf;let a,c,u="",d="",h=!1,p=!1,f="",m=()=>{};const g=(0,io.withConfiguredRipgrepEnv)({...process.env,...Wf,CURSOR_AGENT:"1"}),v={shell:!0,cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform},y="insecure_none"===l.type?(0,Cs.spawn)(t.command,[],v):(0,io.spawnInSandbox)(t.command,[],v,l);y.stdin?.end();const w=e=>{h||(h=!0,clearTimeout(c),m(),n({...e,output:s.getOutput(),outputTruncation:s.getTruncation(),localExecutionTimeMs:Gd(performance.now()-i)}))};c=setTimeout((()=>{if(p=!0,void 0===a&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,a=Ct.Lv.TIMEOUT,m()),void 0!==y.pid&&"win32"!==process.platform)try{return void process.kill(-y.pid,"SIGKILL")}catch{}y.kill("SIGKILL")}),o);const b=()=>{if(void 0===a){if(f="An error occurred while executing the command: Command aborted",a=Ct.Lv.USER_ABORT,void 0!==y.pid&&"win32"!==process.platform)try{return void process.kill(-y.pid,"SIGTERM")}catch{}y.kill("SIGTERM")}};e.signal.aborted?b():(e.signal.addEventListener("abort",b,{once:!0}),m=()=>{e.signal.removeEventListener("abort",b)}),y.stdout?.on("data",(e=>{const t=e.toString();u=qf(u,t),s.append(t)})),y.stderr?.on("data",(e=>{const t=e.toString();d=qf(d,t),s.append(t)})),y.on("error",(e=>{w({stdout:u,stderr:d,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),y.on("close",((e,t)=>{w({stdout:u,stderr:d,returncode:f.length>0?-1:Gf(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:a})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,i=(0,ao.o1)(t.workingDirectory||this.defaultCwd),s=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new Ct.W4({result:{case:"spawnError",value:new Ct.mJ({command:o,workingDirectory:i,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?Po(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:i,timeout:s,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new Ct.W4({result:{case:"permissionDenied",value:new Ct.jn({command:o,workingDirectory:i,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Ct.W4({result:{case:"rejected",value:new Ct.pZ({command:o,workingDirectory:i,reason:Ro(l.reason)})}});a=l.policy,vo()&&(a=Eo(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:n,args:t,workingDirectory:i,sandboxPolicy:a,timeoutMs:s});return this.buildResult({args:t,workingDirectory:i,processResult:u,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{Bf(r)}}}var Jf=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),Kf=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const Zf=51200;function Yf(e){return Buffer.byteLength(e,"utf8")}function Xf(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function Qf(e){return new Kf.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 em(e,t){const r=t?.maxLines??2e3,n=t?.maxBytes??Zf,o=e.split("\n"),i=o.length;if(Yf(o[0]??"")>n)return{content:"",truncation:Qf({truncated:!0,truncatedBy:"bytes",totalLines:i,outputLines:0,outputBytes:0,maxLines:r,maxBytes:n,firstLineExceedsLimit:!0})};const s=[];let a,l=0;for(let e=0;e<o.length;e++){if(s.length>=r){a="lines";break}const t=o[e],i=s.length>0?1:0,c=Yf(t)+i;if(l+c>n){a="bytes";break}s.push(t),l+=c}return{content:s.join("\n"),truncation:Qf({truncated:void 0!==a,truncatedBy:a,totalLines:i,outputLines:s.length,outputBytes:l,maxLines:r,maxBytes:n})}}function tm(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});async function nm(e){const{content:t,truncation:r}=function(e){const t=Zf,r=e.split("\n"),n=r.length,o=[];let i,s=0,a=!1;for(let e=r.length-1;e>=0;e--){if(o.length>=2e3){i="lines";break}const n=r[e],l=o.length>0?1:0,c=Yf(n)+l;if(s+c>t){if(i="bytes",0===o.length){const e=Buffer.from(n,"utf8");o.unshift(e.subarray(Math.max(0,e.length-t)).toString("utf8")),s=Yf(o[0]),a=!0}break}o.unshift(n),s+=c}return{content:o.join("\n"),truncation:Qf({truncated:void 0!==i,truncatedBy:i,totalLines:n,outputLines:o.length,outputBytes:s,maxLines:2e3,maxBytes:t,lastLinePartial:a})}}(e||"(no output)");if(!r.truncated)return{output:t};const n=await(0,no.mkdtemp)((0,a.join)((0,s.tmpdir)(),"pi-bash-")),o=(0,a.join)(n,"output.log");await(0,no.writeFile)(o,e,"utf8");const i=r.totalLines-r.outputLines+1,l=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${Xf(r.outputBytes)} of line ${l} (${Xf(Zf)} limit). Full output: ${o}]`:`[Showing lines ${i}-${l} of ${r.totalLines}. Full output: ${o}]`}`,fullOutputPath:o,truncation:r}}class om{constructor(e){this.shellExecutor=e}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiBashExecutor.execute")),!1),i=await this.shellExecutor.execute(o.ctx,function(e,t){const r=void 0!==e.timeout&&e.timeout>0?Math.round(1e3*e.timeout):2147483647,n=e.command.trim().split(/\s+/)[0]??"";return new Ct.a({command:e.command,timeout:r,toolCallId:t?.execId??"",fileOutputThresholdBytes:BigInt(0),parsingResult:new Ct.HO({parsingFailed:!1,executableCommands:[{name:n,fullText:e.command,args:[]}]})})}(t,r),r);switch(i.result.case){case"success":{const e=await nm(`${i.result.value.stdout}${i.result.value.stderr}`);return new Jf.AH({result:{case:"success",value:new Jf.cV(e)}})}case"failure":{const e=await nm(`${i.result.value.stdout}${i.result.value.stderr}`);return new Jf.AH({result:{case:"success",value:new Jf.cV({...e,output:`${e.output}\n\nCommand exited with code ${i.result.value.exitCode}`})}})}case"timeout":return this.error(`Command timed out after ${Math.round(i.result.value.timeoutMs/1e3)} seconds`);case"rejected":return this.error(i.result.value.reason||"Command aborted");case"permissionDenied":case"spawnError":return this.error(i.result.value.error);default:return this.error("Command failed")}}catch(e){n.error=e,n.hasError=!0}finally{rm(n)}}error(e){return new Jf.AH({result:{case:"error",value:new Jf.bD({error:e})}})}}var im=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function sm(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;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 am=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function lm(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function cm(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 um(e,t){if(0===t.length)return 0;let r=0,n=e.indexOf(t);for(;-1!==n;)r++,n=e.indexOf(t,n+t.length);return r}function dm(e,t){const r=e.split("\n"),n=t.split("\n"),o=Math.max(r.length,n.length);for(let e=0;e<o;e++)if(r[e]!==n[e])return e+1}const hm=new Map;async function pm(e,t){const r=await async function(e){try{return await(0,no.realpath)(e)}catch{return e}}(e),n=hm.get(r)??Promise.resolve();let o;const i=new Promise((e=>{o=e})),s=n.then((()=>i));hm.set(r,s),await n;try{return await t()}finally{o(),hm.get(r)===s&&hm.delete(r)}}function fm(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,Gl.fileURLToPath)(r)),("~"===r||r.startsWith("~/"))&&(r=(0,a.join)((0,s.homedir)(),r.slice(2))),(0,a.normalize)((0,a.isAbsolute)(r)?r:(0,a.resolve)(t??process.cwd(),r))}var mm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class gm{constructor(e,t,r){this.permissionsService=e,this.writeExecutor=t,this.workspacePath=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiEditExecutor.execute")),!1),i=fm(t.path,this.workspacePath);return pm(i,(async()=>{const e=await this.permissionsService.shouldBlockRead(i);if(e)return this.error(`Read blocked: ${sm(e)}`);try{if((await(0,no.stat)(i)).isDirectory())return this.error(`Path is a directory: ${i}`);const e=(await(0,no.readFile)(i)).toString("utf8"),n=function(e,t,r){if(0===r.length)throw new Error("edits must contain at least one replacement.");const{bom:n,text:o}=65279===(i=t).charCodeAt(0)?{bom:i[0],text:i.slice(1)}:{bom:"",text:i};var i;const s=function(e){return e.includes("\r\n")?"\r\n":"\n"}(o),a=lm(o),{matches:l,matchedContent:c}=function(e,t){const r=[];let n=!1;for(const o of t){if(0===o.oldText.length)throw new Error("oldText must not be empty.");const t=lm(o.oldText),i=um(e,t);if(1!==i){if(i>1)throw new Error("oldText must be unique in the file.");n=!0;break}r.push({index:e.indexOf(t),length:t.length,replacement:lm(o.newText)})}if(!n)return{matches:r,matchedContent:e};const o=cm(e),i=[];for(const e of t){const t=cm(lm(e.oldText)),r=um(o,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.");i.push({index:o.indexOf(t),length:t.length,replacement:cm(lm(e.newText))})}return{matches:i,matchedContent:o}}(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 n=e;for(const e of r.reverse())n=n.slice(0,e.index)+e.replacement+n.slice(e.index+e.length);return n}(c,l);if(u===a)throw new Error("edits did not change the file.");const d=n+function(e,t){return"\n"===t?e:e.replace(/\n/g,"\r\n")}(u,s),h=(0,am.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:h,patch:h,firstChangedLine:dm(a,u)}}(t.path,e,t.edits),s=await this.writeExecutor.execute(o.ctx,new _t.hY({path:i,fileText:n.newContent,toolCallId:r?.execId??""}),r);switch(s.result.case){case"success":return new im.u7({result:{case:"success",value:new im.uL({output:`Successfully replaced ${t.edits.length} block(s) in ${t.path}.`,diff:n.diff,patch:n.patch,firstChangedLine:n.firstChangedLine})}});case"rejected":return new im.u7({result:{case:"rejected",value:new im.pE({reason:s.result.value.reason})}});default:return this.error(this.writeErrorMessage(s.result.value,t.path))}}catch(e){return this.error(e instanceof Error?e.message:"Unknown edit error")}}))}catch(e){n.error=e,n.hasError=!0}finally{mm(n)}}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 im.u7({result:{case:"error",value:new im.Nd({error:e})}})}}var vm=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),ym=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wm(e){return e.split(a.sep).join("/")}class bm{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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiFindExecutor.execute")),!1);const n=fm(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Find blocked: ${sm(o)}`);try{if(!(await(0,no.stat)(n)).isDirectory())return this.error(`Not a directory: ${n}`);const e=Math.max(1,t.limit??1e3),r=await async function(e,t,r){const n=[];return await async function e(o){if(n.length>=t)return;const i=await(0,no.readdir)(o,{withFileTypes:!0});for(const s of i){if(n.length>=t)return;if(".git"===s.name||"node_modules"===s.name)continue;const i=(0,a.join)(o,s.name);await r(i)&&(n.push(i+(s.isDirectory()?a.sep:"")),s.isDirectory()&&await e(i))}}(e),n}(n,e,(async e=>!await this.permissionsService.shouldBlockRead(e))),o=t.pattern.includes("/")&&!t.pattern.startsWith("**/")?`**/${t.pattern}`:t.pattern,i=r.map((e=>({raw:e,relative:wm((0,a.relative)(n,e))}))).filter((({relative:e})=>(0,Ko.xF)(e,o,{dot:!0})));if(0===i.length)return this.success("No files found matching pattern");const s=em(i.map((e=>e.relative)).join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=r.length>=e?e:void 0,c=[];return void 0!==l&&c.push(`${e} results limit reached. Use limit=${2*e} for more, or refine pattern`),s.truncation.truncated&&c.push(`${Xf(Zf)} limit reached`),this.success(c.length>0?`${s.content}\n\n[${c.join(". ")}]`:s.content,{resultLimitReached:l,truncation:s.truncation.truncated?s.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{ym(r)}}success(e,t){return new vm.bT({result:{case:"success",value:new vm.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new vm.bT({result:{case:"error",value:new vm.Uy({error:e})}})}}var Sm=r("node:readline"),km=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),Em=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xm{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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiGrepExecutor.execute")),!1);const n=fm(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Search blocked: ${sm(o)}`);try{const e=(await(0,no.stat)(n)).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,n);const o=(0,Cs.spawn)((0,io.getRipgrepBinaryPath)(),r,{stdio:["ignore","pipe","pipe"]}),i=[];let s="",a=!1;const l=Math.max(1,t.limit??100),c=(0,Sm.createInterface)({input:o.stdout});o.stderr?.on("data",(e=>{s+=e.toString()})),c.on("line",(e=>{if(i.length>=l||0===e.trim().length)return;const t=JSON.parse(e);if("match"!==t.type)return;const r=t.data?.path?.text,n=t.data?.line_number;void 0!==r&&void 0!==n&&(i.push({filePath:r,lineNumber:n,lineText:t.data?.lines?.text?.replace(/\n$/,"")}),i.length>=l&&(a=!0,o.kill()))}));const u=await new Promise(((e,t)=>{o.on("error",t),o.on("close",e)}));if(c.close(),!a&&0!==u&&1!==u)return this.error(s.trim()||`ripgrep exited with code ${u}`);if(0===i.length)return this.success("No matches found");const d=[];for(const e of i)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,n,e,Math.max(0,t.context??0)),f=em(h,{maxLines:Number.MAX_SAFE_INTEGER}),m=[];return a&&m.push(`${l} matches limit reached. Use limit=${2*l} for more, or refine pattern`),f.truncation.truncated&&m.push(`${Xf(Zf)} 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?l: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{Em(r)}}async formatMatches(e,t,r,n){const o=[];let i=!1;for(const s of e){const e=r?(0,a.relative)(t,s.filePath):(0,a.basename)(s.filePath);if(0===n&&void 0!==s.lineText){const t=tm(s.lineText);i=i||t.wasTruncated,o.push(`${e}:${s.lineNumber}: ${t.text}`);continue}const l=(await(0,no.readFile)(s.filePath,"utf8")).replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n"),c=Math.max(1,s.lineNumber-n),u=Math.min(l.length,s.lineNumber+n);for(let t=c;t<=u;t++){const r=tm(l[t-1]??"");i=i||r.wasTruncated,o.push(t===s.lineNumber?`${e}:${t}: ${r.text}`:`${e}-${t}- ${r.text}`)}}return{output:o.join("\n"),linesTruncated:i}}success(e,t){return new km.mr({result:{case:"success",value:new km.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new km.mr({result:{case:"error",value:new km.hP({error:e})}})}}var Cm=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),_m=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Pm{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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiLsExecutor.execute")),!1);const n=fm(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`List blocked: ${sm(o)}`);try{if(!(await(0,no.stat)(n)).isDirectory())return this.error(`Not a directory: ${n}`);const e=Math.max(1,t.limit??500),r=(await(0,no.readdir)(n)).sort(((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))),o=[];let i=!1;for(const t of r){if(o.length>=e){i=!0;break}try{const e=(0,a.join)(n,t);if(await this.permissionsService.shouldBlockRead(e))continue;const r=await(0,no.stat)(e);o.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===o.length)return this.success("(empty directory)");const s=em(o.join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=[];return i&&l.push(`${e} entries limit reached. Use limit=${2*e} for more`),s.truncation.truncated&&l.push(`${Xf(Zf)} limit reached`),this.success(l.length>0?`${s.content}\n\n[${l.join(". ")}]`:s.content,{entryLimitReached:i?e:void 0,truncation:s.truncation.truncated?s.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{_m(r)}}success(e,t){return new Cm.pX({result:{case:"success",value:new Cm.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new Cm.pX({result:{case:"error",value:new Cm.iG({error:e})}})}}var Im=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),Tm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Rm{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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiReadExecutor.execute")),!1);const n=function(e,t){const r=fm(e,t);if((0,i.existsSync)(r))return r;for(const e of function(e){const t=(0,a.dirname)(e),r=e.slice(t.length+1),n=new Set;return n.add(e),n.add((0,a.join)(t,r.normalize("NFD"))),n.add((0,a.join)(t,r.replace(/'/g,"’"))),n.add((0,a.join)(t,r.replace(/ /g," "))),n.add((0,a.join)(t,r.replace(/'/g,"’").normalize("NFD"))),[...n]}(r))if((0,i.existsSync)(e))return e;return r}(t.path,this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Read blocked: ${sm(o)}`);try{if((await(0,no.stat)(n)).isDirectory())return this.error(`Path is a directory: ${n}`);const e=(await(0,no.readFile)(n)).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 o=void 0!==t.limit?e.slice(r,r+t.limit).join("\n"):e.slice(r).join("\n"),{content:i,truncation:s}=em(o),a=r+1;let l=i;if(s.firstLineExceedsLimit)l=`[Line ${a} is ${Xf(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${Xf(Zf)} limit. Use bash: sed -n '${a}p' ${t.path} | head -c 51200]`;else if(s.truncated){const t=a+s.outputLines-1;l+=`\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 n=r+t.limit+1;l+=`\n\n[${e.length-(r+t.limit)} more lines in file. Use offset=${n} to continue.]`}return new Im.Q({result:{case:"success",value:new Im.yP({output:l,truncation:s.truncated?s:void 0})}})}catch(e){return this.error(e instanceof Error?e.message:"Unknown read error")}}catch(e){r.error=e,r.hasError=!0}finally{Tm(r)}}error(e){return new Im.Q({result:{case:"error",value:new Im.tB({error:e})}})}}var Am=r("../proto/dist/generated/agent/v1/pi_write_exec_pb.js"),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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Mm{constructor(e,t){this.writeExecutor=e,this.workspacePath=t}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiWriteExecutor.execute")),!1),i=fm(t.path,this.workspacePath);return pm(i,(async()=>{const e=await this.writeExecutor.execute(o.ctx,new _t.hY({path:i,fileText:t.content,toolCallId:r?.execId??""}),r);switch(e.result.case){case"success":return new Am.hO({result:{case:"success",value:new Am.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new Am.hO({result:{case:"rejected",value:new Am.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new Am.hO({result:{case:"error",value:new Am.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new Am.hO({result:{case:"error",value:new Am.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){n.error=e,n.hasError=!0}finally{Om(n)}}}var jm=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function Dm(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class Nm{constructor(e){this.drainer=e}async execute(e,t){try{const e=await this.drainer.drain({cursor:Dm(t.cursor),advance:!1!==t.advance});return new jm.Ev({result:{case:"success",value:new jm.iS({events:e.events.map((e=>new jm.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)}))),nextCursor:(r=e.nextCursor,new jm.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new jm.Ev({result:{case:"error",value:new jm.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $m{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new kt.nt({result:{case:"error",value:new kt.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new kt.nt({result:{case:"success",value:new kt.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var Lm=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}},Fm=function(e){return this instanceof Fm?(this.v=e,this):new Fm(e)},Um=function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof Fm?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}};class Bm{constructor(e){this.source=e,this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume()}consume(){return e=this,t=void 0,n=function*(){var e,t,r,n;try{try{for(var o,i=!0,s=Lm(this.source);!(e=(o=yield s.next()).done);i=!0){n=o.value,i=!1;const e=n;this.pastElements.push(e);const t=[];for(const r of this.forks)t.push(r.write(e).catch((()=>{})));yield Promise.allSettled(t)}}catch(e){t={error:e}}finally{try{i||e||!(r=s.return)||(yield r.call(s))}finally{if(t)throw t.error}}}finally{this.closed=!0;for(const e of this.forks)e.close();this.forks.clear()}},new((r=void 0)||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}));var e,t,r,n}fork(){if(this.closed){const e=this.pastElements;return function(){return Um(this,arguments,(function*(){for(const t of e)yield yield Fm(t)}))}()}const e=(0,m.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return function(){return Um(this,arguments,(function*(){var n,o,i,s;for(const e of t)yield yield Fm(e);try{try{for(var a,l=!0,c=Lm(e);!(n=(a=yield Fm(c.next())).done);l=!0){s=a.value,l=!1;const e=s;yield yield Fm(e)}}catch(e){o={error:e}}finally{try{l||n||!(i=c.return)||(yield Fm(i.call(c)))}finally{if(o)throw o.error}}}finally{r.forks.delete(e)}}))}()}}function zm(e,t){const r=new oo.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const i=o.execId,s=r.get(i);if(void 0!==s)return s;const a=await e.execute(t,n,o);return r.set(i,a),a}}}var Wm=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),Hm=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class qm{constructor(e){this.getCanvasDiagnostics=e}async execute(e,t){try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?Gm(t.path,"diagnostics unavailable"):new Wm.GL({result:{case:"success",value:new Wm.uX({path:t.path,diagnostics:e.map(Vm)})}})}catch(e){return Gm(t.path,e instanceof Error?e.message:String(e))}}}function Gm(e,t){return new Wm.GL({result:{case:"error",value:new Wm.HW({path:e,error:t})}})}function Vm(e){return new Hm.oQ({severity:Jm(e.severity),range:new gp.Q6({start:new gp.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new gp.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function Jm(e){switch(e){case 1:return Hm.h_.ERROR;case 2:return Hm.h_.WARNING;case 3:return Hm.h_.INFORMATION;case 4:return Hm.h_.HINT;default:return Hm.h_.UNSPECIFIED}}class Km{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(e){return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;e<t.length;e++){const n=t[e];".."===n?r.pop():"."!==n&&""!==n&&r.push(n)}return 0===r.length?".":`/${r.join("/")}`}pathToFileUrl(e){return/^[a-zA-Z]:\//.test(e)?`file:///${e.charAt(0).toLowerCase()}:${e.substring(2).replace(/\\/g,"/")}`:(e.startsWith("/")||(e=`/${e}`),`file://${encodeURIComponent(e).replace(/%2F/g,"/")}`)}fileUrlToPath(e){try{const t=new URL(e);if(t.pathname.startsWith("/")&&/^\/[a-zA-Z]:\//.test(t.pathname)){return`${t.pathname[1].toUpperCase()}:${t.pathname.substring(3)}`}return decodeURIComponent(t.pathname)}catch(t){throw new Error(`Invalid file URL format: ${e}`)}}get fsPath(){return this.toPath()}static fromPath(e){return new Km(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new Km(e)}static fromString(e){return new Km(e)}toPath(){return this.fileUrlToPath(this.urlString)}toString(){return this.urlString}serialize(){return this.toString()}toURL(){try{return new URL(this.urlString)}catch(e){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 Zm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Ym{constructor(e,t){this.workspacePath=e,this.diagnosticsProvider=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n;!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,n]=e.withTimeoutAndCancel(1e4);try{const r=(0,ao.o1)(t.path,this.workspacePath);try{const e=await(0,no.stat)(r);if(!e.isFile()&&!e.isDirectory())return new Hm.Ek({result:{case:"fileNotFound",value:new Hm.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new Hm.Ek({result:{case:"fileNotFound",value:new Hm.Mu({path:t.path})}});if("EACCES"===e.code)return new Hm.Ek({result:{case:"permissionDenied",value:new Hm.RP({path:t.path})}});throw e}const n=(0,ao.o1)(r,this.workspacePath),o=new Km(n);await this.diagnosticsProvider.open(e,o);const i=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new Hm.Ek({result:{case:"success",value:new Hm.a1({path:t.path,diagnostics:i,totalDiagnostics:i.length})}})}catch(r){return e.canceled?new Hm.Ek({result:{case:"error",value:new Hm.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new Hm.Ek({result:{case:"error",value:new Hm.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{Zm(r)}}convertDiagnostic(e){return new Hm.oQ({severity:this.convertSeverity(e.severity),range:e.range?new gp.Q6({start:new gp.yX({line:e.range.start.line,column:e.range.start.character}),end:new gp.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 Hm.h_.ERROR;case 2:return Hm.h_.WARNING;case 3:return Hm.h_.INFORMATION;case 4:return Hm.h_.HINT;default:return Hm.h_.UNSPECIFIED}}}var Xm=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function Qm(e){return Xm(this,void 0,void 0,(function*(){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const i=yield function(e,t){return Xm(this,void 0,void 0,(function*(){const r=new Map;if(0===t.length)return r;try{const n=yield new Promise(((r,n)=>{const o=(0,Cs.spawn)("git",["check-attr","linguist-generated","--stdin"],{cwd:e});let i="";o.stdout.on("data",(e=>{i+=e.toString()})),o.stdin.write(`${t.join("\n")}\n`),o.stdin.end(),o.on("close",(e=>{r(i)})),o.on("error",(e=>{n(e)}))}));for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch(e){}return r}))}(t,r);return yield Promise.all(r.map((e=>Xm(this,void 0,void 0,(function*(){const t=i.get(e);if(!0!==t)if(!1!==t)if(function(e){return new eg(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=yield n(e);if(void 0!==t&&function(e,t){return new eg(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))))),o}))}class eg{constructor(e,t){this.name=e,this.extname=a.extname(e).toLowerCase(),this.getContent=t}get lines(){var e;if(void 0===this.cachedLines){const t=null===(e=this.getContent)||void 0===e?void 0:e.call(this);this.cachedLines=t?t.split("\n"):[]}return this.cachedLines}get data(){var e;return null===(e=this.getContent)||void 0===e?void 0:e.call(this)}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*((null==r?void 0:r.length)||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*((null==n?void 0:n.length)||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("<doc>")&&(this.lines[2]||"").includes("<assembly>")&&(this.lines[this.lines.length-2]||"").includes("</doc>")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include <jni.h>")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){var e;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 t=this.lines.slice(0,31).join(" ").match(/<meta(\s+[^>]+)>/gi);if(!t)return!1;for(const r of t){const t=this.extractHtmlMeta(r);if("generator"===(null===(e=t.name)||void 0===e?void 0:e.toLowerCase())&&(t.content||t.value)){const e=t.content||t.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(e))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const tg=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,rg=/^(a|b|i|w|c|o|1|2)\//,ng=e=>{const t=e?.match(tg);return t?.map((e=>e.replace(rg,"").replace(/("|')$/,"")))},og=/^\\?['"]|\\?['"]$/g,ig=e=>{let t=sg(e,"-+").trim();return t=lg(t),t.replace(og,"").replace(rg,"")},sg=(e,t)=>{if(e=ug(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=cg(t);return e.replace(new RegExp(`^${r}+`),"")},ag=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,lg=e=>{const t=ag.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},cg=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${ug(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,ug=e=>`${e??""}`,dg=(0,h.h)("local-git-diff");async function hg(e,t,r={}){const n=await new Promise(((n,o)=>{const i=Ms("git",t,{cwd:e});let s="",a="";i.stdout.on("data",(e=>{s+=e.toString()})),i.stderr.on("data",(e=>{a+=e.toString()})),i.on("close",(e=>{0===e||!0===r.ignoreErrors?n(s):o(new Error(`Git command failed with code ${e}: ${a}`))})),i.on("error",(e=>{!0===r.ignoreErrors?n(s):o(e)}))}));return!0===r.shouldNotTrimOutput?n:n.trim()}function pg(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 n=null,o=null,i=0,s=0,a=null;const l=e=>{const[t,o]=ng(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},c=()=>{n&&!n.chunks.length||l()},u=e=>+(e||1),d=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},h=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{c(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{c(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{c(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{c(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{c(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{c(),n.from=ig(e)}],[/^\+\+\+\s/,e=>{c(),n.to=ig(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,d,h]=t.slice(1);i=+r,s=+d,o={content:e,changes:[],oldStart:+r,oldLines:u(c),newStart:+d,newLines:u(h)},a={oldLines:u(c),newLines:u(h)},n.chunks.push(o)}],[/^\$/,d]],p=[[/^\$/,d],[/^-/,e=>{o&&(o.changes.push({type:"del",del:!0,ln:i++,content:e}),n.deletions++,a.oldLines--)}],[/^\+/,e=>{o&&(o.changes.push({type:"add",add:!0,ln:s++,content:e}),n.additions++,a.newLines--)}],[/^\s+/,e=>{o?.changes.push({type:"normal",normal:!0,ln1:i++,ln2:s++,content:e}),a.oldLines--,a.newLines--}]],f=e=>{a?(e=>{for(const[t,r]of p){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of h){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)f(e);return r})(e);return new ur.o$({diffs:t.map((e=>function(e){const t=new ur.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new ur.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:ur.Wf.UNSPECIFIED})}const fg=["main","master","develop"];class mg{async execute(e,t){return async function(e,t,r){const n=function(e){switch(e){case ur.ek.NAME_STATUS:return ur.ek.NAME_STATUS;case ur.ek.NAME_STATUS_AND_NUMSTAT:return ur.ek.NAME_STATUS_AND_NUMSTAT;case ur.ek.FILE_DIFFS:return ur.ek.FILE_DIFFS;case ur.ek.DIFFS_WITH_BEFORE_AND_AFTER:return ur.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return ur.ek.FILE_DIFFS}}(r.outputFormat),o=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await hg(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of fg){const r=`origin/${t}`;try{return await hg(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await hg(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await hg(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 hg(t,["merge-base",e,r.ref.length>0?r.ref:"HEAD"])).trim()),e})(),i=["diff","--no-color"];r.includeSpaceChanges||i.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&i.push(`-U${r.unifiedContextLines}`),i.push(o),r.ref.length>0&&i.push(r.ref),r.targetPaths.length>0&&(i.push("--"),i.push(...r.targetPaths));const s=await hg(t,i,{shouldNotTrimOutput:!0}),l=pg(s);let c=[];if(r.maxUntrackedFiles>0){c=await async function(e,t){let r=(await hg(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 no.readFile(a.join(e,t),"utf8"),path:t}}catch{return}})))).filter((e=>void 0!==e))}(t,r.maxUntrackedFiles);for(const e of c){const r=await hg(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});l.diffs.push(...pg(r).diffs)}}if(n!==ur.ek.FILE_DIFFS)for(const e of l.diffs)e.chunks=[];if(n===ur.ek.DIFFS_WITH_BEFORE_AND_AFTER){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(l.diffs.map((async i=>{try{if("/dev/null"!==i.from)try{i.beforeFileContents=await hg(t,["show",`${o}:${i.from}`],{shouldNotTrimOutput:!0})}catch{i.beforeFileContents=""}else i.beforeFileContents="";if("/dev/null"!==i.to)if(r.ref.length>0)try{i.afterFileContents=await hg(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}else try{i.afterFileContents=await no.readFile(a.join(t,i.to),"utf8")}catch{try{i.afterFileContents=await hg(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}}else i.afterFileContents=""}catch(t){dg.error(e,"Error fetching file contents for diff",t)}})))}const u=new Map;for(const e of l.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 Qm({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 hg(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){dg.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,n)=>{const o=Ms("git",["patch-id","--stable"],{cwd:e});let i="",s="";o.stdout.on("data",(e=>{i+=e.toString()})),o.stderr.on("data",(e=>{s+=e.toString()})),o.on("close",(e=>{0===e?r(i):n(new Error(`git patch-id failed with code ${e}: ${s}`))})),o.on("error",n),o.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`}(s,function(e){const t=[];for(const r of e){const e=r.contents.split("\n"),n=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===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(c))):void 0,f=!0===r.returnHeadSha?(await hg(t,["rev-parse","HEAD"])).trim():void 0,m=!0===r.returnHeadSha?(await hg(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,g=new ur.df({diff:l,submoduleDiffs:[],patchId:p,headSha:f,hasUncommittedChanges:m}),v=r.maxResponseBytes??0;if(v>0){const e=g.toBinary().byteLength;if(e>v)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${v} byte limit`)}return g}(e,t.cwd,t)}}var gg=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class vg{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName});return new gg.M({allowlisted:r})}}const yg=8388608;var wg=r("../proto/dist/generated/agent/v1/read_exec_pb.js"),bg=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Sg=(0,h.h)("LocalReadExecutor"),kg=async(e,t,r,n)=>{const o=setTimeout((()=>{Sg.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function Eg(e){return e>=32&&e<=126||9===e||10===e||13===e}const xg=Buffer.from("\n---\n");const Cg=[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 _g(e){const t=(0,a.extname)(e).toLowerCase(),r=""===t?"Binary files without an extension are not supported by the read executor":`Binary files of type ${t} are not supported by the read executor`;return new wg.sV({result:{case:"invalidFile",value:new wg.cW({path:e,reason:r})}})}function Pg(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 n=r.offset??1,o=r.limit??(n<0?Math.abs(n):t),i=n<0?Math.max(0,t+n):Math.max(0,n-1);if(i>=t)return{content:e,rangeApplied:!1};const s=Math.min(t,i+o);return{content:e.split("\n").slice(i,s).join("\n"),rangeApplied:!0}}function Ig(e,t,r=8388608){if(0===t.length)return e;const n=r-e.text.length;return n<=0?{text:e.text,truncated:!0}:t.length>n?{text:e.text+t.slice(0,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function Tg(e,t){const r=Ig(e,t);return{text:r.text,truncated:r.truncated}}function Rg(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=Ig(n,"\n")),n=Ig(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function Ag(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 Og extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function Mg(e,t,r,n){const o=void 0!==r.offset||void 0!==r.limit,s=(r.offset??1)<0,a=r.offset??1,l=Math.max(0,a-1),c=void 0===r.limit?void 0:l+r.limit,u=s?Math.abs(a):0,d=[];let h=0,p=!1;const f=[];let m=0,g=!1;const v=[];let y=0,w=!1,b={text:"",truncated:!1},S=0,k=0,E=0,x=!1,C=!1;const _=e=>{let t=e;return!x&&t.length>0&&(x=!0,65279===t.charCodeAt(0)&&(C=!0,t=t.slice(1))),t},P=(e,t)=>{const r=S;if(t&&(e.text.endsWith("\r")?k++:E++),((e,t)=>{if(p&&h>=yg)return;const r=d.length>0?1:0;let n=yg-h;if(r>0){if(n<=0)return void(p=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};d.push(o),h+=r+o.line.text.length,(e.truncated||o.line.truncated)&&(p=!0)})(e,t),s){if(u>0){for(v.push({line:e,hasNewline:t}),y+=e.text.length+1;v.length>u;){const e=v.shift();void 0!==e&&(y-=e.line.text.length+1)}for(;v.length>1&&y>yg;){const e=v.shift();void 0!==e&&(y-=e.line.text.length+1,w=!0)}}}else o&&r>=l&&(void 0===c||r<c)&&((e,t)=>{if(g&&m>=yg)return;const r=f.length>0?1:0;let n=yg-m;if(r>0){if(n<=0)return void(g=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};f.push(o),m+=r+o.line.text.length,e.truncated&&(g=!0),o.line.truncated&&(g=!0)})(e,t);S++};for await(const r of async function*(e,t,r){if("strictUtf8"===r.kind){const r=new Zo.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n=(0,i.createReadStream)(t,{highWaterMark:65536,signal:e.signal});try{for await(const e of n){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 Og;throw e}return}const n=(0,i.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe(uc.decodeStream(r.decoderEncoding));for await(const e of n)yield"string"==typeof e?e:String(e)}(e,t,n)){const e=_(r).split("\n");for(let t=0;t<e.length;t++)b=Tg(b,e[t]),t<e.length-1&&(P(b,!0),b={text:"",truncated:!1})}P(b,!1);const I=k+E,T=I>0&&k/I*100>=5;!function(e,t){if(Pc.has(e)&&Pc.delete(e),Pc.set(e,t),Pc.size<=100)return;const r=Pc.keys().next().value;void 0!==r&&Pc.delete(r)}(t,"utf8"===n.cacheEncoding&&C?"utf8bom":n.cacheEncoding);let R={text:"",truncated:p};if(R=Rg(R,d,T),!o)return{content:R.text,totalLines:S,truncated:R.truncated,rangeApplied:!1};if(""===R.text)return{content:"",totalLines:S,truncated:!1,rangeApplied:!1};if(s){const e=r.limit??u;let t={text:"",truncated:w};return t=Rg(t,v.slice(0,e),T),{content:t.text,totalLines:S,truncated:t.truncated,rangeApplied:!0}}if(l>=S)return{content:R.text,totalLines:S,truncated:R.truncated,rangeApplied:!1};let A={text:"",truncated:g};return A=Rg(A,f,T),{content:A.text,totalLines:S,truncated:A.truncated,rangeApplied:!0}}class jg{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalReadExecutor.execute")),!1);const n=t.path,o=(0,ao.o1)(n,this.workspacePath);if(await kg(e,"permissionsService.shouldBlockRead",3e3,(()=>this.permissionsService.shouldBlockRead(o))))return new wg.sV({result:{case:"permissionDenied",value:new wg.lW({path:o})}});void 0!==this.mcpStateAccessor&&Cf(e,this.mcpStateAccessor,o);try{const r=await kg(e,"stat",3e3,(()=>(0,no.stat)(o)));if(r.isDirectory())return new wg.sV({result:{case:"invalidFile",value:new wg.cW({path:o,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new wg.sV({result:{case:"invalidFile",value:new wg.cW({path:o,reason:"Path is neither a file nor a directory"})}});const n=function(e){return null!==function(e){const t=fs(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(o),i=function(e){const t=fs(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(o);if(n||i)return await this.readTerminalFile(e,o,r,t,i&&!n);const s=await kg(e,"getFormatForFile",3e3,(()=>Dc(o))),l=s.isImageFile,c=function(e){return".pdf"===(0,a.extname)(e).toLowerCase()}(o),u=Ac(o);if(l){const t=await kg(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,no.readFile)(o);return _p(e)}));return new wg.sV({result:{case:"success",value:new wg.mE({path:o,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c){const t=await kg(e,"readPdfBinary",3e3,(()=>(0,no.readFile)(o)));return new wg.sV({result:{case:"success",value:new wg.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(s.isBinaryFile&&u){const t=await kg(e,"readBinaryFile",3e3,(()=>(0,no.readFile)(o)));return new wg.sV({result:{case:"success",value:new wg.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(s.isBinaryFile)return _g(o);{const n=this.useStreamingRead;if(n&&await kg(e,"useStreamingRead",3e3,(()=>n()))){const n=await kg(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=function(e,t,r){const n=function(e,t,r){return Ag(r??Pc.get(e)??t.encoding)}(e,t,r),o=function(e){const t=Ag(e);return"utf8bom"===t?"utf8":t}(n);return"utf8"===o?{kind:"strictUtf8",cacheEncoding:"utf8"}:uc.encodingExists(o)?{kind:"iconv",decoderEncoding:o,cacheEncoding:n}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,n.encodingHint);try{return await Mg(e,t,n,o)}catch(r){if(r instanceof Og)return await Mg(e,t,n,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,o,s,t)));return new wg.sV({result:{case:"success",value:new wg.mE({path:o,output:{case:"content",value:n.content},totalLines:n.totalLines,fileSize:BigInt(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const i=await kg(e,"readText",3e3,(()=>Mc(o,t.encodingHint))),a=await kg(e,"countLines",3e3,(()=>Nc(i))),l=Pg(i,a,t);let c=l.content,u=!1;return c.length>yg&&(c=c.substring(0,yg),u=!0),new wg.sV({result:{case:"success",value:new wg.mE({path:o,output:{case:"content",value:c},totalLines:a,fileSize:BigInt(r.size),truncated:u,rangeApplied:l.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new wg.sV({result:{case:"fileNotFound",value:new wg.Ko({path:o})}}):"EACCES"===t.code||"EPERM"===t.code?new wg.sV({result:{case:"permissionDenied",value:new wg.lW({path:o})}}):new wg.sV({result:{case:"error",value:new wg.F_({path:o,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bg(r)}}async readTerminalFile(e,t,r,n,o){const i=await kg(e,"readTerminalFile",3e3,(()=>(0,no.readFile)(t)));if(o&&(s=i,Cg.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(s,e)))))return _g(t);var s;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"):"",n=function(e,t){const r=e.length;if(r<2*xg.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(xg,r-xg.length-1);return-1===o||o<n?r:function(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(10!==r&&(r<32||r>126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+xg.length,r-4).toString("utf-8"))?o:r}(e,t),o=n<e.length?e.subarray(n).toString("utf-8"):"",i=e.subarray(t,n),s=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,n=0;for(let o=0;o+1<t;o+=2){const t=e[o],i=e[o+1];0===i&&Eg(t)&&r++,0===t&&Eg(i)&&n++}return r>=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}(i);let a;if("utf-16le"===s)a=i.toString("utf16le");else if("utf-16be"===s){const e=i.length-i.length%2,t=Buffer.from(i.subarray(0,e));t.swap16(),a=t.toString("utf16le")}else a=i.toString("utf-8");return 65279===a.charCodeAt(0)&&(a=a.slice(1)),r+a+o}(i).replaceAll("\r\n","\n");const l=Nc(a),c=Pg(a,l,n);a=c.content;let u=!1;return a.length>yg&&(a=a.substring(0,yg),u=!0),new wg.sV({result:{case:"success",value:new wg.mE({path:t,output:{case:"content",value:a},totalLines:l,fileSize:BigInt(r.size),truncated:u,rangeApplied:c.rangeApplied})}})}}var Dg=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),Ng=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $g=(0,Zo.promisify)(Cs.execFile);class Lg{constructor(e){if(this.activeRecording=null,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(!e.childProcess.killed&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await no.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await no.mkdir(this.stagingDir,{recursive:!0}),await no.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return a.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:Dg.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:Dg.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:Dg.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async pathExists(e){try{return await no.access(e),!0}catch{return!1}}async getUniqueArtifactVideoPath(e){const t=a.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;await this.pathExists(a.join(this.artifactsDir,o));)o=`${r}-${i}${n}`,i++;return a.join(this.artifactsDir,o)}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${a.basename(r)}.mp4`)}else o=`${a.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await $g("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await $g("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e]),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),i=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(i))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||i<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:i}}async renderPolished(e){const t=a.join(e,"recording"),r=a.join(t,"recording_full.mp4");return await this.polishedRenderer.renderRecordingSession({stagingSessionDir:e,outputVideoPath:r,fps:Lg.PROXY_TARGET_FPS,includeBrandTag:!0}),await no.access(r,no.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await $g("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e]),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${Lg.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${Lg.PROXY_TARGET_FPS}fps`)}return Lg.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=a.join(t,"recording");await no.mkdir(r,{recursive:!0});const n=a.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await ad(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${Lg.DEFAULT_REFRESH_RATE}Hz`),o=Lg.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${Lg.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${Lg.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",Lg.PROXY_PRESET,"-crf",String(Lg.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],s=(0,Cs.spawn)("ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),l=new Promise(((e,t)=>{let r="",n=!1;s.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);s.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),s.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);s.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),s.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:s,videoStartedPromise:l}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,Cs.spawn)("ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let i="";o.stderr?.on("data",(e=>{i.length<2e4&&(i+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${i.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:s,renderProxies:l}=e,c=a.join(t,"recording"),u=a.join(c,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:s.display.width,displayHeight:s.display.height,apiWidth:s.api.width,apiHeight:s.api.height,inputEvents:h,renderProxies:l??null};await no.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(t.killed||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(e){clearTimeout(o),n(new Error(`Failed to send SIGTERM: ${e instanceof Error?e.message:String(e)}`))}}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new Dg.Tj({result:{case:"failure",value:new Dg.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===Dg.$u.UNSPECIFIED)return new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case Dg.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){e=!0;try{await this.cleanupRecording(this.activeRecording),await no.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}this.activeRecording=null}let r=null,n=null,o=null;try{o=this.buildSessionDir(t.toolCallId||"recording"),await no.mkdir(o,{recursive:!0});const{resolutionString:i,resolution:s}=await ad(this.display),{process:a,videoStartedPromise:l}=await this.startFfmpegRecording(i,o);r=a;const c=function(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}(this.display);n=new Id({displayNum:c,resolution:s}),await n.start();const u=n.getRecordingStartTime();let d;try{d=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}this.activeRecording={childProcess:r,sessionDir:o,startTime:u,inputEventLogger:n,resolution:s,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null},this.onRecordingStartedCallback&&this.onRecordingStartedCallback(n),r.once("exit",((e,t)=>{this.activeRecording&&(this.activeRecording.ffmpegDiedEarly=!0,this.activeRecording.ffmpegDiedTime=Date.now(),this.activeRecording.ffmpegExitCode=e,this.activeRecording.ffmpegExitSignal=t)}));const h=!!t.saveAsFilename;return new Dg.Tj({result:{case:"startSuccess",value:new Dg.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:h})}})}catch(e){if(n)try{await n.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return o&&await no.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:e instanceof Error?e.message:String(e)})}})}}case Dg.$u.SAVE_RECORDING:{if(!this.activeRecording)return new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:"No active recording to save"})}});const e=this.activeRecording;try{const r=await e.inputEventLogger.stop(),n=e.inputEventLogger.getRecordingStartTime();this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e);const o=e.ffmpegStartedEpochMs??n,i=e.sessionDir,{finalVideoPath:s,requestedFilePathRejectedReason:l}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:i}),c=a.join(i,"recording"),u=a.join(c,"recording_render_proxy_1080p.mp4");try{await no.access(u,no.constants.R_OK)}catch{return this.activeRecording=null,new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:`Recording proxy not found at ${u}`})}})}const[d,h,p]=await Promise.all([this.getVideoDurationMs(u),this.getVideoDimensions(u),this.getVideoFramerate(u)]),f={profileVersion:Lg.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:Lg.PROXY_TARGET_FPS,codec:"h264",profile:Lg.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};if(await this.saveRecordingDataPackage({sessionDir:i,durationMs:d,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:r,resolution:e.resolution,renderProxies:f}),this.disablePolishedRendering)await no.copyFile(u,s);else{const e=await this.renderPolished(i);await no.rename(e,s)}return this.activeRecording=null,new Dg.Tj({result:{case:"saveSuccess",value:new Dg.ol({path:s,recordingDurationMs:ar.protoInt64.parse(d.toString()),requestedFilePathRejectedReason:l})}})}catch(t){return await this.cleanupRecording(e),this.invokeStoppedCallbackOnce(),this.activeRecording=null,new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:t instanceof Error?t.message:String(t)})}})}}case Dg.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:"No active recording to discard"})}});const e=this.activeRecording;try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await no.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new Dg.Tj({result:{case:"discardSuccess",value:new Dg.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;return this.activeRecording=null,new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:`Failed to discard recording: ${t instanceof Error?t.message:String(t)}. Session may remain at: ${r}`})}})}}default:{const e=t.mode;return new Dg.Tj({result:{case:"failure",value:new Dg.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{Ng(r)}}}async function Fg(e){const t=await(0,no.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=a.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await Fg(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function Ug(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const i=r===o.length-1;n.push(...Ug(t,e,i))}))}return n}async function Bg(e){if(!await(0,no.access)(e,no.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await Fg(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>Ug(e,"",r===t.length-1))).join("\n")}async function zg(e,t){return Bg(a.join(e,"agent-notes",t))}async function Wg(e){return Bg(a.join(e,"agent-notes","shared"))}Lg.PROXY_TARGET_WIDTH=1920,Lg.PROXY_TARGET_FPS=60,Lg.PROXY_CRF=17,Lg.PROXY_PRESET="veryfast",Lg.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",Lg.DEFAULT_REFRESH_RATE=60;var Hg=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Gg=(0,h.h)("local-exec:request-context");async function Vg(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{Hg(o,(0,c.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{qg(o)}}async function Jg(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function Kg(e,t,r={}){const{projectDir:n,notesSessionId:o,metaAgentNotesEnabled:i,getSmartModeClassifierAutoModeEnabled:a,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:c,getSandboxEnabled:u,getSandboxSupported:d,getNetworkAllowlistInfo:h,userTerminalHint:p,artifactsFolder:f,secretRedactionEnabled:m,getComputerUseSupported:g}=r,v=`${s.platform()} ${s.release()}`,y=(0,io.getSuggestedShell)(p),w=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),b=n,S=n?`${n}/terminals`:void 0,k=n&&!0!==i?`${n}/agent-notes/shared`:void 0,E=n&&o?`${n}/agent-notes/${o}`:void 0,x=n?`${n}/agent-transcripts`:void 0,C=!!u&&u(),_=d?.(),P=a?.();let I;if(h)try{I=await h()}catch{I=void 0}return new Bt.GE({osVersion:v,workspacePaths:t,shell:y,sandboxEnabled:C,projectFolder:b,terminalsFolder:S,agentSharedNotesFolder:k,agentConversationNotesFolder:E,agentTranscriptsFolder:x,timeZone:w,processWorkingDirectory:process.cwd(),artifactsFolder:f,...void 0!==P&&{smartModeClassifierAutoModeEnabled:P},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==m&&{secretRedactionEnabled:m},...void 0!==_&&{sandboxSupported:_},...void 0!==I?.hasDefaults&&{sandboxNetworkHasDefaults:I.hasDefaults},...I?.explicitEntries&&I.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:I.explicitEntries},...void 0!==g&&{computerUseSupported:g()},...void 0!==c&&{isWorkingDirHomeDir:c}})}const Zg={type:"object",properties:{},additionalProperties:!1};function Yg(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>nt.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new sr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function Xg(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new sr.E$({toolName:e.toolName,...r?{}:{description:e.description,inputSchema:void 0!==e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0}})));return!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===Wp))||o.push(new sr.E$({toolName:Wp,...r?{}:{description:Hp,inputSchema:ar.Value.fromJson(Zg)}})),new sr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new sr.U_({enabled:!0,mcpDescriptors:n})}function Qg(e){const t=e?.trim();return t||void 0}function ev(e,t){const r=function(e){return Qg(e.serverIdentifier)}(e);if(r)return r;const n=Qg(e.serverName);return n?t.get(n)??n:void 0}function tv(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}class rv{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(Gg.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(Gg.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r){const n=new Map;for(const t of e)n.has(t.providerIdentifier)||n.set(t.providerIdentifier,t.clientKey);const o=t.map((e=>ev(e,n))).filter((e=>Boolean(e)));return{servers:[...new Set([...e.map((e=>e.clientKey)),...o,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e)).map((([e])=>e))])].map((o=>{const i=e.filter((e=>e.clientKey===o));return{serverName:i[0]?.providerIdentifier??o,serverIdentifier:o,plugin:i[0]?.plugin,marketplace:i[0]?.marketplace,tools:i,instructions:t.filter((e=>ev(e,n)===o)),status:r?.get(o)}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(Gg.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>[t,tv(await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"}))))])));return new Map(n)}(e,this.mcpLease))}}function nv(e){return new xt._W({result:{case:"success",value:new xt.pv({servers:e.servers.map((e=>new xt.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new sr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0}))),instructions:e.instructions,status:e.status})))})}})}class ov{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{}const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return nv({...r,servers:n})}return nv(r)}}class iv{constructor(e,t,r,n,o,i,s,a,l,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.lsExecutor=i,this.mcpStateAccessor=s,this.gitExecutor=a,this.workspacePaths=l,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:u,getSmartModeClassifierAutoModeEnabled:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,createFileWatcher:f,getSandboxEnabled:m,getSandboxSupported:g,getNetworkAllowlistInfo:v,userTerminalHint:y,getMcpFileSystemOptions:w,mcpMetaToolEnabled:b,mcpMetaToolSlimDescriptors:S,alwaysExposeVirtualMcpAuthTool:k,artifactsFolder:E,secretRedactionEnabled:x,attributionConfigProvider:C,isAttributionDisabledByAdmin:_,getAgentSkills:P,additionalRules:I,getComputerUseSupported:T}=c;this.projectDir=u,this.isWorkingDirHomeDir=p,this.getSandboxEnabled=m,this.getSandboxSupported=g,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=d,this.devForceNextSmartModeClassifierBlockToken=h,this.userTerminalHint=y,this.getMcpFileSystemOptions=w,this.mcpMetaToolEnabled=b??!1,this.mcpMetaToolSlimDescriptors=S??!1,this.alwaysExposeVirtualMcpAuthTool=k??!1,this.artifactsFolder=E,this.secretRedactionEnabled=x,this.attributionConfigProvider=C,this.isAttributionDisabledByAdmin=_,this.getAgentSkills=P,this.additionalRules=I??[],this.getComputerUseSupported=T,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,Qe.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hg(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"getGitRepoPathForWorkspacePath"})).stdout.trim()}catch{return null}}(n.ctx,this.gitExecutor,t),i=o?await Xc(n.ctx,this.gitExecutor,o):void 0,s={repoPath:o??void 0,remoteUrl:void 0!==i?Qc(i):void 0};this.cachedWorkspaces.set(t,s)}catch(e){r.error=e,r.hasError=!0}finally{qg(r)}}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,Qe.q6)(),r=Hg(e,(0,c.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId,this.globalCache=this.computeGlobalCache(r.ctx)}catch(t){e.error=t,e.hasError=!0}finally{qg(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hg(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),i={},s=(e,t)=>{const r=performance.now();return t.finally((()=>{i[e]=Math.round(performance.now()-r)}))},[a,l,u,d]=await Promise.all([s("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),s("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),s("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),s("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),h=Math.round(performance.now()-o);return h>1e3&&Gg.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...i,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{qg(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0}async collectWorkspaceCaches(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hg(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let n;if(this.grepProvider.getTrackedState)try{n=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{n=void 0}let o=!0;const i=(await Promise.all(this.workspacePaths.map((async e=>{const t=this.getWorkspaceCache(e);if(void 0===t)return o=!1,void this.ensureWorkspaceCacheWarm(r.ctx,e);const i=n?.[e];if(void 0!==i)return new Bt.DS({path:t.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:t.remoteUrl,isOriginBacked:sa(t.remoteUrl)});if(void 0===t.repoPath)return;const{status:s,branchName:a}=await async function(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[i,s]=await Promise.all([o(Vg(e,t,r,n)),o(Jg(e,t,r,n))]);return{status:i,branchName:s}}(r.ctx,this.gitExecutor,t.repoPath,3e3);return new Bt.DS({path:t.repoPath,status:s,branchName:a,remoteUrl:t.remoteUrl,isOriginBacked:sa(t.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:i,gitRepoInfoComplete:o}}catch(e){t.error=e,t.hasError=!0}finally{qg(t)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hg(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),o=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=Hg(e,(0,c.VI)(n.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),void 0===this.globalCache){const e=this.computeGlobalCache(n.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)}))}return this.globalCache}catch(t){e.error=t,e.hasError=!0}finally{qg(e)}},s=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,v,y,w]=await Promise.all([l("globalCache",i()),l("mcpState",this.mcpStateAccessor.getState(n.ctx)),l("env",Kg(n.ctx,this.workspacePaths,{projectDir:o,notesSessionId:t.notesSessionId,metaAgentNotesEnabled:!1,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.artifactsFolder,secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported})),l("git",this.collectWorkspaceCaches(n.ctx)),l("conversationNotes",o&&t.notesSessionId?zg(o,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",o?Wg(o):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(n.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",this.getAgentSkills?this.getAgentSkills(n.ctx):Promise.resolve([]))]),b=performance.now()-s;for(const[e,t]of Object.entries(a))n.span.setAttribute(`requestContext.timing.${e}Ms`,t);n.span.setAttribute("requestContext.timing.totalMs",Math.round(b)),b>1e3&&Gg.warn(n.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(b),...a});const S=this.mcpMetaToolEnabled?Xg(d,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors}):void 0,k=this.attributionConfigProvider?.get(),E=!y&&(k?.attribution?.attributeCommitsToAgent??!0),x=!y&&(k?.attribution?.attributePRsToAgent??!0),C=new Bt.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}]:[],...Yg(d,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors}),conversationNotesListing:m,sharedNotesListing:g,customSubagents:u.customSubagents,mcpFileSystemOptions:v,mcpMetaToolOptions:S,supportsMcpAuth:!0,commitAttributionMessage:E?"enabled":void 0,prAttributionMessage:x?"enabled":void 0,agentSkills:w});return null!==u.cloudRule&&void 0!==u.cloudRule&&(C.cloudRule=u.cloudRule),C}catch(e){r.error=e,r.hasError=!0}finally{qg(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hg(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=await this.computeCachedRequestContext(n.ctx,t);return new Bt._G({result:{case:"success",value:new Bt.yW({requestContext:e})}})}catch(e){return n.span.recordException(e),new Bt._G({result:{case:"error",value:new Bt.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{qg(r)}}}function sv(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Ct._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class lv{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new Ct.W4({result:{case:"success",value:new Ct.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Io(e.sandboxPolicy)}):new Ct.W4({result:{case:"failure",value:new Ct.xC({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Io(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const i=Date.now(),s=new AbortController,a=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal,l=setTimeout((()=>{s.abort()}),n);try{let n,s,c="",u="",d=null,h=!1;const p=o?{perRepo:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:p,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?c+=o.data:"stderr"===o.type?u+=o.data:"exit"===o.type&&(d=null!=o.code?0|o.code:null,n=o.outputLocation,h=o.aborted,s=Gd(o.localExecutionTimeMs));clearTimeout(l);const f=Date.now()-i,m={command:t.command,workingDirectory:r,exitCode:h?-1:d??-1,signal:h?"SIGTERM":"",stdout:c,stderr:u,executionTime:f,localExecutionTimeMs:s,sandboxPolicy:o,outputLocation:n};return this.buildResultFromExit(m)}catch(i){return clearTimeout(l),s.signal.aborted&&!e.signal.aborted?new Ct.W4({result:{case:"timeout",value:new Ct.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:Io(o)}):e.signal.aborted?new Ct.W4({result:{case:"rejected",value:new Ct.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Io(o)}):new Ct.W4({result:{case:"spawnError",value:new Ct.mJ({command:t.command,workingDirectory:r,error:i instanceof Error?i.message:"Unknown error"})},sandboxPolicy:Io(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalShellExecutor.execute");const o=t.command,i=t.requestedSandboxPolicy?Po(t.requestedSandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(),a=sv(t),l=(0,ao.o1)(s);if(!t.parsingResult)return new Ct.W4({result:{case:"spawnError",value:new Ct.mJ({command:o,workingDirectory:l,error:"Parsing result is required"})}});let u;if(t.skipApproval)u=i;else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:l,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:qt(t)},i);if("block"===e.kind)return"permissionsConfig"===e.reason.type&&e.reason.isReadonly?new Ct.W4({result:{case:"permissionDenied",value:new Ct.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Ct.W4({result:{case:"rejected",value:new Ct.pZ({command:o,workingDirectory:l,reason:Ro(e.reason)})}});u=e.policy}if(vo()&&(u=Eo(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await this.ignoreService.getCursorIgnoreMapping();u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,s,a,u)}catch(e){r.error=e,r.hasError=!0}finally{av(r)}}}var cv=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class uv{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new Ct.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new cv.e({allowlisted:n})}}class dv{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new Ct.jK({status:Ct.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}var hv=r("../utils/dist/workspace-paths.js"),pv=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},fv=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mv=(0,h.h)("local-exec:shell-core"),gv="win32"===process.platform,vv=["CURSOR_CONVERSATION_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function yv(e){return`'${e.replace(/'/g,"'\\''")}'`}function wv(e,t){return e[t]??process.env[t]}function bv(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}class Sv{constructor(e,t,r,n,o){this.executor=e,this.workspacePath=t,this.projectDir=r,this.shellOutputBackpressureOptions=n,this.extraEnvProvider=o}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{pv(r,(0,c.VI)(e.withName("ShellCoreExecutor.execute")),!1);const n=performance.now(),s=t.workingDirectory||await this.executor.getCwd(),l=(0,ao.o1)(s,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,v={CURSOR_AGENT:"1"};t.conversationId&&(v.CURSOR_CONVERSATION_ID=(0,hv.sh)(t.conversationId)),this.projectDir&&(v.AGENT_TRANSCRIPTS=a.join(this.projectDir,hv.O2));const y=this.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(v,y),function(e){const t=[`builtin unset ${vv.join(" ")} 2>/dev/null || true`];for(const r of vv){const n=wv(e,r);void 0!==n&&t.push(`builtin export ${r}=${yv(n)}`)}const r=t.join("; "),n=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),o=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,n,r].filter((e=>void 0!==e&&""!==e)).join("; ")}(v);const w=function(e,t){const r=wv(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(wv(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,i=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==i?.type&&"workspace_readonly"!==i?.type)return e;const s=o?.type===i.type?{...o}:{type:i.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==s.type?s.additionalReadonlyPaths=bv(s.additionalReadonlyPaths,a):s.additionalReadwritePaths=bv(s.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==s.type?s.additionalReadonlyPaths=bv(s.additionalReadonlyPaths,e.path):s.additionalReadwritePaths=bv(s.additionalReadwritePaths,e.path);return{...e,perUser:s}}(t.sandboxPolicy,v),b=(0,io.getSandboxPolicyType)(w??io.INSECURE_NONE_SANDBOX_POLICY);w&&(yield{type:"start",sandboxed:"workspace_readonly"===b||"workspace_readwrite"===b}),t.askpassConfig&&!gv&&(v.SUDO_ASKPASS=t.askpassConfig.helperPath,v.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,v.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let S=0,k="";for await(const r of this.executor.execute(e,t.command,{signal:g,workingDirectory:l,env:v,sandboxPolicy:w,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,bufferOutputEvents:this.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.shellOutputBackpressureOptions?.outputLimiterOptions})){if(S=0,k="",("stdout"===r.type||"stderr"===r.type)&&(k=r.data.toString(),S=r.data.length,u))if(u.size+=S,u.lineCount+=k.split("\n").length-1,u.size>Jd);else if(u.file)u.file.write(k);else if(u.buffer+=k,u.size>u.threshold){const e=a.join(this.projectDir,Vd);u.path=a.join(e,`${(0,o.randomUUID)()}.txt`),await(0,no.mkdir)(a.dirname(u.path),{recursive:!0}),u.file=(0,i.createWriteStream)(u.path),u.file.write(u.buffer),u.buffer=""}switch(r.type){case"stdout":p||(d+S>Td?(p=!0,yield{type:"stdout_trimmed"}):(d+=S,yield{type:"stdout",data:k}));break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:io.SHELL_OUTPUT_SUPPRESSED_NOTICE});break;case"stderr":f||(h+S>Td?(f=!0,yield{type:"stderr_trimmed"}):(h+=S,yield{type:"stderr",data:k}));break;case"exit":{const e=Math.max(0,Math.round(performance.now()-n));let t;u?.file&&(await new Promise((e=>u.file.end(e))),t=new gp.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{fv(r)}}async getCwd(){return this.executor.getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class kv{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{pv(r,(0,c.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),mv.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{fv(r)}}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Ev{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}var xv=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Cv=(0,h.h)("local-exec:shell-stream");class _v{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===Ct.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:Ct.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:Ct.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 Pv{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map}async forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e),r=t?.requestBackground();return r?new Ct.jK({status:Ct.iA.ACCEPTED,shellResult:r}):new Ct.jK({status:Ct.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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const n=t.command;let o=t.requestedSandboxPolicy?Po(t.requestedSandboxPolicy):void 0;if(o&&"insecure_none"!==o.type){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}const i=t.workingDirectory||await this.coreExecutor.getCwd(),s=sv(t),a=(0,ao.o1)(i),l=Date.now();if(!t.parsingResult)throw new Error("Parsing result is required");const u=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0},o);if("block"===u.kind)return"permissionsConfig"===u.reason.type?void(yield new Ct.FI({event:{case:"permissionDenied",value:new Ct.jn({command:n,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:u.reason.isReadonly??!1})}})):void(yield new Ct.FI({event:{case:"rejected",value:new Ct.pZ({command:n,workingDirectory:a,reason:Ro(u.reason)})}}));if(Cv.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:o?.type??"undefined",parserCommandCount:t.parsingResult?.executableCommands.length??0,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval)Cv.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"});else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:a,timeout:s,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:qt(t)},o);if("block"===r.kind){if(Cv.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 Ct.FI({event:{case:"permissionDenied",value:new Ct.jn({command:n,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const o=Ro(r.reason);return void(yield new Ct.FI({event:{case:"rejected",value:new Ct.pZ({command:n,workingDirectory:a,reason:o})}}))}o=r.policy,Cv.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:o.type})}if(vo()&&(o=Eo(n,t.parsingResult),"insecure_none"!==o.type)){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}yield new Ct.FI({event:{case:"start",value:new Ct.tD({sandboxPolicy:Io(o)})}});const d=t.timeoutBehavior===Ct._d.BACKGROUND,h=d&&!t.closeStdin&&void 0===t.smartModeApproval,p=new AbortController,f=d?p.signal:e.signal?AbortSignal.any([e.signal,p.signal]):p.signal,m=!0,g=o?{perRepo:o}:void 0,v=this.coreExecutor.execute(e,{command:n,workingDirectory:i,signal:f,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:g,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:h,showElapsedTime:m});let y;d||(y=setTimeout((()=>p.abort()),s));const w=d?new _v(v[Symbol.asyncIterator](),s):null;let b,S,k,E="",x=!1;const C=t.toolCallId&&w?{requestBackground:()=>{if(w.requestBackground())return k=k??this.backgroundShellManager.generateShellId(),new Ct.W4({result:{case:"success",value:new Ct.QR({shellId:k,pid:S,command:n,workingDirectory:a,msToWait:Gd(Date.now()-l),backgroundReason:Ct.Jg.USER_REQUEST,interleavedOutput:E})}})}}:void 0;t.toolCallId&&C&&this.activeForegroundExecutions.set(t.toolCallId,C);const _=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===C&&this.activeForegroundExecutions.delete(t.toolCallId)};let P;w&&e.signal&&e.signal.addEventListener("abort",(()=>{w.backgroundRequested||(p.abort(),w.abort())}),{once:!0});const I=t.hardTimeout;void 0!==I&&I>0&&(P=setTimeout((()=>{void 0!==k?this.backgroundShellManager.abort(k)||p.abort():(x=!0,p.abort(),w?.abort())}),I));const T=w?.iterate()??v;try{for await(const t of T)if("stdout"===t.type)E+=t.data,yield new Ct.FI({event:{case:"stdout",value:new Ct.o0({data:t.data})}});else if("stderr"===t.type)E+=t.data,yield new Ct.FI({event:{case:"stderr",value:new Ct.Db({data:t.data})}});else if("stdin_ready"===t.type)b=t.stdin,S=t.pid;else if("exit"===t.type){let r;t.aborted&&(r=e.signal?.aborted?Ct.Lv.USER_ABORT:w?.timedOut||p.signal.aborted?Ct.Lv.TIMEOUT:Ct.Lv.USER_ABORT),yield new Ct.FI({event:{case:"exit",value:new Ct.vb({code:(t.code??0)>>>0,cwd:await this.coreExecutor.getCwd(),outputLocation:t.outputLocation,aborted:t.aborted,abortReason:r,localExecutionTimeMs:Gd(t.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof io.SandboxUnsupportedError))throw r;const i=o?.type??"unknown";return Cv.warn(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:i,reason:r.reason}),void(yield new Ct.FI({event:{case:"sandboxUnsupported",value:new Ct.rI({command:n,workingDirectory:a,sandboxPolicyType:i,reason:r.reason??r.message,isReadonly:"workspace_readonly"===i})}}))}finally{clearTimeout(y),w?.backgroundRequested||clearTimeout(P),_()}if(w?.backgroundRequested&&!x){const r=k??this.backgroundShellManager.generateShellId();k=r;const o=w.backgroundReasonValue===Ct.Jg.USER_REQUEST?Ct.Jg.USER_REQUEST:Ct.Jg.TIMEOUT,i=o===Ct.Jg.USER_REQUEST?Date.now()-l:s;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:n,workingDirectory:a,toolCallId:t.toolCallId,sandboxPolicy:g,initialOutput:E,stdin:b,pid:S,abortController:p,eventIterator:w.getHandoffIterator(),startTime:l,showElapsedTime:m,description:t.description,outputNotification:t.outputNotification}),yield new Ct.FI({event:{case:"backgrounded",value:new Ct.Y9({shellId:r,command:n,workingDirectory:a,pid:S,msToWait:m?i:void 0,reason:o})}})}else e.signal?.aborted&&void 0!==w?.stopReasonValue?(clearTimeout(P),yield new Ct.FI({event:{case:"exit",value:new Ct.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(),aborted:!0,abortReason:Ct.Lv.USER_ABORT})}})):clearTimeout(P)}catch(e){r.error=e,r.hasError=!0}finally{xv(r)}}}var Iv=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class Tv{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new Iv.M({allowlisted:r})}}var Rv=r("node:constants");const Av="win32"===process.platform;function Ov(e,t){return Av&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==a.sep&&(e+=a.sep),t.startsWith(e))}process.platform;const Mv=(0,a.join)((0,s.homedir)(),".cursor","projects"),jv=(0,a.join)((0,s.homedir)(),".cursor","worktrees");function Dv(e){return Ov(Mv,e)&&e!==Mv}function Nv(e){return Ov(jv,e)&&e!==jv}function $v(e,t){const r=function(e){if(!Ov(Mv,e))return;if(e===Mv)return;const t=(0,a.relative)(Mv,e).split(a.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}var Lv=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Fv=(0,h.h)("LocalWriteExecutor"),Uv=async(e,t,r,n)=>{const o=setTimeout((()=>{Fv.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};class Bv{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:i,onWriteForAiTracking:s}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=i,this.onWriteForAiTracking=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,o=t.path,i=t.fileText,s=t.fileBytes.length>0?t.fileBytes:void 0,l=(0,ao.o1)(o,this.workspacePath),u=$v(l,["assets","agent-tools","swarm-agents"]);if((0,ao.fl)({targetPath:l,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new _t.v3({result:{case:"error",value:new _t.QM({path:l,error:ao.PS})}});let d,h=!1;try{(await(0,no.stat)(l)).size<=Rd?d=await Uv(n,"readText before write",3e3,(()=>Mc(l,t.encodingHint))):h=!0}catch{}const p=await Uv(n,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(n,l,i)));if(p){const e=await Uv(n,"handleBlockReason",3e3,(()=>To(p,{onNeedsApproval:async(e,r)=>{const n="fileEdit"!==r?.type||r.isNewFile,o="fileEdit"===r?.type?r.diffString:i,s="fileEdit"===r?.type?r.blockReason:void 0,a=await this.pendingDecisionProvider.requestApproval({type:Ad.Write,details:{path:l,reason:e,isNewFile:n,diffString:o,before:d,after:i,blockReason:s},toolCallId:t.toolCallId});return a.approved?null:new _t.v3({result:{case:"rejected",value:new _t.en({path:l,reason:a.reason||""})}})},onUserRejected:e=>new _t.v3({result:{case:"rejected",value:new _t.en({path:l,reason:e||""})}}),onPermissionDenied:(e,t)=>new _t.v3({result:{case:"permissionDenied",value:new _t.U7({path:l,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const f=(0,a.dirname)(l);try{await Uv(n,"mkdir",3e3,(()=>(0,no.mkdir)(f,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new _t.v3({result:{case:"permissionDenied",value:new _t.U7({path:l,directory:f,operation:"create_directory",error:"Permission denied"})}}):new _t.v3({result:{case:"error",value:new _t.QM({path:l,error:e.message})}})}let m,g;if(void 0!==s)m=s,g=0;else{const e=await Uv(n,"getBufferForWrite",3e3,(()=>jc(l,i,this.workspacePath,t.encodingHint)));m=e.buffer,g=e.lines}try{await Uv(n,"writeFile",3e3,(async()=>{let e;await(0,no.writeFile)(l,m,{flush:!0});try{e=await(0,no.open)((0,a.dirname)(l),Rv.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new _t.v3({result:{case:"permissionDenied",value:new _t.U7({path:l,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new _t.v3({result:{case:"noSpace",value:new _t.bM({path:l})}}):new _t.v3({result:{case:"error",value:new _t.QM({path:l,error:e.message})}})}if(this.fileChangeTracker&&void 0===s&&!u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(l,d,i,e)}if(this.onWriteForAiTracking&&void 0===s&&!u){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:l,beforeContent:d,afterContent:i,metadata:e})}catch(e){Fv.warn(n,"onWriteForAiTracking failed (write succeeded)",{path:l,error:e instanceof Error?e.message:String(e)})}}const v=m.byteLength;let y;if(t.returnFileContentAfterWrite)try{y=await Uv(n,"readText after write",3e3,(()=>Mc(l,t.encodingHint)))}catch{}return new _t.v3({result:{case:"success",value:new _t.j6({path:l,linesCreated:g,fileSize:v,...void 0!==y&&{fileContentAfterWrite:y}})}})}catch(e){r.error=e,r.hasError=!0}finally{Lv(r)}}}const zv=(0,h.h)("local-exec:provider");class Wv extends G{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,a.join)(e,".cursor/sandbox.json");try{const r=(0,i.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,io.parseSandboxPolicyJson)(n);return(0,io.resolvePolicyPaths)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.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.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig;const o=this.terminalExecutor??(0,io.createDefaultTerminalExecutor)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let l;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,a.dirname)(e)));l=e.every((t=>t===e[0]))?e[0]:void 0}else l=t;let c=new Sv(o,t??(0,s.homedir)(),this.projectDir,e.shellOutputBackpressureOptions,e.shellExtraEnvProvider);e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Ev(c,this.askpassConfig)),this.shellManager&&(c=new kv(c,this.shellManager));const u=e.overrideShellExecutor??new lv(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore);this.register(Pt,zm(u)),this.register(ht,zm(new Vf(this.permissionsService,this.ignoreService,l??t??this.projectDir)));const d=e.overrideWriteExecutor??new Bv(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:l,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking});this.register(Tt,zm(d)),this.register(se,zm(new Md(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,l,e.onDeleteForAiTracking))),this.register(le,zm(new Ld)),this.register(ce,new mg);const h=this.mcpStateAccessor??new rv(this.mcpLease);this.register(ue,zm(new Nf(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:h})));const p=zm(e.overrideReadExecutor??new jg(this.permissionsService,l,{mcpStateAccessor:h,useStreamingRead:e.useStreamingRead}));this.register(bt,p),e.registerRedactedReadExecutor&&this.register(St,p);const f=new Uf(this.permissionsService,this.ignoreService,l);this.register(tt,zm(f)),this.register(yt,zm(new Rm(this.permissionsService,l))),this.register(pt,zm(new om(u))),this.register(ft,zm(new gm(this.permissionsService,d,l))),this.register(wt,zm(new Mm(d,l))),this.register(gt,zm(new xm(this.permissionsService,l))),this.register(mt,zm(new bm(this.permissionsService,l))),this.register(vt,zm(new Pm(this.permissionsService,l))),this.register(ae,zm(new Ym(l,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(oe,zm(new qm(e.getCanvasDiagnostics))),this.register(at,zm(new hf(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded))),this.register(lt,zm(new pf(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ct,zm(new ff(this.mcpLease,l||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(ut,zm(new ov(h,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const m=zm(this.sharedRequestContextExecutor??new iv(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,f,h,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,ao.yn)(t,(0,s.homedir)()),createFileWatcher:this.createFileWatcher,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:e.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,artifactsFolder:e.artifactsFolder,secretRedactionEnabled:e.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor}));this.register(Ut,{execute:async(t,r,n)=>{const o=await m.execute(t,r,n);if("success"!==o.result.case||void 0===o.result.value.requestContext)return o;const i=o.clone();if("success"!==i.result.case)return o;const s=i.result.value.requestContext;if(void 0===s)return i;const a=await h.getState(t),l=Yg(a,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors});if(s.tools=l.tools,s.mcpInstructions=l.mcpInstructions,s.mcpMetaToolOptions=this.mcpMetaToolEnabled?Xg(a,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors}):void 0,s.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t)),void 0!==e.getMountedAgentStores&&void 0!==s.env)try{const r=await e.getMountedAgentStores(t);s.env.mountedAgentStores=r.map((e=>e.clone()))}catch{s.env.mountedAgentStores=[],zv.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new Go(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(ee,zm(this.backgroundShellExecutor));const g=new Pv(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(It,function(e,t){const r=new oo.q({max:10,ttl:t?.ttl});return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const i=o.execId,s=r.get(i);if(s)return void(yield*s.fork());const a=e.execute(t,n,o),l=new Bm(a);r.set(i,l),yield*l.fork()}}}(g)),void 0!==e.agentStoreConflictDrainer&&this.register(X,new Nm(e.agentStoreConflictDrainer)),this.register(zt,new uv(this.permissionsService)),this.register(dt,new vg(this.permissionsService)),this.register(Qt,new Tv(this.permissionsService));const v=new dv(g);this.register(Wt,zm(v));const y=!1===e.enableWriteBackgroundShellStdin?new $m((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $m(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(te,zm(y)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(ie,zm(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new Lg({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Ft,zm(this.recordScreenExecutor))}}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function Hv(e){return e.replace(/\\/g,"/")}function qv(e,t){for(const r of t){const t=Hv(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var Gv;function Vv(e,t){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return Gv.Plugin;const r=Hv(e.fullPath);return qv(r,t.builtinDirs)?Gv.Builtin:qv(r,t.userDirs)?Gv.UserHome:(qv(r,t.workspaceDirs),Gv.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserHome=1]="UserHome",e[e.Workspace=2]="Workspace",e[e.Plugin=3]="Plugin"}(Gv||(Gv={}));var Jv=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kv=(0,Zo.debuglog)("merged-agent-skills");class Zv{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,c.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(Kv("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),[o,i]=await Promise.all([Promise.all(n),Promise.resolve(this.getDisabledManagedSkillPaths()).catch((e=>(Kv("getDisabledManagedSkillPaths rejected; fail-open: %s",e instanceof Error?e.message:String(e)),[])))]),s=o.flat(),l=new Set,u=[];for(const e of s){const t=$u(e.fullPath);l.has(t)||(l.add(t),u.push(e))}let d=u;i.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,i))));const h=this.getPromptSortContext;return void 0!==h?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bu(e.userHomeDirectory).dirPath],r=ku(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,a.join)(t,".cursor","rules"));for(const e of Su(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,t)=>({skill:e,index:t,tier:Vv(e,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,h()):d}catch(e){t.error=e,t.hasError=!0}finally{Jv(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()}),Zv.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()}}Zv.CHANGE_COALESCE_MS=1500;const Yv=(0,h.h)("skill-sync-manifest"),Xv=".sync-manifest.json";async function Qv(e,t){try{const r=await(0,no.readFile)((0,a.join)(e,Xv),"utf-8"),n=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)}(n)?n:(Yv.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||Yv.warn(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ey(e,t,r){e.skills[t]={lastSyncedAt:r}}function ty(e,t){delete e.skills[t]}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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ny=(0,h.h)("builtin-skills-sync");function oy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iy(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||a.posix.isAbsolute(t)||a.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===a.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function sy(e){const t=tl(e.content),r=oy(t.data)?t.data:{};return rl(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...oy(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ay(e,t,r){const n=(0,a.join)(t,r.id),o=(0,a.join)(n,"SKILL.md"),i=r.fileContent,s=Object.keys(r.resources),l=await ly(n);if(s.length>0||l.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...l]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,no.readFile)((0,a.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,a.join)(e,t.id),n=await(0,no.mkdtemp)((0,a.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,no.writeFile)((0,a.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,a.join)(n,...e.split("/"));await(0,no.mkdir)((0,a.dirname)(t),{recursive:!0}),await(0,no.writeFile)(t,r,"utf-8")}try{await(0,no.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==e.code)throw e}try{await(0,no.rename)(n,r)}catch(e){throw i&&(await(0,no.rename)(o,r),i=!1),e}i&&(await(0,no.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,no.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,no.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||ny.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,no.mkdir)(n,{recursive:!0}),await(0,no.writeFile)(o,i,"utf-8"),!0}async function ly(e,t=""){const r=t?(0,a.join)(e,...t.split("/")):e;let n;try{n=await(0,no.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===e.code)return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await ly(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function cy(e,t){try{return(await(0,no.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||ny.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function uy(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 n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("syncBuiltinSkills")),!1).ctx,i=Date.now(),l=(0,a.join)((0,s.homedir)(),".cursor","skills-cursor");await(0,no.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([Qv(l,o),cy(o,l)]),h=u.lastInventoryAt;(void 0===h||i-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,a.join)(t,e),[o,i]=await Promise.all([dy((0,a.join)(r,"SKILL.md")),"canvas"===e?dy((0,a.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ny.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ny.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(o,l,d,u),u.lastInventoryAt=i);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ny.warn(o,"Skipping managed skill with unsafe id",{skillId:e.id});const f=new Set([...p.keys(),...d]);let m=0,g=0;const v=[];for(const e of f)try{const t=p.get(e),r=u.skills[e],n=r?i-r.lastSyncedAt:0,s=void 0!==r&&n>2592e5;if(t&&!1!==t.enabled)iy(t),await ay(o,l,{id:e,fileContent:sy(t),resources:t.resources??{}})?m++:g++,ey(u,e,i);else if(!1===t?.enabled||s){const n=!1===t?.enabled?"enabled_false":"grace_expired";await(0,no.rm)((0,a.join)(l,e),{recursive:!0,force:!0}),ty(u,e),v.push(e),ny.info(o,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?i-r.lastSyncedAt:null})}else r||ey(u,e,i)}catch(t){ny.warn(o,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,a.join)(e,".sync-manifest.json.tmp"),n=(0,a.join)(e,Xv);await(0,no.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,no.rename)(r,n)}(l,u)}catch(e){ny.warn(o,"Failed to persist sync manifest",{skillDir:l,error:String(e)})}return{synced:m,upToDate:g,removed:v}}catch(e){r.error=e,r.hasError=!0}finally{ry(r)}var n}async function dy(e){try{return await(0,no.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const hy=(0,h.h)("managed-skills-sync");function py(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 fy{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,i="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,s=r.mcpConfig;s&&t.push(...us(s,e,n,o,i,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=py(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var my=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function gy(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class vy{constructor(e,t,r,n,o,i){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=i,this.plugins=[],this._loadFailures=[],this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Xo,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{let t=[];try{t=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const r=new Set(e.plugins.map((e=>e.installPath))),n=t.filter((e=>!r.has(e.installPath)));return this.plugins=[...e.plugins,...n],this._loadFailures=e.failures,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${n.length} extension), ${e.failures.length} failures`),this.plugins})).catch((async e=>{this.pluginLogger.log("error",`Failed to load plugins: ${e}`);try{const e=await this._reloadExtensionPlugins();this.plugins=[...e]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${e}`),this.plugins=[]}return this._loadFailures=[],this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=gy(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,i=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let s,a,l;for(const c of t){let t;try{t=await Wl({...c,log:c.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=>o(e)&&void 0===e.loadError));if(void 0!==u){s=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,l=t.failures.find((t=>i(t,e)))}}if(void 0===s){if(void 0!==a){const t=n(a),r={...l??{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=>!i(e,t))),r]}return}const c=this.plugins.findIndex(o);if(-1===c)this.plugins=[...this.plugins,s];else{const e=[...this.plugins];e[c]=s,this.plugins=e}this.loadedOnce=!0;const u=n(s);return this._loadFailures=this._loadFailures.filter((e=>!i(e,u))),s}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,a.resolve)(e),n=await(0,no.realpath)(r);if(!(await(0,no.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const o=s.homedir();if(n.split(a.sep).filter(Boolean).length<3||n===o||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let i=this._extensionPlugins.get(t);if(i||(i=new Map,this._extensionPlugins.set(t,i)),i.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const l=(0,a.basename)(n),c=await this._loadExtensionPluginContent(n,t);i.set(n,c),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${l} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,a.resolve)(e);let o;try{o=await(0,no.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,a.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Fl(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${e}`);const o=this._extensionPlugins.get(n),i=o?.get(r);i&&t.push(i)}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,Qe.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,c.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=gy(this.marketplaceOptions,this.userHomeDirectory),s=o.importThirdPartyPlugins,l=o.loadUserLocalPlugins??!0,u=o.loadCursorFirstParty??i.length>0;if(!s&&!u&&!l)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[]};this.pluginLogger.increment("local_plugins_service.load.start",1);const d=this.workspacePaths[0]??void 0,h=(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 function(e){return yl(this,arguments,void 0,(function*(e,t={}){var r,n,o,i,s;const l=null!==(r=t.log)&&void 0!==r?r:Xo,c=performance.now(),u=null===(n=t.loadClaude)||void 0===n||n,d=null===(o=t.loadUserLocal)||void 0===o||o,h=null!==(i=t.marketplaceSources)&&void 0!==i?i:[],p=null!==(s=t.loadCursorFirstParty)&&void 0!==s?s:h.length>0,f=[],m=[];let g;u&&f.push(zl(e,void 0,{userHomeDir:t.userHomeDir,onError:t.onError,log:l})),p&&h.length>0&&(g=Promise.all(h.map((e=>{var r,n;return Wl(Object.assign(Object.assign({},e),{userHomeDir:null!==(r=e.userHomeDir)&&void 0!==r?r:t.userHomeDir,log:null!==(n=e.log)&&void 0!==n?n:l}))})))),d&&f.push(function(){return yl(this,arguments,void 0,(function*(e={}){var t,r,n;const o=null!==(r=e.log)&&void 0!==r?r:Xo,i=performance.now(),s=null!==(n=e.userHomeDir)&&void 0!==n?n:process.env.HOME;if(!s)return o.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const l=(0,a.join)(s,".cursor","plugins","local");let c;try{c=yield(0,no.readdir)(l,{withFileTypes:!0})}catch(e){return o.log("info",`loadUserLocalPlugins: ${l} not found or not readable (${(performance.now()-i).toFixed(1)}ms)`),[]}const u=yield(0,no.realpath)(l).catch((()=>(0,a.resolve)(l))),d=[];for(const r of c){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,a.join)(l,r.name);try{if(r.isSymbolicLink()){let e;try{e=yield(0,no.realpath)(n)}catch(e){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{va(u,e)}catch(t){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${l}`);continue}}if(!(yield(0,no.stat)(n)).isDirectory()){r.isSymbolicLink()&&o.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const i=performance.now(),s=yield null===(t=e.localPluginVariablesLookup)||void 0===t?void 0:t.call(e,r.name),{displayName:a,description:c,authorName:h,variablesSchema:p,skills:f,rules:m,agents:g,commands:v,mcpConfig:y,capabilities:w,hooks:b}=yield Fl(n,r.name,void 0,{configuredVariables:s}),S={source:"user-local",sourceInfo:{name:r.name,localPath:n}};d.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:S,installPath:n},void 0!==a&&{displayName:a}),void 0!==c&&{description:c}),void 0!==h&&{authorName:h}),{variablesSchema:p,skills:f,rules:m,agents:g,commands:v,mcpConfig:null!=y?y:void 0,capabilities:w,hooks:b})),o.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-i).toFixed(1)}ms`)}catch(e){o.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return o.log("info",`loadUserLocalPlugins completed in ${(performance.now()-i).toFixed(1)}ms (${d.length} plugins loaded)`),d}))}({userHomeDir:t.userHomeDir,log:l,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[v,y]=yield Promise.all([Promise.all(f),null!=g?g:Promise.resolve([])]),w=[];for(const e of y)w.push(...e.plugins),m.push(...e.failures);w.push(...v.flat());const b=new Set,S=[];for(const e of w){if(!e.installPath){S.push(e);continue}const t=yield(0,no.realpath)(e.installPath).catch((()=>e.installPath));b.has(t)||(b.add(t),S.push(e))}const k=new Map,E=[];for(const e of S){const t=Hl(e);if(void 0!==t){const r=k.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=E.findIndex((e=>Hl(e)===t&&e.loadError));-1!==r&&E.splice(r,1),k.set(t,!0),E.push(e);continue}k.set(t,n)}E.push(e)}const x=performance.now()-c;return l.log("info",`loadAllPlugins completed in ${x.toFixed(1)}ms (claude=${u}, userLocal=${d}, marketplace=${h.length} sources, total=${E.length} plugins, failures=${m.length})`),{plugins:E,failures:m}}))}(d,{userHomeDir:this.userHomeDirectory,loadClaude:s,loadUserLocal:l,loadCursorFirstParty:u&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:h}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${e}`),{plugins:[],failures:[]}}}catch(t){e.error=t,e.hasError=!0}finally{my(e)}}}const yy=BigInt(0),wy=BigInt(8),by=BigInt(16),Sy=BigInt(65535);function ky(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Ey(e){const t=e.split(".");if(4!==t.length)return;let r=yy;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<<wy|BigInt(t)}return{version:4,value:r}}function xy(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=Ey(n);if(!o)return;t.push(Number(o.value>>by&Sy)),t.push(Number(o.value&Sy))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Cy(e){var t;return null!==(t=Ey(e))&&void 0!==t?t:function(e){const t=ky(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=xy(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<by|BigInt(t)),yy)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),i=xy(n),s=xy(o);if(!i||!s)return;const a=i.length+s.length;return a>7?void 0:{version:6,value:[...i,...new Array(8-a).fill(0),...s].reduce(((e,t)=>e<<by|BigInt(t)),yy)}}(e)}function _y(e,t){const r=ky(e),n=ky(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=Cy(t.slice(0,r)),o=Cy(e);if(!n||!o||n.version!==o.version)return!1;const i=Number(t.slice(r+1)),s=4===n.version?32:128;if(!Number.isInteger(i)||i<0||i>s)return!1;const a=BigInt(s-i);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Py(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(e){return}}(e);return!!r&&function(e,t){return t.some((t=>_y(e,t)))}(r.hostname,t)}const Iy=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Ty(e){return e.trim().split(/\s+/).filter(Boolean)}function Ry(e){var t;const r=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 Ty(t)[0]}(e);if(!r)return!1;const n=r.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),o=(null!==(t=n[n.length-1])&&void 0!==t?t:"").replace(/\.exe$/i,"").toLowerCase();return Iy.has(o)}function Ay(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 Oy(e,t){return e.commandName.localeCompare(t.commandName)}function My(e){var t;return null!==(t=e.split(" ")[0])&&void 0!==t?t:e}function jy(e,t){return function(e,t){const r=function(e){var t;const r=new Set,n=[];for(const o of e){const e=o.trim();if(!e||r.has(e))continue;r.add(e);const i=Ty(e),s=null!==(t=i[0])&&void 0!==t?t:e;n.push({id:e,label:e,value:e,commandName:s,tokenCount:i.length,indentLevel:0,tokens:i,ancestorIds:[e]})}n.sort(Oy);for(let e=0;e<n.length;e++){const t=n[e],r=new Set(t.tokens);let o,i=!1;for(let s=0;s<e;s++){const e=n[s];if(e.commandName!==t.commandName)continue;if(e.tokenCount>=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!r.has(t)){a=!1;break}if(!a)continue;const l=Ay(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,i=l):e.tokenCount===o.tokenCount&&l&&!i&&(o=e,i=!0):(o=e,i=l)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const o=n.filter((e=>!n.some((t=>t.id!==e.id&&t.tokenCount<e.tokenCount&&Ay(t.tokens,e.tokens))))).map((e=>e.id));return{options:n,defaultSelectedOptionIds:o}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],i=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),i.add(My(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),s=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(s.length>0){const e=s.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),i.add(My(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length<t.id.length?e:t));o.push(e.id),i.add(My(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const s=n.filter((e=>!i.has(My(e))));return{defaultSelectedOptionIds:[...new Set([...s,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}function Dy(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function Ny(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 $y(e,t){const r=(0,ao.o1)(e,t);try{return Dy(await(0,no.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return Dy(r,r,Ny(t));try{if((await(0,no.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,no.readlink)(r)}catch{}return Dy(r,r,{status:"danglingSymlink",symlinkTarget:e})}return Dy(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){const t=e;return"ENOENT"===t.code?async function(e){let t=(0,a.dirname)(e);const r=[(0,a.basename)(e)];for(;(0,a.dirname)(t)!==t;){try{const n=await(0,no.realpath)(t);return Dy((0,a.join)(n,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return Dy(e,e,Ny(r))}r.unshift((0,a.basename)(t)),t=(0,a.dirname)(t)}return Dy(e,e,{status:"newFile"})}(r):Dy(r,r,Ny(t))}}}function Ly(e){return"resolved"===e.status||"newFile"===e.status}function Fy(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}var Uy=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},By=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zy=(0,h.h)("permissions-service"),Wy=(0,p.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 Hy(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 qy(e){return[...new Set(e)]}function Gy(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Vy(e,t){const r="win32"===process.platform||"darwin"===process.platform,n=r?e.toLowerCase():e,o=r?t.toLowerCase():t;if(n===o)return!0;const i=o.endsWith(a.sep)?o:o+a.sep;return n.startsWith(i)}function Jy({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),i=r.relative(n,o);return""===i||".."!==i&&!i.startsWith(`..${r.sep}`)&&!r.isAbsolute(i)}function Ky(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Zy(e){return"<"!==e.operator&&"<&"!==e.operator}function Yy(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Xy(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function Qy({targetText:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n,pathModule:o,tempPathOptions:i}){if(""!==o.parse(e).root&&!o.isAbsolute(e))return;const s=await n(e,t);if(Ly(s.resolution)){for(const e of r){const t=await n(e);if(Ly(t.resolution)&&Jy({basePath:t.resolvedPath,targetPath:s.resolvedPath,pathModule:o}))return"workspace-file"}return sw(s.resolvedPath,i)?"tmp-file":void 0}}function ew(e){return qy(e.map((e=>e.trim())).filter(Boolean))}function tw(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const i=`${t} ${o.join(" ")}`;return i===n?[n]:[n,i]}function rw(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function nw(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new Ct.r6({type:"word",value:e})));return new Ct.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function ow(e,t={}){return{type:e,...t}}function iw(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1],n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function sw(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),i=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(i)}return!1}const i=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},s=i(e);return(void 0===o||!Jy({basePath:i(o),targetPath:s,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>s.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>s.startsWith(e))))}function aw(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,io.isNetworkEnabledByPolicy)(e.networkPolicy),n=(0,io.isNetworkEnabledByPolicy)(t.networkPolicy);if(r&&!n)return!1;const o=(0,io.isAllowAllNetworkByPolicy)(e.networkPolicy),i=(0,io.isAllowAllNetworkByPolicy)(t.networkPolicy);return!(o&&n&&!i)&&("workspace_readonly"===e.type&&"workspace_readwrite"===t.type||e.type===t.type)}class lw{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&aw(t,r);this.state=o?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!aw(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function cw(e){return e?.type??"undefined"}class uw{constructor(e,t,r,n,o,i=!1,l){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=i,this.rootDirectories=Array.isArray(o)?o:[o??process.cwd()],this.perUserSandboxConfigPath=l?.perUserSandboxConfigPath??(0,a.join)((0,s.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=l?.mcpAllowlistLog}async shouldBlockRead(e,{cursorIgnoreChecked:t=!1}={}){const r=(0,ao.o1)(e),n=await iu(r);return null===n?{type:"unsafeResolution",message:Hy("Read","path",r)}:await this.ignoreService.isRepoBlocked(n)?{type:"adminBlock",source:"Team repo blocklist"}:await this.isPathExplicitlyDenied("Read",r)?{type:"permissionsConfig"}:!Dv(n)&&!Nv(n)&&(!t&&await this.ignoreService.isCursorIgnored(n)?{type:"cursorIgnore"}:(await this.isPathExplicitlyAllowed("Read",r),!1))}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Uy(n,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const o=await $y(t);if(!Ly(o.resolution))return{type:"unsafeResolution",message:Fy(o.originalPath,o.resolution)};const i=o.resolvedPath,u=i;if(await this.ignoreService.isRepoBlocked(u))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",i))return{type:"permissionsConfig"};const d=o.originalPath.split(a.sep).pop()?.toLowerCase()??"",h=i.split(a.sep).pop()?.toLowerCase()??"";if(".cursorignore"===d||".cursorignore"===h)return{type:"permissionsConfig"};const p=Dv(u),f=Nv(u),m=!p&&!f&&await this.ignoreService.isCursorIgnored(u);if(p||f);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",i))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(i))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 $y(e);if(!Ly(t.resolution))continue;const r=t.resolvedPath;if(Vy(i,r)){const e=(0,a.relative)(r,i).split(a.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const v=async()=>{let e=!1,t="";try{t=await Mc(i),e=!1}catch{e=!0}let n="";if(e)n=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,am.YB)("a","b",e(t),e(r),"","",{context:2});n=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:n}};let y,w=!1;for(const e of this.rootDirectories){const t=await $y(e);if(!Ly(t.resolution))continue;const r=t.resolvedPath;if(Vy(i,r)){w=!0,y=r;break}}const b=w?void 0:function(e){if(!Nv(e))return;const t=(0,a.relative)(jv,e).split(a.sep).filter(Boolean);return 0!==t.length?(0,a.join)(jv,t[0]):void 0}(i);if(!w&&void 0===b){if(function(e){return sw(e,{platform:process.platform,env:process.env,pathModule:l,homeDirectory:(0,s.homedir)()})}(i))return!1;if($v(i,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,s.homedir)()}${a.sep}.cursor${a.sep}`;if(i.startsWith(e)){const e=i.split(a.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const S=y??b,k=i;let E=(0,a.relative)(S,k).split(a.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 v();return{type:"needsApproval",approvalReason:`Protected config file: ${E[E.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,io.isHardcodedWriteProtected)(i,S)){const e=E[E.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}return await this.checkCursorFileProtection(E)||!1}catch(e){n.error=e,n.hasError=!0}finally{By(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await iu(t.workingDirectory);if(null===n){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Hy("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(n))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const o=(await this.getPermissions()).userConfiguredPolicy,i=r??o;return"workspace_readonly"===o.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,n){const o=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory},n);if("block"===o.kind)return o;const i=await this.getPermissions(),s=i.approvalMode,a="unrestricted"===s,l=i.userConfiguredPolicy,c=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(zy.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:s,userConfiguredPolicyType:cw(l),requestedPolicyType:cw(n),effectiveRequestedPolicyType:cw(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Gt(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 zy.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:s,userConfiguredPolicyType:cw(l),requestedPolicyType:cw(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const u=r.parsingResult.executableCommands,d=r.parsingResult.hasRedirects,h=!0===r.parsingResult.allRedirectsAreDevNull,p=r.parsingResult.parsingFailed,f=r.classifierResult,m=r.smartModeApprovalReason,g=r.smartModeApprovalRequestId,v=void 0!==f&&!f.classificationFailed&&f.commands.length>0?f:void 0,y="allowlist"===s&&i.smartAllowlistEnabled?v?.commands:void 0,w=void 0!==y,b=y?y.map(nw):u,S=void 0!==y?y.map(tw):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==v?v.commands.map(tw):S;if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,io.isNetworkEnabledByPolicy)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,io.isAllowAllNetworkByPolicy)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}f&&zy.info(e,"Smart allowlist: classifier result received",{classificationFailed:f.classificationFailed,suggestedSandboxMode:f.suggestedSandboxMode,commandCount:f.commands.length,suggestedAllowlistEntryCount:f.commands.filter((e=>e.suggestedAllowlistEntry)).length});let E=!1;const x=[],C=[];let _=[],P=[],I=[];const T=ew(i.smartAllowlistDenylist??[]);if(T.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;e<k.length;e++){const r=k[e];if(r&&0!==r.length&&T.some((e=>rw(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(zy.info(e,"Command blocklist: commands require approval",{count:P.length}),x.push(`In blocklist: ${P.join(", ")}`))}if(w&&f){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));zy.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:T.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;e<f.commands.length;e++){if(n[e])continue;const t=f.commands[e];t&&s.push(t)}if(_=ew(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(Ry(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],i=[t];for(const e of r)i.push(e),o.push(i.join(" "));const s=[t,...n].join(" ");return o.includes(s)||o.push(s),ew(o)}(e)))),I=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>_.includes(e))),_.length>0){const e=jy(_,I),t=e.length>0?e.join(", "):_.join(", ");C.push(`Not in allowlist: ${t}`)}E=o&&0===P.length,E&&zy.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const R="ask-every-time"===s||"insecure_none"===n.type&&"allowlist"===s?void 0:l,A=b.map(((e,t)=>new lw(e,n,R,S[t])));if((0===b.length||p&&!w)&&!a){zy.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:s,requestedPolicyType:cw(n),userConfiguredPolicyType:cw(l),isSmartAllowlistActive:w,parsingFailed:p,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==m,hasSmartModeApprovalRequestId:void 0!==g});const o={type:Ad.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:m??(p?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:m,smartModeApprovalRequestId:g}},i=await this.pendingDecisionStore.requestApproval(o);return i.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:i.reason}}}if(await this.hasHardDeny(e,A))return{kind:"block",reason:{type:"permissionsConfig"}};const{allRedirectsAreWorkspaceFileSafe:O,redirectsAllowlistSafe:M}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory),j=await this.teamSettingsService.getAutoRunControls(),D={type:"insecure_none"};for(const e of A)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:M,autoRunControls:j,applyTeamAllowlist:c})&&e.approveWithPolicy(D);for(const e of A)j&&this.isInTeamBlocklist(j,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of A)"rm"===e.command.name&&e.deny();const $=this.buildShellApprovalDecisionFacts({commands:A,autoRunControls:j,shouldApplyTeamShellAllowlist:c,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return zy.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=Gt(r.hookApprovalRequirement),F=r.hookApprovalRequirement?.reason,U=L?void 0:this.getShellAutoApprovalPolicy({approvalMode:s,isUnrestricted:a,requestedPolicy:n,facts:$,preserveRequestedPolicyForAllowlistedCommands:w}),B=void 0!==U&&$.allCommandsAllowlisted&&"insecure_none"===U.type&&"allowlistEscalated"in U&&!0===U.allowlistEscalated;if(U&&(void 0===m||B)){w&&$.allCommandsPreapproved&&!$.allCommandsAllowlisted&&zy.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(U);return zy.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:s,requestedPolicyType:cw(n),userConfiguredPolicyType:cw(l),autoApprovalPolicyType:cw(U),mergedPolicyType:cw(t),isSmartAllowlistActive:w,smartModeApprovalBypassedByAllowlist:B,allCommandsRunnable:$.allCommandsRunnable,allCommandsAllowlisted:$.allCommandsAllowlisted,allCommandsPreapproved:$.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==m,commandCount:A.length}),{kind:"allow",policy:t}}let z=(w||(!d||h||O)&&!p)&&("allowlist"===s||"ask-every-time"===s)&&$.canAllowlistInPrompt;const W=[],H=void 0!==m,q=$.notInTeamAllowlist.length>0&&($.hasSecurityDenies||$.hasSoftDenies||!$.allCommandsRunnable);if(void 0!==m&&W.push(m),L&&(H||W.push(F?`Hook requested approval: ${F}`:"Hook requested approval"),z=!1),x.length>0&&(H||W.push(...x),z=!1),!H)if(w&&C.length>0)W.push(...C);else if($.unapprovedCommands.length>0){const e=jy(this.generateAllowlistPatterns($.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):$.unapprovedCommands.map((e=>e.command.fullText)).join(", ");W.push(`Not in allowlist: ${t}`)}if($.hasSecurityDenies&&(H||($.rmDeniedByDeleteProtection.length>0&&W.push("Delete protection is enabled"),$.teamBlocklistedCommands.length>0&&W.push(`In team blocklist: ${$.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),q){const t=$.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");zy.info(e,"Shell permissions: commands not in team allowlist",{commandCount:$.notInTeamAllowlist.length}),H||W.push(`Not in team allowlist: ${t}`),z=!1}const G=W.join(" • "),V=[];if(z){const e=void 0!==m?A.filter((e=>"allowlisted"!==e.state)):$.unapprovedCommands;V.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const J=w&&C.length>0,K=J?_:V,Z=J&&I.length>0?I:void 0,Y="insecure_none"!==n.type&&"insecure_none"!==l.type,X="insecure_none"!==n.type,Q=[void 0!==m?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,x.length>0?"command_blocklist":void 0,w&&C.length>0?"smart_allowlist_miss":void 0,$.unapprovedCommands.length>0?"unapproved_commands":void 0,$.hasSecurityDenies?"security_denies":void 0,q?"team_allowlist_miss":void 0].filter((e=>void 0!==e));zy.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:s,requestedPolicyType:cw(n),userConfiguredPolicyType:cw(l),isSandboxAvailable:Y,isSandboxEnabled:X,canAllowlist:z,isSmartAllowlistActive:w,hasSmartModeApprovalReason:void 0!==m,hasSmartModeApprovalRequestId:void 0!==g,hookForcesPrompt:L,approvalReasonTypes:Q,commandCount:A.length,unapprovedCommandCount:$.unapprovedCommands.length,deniedCommandCount:$.deniedCommands.length,notInTeamAllowlistCount:$.notInTeamAllowlist.length,notAllowedCommandCount:K.length,suggestedAllowlistEntryCount:Z?.length??0,allCommandsRunnable:$.allCommandsRunnable,allCommandsAllowlisted:$.allCommandsAllowlisted,allCommandsPreapproved:$.allCommandsPreapproved,hasSecurityDenies:$.hasSecurityDenies,hasSoftDenies:$.hasSoftDenies});const ee={type:Ad.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:G,isSandboxAvailable:"allowlist"===s&&Y,isSandboxEnabled:"allowlist"===s&&X,canAllowlist:z,notAllowedCommands:K,suggestedAllowlistEntries:Z,smartModeApprovalReason:m,smartModeApprovalRequestId:g}},te=await this.pendingDecisionStore.requestApproval(ee);if(te.approved){const e="unrestricted"===s?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:te.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),i=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:s}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory);if(!s)return!1;const a=r.classifierResult,l=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,c=(o.smartAllowlistEnabled??!1)&&void 0!==l;if(r.parsingResult.parsingFailed&&!c)return!1;const u=r.parsingResult.executableCommands,d=c?l.commands.map(nw):u;if(0===d.length)return!1;const h=c?l.commands.map(tw):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==l?l.commands.map(tw):h,f={type:"insecure_none"},m=d.map(((e,t)=>new lw(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=ew(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>rw(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const v=await this.teamSettingsService.getAutoRunControls();if(void 0!==v&&m.some((e=>this.isInTeamBlocklist(v,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:s,autoRunControls:v,applyTeamAllowlist:i}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=await this.foldPerUserFilePolicy(e),r=t.skipStatsigDefaults?t:await this.applyStatsigDefaults(t),n=await this.loadPerRepoFilePolicy(r.type),o=await this.buildTeamAdminPolicy(r.type),i=(0,io.isAllowAllNetworkByPolicy)(e.networkPolicy),{policy:s}=await(0,io.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:r,perRepo:n,teamAdmin:o});return i?{...s,networkPolicy:(0,io.networkAllowAllPolicy)()}:s}async foldPerUserFilePolicy(e){const t=await(0,io.loadSandboxPolicyFromFileOrUndefined)(this.perUserSandboxConfigPath,(0,s.homedir)());if(!t||"insecure_none"===t.type)return e;let r=(0,io.mergeNetworkPolicies)(t.networkPolicy,e.networkPolicy);r&&void 0!==e.networkPolicy?.default&&(r={...r,default:e.networkPolicy.default});const n=(0,io.mergePathsUnion)(t.additionalReadonlyPaths,e.additionalReadonlyPaths),o={...e,networkPolicy:r,additionalReadonlyPaths:n.length>0?n:void 0};if("workspace_readwrite"===e.type&&"workspace_readwrite"===t.type){const r=(0,io.mergePathsUnion)(t.additionalReadwritePaths,e.additionalReadwritePaths);return{...o,additionalReadwritePaths:r.length>0?r:void 0}}return o}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,io.isAllowAllNetworkByPolicy)(e.networkPolicy))return e;const r={default:"deny",allow:qy(t.allowlist)};return{...e,networkPolicy:(0,io.mergeNetworkPolicies)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,io.loadSandboxPolicyFromFileOrUndefined)((0,a.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?ow(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict}):r:void 0}async buildTeamAdminPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return ow(e,{networkPolicy:(0,io.networkDisabledPolicy)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=qy(t.allowlist)),t.denylist.length>0&&(r.deny=qy(t.denylist)),ow(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){const r=e.hasRedirects,n=e.parsingFailed,o=!0===e.allRedirectsAreDevNull,i=!(!r||o||n)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n=$y,pathModule:o=l,tempPathOptions:i={platform:process.platform,env:process.env,pathModule:o,homeDirectory:(0,s.homedir)()}}){if(!e.hasRedirects)return!0;const a=e.redirects;if(0===a.length)return!1;const c=e.executableCommands.length>1,u=Gy();for(const e of a){if(Xy(e))continue;const s=c?Gy():u,{operator:a,targetText:l}=e,h=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=Yy(l),t=void 0===e?void 0:s.fdTargets.get(e);if("original-stdout"!==(d=t)&&"original-stderr"!==d&&"dev-null"!==d&&"workspace-file"!==d&&"tmp-file"!==d){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}for(const e of h)s.fdTargets.set(e,t);continue}if("<&"===a){const e=Yy(l),t=void 0===e?void 0:s.fdTargets.get(e);if("dev-null"!==t){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}for(const e of h)s.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of h)s.fdTargets.set(e,"dev-null");continue}if(!Ky(a)||void 0===l){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}const p=await Qy({targetText:l,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n,pathModule:o,tempPathOptions:i});if(!p){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}for(const e of h)s.fdTargets.set(e,p)}var d;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories}),a=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(Zy))}({parsingResult:e,hasRedirects:r,parsingFailed:n,allRedirectsAreAllowlistSafe:o,allRedirectsAreWorkspaceFileSafe:i});return{allRedirectsAreAllowlistSafe:o,allRedirectsAreWorkspaceFileSafe:i,redirectsAllowlistSafe:a}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const i=e.filter((e=>"denied"===e.state)),s=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],l=i.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),c=o?i.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:i.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===i.length&&0===a.length,unapprovedCommands:s,deniedCommands:i,notInTeamAllowlist:a,teamBlocklistedCommands:l,rmDeniedByDeleteProtection:c}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=this.getEmptyShellAllowlistCandidates(t),o=await this.pendingDecisionStore.requestApproval({type:Ad.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:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==iw(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=iw(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),i=this.matchGlob(r.argsPattern,e);if(t&&i)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===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 n of e)Ry(n.name)||(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}matchesPathEntry(e,t,r){const n=new RegExp(`^\\s*${e}\\s*\\((.*)\\)\\s*$`),o=t.match(n);if(!o)return!1;const i=(o[1]??"").trim(),s=this.expandTilde(i);return this.matchGlob(s,r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}expandTilde(e){return"~"===e?(0,s.homedir)():e.startsWith("~/")?(0,s.homedir)()+e.slice(1):e}matchGlob(e,t){return function(e,t){const r=e.trim(),n=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(r),o=`^${n.replace(/\\\*/g,".*")}$`;try{return new RegExp(o).test(t)}catch(e){return r===t}}(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t){const r={stack:[],error:void 0,hasError:!1};try{Uy(r,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:n,toolName:o,providerIdentifier:i,args:s}=t,a=e=>{this.mcpAllowlistLog?.(e)};a(`[permissions-service] shouldBlockMcp: toolName="${o}", providerIdentifier="${i}"`);const l=await this.getPermissions(),u=await this.teamSettingsService.getMcpToolControls(),d=!0===u?.enabled;if(await this.isMcpExplicitlyDenied(e,i,o))return a(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig"};const h=t.smartModeApproval?.reason;if(void 0!==h)return"workspace_readonly"===l.userConfiguredPolicy.type&&"unrestricted"!==l.approvalMode?(a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0}):(a(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${o}", providerIdentifier="${i}"`),!(d?this.isMcpInTeamAllowlist(u,{providerIdentifier:i,toolName:o}):await this.isMcpExplicitlyAllowed(e,i,o))&&{type:"needsApproval",approvalReason:h,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:i,args:s,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:h,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(d){const t=this.isMcpInTeamAllowlist(u,{providerIdentifier:i,toolName:o});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${o}", providerIdentifier="${i}"`),!1}else{const t=await this.isMcpExplicitlyAllowed(e,i,o);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${o}", providerIdentifier="${i}"`),!1}if("workspace_readonly"===l.userConfiguredPolicy.type&&"unrestricted"!==l.approvalMode)return a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===l.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return a(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${o}", providerIdentifier="${i}"`),!1;a(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${o}", providerIdentifier="${i}"`)}return a(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${o}", providerIdentifier="${i}", approvalMode="${l.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${o}`,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:i,args:s,canAllowlist:!0}}}catch(e){r.error=e,r.hasError=!0}finally{By(r)}}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t;if(await this.isMcpExplicitlyDenied(r,n,o))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o}):await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const i=e.slice(0,o).trim().toLowerCase(),s=e.slice(o+1).trim().toLowerCase(),a=t.lastIndexOf("::mcpScope:"),l=(-1===a?t:t.slice(0,a)).toLowerCase().trim(),c=r.toLowerCase().trim(),u="*"===i||this.matchGlob(i,l),d="*"===s||this.matchGlob(s,c),h=u&&d,p=`[permissions-service] ${n}: serverPattern="${i}", toolPattern="${s}", normalizedProviderIdentifier="${l}", normalizedToolName="${c}", serverMatches=${u}, toolMatches=${d}, result=${h}`;return this.mcpAllowlistLog?.(p),h}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){Wy.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&_y(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r}){return e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r})))}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var dw=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const hw=3e5;BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function pw({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=(r.networkAllowlist??[]).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Py(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class fw{constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new dw.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new dw.aYW({}))}}class mw{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchTime=0,this.lastReposFetchTime=0,this.lastDefaultAllowlistFetchTime=0,this.lastFetchSucceeded=!0,this.settingsPromise=this.fetchSettings()}invalidateCache(){this.lastFetchTime=0,this.lastDefaultAllowlistFetchTime=0,this.defaultAllowlistPromise=void 0}async fetchSettings(){this.lastFetchTime=Date.now();try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e}catch(e){return void(this.lastFetchSucceeded=!1)}}async getTeamAdminSettings(){return(Date.now()-this.lastFetchTime>hw||void 0===await this.settingsPromise)&&(this.settingsPromise=this.fetchSettings()),this.settingsPromise}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(function(e,t){return!(0,Kd.YaX)(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Kd.MEY)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const i=pw({failOpenWhenEmpty:!1,server:e,settings:t});if(i.blocked)return i}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pw({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;return await this.isMcpSettingsOverhaulEnabled()?(0,Kd._NE)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1}):{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 isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=(0,Kd.FC3)({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers,isMcpSettingsOverhaulEnabled:!0});return 0!==r.length?{enabled:!0,mcpToolAllowlist:r,allowUserOverride:t?.allowUserOverrideMcpServers??!1}: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;return{sandboxingDisabled:t?.sandboxing===dw.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===dw._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===dw.i24.ALWAYS_DISABLED}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async getDefaultNetworkAllowlist(){const e=Date.now();return(!this.defaultAllowlistPromise||e-this.lastDefaultAllowlistFetchTime>hw)&&(this.lastDefaultAllowlistFetchTime=e,this.defaultAllowlistPromise=this.fetchDefaultAllowlist()),this.defaultAllowlistPromise}async fetchDefaultAllowlist(){if(!this.defaultAllowlistProvider)return{allowlist:[],available:!0};try{return{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}}catch{return{allowlist:[],available:!1}}}getTeamRepos(){const e=Date.now();(!this.teamReposPromise||e-this.lastReposFetchTime>hw)&&(this.teamReposPromise=this.teamAdminSettingsProvider.getTeamRepos(),this.lastReposFetchTime=e);const t=this.teamReposPromise;return t.catch((e=>{throw this.teamReposPromise===t&&(this.teamReposPromise=void 0),e}))}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}function gw(){return(0,a.join)(function(){const e=process.env.CURSOR_DATA_DIR;return(null==e?void 0:e.trim())?e:(0,a.join)((0,s.homedir)(),".cursor")}(),"projects")}function vw(e){return(0,a.join)(gw(),(0,hv.r_)(e))}const yw=Yo.z.any().transform(((e,t)=>{if(e instanceof Ze.Gmx)return e;try{return Ze.Gmx.fromJson(e,{ignoreUnknownFields:!1})}catch(r){return t.addIssue({code:Yo.z.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)}),e}})),ww=Yo.z.object({type:Yo.z.literal("command"),command:Yo.z.string().min(1),padding:Yo.z.number().int().min(0).optional(),updateIntervalMs:Yo.z.number().int().positive().optional(),timeoutMs:Yo.z.number().int().positive().optional()}),bw=Yo.z.object({allow:Yo.z.array(Yo.z.string()),deny:Yo.z.array(Yo.z.string())}),Sw=Yo.z.object({vimMode:Yo.z.boolean(),defaultBehavior:Yo.z.enum(["ide","agent"]).optional()}),kw=Yo.z.object({showLineNumbers:Yo.z.boolean().default(!1),showThinkingBlocks:Yo.z.boolean().default(!1),showStatusIndicators:Yo.z.boolean().default(!1),showStatusLineRunningTime:Yo.z.boolean().default(!1),mode:Yo.z.enum(["zen","standard"]).default("zen")}),Ew=Yo.z.object({enabled:Yo.z.boolean().default(!1),mode:Yo.z.enum(["access-key","team-role"]).default("access-key"),region:Yo.z.string().optional(),testModel:Yo.z.string().optional(),teamRoleArn:Yo.z.string().optional(),teamExternalId:Yo.z.string().optional()}),xw=Yo.z.object({id:Yo.z.string(),value:Yo.z.string()}),Cw=Yo.z.object({modelId:Yo.z.string(),parameters:Yo.z.array(xw)}),_w=Yo.z.object({ghostMode:Yo.z.boolean(),privacyMode:Yo.z.number().optional(),updatedAt:Yo.z.number()}),Pw=Yo.z.object({backendUrl:Yo.z.string(),authCacheKey:Yo.z.string(),teamId:Yo.z.number().optional(),available:Yo.z.boolean(),updatedAt:Yo.z.number()}),Iw=Yo.z.object({agentUrl:Yo.z.string(),agentnUrl:Yo.z.string()}),Tw=Yo.z.object({backendUrl:Yo.z.string(),authCacheKey:Yo.z.string().optional(),teamId:Yo.z.number().optional(),agentUrlConfig:Iw.optional(),cliSandboxDefaultEnabled:Yo.z.boolean().optional(),serverHttp2Config:Yo.z.number().optional(),updatedAt:Yo.z.number()}),Rw=Yo.z.object({email:Yo.z.string().optional(),displayName:Yo.z.string().optional(),teamId:Yo.z.number().optional(),teamName:Yo.z.string().optional(),userId:Yo.z.number().optional(),authId:Yo.z.string().optional(),organizationId:Yo.z.string().optional()}),Aw=Yo.z.object({useHttp1ForAgent:Yo.z.boolean().default(!1)}),Ow=Yo.z.object({mode:Yo.z.enum(["disabled","enabled"]).default("disabled"),networkAccess:Yo.z.preprocess((e=>"allowlist"===e?"user_config_with_defaults":"enabled"===e?"allow_all":e),Yo.z.enum(["user_config_only","user_config_with_defaults","allow_all"])).optional(),networkAllowlist:Yo.z.array(Yo.z.string()).default([]).optional()}),Mw=Yo.z.object({attributeCommitsToAgent:Yo.z.boolean().default(!0),attributePRsToAgent:Yo.z.boolean().default(!0)}),jw=Yo.z.object({conversationId:Yo.z.string(),lastUpdatedAt:Yo.z.number()}),Dw=Yo.z.object({permissions:bw}),Nw=Dw.extend({version:Yo.z.number(),editor:Sw,display:kw.default({showLineNumbers:!1,showThinkingBlocks:!1,showStatusIndicators:!1,showStatusLineRunningTime:!1,mode:"zen"}),notifications:Yo.z.boolean().default(!0),hints:Yo.z.boolean().default(!0),modelSlashCommands:Yo.z.boolean().default(!0),rewind:Yo.z.boolean().default(!0),statusLine:ww.optional(),channel:Yo.z.literal("static").or(Yo.z.literal("prod")).or(Yo.z.literal("lab")).or(Yo.z.literal("prod-stable-internal")).optional(),model:yw.optional(),bedrock:Ew.optional(),awsAuthRefresh:Yo.z.string().optional(),hasChangedDefaultModel:Yo.z.boolean().default(!1).optional(),maxMode:Yo.z.boolean().default(!1).optional(),maxModeAutoEnabled:Yo.z.boolean().optional(),modelParameters:Yo.z.record(Yo.z.string(),Yo.z.array(xw)).optional(),selectedModel:Cw.optional(),modelSelectionHistory:Yo.z.array(Yo.z.string()).max(32).optional(),exploreSubagentModel:Yo.z.enum(["default","inherit"]).default("default"),privacyCache:_w.optional(),autoReviewAvailabilityCache:Pw.optional(),serverConfigCache:Tw.optional(),authInfo:Rw.optional(),network:Aw.default({useHttp1ForAgent:!1}),approvalMode:Yo.z.enum(["allowlist","unrestricted","auto-review"]).default("allowlist").optional(),autoAcceptWebSearch:Yo.z.boolean().default(!1),sandbox:Ow.optional(),showSandboxIntro:Yo.z.boolean().default(!1).optional(),runEverythingSettingsPromptStreak:Yo.z.number().int().nonnegative().optional(),runEverythingSettingsPromptCooldownUntilMs:Yo.z.number().int().nonnegative().optional(),attribution:Mw.optional(),webFetchDomainAllowlist:Yo.z.array(Yo.z.string()).default([]).optional(),conversationClassificationScoredConversations:Yo.z.array(jw).optional()}),$w=Dw.strict().extend({});Nw.merge($w),new Set(["asb","staging"]);var Lw=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class Fw{constructor(e,t){this.storage=e,this.prefix=t}loadTokens(e){return Lw(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.prefix+e)}))}saveTokens(e,t){return Lw(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.prefix+e,t)}))}loadClientInformation(e){return Lw(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.prefix+e)}))}saveClientInformation(e,t){return Lw(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.prefix+e,t)}))}}class Uw{constructor(e,t){this.storage=e,this.prefix=t}isServerApproved(e,t,r){return Lw(this,void 0,void 0,(function*(){return this.storage.isServerApproved(this.prefix+e,t,r)}))}}class Bw{constructor(e){this.loaders=e}load(e){return Lw(this,arguments,void 0,(function*(e,t=!0){const r=yield Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw yield Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),i={};for(let e=0;e<o.length;e++){const t=o[e],r=this.loaders[e].prefix,n=t.getClients();for(const[e,t]of Object.entries(n)){const n=r+e;n in i||(i[n]=t)}}return new Jh(i)}))}loadClient(e,t){return Lw(this,arguments,void 0,(function*(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return yield n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}))}clearClient(e){var t;for(const{loader:r,prefix:n}of this.loaders){if(!e.startsWith(n))continue;const o=e.slice(n.length);null===(t=r.clearClient)||void 0===t||t.call(r,o)}}clearAllMcpCaches(){var e;for(const{loader:t}of this.loaders)null===(e=t.clearAllMcpCaches)||void 0===e||e.call(t)}}class zw{constructor(e,t,r,n,o=!1,i,l,c=a.join((0,s.homedir)(),".cursor","mcp.json")){const u=Array.isArray(e)?e:[e],d=[];for(let e=0;e<u.length;e++){const t=u[e],r=a.join(t,".cursor","mcp.json"),n=`project-${e}-${a.basename(t)}-`;d.push({path:r,prefix:n})}d.push({path:c,prefix:"user-"});const h=new Map;for(const{path:e,prefix:t}of d)h.has(e)&&"user-"!==t||h.set(e,t);const p=[];for(const[e,s]of h){const a=o?"":s,u=new Fw(t,a),d=new Uw(n,a),h=e===c,f=[new sh,...h?[]:[new th(d)],new dp(r),...l?[new eh(l)]:[]];p.push({prefix:a,loader:new hp(e,u,f,i)})}this.loader=new Bw(p)}static init(e,t,r,n=!1,o){const i=new mp(a.join(r,"mcp-auth.json"));(function(e){return Lw(this,void 0,void 0,(function*(){yield(0,no.rm)(a.join(e,"mcp-cache.json"),{force:!0})}))})(r).catch((()=>{}));const s=n?{isServerApproved:()=>Promise.resolve(!0)}:new rh(a.join(r,"mcp-approvals.json"),t);return new zw(t,i,e,s,!0,void 0,o)}load(e){return Lw(this,arguments,void 0,(function*(e,t=!0){return this.loader.load(e,t)}))}loadClient(e,t){return Lw(this,arguments,void 0,(function*(e,t,r=!1){return this.loader.loadClient(e,t,r)}))}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const Ww=new Bd,Hw={resolveWorkspaceState(e){return t=this,r=void 0,o=function*(){var t,r,n,o,i,s,a;const l=null!==(n=null!==(r=e.workingDirectory)&&void 0!==r?r:e.projectRoot)&&void 0!==n?n:null===(t=e.workspaceRoots)||void 0===t?void 0:t[0],c=null!==(o=e.projectRoot)&&void 0!==o?o:void 0!==l?null!==(i=yield Yc((0,Qe.q6)(),Ww,l))&&void 0!==i?i:l:void 0,u=null!==(s=e.workspaceRoots)&&void 0!==s?s:void 0!==c?[c]:void 0!==l?[l]:[];return{workingDirectory:l,projectRoot:c,projectDirectory:null!==(a=e.projectDirectory)&&void 0!==a?a:void 0!==c?vw(c):void 0,workspaceRoots:u,createdAt:new Date}},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}};var qw=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Gw=(0,h.h)("ControlledConversationActionManager");class Vw{get signal(){return this.abortController.signal}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.abortStarted=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,m.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortController.signal.aborted||this.abortStarted)return;const r=null==t?void 0:t.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new Ze.QFf({action:{case:"cancelAction",value:new Ze.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}submitConversationAction(e){return qw(this,void 0,void 0,(function*(){if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}yield this.clientStream.write(e)}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){var e;null===(e=this.clientStream)||void 0===e||e.close()}resetStream(){var e;null===(e=this.clientStream)||void 0===e||e.close(),this.clientStream=(0,m.Jt)(),this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:e})}}))}run(e,t){return qw(this,void 0,void 0,(function*(){var r,n,o,i;this.runActive=!0;try{try{for(var s,a=!0,l=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.clientStream);!(r=(s=yield l.next()).done);a=!0){i=s.value,a=!1;const r=i;try{yield t.write(r)}catch(t){Gw.error(e,"Error writing conversation action",t)}}}catch(e){n={error:e}}finally{try{a||r||!(o=l.return)||(yield o.call(l))}finally{if(n)throw n.error}}}finally{this.runActive=!1}}))}dispose(){this.abortCallbacks.length=0}}let Jw={warn:console.warn.bind(console),error:console.error.bind(console)};const Kw=new Vo.AsyncLocalStorage;function Zw(){var e;return null!==(e=Kw.getStore())&&void 0!==e?e:Jw}const Yw={warn(...e){Zw().warn(...e)},error(...e){Zw().error(...e)}};var Xw=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function Qw(e){var t;if("userMessageAction"===e.action.case)return null===(t=e.action.value.userMessage)||void 0===t?void 0:t.text}function eb(e,t,r){var n,o;const i=null===(n=e.runOptions)||void 0===n?void 0:n.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:null!==(o=null==i?void 0:i.modelId)&&void 0!==o?o:"unknown",modelId:null==i?void 0:i.modelId,modelParams:null==i?void 0:i.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function tb(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}const rb="cursor-plugins/local";function nb(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===rb)return r}var ob=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class ib extends Vh{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}dispose(){return ob(this,void 0,void 0,(function*(){this.disposed||(this.disposed=!0,yield this.runtimeManager.closeAllClients())}))}}class sb{constructor(e){this.storagePath=e}isServerDisabled(e){return ob(this,void 0,void 0,(function*(){try{const t=yield(0,no.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(yield this.writeDisabledServers([]),!1)}catch(e){if("ENOENT"===e.code)return!1;throw e}}))}writeDisabledServers(e){return ob(this,void 0,void 0,(function*(){yield(0,no.mkdir)((0,a.dirname)(this.storagePath),{recursive:!0}),yield(0,no.writeFile)(this.storagePath,JSON.stringify(e,null,2))}))}}class ab{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}getDefinitions(){return ob(this,void 0,void 0,(function*(){let e;try{e=yield this.pluginMcpService.getPluginMcpServers()}catch(e){return Yw.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&pb(r))continue;const e=pp(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}}):Yw.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 lb{constructor(e){this.servers=e}getDefinitions(){return ob(this,void 0,void 0,(function*(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:hb(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}))}}function cb(){return{getDotCursorProtection:()=>ob(this,void 0,void 0,(function*(){return!1})),getShouldBlockMcp:()=>ob(this,void 0,void 0,(function*(){return!1})),getDeleteFileProtection:()=>ob(this,void 0,void 0,(function*(){return!1})),getIsHeadlessDisabled:()=>ob(this,void 0,void 0,(function*(){return!1})),isServerBlocked:()=>ob(this,void 0,void 0,(function*(){return!1})),getTeamRepos:()=>ob(this,void 0,void 0,(function*(){})),getAutoRunControls:()=>ob(this,void 0,void 0,(function*(){return{enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}})),getMcpToolControls:()=>ob(this,void 0,void 0,(function*(){})),getNetworkAccessControls:()=>ob(this,void 0,void 0,(function*(){return{allowlist:[],denylist:[],available:!0}})),getMcpNetworkControlsConfig:()=>ob(this,void 0,void 0,(function*(){return{enabled:!1}})),getDefaultNetworkAllowlist:()=>ob(this,void 0,void 0,(function*(){return{allowlist:[],available:!0}})),getSandboxingControls:()=>ob(this,void 0,void 0,(function*(){return{sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}})),isAttributionDisabledByAdmin:()=>ob(this,void 0,void 0,(function*(){return!1})),invalidateCache:()=>{}}}function ub(e={}){var t,r,n;const o=null!==(t=e.teamSettingsService)&&void 0!==t?t:cb(),i=null!==(r=e.ignoreApprovals)&&void 0!==r&&r,l=null!==(n=e.importThirdPartyPlugins)&&void 0!==n&&n;return{createLease(t){return ob(this,void 0,void 0,(function*(){var r,n,c,u,d,h;const p=t.workspaceState,f=null!==(r=p.projectRoot)&&void 0!==r?r:p.workingDirectory,m=p.projectDirectory;if(!f||!m)return new Gh;const g=new sb((0,a.join)(m,"mcp-disabled.json")),v=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:o,disabledStore:i,includeProjectMcp:l,includeUserMcp:c}=e;if(l&&c)return zw.init(t,r,n,o,i);if(!l&&!c)return;const u=new mp((0,a.join)(n,"mcp-auth.json")),d=o?{isServerApproved:()=>Promise.resolve(!0)}:new rh((0,a.join)(n,"mcp-approvals.json"),r),h=[new sh,new th(d),new dp(t),new eh(i)],p=[];return l&&p.push({prefix:"",loader:new hp((0,a.join)(r,".cursor","mcp.json"),u,h)}),c&&p.push({prefix:"",loader:new hp((0,a.join)((0,s.homedir)(),".cursor","mcp.json"),u,h)}),db(p)}({teamSettingsService:o,projectRoot:f,projectDirectory:m,ignoreApprovals:i,disabledStore:g,includeProjectMcp:null===(n=e.includeProjectMcp)||void 0===n||n,includeUserMcp:null===(c=e.includeUserMcp)||void 0===c||c}),y=[],w=null!==(u=e.inlineMcpServers)&&void 0!==u?u:{};if(Object.keys(w).length>0){const e=new mp((0,a.join)(m,"mcp-auth.json")),t=[new sh,new dp(o)];y.push({prefix:"",loader:new cp(new lb(w),e,t)})}const b=nb(t.services.pluginBootstrapOutputs);if(b&&(null===(d=e.includePluginMcp)||void 0===d||d)){const e=new rh((0,a.join)(m,"mcp-approvals.json"),f),t=new mp((0,a.join)(m,"mcp-auth.json")),r=[new sh];i||r.push(new th(e)),r.push(new dp(o),new eh(g));const n=new fy(b.pluginsService),s=new cp(new ab(n,l),t,r);y.push({prefix:"",loader:s})}if(v&&y.push({prefix:"",loader:v}),0===y.length)return new Gh;const S=db(y),k=yield S.load(null!==(h=e.initializationCtx)&&void 0!==h?h:(0,Qe.q6)(),e.cache);return new ib(k)}))}}}function db(e){return 1===e.length?e[0].loader:new Bw(e)}function hb(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?Object.assign(Object.assign({},r),{type:"sse"}):r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function pb(e){return"claude-plugin"===e.pluginSource}var fb=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},mb=function(e){return this instanceof mb?(this.v=e,this):new mb(e)};function gb(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===(null==t?void 0:t.case)}function vb(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class yb{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>yb.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=null==n?void 0:n.skipPathWriteDrain,this.onWakeWrittenPath=null==n?void 0:n.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=null==n?void 0:n.forceWrittenPathBeforeDrain}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===Tt.symbol||e===se.symbol||e===wt.symbol||e===ft.symbol?{kind:"path"}:e===Pt.symbol||e===It.symbol||e===ee.symbol||e===pt.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,i=this.skipPathWriteDrain,s=this.forceWrittenPathBeforeDrain,a=this.onWakeWrittenPath,l=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=vb(e);void 0!==r&&(o.wakeForWrittenPath(r),null==a||a(r,t))}else o.wakeExposedMounts()}catch(e){}},c=this.cacheCarriersForExecId.bind(this),u=this.carriersByExecId,d=this.inFlightByExecId,h=(e,t)=>fb(this,void 0,void 0,(function*(){const r=null==t?void 0:t.hookContextCollector;if(void 0===r)return[];if(!1===(null==t?void 0:t.deliverAgentStoreConflictNotices))return[];const o=void 0!==(null==t?void 0:t.execId)&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=u.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=d.get(o);if(void 0!==t){const e=yield t;return e.length>0&&r.push(...e),e}}const i=t=>fb(this,void 0,void 0,(function*(){const r=n(e);let i=[];try{const e=yield r.peek();if(i=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&c(o,e.carriers),e.carriers;i.length>0&&r.ack(i);const n=[];return void 0!==o&&c(o,n),n}catch(e){return i.length>0&&r.release(i),[]}}));if(void 0===o)return yield i(r);const s=i(r);d.set(o,s);try{return yield s}finally{d.get(o)===s&&d.delete(o)}}));return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,a)=>{const c=t.execute.call(t,n,o,a);return"object"==typeof(u=c)&&null!==u&&Symbol.asyncIterator in u&&"function"==typeof u[Symbol.asyncIterator]?function(){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof mb?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(){var t,r,i,s;let u=!1,d=!1,p=!1;try{try{for(var f,m=!0,g=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(c);!(t=(f=yield mb(g.next())).done);m=!0){s=f.value,m=!1;const t=s;if(e===It.symbol&&gb(t)){if(!u){l(o,n);const e=yield mb(h(n,a));u=!0,e.length>0&&(yield yield mb(new Ct.FI({event:{case:"hookContext",value:new Ct.Ng({hookAdditionalContexts:[...e]})}})))}yield yield mb(t)}else yield yield mb(t)}}catch(e){r={error:e}}finally{try{m||t||!(i=g.return)||(yield mb(i.call(g)))}finally{if(r)throw r.error}}p=!0}catch(e){throw d=!0,e}finally{l(o,n),u||d||!p||(yield mb(h(n,a)))}}))}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(c)?(()=>fb(this,void 0,void 0,(function*(){try{const t=yield c;return l(o,n),e===Tt.symbol&&!0===(null==i?void 0:i())&&!0===(null==a?void 0:a.enableAgentStoreConflictNotices)||(yield function(e,t,r){return fb(this,void 0,void 0,(function*(){if(void 0===e||"path"!==(null==r?void 0:r.kind))return;const n=vb(t);if(void 0!==n)try{yield e(n)}catch(e){}}))}(s,o,r),yield h(n,a)),t}catch(e){throw l(o,n),e}})))():(l(o,n),c);var u}})}}yb.CARRIERS_BY_EXEC_ID_MAX=32,Error,i.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed"]),Math.max(1,Math.floor(8192));const wb=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"];function bb(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,wb)}function Sb(e){const t=(0,hv.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,hv.sh)(e.parentConversationId);return`${hv.O2}/${r}/subagents/${t}.${e.ext}`}return`${hv.O2}/${t}/${t}.${e.ext}`}function kb(e){const t=(0,hv.sh)(e.conversationId);return`${hv.O2}/${t}.${e.ext}`}function Eb(e){var t,r;const n=null!==(t=e.exts)&&void 0!==t?t:["jsonl","txt"],o=null===(r=e.includeLegacy)||void 0===r||r,i=[],s=e=>{i.includes(e)||i.push(e)};for(const t of n)s(Sb({conversationId:e.conversationId,ext:t,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&s(Sb({conversationId:e.conversationId,ext:t,kind:"primary"})),o&&s(kb({conversationId:e.conversationId,ext:t}));return i}var xb;(()=>{var e;const t=null===(e=globalThis.Intl)||void 0===e?void 0:e.Segmenter;t&&new t(void 0,{granularity:"grapheme"})})(),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(xb||(xb={}));var Cb=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},_b=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Ib(e){switch(e){case Ze.xyI.AGENT:return"agent";case Ze.xyI.ASK:return"ask";case Ze.xyI.PLAN:return"plan";case Ze.xyI.DEBUG:return"debug";case Ze.xyI.TRIAGE:return"triage";case Ze.xyI.PROJECT:return"project";case Ze.xyI.MULTITASK:return"multitask";case Ze.xyI.CUSTOM:return"custom";case Ze.xyI.UNSPECIFIED:default:return"agent"}}function Tb(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 Rb(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 Ab=new TextEncoder,Ob=new TextDecoder,Mb=new class{serialize(e){const t=JSON.stringify(e,Tb);return Ab.encode(t)}deserialize(e){const t=Ob.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Rb):JSON.parse(t)}};function jb(e){var t;const r=e.providerOptions;return!0===(null===(t=null==r?void 0:r.cursor)||void 0===t?void 0:t.isSummary)}function Db(e,t,r){return Cb(this,void 0,void 0,(function*(){const n=[];let o=0,i=0,s=0,a=0,l=0,c=0,u=0;for(const h of r){const r=yield t.getBlob(e,h);if(r){if(r.length>5e6){n.push((void 0,{role:"assistant",content:`[Oversize transcript blob omitted: ${d=r.length,`${(d/1e6).toFixed(1)} MB`}]`})),l++,c+=r.length,u=Math.max(u,r.length);continue}try{const e=performance.now(),t=Mb.deserialize(r),l=performance.now()-e;n.push(t),o++,i+=r.length,s=Math.max(s,r.length),a+=l}catch(e){}}}var d;return{messages:n,hydratedBlobCount:o,hydratedBlobBytes:i,largestHydratedBlobBytes:s,totalDeserializeDurationMs:a,omittedOversizeBlobCount:l,omittedOversizeBlobBytes:c,largestOmittedOversizeBlobBytes:u}}))}function Nb(e,t){switch(e.type){case"text":return t?$b(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 $b(e){return bb(e)}function Lb(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function Fb(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?$b(e):e;return r?Lb(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=Lb(t?$b(e.text):e.text);return Nb(Object.assign(Object.assign({},e),{text:r}),!1)}return Nb(e,t)})).filter(Boolean).join("\n")}function Ub(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?$b(n):n,i="assistant"===e.role?Lb(o):o;i.trim()&&(r.text=i)}else if(Array.isArray(n)){const o=[],i=[],s=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?$b(r.text):r.text,i="assistant"===e.role?Lb(n):n;i.trim()&&o.push(i);break}case"reasoning":r.text.trim()&&i.push(r.text);break;case"redacted-reasoning":i.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":s.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),i.length>0&&(r.thinking=i.join("\n")),s.length>0&&(r.toolCalls=s),a&&(r.toolResult=a)}return r}function Bb(e){return e.endsWith("\n")?e:`${e}\n`}function zb(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify(Object.assign({type:"turn_ended"},t)))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function Wb(e){if("system"===e.role||jb(e))return;const t=Ub(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class Hb{constructor(e,t,r,n={}){var o,i,s;this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:null===(o=n.writeText)||void 0===o||o,writeJson:null!==(i=n.writeJson)&&void 0!==i&&i,writeJsonl:null!==(s=n.writeJsonl)&&void 0!==s&&s,pathResolver:n.pathResolver,appendFile:n.appendFile}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=Sb({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}writeFromStateFull(e,t,r){return Cb(this,arguments,void 0,(function*(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const i=_b(o,(0,c.VI)(e.withName("writeFromState")),!1);try{const e=yield function(e,t,r){return Cb(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=_b(n,(0,c.VI)(e.withName("hydrateSummaryArchives")),!1);let i=0;const s=(0,c.OA)(o.ctx),a=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=yield Promise.all(r.summaryArchives.map((e=>Cb(this,void 0,void 0,(function*(){i++;const r=yield t.getBlob(s,e);if(r)try{const e=Ze.Anz.fromBinary(r);return i+=e.summarizedMessages.length,yield Db(s,t,e.summarizedMessages)}catch(e){}return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}})))));for(const e of g)a.push(...e.messages),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);o.span.setAttribute("getBlobCount",i),o.span.setAttribute("hydratedBlobCount",l),o.span.setAttribute("hydratedBlobBytes",u),o.span.setAttribute("largestHydratedBlobBytes",d),o.span.setAttribute("totalDeserializeDurationMs",h),o.span.setAttribute("omittedOversizeBlobCount",p),o.span.setAttribute("omittedOversizeBlobBytes",f),o.span.setAttribute("largestOmittedOversizeBlobBytes",m);const v=_b(n,(0,c.VI)(e.withName("hydratePromptMessages")),!1),y=yield Db(s,t,r.rootPromptMessagesJson);v.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),v.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),v.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),v.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),v.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),v.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),v.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),v.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const w=y.messages.filter((e=>"system"!==e.role&&!jb(e)));return a.push(...w),a}catch(e){n.error=e,n.hasError=!0}finally{Pb(n)}}))}(i.ctx,this.blobStore,t),{overviewFactory:o}=n,s=zb(n);if(0===e.length&&0===s.jsonlLines.length)return!0;let a;if((this.options.writeText||o)&&(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,n="assistant"===e.role,o=Fb(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(e)),this.options.writeText){const e=null!=a?a:"",t=s.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${s.textSuffixes.join("\n")}`:s.textSuffixes.join("\n"):e;t.trim()&&(yield this.writeFile(this.resolveFilePath(r,"txt"),t))}if(this.options.writeJson){const n=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=Ub(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(n||s.jsonlLines.length>0){const e=Object.assign({mode:Ib(t.mode),messages:n?JSON.parse(n):[]},s.jsonFields);yield 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=Wb(e);t&&r.push(t)}return r.join("\n")}(e);let n=[t,...s.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&o&&(null==a?void 0:a.trim()))try{const e=(yield o(a)).trim();e&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,e))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&(yield this.writeFile(this.resolveFilePath(r,"jsonl"),Bb(n)))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{Pb(o)}}))}writeFromStateIncremental(e,t,r,n){return Cb(this,arguments,void 0,(function*(e,t,r,n,o={}){const i={stack:[],error:void 0,hasError:!1};try{const s=t.rootPromptMessagesJson.length,a=zb(o),l=a.jsonlLines.length>0;if(s===n&&!l&&!o.overviewFactory)return s;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&s>=n&&(s>n||l))||o.overviewFactory)return(yield this.writeFromStateFull(e,t,r,o))?s:0;const d=_b(i,(0,c.VI)(e.withName("writeFromStateIncremental")),!1);if(s===n&&l)try{return yield u(this.resolveFilePath(r,"jsonl"),Bb(a.jsonlLines.join("\n"))),s}catch(n){return console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",n),(yield this.writeFromStateFull(e,t,r,o))?s:0}try{const e=t.rootPromptMessagesJson.slice(n),o=yield Db(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const i=[];for(const e of o.messages){const t=Wb(e);t&&i.push(t)}if(i.push(...a.jsonlLines),i.length>0){const e=Bb(i.join("\n"));yield u(this.resolveFilePath(r,"jsonl"),e)}return s}catch(n){return console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",n),(yield this.writeFromStateFull(e,t,r,o))?s:0}}catch(e){i.error=e,i.hasError=!0}finally{Pb(i)}}))}}class qb extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class Gb extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}function Vb(e,t){return r=this,n=void 0,i=function*(){try{return yield e()}catch(e){const r=e instanceof Error?e.message:String(e),n=function(e,t){return`${null!=e?e:"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${Jb}`}(t,r);throw new Gb(n,e)}},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{l(i.next(e))}catch(e){t(e)}}function a(e){try{l(i.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,a)}l((i=i.apply(r,n||[])).next())}));var r,n,o,i}const Jb="To view or modify configured hooks, go to Cursor Settings > Hooks.",Kb="Agent note: Do not suggest workarounds to the blocked tool.";function Zb(e){return e.includes(Kb)?e:`${e}\n\n${Kb}`}function Yb(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function Xb(e,t){return Zb(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${Jb}`)}function Qb(e){return function(e){return e instanceof qb}(e)||function(e){return e instanceof Gb}(e)}var eS=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class tS{constructor(e,t,r,n,o,i,s,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.teamHooksReadyPromise=i,this.onHookExecution=s,this.options=a,this.config=e}emitHookExecution(e){var t,r;const n=Object.assign(Object.assign({},e),{transportMode:null!==(r=e.transportMode)&&void 0!==r?r:"prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode()});try{null===(t=this.onHookExecution)||void 0===t||t.call(this,n)}catch(e){}}getCommandHookPayloadTransportMode(){var e;return"stdin"===(null===(e=this.options)||void 0===e?void 0:e.commandHookPayloadTransport)?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}writeCommandHookStdinPayload(e,t){return eS(this,void 0,void 0,(function*(){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{yield(0,hs.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}))}updateConfig(e){this.config=e}setSessionEnvironment(e){this.sessionEnv=Object.assign(Object.assign({},this.sessionEnv),e)}clearSessionEnvironment(){this.sessionEnv=void 0}getTranscriptPathIfExists(e){return eS(this,void 0,void 0,(function*(){try{const t=(0,hv.Rv)((0,s.homedir)(),this.workspacePath),r=Eb({conversationId:e,kind:"primary"}).map((e=>(0,a.join)(t,e)));for(const e of r)try{return yield(0,no.access)(e),e}catch(e){}return null}catch(e){return null}}))}getSubagentTranscriptPathIfExists(e){return eS(this,void 0,void 0,(function*(){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,hv.Rv)((0,s.homedir)(),this.workspacePath),n=Eb({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,a.join)(e,t)));for(const e of n)try{return yield(0,no.access)(e),e}catch(e){}return null}catch(e){return null}}))}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks].some((t=>{const r=null==t?void 0:t.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,this.config.userHooks];for(const n of r){const r=null==n?void 0:n.hooks[e];if(r&&(t?Se(r,t):r).some((e=>!0===e.failClosed)))return!0}return!1}getCwdForSource(e){var t,r,n,o;const i=this.config.configDirs;switch(e){case"enterprise":return null!==(t=null==i?void 0:i.enterprise)&&void 0!==t?t:this.workspacePath;case"team":return null!==(r=null==i?void 0:i.team)&&void 0!==r?r:this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":default:return this.workspacePath;case"user":return null!==(n=null==i?void 0:i.user)&&void 0!==n?n:this.workspacePath;case"claude-user":return null!==(o=null==i?void 0:i.claudeUser)&&void 0!==o?o:this.workspacePath}}buildHookEnvironment(e){return Object.assign(Object.assign(Object.assign(Object.assign({CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version},this.globalContext.user_email&&{CURSOR_USER_EMAIL:this.globalContext.user_email}),e&&{CURSOR_TRANSCRIPT_PATH:e}),{CLAUDE_PROJECT_DIR:this.workspacePath}),this.sessionEnv)}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=r.loop_count,o=t.loop_limit;return null!==o&&(void 0===o?n>=5:n>=o)}executeHookForStep(e,t){return eS(this,void 0,void 0,(function*(){var r,n,o,i,s,a,l,c;this.teamHooksReadyPromise&&(yield this.teamHooksReadyPromise);const u=function(e){return je.includes(e)}(e),d=t,h=u?null:d.conversation_id?yield this.getTranscriptPathIfExists(d.conversation_id):null;let p;if(e===de.subagentStop){const e=t;p=e.subagent_id?yield this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const f=u?void 0:null!==(c=d.session_id)&&void 0!==c?c:d.conversation_id,m=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),void 0!==f&&{session_id:f}),{hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.globalContext.user_email}),!u&&{transcript_path:h}),e===de.subagentStop&&{agent_transcript_path:null!=p?p:null}),g=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return t.command||void 0;case"beforeMCPExecution":case"afterMCPExecution":{const e=t;return e.tool_name?`MCP:${e.tool_name}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return t.subagent_type||void 0;case"preToolUse":case"postToolUse":case"postToolUseFailure":return t.tool_name||void 0;default:return}}(e,m),v=[],y=(e,t)=>{if(!e)return;const r=Se(e,g),n=this.getCwdForSource(t);for(const e of r)Re(e)?this.promptHookClient&&v.push({type:"prompt",script:e,source:t}):("command"===(o=e).type||void 0===o.type)&&v.push({type:"command",script:e,cwd:n,source:t});var o};if(y(null===(r=this.config.enterpriseHooks)||void 0===r?void 0:r.hooks[e],"enterprise"),y(null===(n=this.config.teamHooks)||void 0===n?void 0:n.hooks[e],"team"),y(null===(o=this.config.projectHooks)||void 0===o?void 0:o.hooks[e],"project"),y(null===(i=this.config.userHooks)||void 0===i?void 0:i.hooks[e],"user"),y(null===(s=this.config.claudeProjectLocalHooks)||void 0===s?void 0:s.hooks[e],"claude-project-local"),y(null===(a=this.config.claudeProjectHooks)||void 0===a?void 0:a.hooks[e],"claude-project"),y(null===(l=this.config.claudeUserHooks)||void 0===l?void 0:l.hooks[e],"claude-user"),0!==v.length)return this.executeAllAndMerge(e,v,m)}))}executeAllAndMerge(e,t,r){return eS(this,void 0,void 0,(function*(){const n=t.map(((t,n)=>eS(this,void 0,void 0,(function*(){const{source:o,attribution:i}=t;try{return"prompt"===t.type?this.executePromptHook(e,t.script,r,o,n,i):this.executeCommandHook(e,t.script,t.cwd,r,o,n,i)}catch(r){if(!0===t.script.failClosed){const t=Yb(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),i=Fe(e,t);if(i)return{success:!0,data:i,source:o,index:n}}return{success:!1,source:o,index:n}}})))),o=yield Promise.all(n),i=[];for(const e of o)e.success&&void 0!==e.data&&i.push(e.data);return function(e,t){var r;if(0===t.length)return;if(1===t.length)return t[0];const n=Me.includes(e),o=e===de.sessionStart,i=e===de.workspaceOpen,s=Te.has(e),a={};for(const e of t){const t=e;for(const[e,u]of Object.entries(t))if(void 0!==u)if(i&&"pluginPaths"===e&&Array.isArray(u)){const t=null!==(r=a[e])&&void 0!==r?r:[],n=new Set(t),o=[...t];for(const e of u)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));a[e]=o}else"permission"===e&&n?a[e]=(c=u,"deny"===(l=a[e])||"deny"===c?"deny":"ask"===l||"ask"===c?"ask":"allow"===l||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof u?a[e]=De(a[e],u):"continue"!==e||"boolean"!=typeof u?a[e]=o&&"env"===e&&"object"==typeof u&&null!==u?Ne(a[e],u):u:void 0===a[e]?a[e]=u:a[e]=a[e]&&u:a[e]=De(a[e],u)}var l,c;return a}(e,i)}))}executeCommandHook(e,t,r,n,o,i,s){return eS(this,void 0,void 0,(function*(){var a,l,c,u,d,h,p,f;if(this.shouldSkipHookDueToLoopLimit(e,t,n))return{success:!1,source:o,index:i};const m=Date.now(),g=Buffer.byteLength(JSON.stringify(n),"utf8");let v;try{v=yield this.executeCommandScript({script:t,cwd:r,request:n})}catch(r){const n=r instanceof Error?r.message:String(r),a=n.toLowerCase().includes("timed out"),l=Date.now()-m,c=a?"timeout":"spawn_error";if(!0===t.failClosed){const r=Yb(`Hook "${t.command}" execution failed: ${n}`),u=Fe(e,r);if(u)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:a?"timeout":"blocked",latencyMs:l,payloadSizeBytes:g,errorClass:c,failClosed:!0,timedOut:a},s)),{success:!0,data:u,source:o,index:i}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:a?"timeout":"failed",latencyMs:l,payloadSizeBytes:g,errorClass:c,failClosed:!0===t.failClosed,timedOut:a},s)),{success:!1,source:o,index:i}}if(2===v.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(v.stdout,v.stderr,t.command),n=Fe(e,r);return n?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:v.exitCode},s)),{success:!0,data:n,source:o,index:i}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:v.exitCode},s)),{success:!1,source:o,index:i})}if(0!==v.exitCode&&null!==v.exitCode){if(!0===t.failClosed){const r=Yb(`Hook "${t.command}" failed with exit code ${v.exitCode}${v.stderr?`: ${v.stderr.trim()}`:""}`),n=Fe(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"exit_nonzero",failClosed:!0,exitCode:v.exitCode},s)),{success:!0,data:n,source:o,index:i}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:v.exitCode},s)),{success:!1,source:o,index:i}}const y=v.stdout.trim();if(!y){if(!0===t.failClosed){const r=Yb(`Hook "${t.command}" returned no output.`),n=Fe(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"empty_stdout",failClosed:!0,exitCode:null!==(l=v.exitCode)&&void 0!==l?l:void 0},s)),{success:!0,data:n,source:o,index:i}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:null!==(c=v.exitCode)&&void 0!==c?c:void 0},s)),{success:!1,source:o,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=Ue(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=Ue(t.slice(e));if(void 0!==r)return r.value}}(y);if(void 0===w){const r=Le({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(u=v.exitCode)&&void 0!==u?u:void 0},s)),{success:!0,data:r.blockResponse,source:o,index:i}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(d=v.exitCode)&&void 0!==d?d:void 0},s)),{success:!1,source:o,index:i})}const b=Oe(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:null===(a=this.options)||void 0===a?void 0:a.enableClaudeNestedHookSpecificOutputCompatibility});if(b.success){const r=b.data,n="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:n?"blocked":"success",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:null!==(h=v.exitCode)&&void 0!==h?h:void 0},s)),{success:!0,data:b.data,source:o,index:i}}const S=Le({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return S.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(p=v.exitCode)&&void 0!==p?p:void 0},s)),{success:!0,data:S.blockResponse,source:o,index:i}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(f=v.exitCode)&&void 0!==f?f:void 0},s)),{success:!1,source:o,index:i})}))}executePromptHook(e,t,r,n,o,i){return eS(this,void 0,void 0,(function*(){var s,a;if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const l=1e3*(null!==(s=t.timeout)&&void 0!==s?s:60),c=Date.now(),u=Buffer.byteLength(JSON.stringify(r),"utf8"),d=(0,Qe.q6)(),[h,p]=d.withTimeoutAndCancel(l);try{const s=JSON.parse(JSON.stringify(r)),l=yield this.promptHookClient.evaluatePromptHook(h,{prompt:t.prompt,hookInputJson:s,modelName:t.model});if(l.ok){const r=function(e){return $e(e)?{permission:"allow"}:e===de.beforeSubmitPrompt||e===de.sessionStart?{continue:!0}:e===de.stop?{}:void 0}(e);return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed},i)),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=null!==(a=l.reason)&&void 0!==a?a:"Prompt hook blocked this action",s=Fe(e,r);return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed},i)),s?{success:!0,data:s,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=Yb(`Prompt hook failed: ${s}`),r=Fe(e,t);if(r)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a},i)),{success:!0,data:r,source:n,index:o}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a},i)),{success:!1,source:n,index:o}}finally{p()}}))}executeCommandScript(e){return eS(this,void 0,void 0,(function*(){var t,r,n,o,i;const{script:l,cwd:c,request:u}=e,d=1e3*(null!==(i=l.timeout)&&void 0!==i?i:60),h=Date.now(),p=JSON.stringify(u);let f;const m=new AbortController,g=setTimeout((()=>{m.abort()}),d);try{const e="win32"===process.platform,i=this.getCommandHookPayloadTransportMode(),b=this.shouldUseCommandHookDirectStdinTransport();let S;if(b)S=l.command;else if("windows_temp_file"===i){f=yield(0,no.mkdtemp)((0,a.join)((0,s.tmpdir)(),"cursor-hooks-"));const e=(0,a.join)(f,"payload.json");yield(0,no.writeFile)(e,p,{encoding:"utf8",flag:"wx"}),S=function(e,t){const r=e.replace(/'/g,"''"),n=function(e){const t=e.trimStart();if(0===t.length)return e;if(t.startsWith("&"))return e;const r=t.charAt(0);return"'"===r||'"'===r?`& ${e}`:e}(t);return`$OutputEncoding = [System.Text.Encoding]::UTF8; Get-Content -LiteralPath '${r}' -Raw | & { $input | ${n} }`}(e,l.command)}else S=e?`@'\n${p.replace(/'/g,"''")}\n'@ | & ${l.command}`:`${l.command} <<'CURSOR_HOOK_EOF'\n${p}\nCURSOR_HOOK_EOF`;const k=u,E=this.buildHookEnvironment(k.transcript_path),x={};for(const[e,t]of Object.entries(E))void 0!==t&&(x[e]=t);const C=(0,Qe.q6)();let _="",P="",I=null,T=!1;try{for(var v,y=!0,w=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.shellExecutor.execute(C,S,{workingDirectory:c,signal:m.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:x,pipeStdin:b}));!(t=(v=yield w.next()).done);y=!0){o=v.value,y=!1;const e=o;switch(e.type){case"stdin_ready":b&&(yield this.writeCommandHookStdinPayload(e.stdin,p),T=!0);break;case"stdout":_+=e.data.toString("utf8");break;case"stderr":P+=e.data.toString("utf8");break;case"exit":I=e.code}}}catch(e){r={error:e}}finally{try{y||t||!(n=w.return)||(yield n.call(w))}finally{if(r)throw r.error}}if(b&&!T)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(g);const R=Date.now()-h;if(m.signal.aborted)throw new Error(`Hook script timed out after ${d}ms`);return{stdout:_,stderr:P,exitCode:I,duration:R}}catch(e){if(clearTimeout(g),Date.now(),m.signal.aborted)throw new Error(`Hook script timed out after ${d}ms`);throw e}finally{if(f)try{yield(0,no.rm)(f,{recursive:!0,force:!0})}catch(e){}}}))}}var rS=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function nS(e){switch(null!=e?e:(0,s.platform)()){case"darwin":return a.join("/Library","Application Support","Cursor","hooks.json");case"win32":return a.join("C:\\","ProgramData","Cursor","hooks.json");default:return a.join("/etc","cursor","hooks.json")}}class oS{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}load(){return rS(this,arguments,void 0,(function*(e={}){var t,r;const{loadProjectHooks:n=!0}=e,o={errors:[],configDirs:{}},i=null!==(r=null!==(t=this.paths.projectConfigPath)&&void 0!==t?t:this.paths.claudeProjectConfigPath)&&void 0!==r?r:this.paths.claudeProjectLocalConfigPath,s=i?a.dirname(a.dirname(i)):void 0,l=(e,t)=>{if(!e||!s)return;if(t)return s;const r=a.relative(a.resolve(s),a.resolve(e));return".."===r||r.startsWith(`..${a.sep}`)||a.isAbsolute(r)?void 0:s},c=(e,t,r,n,i,s,l,c)=>rS(this,void 0,void 0,(function*(){if(e)try{if(!(yield this.fileReader.exists(e)))return;if(l&&this.fileReader.pathContainsSymlink&&(yield this.fileReader.pathContainsSymlink(e,l)))return o.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${s} config via symlink path: ${e}`);const u=yield this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=c(u);d?(o[r]=d,((e,t)=>{o.configDirs[e]=a.dirname(t)})(n,e)):h&&o.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){o.errors.push({source:t,message:`Error accessing ${s} config file: ${String(e)}`})}})),u=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:l(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:l(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:l(this.paths.userConfigPath,!1)},{path:n?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:l(this.paths.projectConfigPath,!0)}];for(const e of u)yield c(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const d=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:l(this.paths.claudeUserConfigPath,!1)},{path:n?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:l(this.paths.claudeProjectConfigPath,!0)},{path:n?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:l(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of d)yield c(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(o),o}))}getHookKey(e){return Re(e)?`prompt:${e.prompt}`:`command:${e.command}`}dedupeClaudeHooksAgainstCursorHooks(e){const t=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks],r=new Map;for(const e of t)if(null==e?void 0:e.hooks)for(const[t,n]of Object.entries(e.hooks)){if(!n)continue;let e=r.get(t);e||(e=new Set,r.set(t,e));for(const t of n)e.add(this.getHookKey(t))}const n=(e,t)=>{if(null==e?void 0:e.hooks)for(const[n,o]of Object.entries(e.hooks)){if(!o)continue;const i=r.get(n);if(!i||0===i.size)continue;const s=o.filter((e=>{const r=this.getHookKey(e);return!i.has(r)||(this.logger.info(`Removed duplicate ${t} hook for ${n}: ${r}`),!1)}));s.length!==o.length&&(e.hooks[n]=s)}};n(e.claudeUserHooks,"claude-user"),n(e.claudeProjectHooks,"claude-project"),n(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 n=r;for(const[e,r]of Object.entries(n))if(e in he&&Array.isArray(r)){const n=!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||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=be(r,this.logger),o=Ke(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const r=this.parseJSONC(e),n=Ke(r);if(!n.isValid)return{error:`Invalid ${t} config: ${n.errors.join("; ")}`};const o=r;return o.hooks?{config:o}:{error:`Invalid ${t} config: missing 'hooks' property`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks];for(const e of r)if(null==e?void 0:e.hooks)for(const r of Object.keys(e.hooks))t.add(r);return t}}class iS{constructor(e){this.config=e,this.configuredSteps=oS.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var sS=r("node:perf_hooks");function aS(e,t){void 0!==e&&t.length>0&&e.push(...t)}class lS 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 cS=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function uS({hookEventName:e,additionalContext:t}){const r=function(e){const t=null==e?void 0:e.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new lS({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new cS.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Te).map((e=>{if(!function(e){return e===de.sessionStart||e===de.beforeSubmitPrompt||e===de.preToolUse||e===de.postToolUse||e===de.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}]})));var dS=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},hS=function(e){return this instanceof hS?(this.v=e,this):new hS(e)};const pS=(0,h.h)("generic-hooks");function fS(e,t,r,n){try{return uS({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof lS)return pS.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const mS=e=>Math.round(1e3*e)/1e3;function gS(e,t,r,n,i,s){var a,l,c,u,d,h,p;const f=n(e),m=null!==(u=null===(a=i.getToolCallId)||void 0===a?void 0:a.call(i,t))&&void 0!==u?u:(0,o.randomUUID)(),g=null!==(d=null===(l=i.getExtraHookFields)||void 0===l?void 0:l.call(i,t))&&void 0!==d?d:{},v={baseHookRequest:f,toolUseId:m,toolInput:i.createToolInput(t),extraHookFields:g,hookContextCollector:null!==(p=null!==(h=null==s?void 0:s.hookContextCollector)&&void 0!==h?h:null===(c=i.getHookContextCollector)||void 0===c?void 0:c.call(i,t))&&void 0!==p?p:[]},y=function(e,t,r,n){let{toolInput:o,extraHookFields:i,hookContextCollector:s}=n;const{baseHookRequest:a,toolUseId:l}=n;return{fireFailureAsync:(n,c,u,...d)=>dS(this,[n,c,u,...d],void 0,(function*(n,c,u,d=!1){try{const h=yield t.executeHookForStep(de.postToolUseFailure,Object.assign(Object.assign(Object.assign({},a),{tool_name:r,tool_input:o,error_message:c,failure_type:u,duration:n,tool_use_id:l,is_interrupt:d}),i));aS(s,fS(e,r,de.postToolUseFailure,null==h?void 0:h.additional_context))}catch(t){pS.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}})),fireSuccessAsync:(n,c)=>dS(this,void 0,void 0,(function*(){try{const u=yield t.executeHookForStep(de.postToolUse,Object.assign(Object.assign(Object.assign({},a),{tool_name:r,tool_input:o,tool_output:c,duration:n,tool_use_id:l}),i));aS(s,fS(e,r,de.postToolUse,null==u?void 0:u.additional_context))}catch(t){pS.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}})),getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{i=e,n.extraHookFields=e}}}(e,r,i.toolName,v);return{hookContext:v,helpers:y}}function vS(e,t,r,n,o,i,s,a){return dS(this,void 0,void 0,(function*(){var l,c;const{baseHookRequest:u,toolUseId:d,extraHookFields:h}=n;try{const a=yield r.executeHookForStep(de.preToolUse,Object.assign(Object.assign(Object.assign({},u),{tool_name:i.toolName,tool_input:o.getToolInput(),tool_use_id:d}),h));if("deny"===(null==a?void 0:a.permission)){const r=a.user_message||`${i.toolName} blocked by preToolUse hook`,l=Zb(r);try{aS(n.hookContextCollector,uS({hookEventName:de.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof lS))throw t;pS.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:i.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return yield o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:s(t,l),reason:l}}(null==a?void 0:a.updated_input)&&i.applyUpdatedInput&&(i.applyUpdatedInput(t,a.updated_input),o.setToolInput(i.createToolInput(t)),i.getExtraHookFields&&o.setExtraHookFields(i.getExtraHookFields(t))),aS(n.hookContextCollector,uS({hookEventName:de.preToolUse,additionalContext:null==a?void 0:a.additional_context}))}catch(n){const a=null!==(c=null===(l=r.hasFailClosedHooksForStep)||void 0===l?void 0:l.call(r,de.preToolUse,i.toolName))&&void 0!==c&&c,u=n instanceof lS;if(a){const e=Yb(`${u?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return yield o.fireFailureAsync(0,e,"error"),{type:"rejected",result:s(t,e),reason:e}}pS.warn(e,u?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",Object.assign({toolName:i.toolName,error:n instanceof Error?n.message:String(n)},u?{actualLength:n.actualLength,maxLength:n.maxLength}:{}))}if(a)try{const i=yield a({ctx:e,args:t,baseHookRequest:u,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:d,extraHookFields:n.extraHookFields});if(void 0!==i){const e="Pre-execution hook returned rejection";return yield o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:i,reason:e}}}catch(e){if(Qb(e))return yield o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:s(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}))}function yS(e){return e.toolCallId}function wS(e,t,r,n){return{execute(o,i,s){return dS(this,void 0,void 0,(function*(){var a,l,c,u,d,h,p,f,m,g;const{hookContext:v,helpers:y}=gS(o,i,t,r,n,s);let w;try{w=yield vS(o,i,t,v,y,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw null===(a=n.runCleanup)||void 0===a||a.call(n,v.toolUseId),e}if("rejected"===w.type)return null===(l=n.runCleanup)||void 0===l||l.call(n,v.toolUseId),w.result;const b=sS.performance.now();try{const r=yield e.execute(o,i,s),a=mS(sS.performance.now()-b);if(n.runPostExecutionHooks)try{const e=yield n.runPostExecutionHooks({ctx:o,args:i,result:r,baseHookRequest:v.baseHookRequest,hookExecutor:t,toolInput:y.getToolInput(),toolUseId:v.toolUseId,executionDurationMs:a,extraHookFields:v.extraHookFields});if(void 0!==e)return yield y.fireSuccessAsync(a,JSON.stringify(n.createSuccessOutput(i,e))),null===(c=n.runCleanup)||void 0===c||c.call(n,v.toolUseId),e}catch(e){if(Qb(e))return yield y.fireFailureAsync(a,e.reason,e.failureType),null===(u=n.runCleanup)||void 0===u||u.call(n,v.toolUseId),n.createRejectedResult(i,e.reason);pS.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(r)?yield y.fireSuccessAsync(a,JSON.stringify(n.createSuccessOutput(i,r))):yield y.fireFailureAsync(a,n.getErrorMessage(r),null!==(m=null===(d=n.getFailureType)||void 0===d?void 0:d.call(n,r))&&void 0!==m?m:"error",null!==(g=null===(h=n.isInterrupt)||void 0===h?void 0:h.call(n,r))&&void 0!==g&&g),null===(p=n.runCleanup)||void 0===p||p.call(n,v.toolUseId),r}catch(e){const t=mS(sS.performance.now()-b);throw yield y.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),null===(f=n.runCleanup)||void 0===f||f.call(n,v.toolUseId),e}}))}}}function*bS(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}var SS=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class kS{readFile(e){return SS(this,void 0,void 0,(function*(){try{return yield no.readFile(e,"utf-8")}catch(e){if("ENOENT"===(null==e?void 0:e.code))return;throw e}}))}exists(e){return SS(this,void 0,void 0,(function*(){try{return yield no.access(e),!0}catch(e){return!1}}))}pathContainsSymlink(e,t){return SS(this,void 0,void 0,(function*(){return function(e,t){return r=this,n=void 0,i=function*(){const r=a.resolve(e),n=a.resolve(t),o=a.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${a.sep}`)||a.isAbsolute(o))return!0;const i=o.split(a.sep).filter((e=>e.length>0));let s=n;for(const e of i){s=a.join(s,e);try{if((yield(0,no.lstat)(s)).isSymbolicLink())return!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!0;throw e}}return!1},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{l(i.next(e))}catch(e){t(e)}}function a(e){try{l(i.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,a)}l((i=i.apply(r,n||[])).next())}));var r,n,o,i}(e,t)}))}}class ES{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}execute(e,t,r){return n=this,o=void 0,s=function*(){this.teamHooksReadyPromise&&(yield this.teamHooksReadyPromise);const n=yield this.innerExecutor.execute(e,t,r),o=yield this.hooksAdditionalContextPromise,i=this.hooksConfigLease?new Bt.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||i)){const e=n.result.value.requestContext,t=new Bt.bb(Object.assign(Object.assign(Object.assign({},e),o&&{hooksAdditionalContext:o}),i&&{hooksConfig:i}));return new Bt._G({result:{case:"success",value:new Bt.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n},new((i=void 0)||(i=Promise))((function(e,t){function r(e){try{l(s.next(e))}catch(e){t(e)}}function a(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i((function(e){e(n)}))).then(r,a)}l((s=s.apply(n,o||[])).next())}));var n,o,i,s}}function xS(e){return!!e&&e.type!==xo.vc.INSECURE_NONE&&e.type!==xo.vc.UNSPECIFIED}const CS="Shell";function _S(e){return t=this,r=arguments,o=function*({hookExecutor:e,baseHookRequest:t,command:r,cwd:n,sandbox:o}){const i=yield e.executeHookForStep(de.beforeShellExecution,Object.assign(Object.assign({},t),{command:r,cwd:n,sandbox:o}));if("deny"===(null==i?void 0:i.permission)){const e=Xb("Command execution",i.user_message);throw new qb(e)}if("ask"===(null==i?void 0:i.permission))return s=i.user_message,new Ct.In({kind:Ct.b.FORCE_PROMPT,reason:s});var s},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}const PS={toolName:CS,getToolCallId:yS,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 kt.Lt({result:{case:"rejected",value:new Ct.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:e=>{return t=void 0,r=void 0,o=function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",i=xS(t.sandboxPolicy);Ht(t,yield _S({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:i}))},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}};class IS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,PS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TS={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new kt.nt({result:{case:"error",value:new kt.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 RS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,TS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AS={toolName:"ComputerUse",getToolCallId:yS,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new nd.ks({result:{case:"error",value:new nd.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 OS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,AS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const MS={toolName:"Delete",getToolCallId:yS,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Et.Pi({result:{case:"rejected",value:new Et.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 jS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,MS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DS={toolName:"ReadLints",getToolCallId:yS,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Hm.Ek({result:{case:"rejected",value:new Hm.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 NS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,DS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $S={toolName:"Fetch",getToolCallId:yS,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Nd.uN({result:{case:"error",value:new Nd.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 LS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,$S)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FS={toolName:"Grep",getToolCallId:yS,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 zd.Ud({result:{case:"error",value:new zd.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 US{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,FS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const BS={toolName:"List",getToolCallId:yS,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 $f.fv({result:{case:"rejected",value:new $f.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 zS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,BS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var WS=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const HS=(0,h.h)("hooks-exec:mcp");function qS(e,t,r,n){try{return uS({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof lS)return HS.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class GS{constructor(e,t,r,n){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n}execute(e,t,r){return WS(this,void 0,void 0,(function*(){var n,i,s,a,l,c;if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);const u=this.baseHookRequestExtractor(e),d=(0,o.randomUUID)(),h=null!==(a=null==r?void 0:r.hookContextCollector)&&void 0!==a?a:[];let p=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])));const f=`MCP:${t.toolName}`;try{const r=yield this.hookExecutor.executeHookForStep(de.preToolUse,Object.assign(Object.assign({},u),{tool_name:f,tool_input:p,tool_use_id:d}));if("deny"===(null==r?void 0:r.permission)){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{aS(h,uS({hookEventName:de.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof lS))throw t;HS.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:f,actualLength:t.actualLength,maxLength:t.maxLength})}return yield this.firePostToolUseFailureAsync(e,u,f,p,t,"permission_denied",0,d,!1,h),new xt.iz({result:{case:"permissionDenied",value:new xt.HQ({error:Xb("MCP tool execution",t),isReadonly:!1})}})}if(null==r?void 0:r.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))void 0!==n&&(t.args[e]=ar.Value.fromJson(n));p=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])))}catch(t){HS.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}aS(h,uS({hookEventName:de.preToolUse,additionalContext:null==r?void 0:r.additional_context}))}catch(t){const r=null!==(l=null===(i=(n=this.hookExecutor).hasFailClosedHooksForStep)||void 0===i?void 0:i.call(n,de.preToolUse,f))&&void 0!==l&&l,o=t instanceof lS;if(r){const r=Yb(`${o?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return yield this.firePostToolUseFailureAsync(e,u,f,p,r,"error",0,d,!1,h),new xt.iz({result:{case:"permissionDenied",value:new xt.HQ({error:Xb("MCP tool execution",r),isReadonly:!1})}})}HS.warn(e,o?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",Object.assign({toolName:f,error:t instanceof Error?t.message:String(t)},o?{actualLength:t.actualLength,maxLength:t.maxLength}:{}))}const m=yield null===(s=this.mcpLease)||void 0===s?void 0:s.getClient(e,t.providerIdentifier),g=null==m?void 0:m.config;let v;const y=g&&"url"in g&&g.url?g.url:void 0;v=void 0!==y?{url:y}:g&&"command"in g?{command:[g.command,...null!==(c=g.args)&&void 0!==c?c:[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const w=Object.assign({mcp_server_name:t.providerIdentifier},void 0!==y?{mcp_server_url:y}:{}),b=Object.assign(Object.assign(Object.assign(Object.assign({},u),{tool_name:t.toolName,tool_input:JSON.stringify(p)}),w),v),S=yield this.hookExecutor.executeHookForStep(de.beforeMCPExecution,b);if("deny"===(null==S?void 0:S.permission)){const t=Xb("MCP tool execution",S.user_message);return yield this.firePostToolUseFailureAsync(e,u,f,p,t,"permission_denied",0,d,!1,h),new xt.iz({result:{case:"permissionDenied",value:new xt.HQ({error:t,isReadonly:!1})}})}const k=sS.performance.now();try{const n=yield this.innerExecutor.execute(e,t,r),o=mS(sS.performance.now()-k);let i="{}";if("success"===n.result.case)try{const e=n.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"}));i=JSON.stringify({content:e,isError:n.result.value.isError})}catch(t){HS.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),i=JSON.stringify({error:"Failed to serialize result"})}else"error"===n.result.case?i=JSON.stringify({error:n.result.value.error}):"rejected"===n.result.case?i=JSON.stringify({rejected:!0,reason:n.result.value.reason}):"permissionDenied"===n.result.case&&(i=JSON.stringify({permissionDenied:!0,error:n.result.value.error}));const s=Object.assign(Object.assign(Object.assign({},u),{tool_name:t.toolName,tool_input:JSON.stringify(p),result_json:i,duration:o}),w);yield this.hookExecutor.executeHookForStep(de.afterMCPExecution,s);const a=yield this.firePostToolUse(e,u,f,p,i,o,d,h);if(void 0!==(null==a?void 0:a.updated_mcp_tool_output))try{const e=a.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new xt._Z({content:{case:"text",value:new xt.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 xt._Z({content:{case:"text",value:new xt.zN({text:String(e.text)})}})):t.push(new xt._Z({content:{case:"text",value:new xt.zN({text:JSON.stringify(e)})}}))}else t.push(new xt._Z({content:{case:"text",value:new xt.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new xt.iz({result:{case:"success",value:new xt.QW({content:t,isError:r})}})}catch(t){return HS.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),n}return n}catch(t){const r=mS(sS.performance.now()-k),n=t instanceof Error?t.message:String(t);throw yield this.firePostToolUseFailureAsync(e,u,f,p,n,"error",r,d,!1,h),t}}))}firePostToolUse(e,t,r,n,o,i,s,a){return WS(this,void 0,void 0,(function*(){try{const l=yield this.hookExecutor.executeHookForStep(de.postToolUse,Object.assign(Object.assign({},t),{tool_name:r,tool_input:n,tool_output:o,duration:i,tool_use_id:s}));return aS(a,qS(e,r,de.postToolUse,null==l?void 0:l.additional_context)),l}catch(t){return void HS.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}))}firePostToolUseFailureAsync(e,t,r,n,o,i,s,a,l,c){return WS(this,void 0,void 0,(function*(){try{const u=yield this.hookExecutor.executeHookForStep(de.postToolUseFailure,Object.assign(Object.assign({},t),{tool_name:r,tool_input:n,error_message:o,failure_type:i,duration:s,tool_use_id:a,is_interrupt:l}));aS(c,qS(e,r,de.postToolUseFailure,null==u?void 0:u.additional_context))}catch(t){HS.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}))}}const VS={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new xt.kP({result:{case:"error",value:new xt.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 JS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,VS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KS={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 xt.ZD({result:{case:"error",value:new xt.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 ZS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,KS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const YS={toolName:"Read",getToolCallId:yS,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new wg.sV({result:{case:"rejected",value:new wg.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:e=>{return t=void 0,r=void 0,o=function*(){const{args:t,result:r,baseHookRequest:n,hookExecutor:o}=e;if("success"!==r.result.case)return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",s=yield Vb((()=>o.executeHookForStep(de.beforeReadFile,Object.assign(Object.assign({},n),{content:i,file_path:t.path,attachments:[]}))),"File read");if("deny"===(null==s?void 0:s.permission)){const e=Xb("File read",s.user_message);throw new qb(e)}},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}};class XS{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,YS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const QS={toolName:"RecordScreen",getToolCallId:yS,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new Dg.Tj({result:{case:"failure",value:new Dg.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 ek{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,QS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var tk=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function rk(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const nk={toolName:CS,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return Object.assign({command:e.command,cwd:t},"number"==typeof r&&r>0&&{timeout:r})},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new Ct.W4({result:{case:"rejected",value:new Ct.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:rk(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:e=>tk(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"";Ht(t,yield _S({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:xS(t.requestedSandboxPolicy)}))})),runPostExecutionHooks:e=>tk(void 0,void 0,void 0,(function*(){const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:i}=e,s=rk(r);yield o.executeHookForStep(de.afterShellExecution,Object.assign(Object.assign({},n),{command:t.command,output:s,duration:i,sandbox:xS(t.requestedSandboxPolicy)}))}))};class ok{constructor(e,t,r){this.wrappedExecutor=wS(e,t,r,nk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var ik=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class sk{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(){var e,t;return null!==(t=null===(e=this.exitEvent)||void 0===e?void 0:e.aborted)&&void 0!==t&&t}getExitCode(){var e,t;return null!==(t=null===(e=this.exitEvent)||void 0===e?void 0:e.code)&&void 0!==t?t:0}}const ak={toolName:CS,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return Object.assign({command:e.command,cwd:t},"number"==typeof r&&r>0&&{timeout:r})},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new Ct.FI({event:{case:"rejected",value:new Ct.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new Ct.FI({event:{case:"hookContext",value:new Ct.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new sk,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:e=>ik(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",i=xS(t.requestedSandboxPolicy);Ht(t,yield _S({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:i}))})),runPostExecutionHooks:e=>ik(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:i}=e,s=xS(t.requestedSandboxPolicy);yield n.executeHookForStep(de.afterShellExecution,Object.assign(Object.assign({},r),{command:t.command,output:o.getOutput(),duration:i,sandbox:s}))}))};class lk{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{execute(o,i,s){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof hS?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(){var a,l,c,u,d,h,p,f;const{hookContext:m,helpers:g}=gS(o,i,t,r,n,s),v=n.runPreExecutionHooks?e=>dS(this,void 0,void 0,(function*(){yield n.runPreExecutionHooks(e)})):void 0,y=yield hS(vS(o,i,t,m,g,n,((e,t)=>n.createRejectedEvent(e,t)),v));if("rejected"===y.type){yield yield hS(y.result);for(const e of bS(n,m))yield yield hS(e);return yield hS(void 0)}const w=sS.performance.now(),b=n.createResultCollector();let S=!1;try{try{for(var k,E=!0,x=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(e.execute(o,i,s));!(a=(k=yield hS(x.next())).done);E=!0){u=k.value,E=!1;const e=u;b.onEvent(e),yield yield hS(e)}}catch(e){l={error:e}}finally{try{E||a||!(c=x.return)||(yield hS(c.call(x)))}finally{if(l)throw l.error}}}catch(e){S=!0;const t=mS(sS.performance.now()-w),r=e instanceof Error?e.message:String(e);yield hS(g.fireFailureAsync(t,r,"error"));for(const e of bS(n,m))yield yield hS(e);throw e}const C=mS(sS.performance.now()-w);if(n.runPostExecutionHooks)try{yield hS(n.runPostExecutionHooks({ctx:o,args:i,baseHookRequest:m.baseHookRequest,hookExecutor:t,toolInput:g.getToolInput(),toolUseId:m.toolUseId,extraHookFields:m.extraHookFields,collector:b,executionDurationMs:C}))}catch(e){pS.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(!S)if(b.isAborted())yield hS(g.fireFailureAsync(C,"Command was aborted","error",!0));else if(null===(p=null===(d=n.isStreamSuccess)||void 0===d?void 0:d.call(n,b))||void 0===p||p)yield hS(g.fireSuccessAsync(C,JSON.stringify(n.createSuccessOutput(i,b))));else{const e=null!==(f=null===(h=n.getStreamErrorMessage)||void 0===h?void 0:h.call(n,i,b))&&void 0!==f?f:`Command failed with exit code ${b.getExitCode()}`;yield hS(g.fireFailureAsync(C,e,"error"))}for(const e of bS(n,m))yield yield hS(e)}))}}}(e,t,r,ak)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var ck=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class uk{constructor(e,t,r){const n=new Map;this.wrappedExecutor=wS(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:yS,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 _t.v3({result:{case:"error",value:new _t.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:e=>ck(this,void 0,void 0,(function*(){const{args:r,toolUseId:n}=e;let o,i=!1;try{(yield(0,no.stat)(r.path)).size>262144?i=!0:o=yield Mc(r.path)}catch(e){}t.set(n,{contentBeforeWrite:o,fileTooLarge:i})})),runCleanup:e=>{t.delete(e)},runPostExecutionHooks:r=>ck(this,void 0,void 0,(function*(){const{args:n,result:o,baseHookRequest:i,toolUseId:s}=r,a=t.get(s);if("success"!==o.result.case)return;const{contentBeforeWrite:l,fileTooLarge:c}=null!=a?a:{fileTooLarge:!1};let u;u=c||void 0===l?[{old_string:"",new_string:n.fileText}]:l===n.fileText?[]:function(e,t){const r=(0,am.YB)("","",e,t,"","",{context:0});return 0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(l,n.fileText);const d=Object.assign(Object.assign({},i),{file_path:n.path,edits:u}),h=yield e.executeHookForStep(de.afterFileEdit,d);if(n.returnFileContentAfterWrite&&void 0!==h){const e=o.result.value.path;try{const t=yield Mc(e),r=Nc(t),n=Buffer.byteLength(t,"utf8");return new _t.v3({result:{case:"success",value:new _t.j6(Object.assign(Object.assign({},o.result.value),{fileContentAfterWrite:t,linesCreated:r,fileSize:n}))}})}catch(e){return}}}))}}(t,n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class dk{constructor(e,t,r,n,o,i,s){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=i,this.hooksConfigLease=s}get(e){var t;if(e.symbol===Ye.symbol)return new Xe(this.hookExecutor);const r=this.innerAccessor.get(e);return e.symbol===Pt.symbol?new ok(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===It.symbol?new lk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Tt.symbol?new uk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===at.symbol?new GS(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease):e.symbol===bt.symbol||e.symbol===St.symbol?new XS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===tt.symbol?new zS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ue.symbol?new US(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===le.symbol?new LS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===se.symbol?new jS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ae.symbol?new NS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===lt.symbol?new JS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ct.symbol?new ZS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ee.symbol?new IS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===te.symbol?new RS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ie.symbol?new OS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ft.symbol?new ek(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ut.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new ES(r,null!==(t=this.hooksAdditionalContextPromise)&&void 0!==t?t:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease):r}*entries(){var e;for(const[t,r]of this.innerAccessor.entries())t.symbol===Pt.symbol?yield[t,new ok(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===It.symbol?yield[t,new lk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Tt.symbol?yield[t,new uk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===at.symbol?yield[t,new GS(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease)]:t.symbol===bt.symbol||t.symbol===St.symbol?yield[t,new XS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===tt.symbol?yield[t,new zS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ue.symbol?yield[t,new US(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===le.symbol?yield[t,new LS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===se.symbol?yield[t,new jS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ae.symbol?yield[t,new NS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===lt.symbol?yield[t,new JS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ct.symbol?yield[t,new ZS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ee.symbol?yield[t,new IS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===te.symbol?yield[t,new RS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ie.symbol?yield[t,new OS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ft.symbol?yield[t,new ek(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ut.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[t,new ES(r,null!==(e=this.hooksAdditionalContextPromise)&&void 0!==e?e:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease)]:yield[t,r];yield[Ye,new Xe(this.hookExecutor)]}}var hk,pk=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},fk=function(e){return this instanceof fk?(this.v=e,this):new fk(e)};const mk={cursor_version:null!==(hk=process.env.AGENT_CLI_STATIC_VERSION)&&void 0!==hk?hk:"1.0.0",user_email:null};function gk(e=process.cwd()){let t=e;const r={getCwd(){return pk(this,void 0,void 0,(function*(){return t}))},clone:e=>gk(null!=e?e:t),execute(e,r){return function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof fk?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,(function*(e,r,n={}){var o,i,s,a,l,c;const u=null!==(l=n.workingDirectory)&&void 0!==l?l:t;t=u;const d=function(e){return"win32"===process.platform?{executable:(0,io.getPowerShellExecutable)(),args:[...Ge,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),h=(0,Cs.spawn)(d.executable,[...d.args],{cwd:u,env:Object.assign(Object.assign({},process.env),null!==(c=n.env)&&void 0!==c?c:{}),signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),p=[];let f,m,g=!1;const v=()=>{null==f||f(),f=void 0},y=e=>{p.push(e),v()};for(h.on("spawn",(()=>{var e;!0===n.pipeStdin&&y({type:"stdin_ready",stdin:null!==(e=h.stdin)&&void 0!==e?e:void 0})})),null===(o=h.stdout)||void 0===o||o.setEncoding("utf8"),null===(i=h.stdout)||void 0===i||i.on("data",(e=>{y({type:"stdout",data:String(e)})})),null===(s=h.stderr)||void 0===s||s.setEncoding("utf8"),null===(a=h.stderr)||void 0===a||a.on("data",(e=>{y({type:"stderr",data:String(e)})})),h.on("error",(e=>{m=e,g=!0,v()})),h.on("close",(e=>{y({type:"exit",code:e}),g=!0}));!g||p.length>0;)0!==p.length?yield yield fk(p.shift()):yield fk(new Promise((e=>{f=e})));if(void 0!==m)throw m}))}};return r}function vk(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function yk(e){return"string"==typeof e&&e.length>0?e:void 0}function wk(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function bk(e){if(Array.isArray(e)&&e.every(wk))return e.map((e=>({id:e.id,value:e.value})))}class Sk{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}dispose(){return pk(this,void 0,void 0,(function*(){yield this.sessionHooksRuntime.dispose()}))}}function kk(e={}){return{createHooksRuntime:t=>function(e){return pk(this,arguments,void 0,(function*(e,t={}){const r=yield new oS(new kS,function(e,t){var r,n,o,i,l;const c=null!==(n=null!==(r=e.projectRoot)&&void 0!==r?r:e.workingDirectory)&&void 0!==n?n:e.workspaceRoots[0],u=null===(o=t.includeProjectHooks)||void 0===o||o,d=null===(i=t.includeUserHooks)||void 0===i||i;return{enterpriseConfigPath:null===(l=t.includeEnterpriseHooks)||void 0===l||l?nS():void 0,userConfigPath:d?(0,a.join)((0,s.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:d?(0,a.join)((0,s.homedir)(),".claude","settings.json"):void 0,projectConfigPath:u&&void 0!==c?(0,a.join)(c,".cursor","hooks.json"):void 0,claudeProjectConfigPath:u&&void 0!==c?(0,a.join)(c,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:u&&void 0!==c?(0,a.join)(c,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new iS(r),o=function(e){var t,r,n;return null!==(n=null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workingDirectory)&&void 0!==r?r:e.workspaceRoots[0])&&void 0!==n?n:process.cwd()}(e),i=function(e){var t;return Object.freeze(Object.assign(Object.assign({},mk),null!==(t=e.globalContext)&&void 0!==t?t:{}))}(t);return{projectDir:e.projectRoot,workspacePath:o,hooksConfig:r,hooksConfigLease:n,globalContext:i,createSessionRuntime(){var e;const s=new tS(r,o,i,(null!==(e=t.createTerminalExecutor)&&void 0!==e?e:gk)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(a=t.useCommandHookStdinTransport,!0===a?"stdin":"legacy")});var a;return{hookExecutor:s,hooksConfigLease:n,dispose(){return pk(this,void 0,void 0,(function*(){s.clearSessionEnvironment()}))}}},dispose(){return pk(this,void 0,void 0,(function*(){}))}}}))}(t.workspaceState,e)}}var Ek=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");function xk(e){return t=this,r=void 0,o=function*(){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&(yield e.dispose())},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}var Ck=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function _k(e={}){var t,r,n,o,i,a;const l=null!==(t=e.getThirdPartyExtensibilityEnabled)&&void 0!==t?t:()=>!0,c=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,u=null===(n=e.includeProjectExtensibility)||void 0===n||n,d=null===(o=e.includeUserExtensibility)||void 0===o||o,h=null===(i=e.includeManagedSkills)||void 0===i||i,p=null===(a=e.includePluginExtensibility)||void 0===a||a,f=new Bd,m=(0,s.homedir)(),g=bu(m).dirPath;let v,y=!0;return{prepareLocalExtensibility(){return Ck(this,void 0,void 0,(function*(){y=h&&(yield function(e){return Ck(this,void 0,void 0,(function*(){if(!e)return!1;const t=(0,lr.createClient)(Ek.I,e),r=yield async function(e,t){try{const r=await t.getManagedSkills()??[],n=await uy(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return hy.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,Qe.q6)(),{getManagedSkills:()=>Ck(this,void 0,void 0,(function*(){var e;return null!==(e=(yield t.getManagedSkills(new dw.X8g({}))).skills)&&void 0!==e?e:[]}))});return"synced"===r.status}))}(e.dashboardTransport))}))},loadLocalExtensibility(t){return Ck(this,void 0,void 0,(function*(){var r,n;const o=t.workspaceState,i=null!==(r=o.projectRoot)&&void 0!==r?r:o.workingDirectory;if(!i)return v=void 0,{cursorRulesService:Mk(),getAgentSkills:e=>Ck(this,void 0,void 0,(function*(){return[]}))};const s=(0,Qe.q6)(),a=null===(n=e.loadNestedRules)||void 0===n||n,h=function(e,t){const r=Pk(t);return{getAllCursorRules(t){return Ck(this,void 0,void 0,(function*(){return Ik(yield e.getAllCursorRules(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(u?new Bu(s,f,i,a,l,void 0):Mk(),{allowedRoots:u?[i]:[],excludedRoots:[]}),w=function(e,t){const r=Pk(t);return{getAllCursorRules(t){return Ck(this,void 0,void 0,(function*(){return Ik(yield e.getAllCursorRules(t),r)}))},getAllAgentSkills(t){return Ck(this,void 0,void 0,(function*(){return Ik(yield e.getAllAgentSkills(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new zu(s,u?[i]:[],m,f,a,void 0,l,Promise.resolve(),"sdk"),{allowedRoots:[...u?[i]:[],...d?[m]:[],...y?[g]:[]],excludedRoots:y?[]:[g]}),b=u?new Qu(i,l):new Vu,S=nb(t.services.pluginBootstrapOutputs),k=S&&p?new Hu(s,(()=>({importThirdPartyPlugins:c})),void 0,S.pluginsService):void 0,E=S&&p?new rd((()=>({importThirdPartyPlugins:c})),S.pluginsService):void 0,x=new Uu([h,w,...k?[k]:[]]),C=new Zv([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:u?[i]:[],userHomeDirectory:m}))),_=new td([b,...E?[E]:[]]);return v={localRulesService:h,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:E,mergedCursorRulesService:x,mergedAgentSkillsService:C,mergedSubagentsService:_},{cursorRulesService:x,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:_}}))},disposeLocalExtensibility(){return Ck(this,void 0,void 0,(function*(){if(!v)return;const e=v;v=void 0,yield function(e){return Ck(this,void 0,void 0,(function*(){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{yield xk(e)}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}))}(e)}))}}}function Pk(e){const t=Promise.all(e.allowedRoots.map(Ak)),r=Promise.all(e.excludedRoots.map(Ak));return e=>Ck(this,void 0,void 0,(function*(){const[n,o,i]=yield Promise.all([Ok(e.fullPath),t,r]);return void 0!==n&&!i.some((e=>Tk(n,e)))&&o.some((e=>Tk(n,e)))}))}function Ik(e,t){return Ck(this,void 0,void 0,(function*(){const r=yield Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}))}function Tk(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function Rk(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}function Ak(e){return Ck(this,void 0,void 0,(function*(){try{return Rk(yield(0,no.realpath)(e))}catch(t){return Rk(e)}}))}function Ok(e){return Ck(this,void 0,void 0,(function*(){try{return Rk(yield(0,no.realpath)(e))}catch(e){return}}))}function Mk(){return{getAllCursorRules(){return Ck(this,void 0,void 0,(function*(){return[]}))},reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}var jk=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function Dk(e={}){var t,r,n,o;const i=null!==(t=e.userHomeDirectory)&&void 0!==t?t:(0,s.homedir)(),l=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,c=null!==(n=e.pluginLogger)&&void 0!==n?n:{log(e,t,r){switch(e){case"warn":Yw.warn("[local-plugins-bootstrap]",t,null!=r?r:{});break;case"error":Yw.error("[local-plugins-bootstrap]",t,null!=r?r:{})}},increment(){},distribution(){},captureException(e,t){Yw.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,null!=t?t:{})}},u=Nk(e.marketplaceOptions),d=void 0!==e.dashboardTransport,h=null!==(o=e.loadCursorFirstParty)&&void 0!==o?o:u||d;return{loadPluginBootstrapOutputs(t){return jk(this,void 0,void 0,(function*(){var r;const n=function(e){var t,r;return null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workspaceRoots[0])&&void 0!==r?r:e.workingDirectory}(t.workspaceState),{discoveredEntries:o,failures:s}=yield function(e){return jk(this,void 0,void 0,(function*(){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(yield sc(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),u=null!==(r=e.marketplaceOptions)&&void 0!==r?r:e.dashboardTransport?function(e){const t=(0,a.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,lr.createClient)(Ek.I,e.dashboardTransport),n=Xa((()=>jk(this,void 0,void 0,(function*(){try{return yield r.getEffectiveUserPlugins(new dw.EwF({}))}catch(e){return{plugins:[]}}}))),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Xa((()=>jk(this,void 0,void 0,(function*(){var e,t;if(void 0===o)return{plugins:[]};try{const n=yield sc(o);if(0===n.length)return{plugins:[]};const i=n.filter((e=>e.entry.gitUrl)),s=n.filter((e=>!e.entry.gitUrl)),a=i.filter((({entry:e})=>{const t=e.gitUrl;return!t||rc(t)})).map((({key:e,entry:t})=>{const r=ac(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let l=[];if(s.length>0)try{const n=s.map((e=>{const t=ac(e.key);return new dw.vwy({name:t.name,marketplaceName:t.marketplaceName})}));l=null!==(t=null===(e=(yield r.resolvePluginsByRef(new dw.WvV({refs:n}))).plugins)||void 0===e?void 0:e.map((e=>({plugin:e,isEnabled:!0}))))&&void 0!==t?t:[]}catch(e){}return{plugins:[...a,...l]}}catch(e){return{plugins:[]}}}))),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new Es(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new Es(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:n,userHomeDirectory:i}):void 0,d=Nk(u),p=new vy(void 0!==n?[n]:[],i,(()=>({importThirdPartyPlugins:l,loadCursorFirstParty:h})),u,c);let f=[];const m=[...s];try{f=yield 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})}o.length>0&&!d&&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:o.length}});const g={kind:rb,discoveredEntries:o,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,dispose(){return jk(this,void 0,void 0,(function*(){}))}};for(const e of m)Yw.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)Yw.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 Nk(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}var $k=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class Lk{getAllCursorRules(e){return $k(this,void 0,void 0,(function*(){return[]}))}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}class Fk extends Wv{constructor(e,t){super(e),this.sessionMcpLease=t}dispose(){const e=Object.create(null,{dispose:{get:()=>super.dispose}});return $k(this,void 0,void 0,(function*(){try{yield e.dispose.call(this)}finally{yield xk(this.sessionMcpLease)}}))}}function Uk(e){const t=new Bd;return{createResources(r){return $k(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c,u;const d=null!==(i=null===(n=e.createSessionDependencies)||void 0===n?void 0:n.call(e,r))&&void 0!==i?i:{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!d.pendingDecisionStore||!d.fileChangeTracker||!d.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const h=null!==(s=r.workspaceServices.cursorRulesService)&&void 0!==s?s:new Lk,p=null!==(a=r.workspaceServices.subagentsService)&&void 0!==a?a:new Vu,f=null!==(l=r.workspaceServices.mcpLease)&&void 0!==l?l:new Gh,m=void 0!==r.options.mcpServersOverride&&void 0!==e.createSessionMcpLease?yield e.createSessionMcpLease(r,r.options.mcpServersOverride):void 0,g=(v=null!=m?m:f,0===(y=null!==(c=r.options.extraMcpTools)&&void 0!==c?c:[]).length?v:"onDidChange"in(w=v)&&"function"==typeof w.onDidChange?new Dd(v,y):new jd(v,y));var v,y,w;try{const n={pendingDecisionStore:d.pendingDecisionStore,fileChangeTracker:d.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:d.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:g,mcpStateAccessor:null===(o=e.createMcpStateAccessor)||void 0===o?void 0:o.call(e,g),cursorRulesService:h,subagentsService:p,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:null!==(u=e.defaultSandboxPolicy)&&void 0!==u?u:{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills};return void 0===m?new Wv(n):new Fk(n,m)}catch(e){throw yield xk(m),e}}))}}}var Bk=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const zk=["cursorRulesService","getAgentSkills","subagentsService"],Wk=new WeakSet;function Hk(e){("object"==typeof e&&null!==e||"function"==typeof e)&&Wk.add(e)}function qk(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&Wk.has(e)}function Gk(e,t){const r=Object.keys(t).filter((e=>!zk.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${zk.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of zk)Object.hasOwn(t,r)&&(e[r]=t[r])}function Vk(e,t,r){return Bk(this,void 0,void 0,(function*(){var n,o,i;const s={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{s.config=e.config?yield e.config.loadConfig(t):void 0,s.plugins=e.plugins?yield e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:s});s.pluginBootstrapOutputs=e.pluginBootstrap?yield e.pluginBootstrap.loadPluginBootstrapOutputs(o()):s.pluginBootstrapOutputs,s.mcpLease=e.mcp?yield e.mcp.createLease(o()):void 0,s.hooksRuntime=e.hooks?yield e.hooks.createHooksRuntime(o()):void 0,(null===(n=e.localExtensibility)||void 0===n?void 0:n.prepareLocalExtensibility)&&(yield e.localExtensibility.prepareLocalExtensibility(o()));const a=e.localExtensibility?yield e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==a&&(Hk(a.cursorRulesService),Hk(a.subagentsService),Object.assign(s,a));for(const t of null!==(i=e.workspaceServicesContributors)&&void 0!==i?i:[]){const e=yield t.contributeServices(o());void 0!==e&&Gk(s,e)}return s}catch(t){try{yield Jk(s,{disposeLocalExtensibility:null===(o=e.localExtensibility)||void 0===o?void 0:o.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}}))}function Jk(e,t){return Bk(this,void 0,void 0,(function*(){const r=null==t?void 0:t.preserveSharedContributorsFrom;let n;const o=e=>Bk(this,void 0,void 0,(function*(){try{yield xk(e)}catch(e){null!=n||(n=e)}}));if(e.subagentsService===(null==r?void 0:r.subagentsService)||qk(e.subagentsService)||(yield o(e.subagentsService)),e.cursorRulesService===(null==r?void 0:r.cursorRulesService)||qk(e.cursorRulesService)||(yield o(e.cursorRulesService)),null==t?void 0:t.disposeLocalExtensibility)try{yield t.disposeLocalExtensibility()}catch(e){null!=n||(n=e)}yield o(e.hooksRuntime),yield o(e.mcpLease);try{yield function(e){return Bk(this,void 0,void 0,(function*(){let t;for(let r=e.length-1;r>=0;r-=1)try{yield xk(e[r])}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}))}(e.pluginBootstrapOutputs)}catch(e){null!=n||(n=e)}if(void 0!==n)throw n}))}var Kk=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function Zk(e){return Kk(this,void 0,void 0,(function*(){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{yield xk(o)}catch(e){null!=r||(r=e)}}}if(void 0!==r)throw r}))}const Yk=["project","user","team","mdm","plugins"],Xk=new Set([...Yk,"all"]);function Qk(e){if(void 0===e||0===e.length)return tE([]);for(const t of e)if(!Xk.has(t))throw new Error(`Unsupported setting source "${String(t)}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return Object.assign(Object.assign({},tE(Yk)),{all:!0})}return tE(e)}function eE(e,t){return e[t]}function tE(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 rE=Object.freeze({}),nE=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:rE});var oE=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function iE(){return oE(this,arguments,void 0,(function*(e={}){var t,r;const n=function(e={}){var t;return{workspace:null!==(t=e.workspace)&&void 0!==t?t:Hw,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),i=yield n.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),s=yield function(e,t){return r=this,n=void 0,i=function*(){return e.resolvePolicy(t)},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{l(i.next(e))}catch(e){t(e)}}function a(e){try{l(i.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(s,a)}l((i=i.apply(r,n||[])).next())}));var r,n,o,i}(null!==(r=e.policyAdapter)&&void 0!==r?r:function(e={}){const t=Object.freeze(Object.assign(Object.assign({},nE.metadata),e.metadata)),r=Object.assign(Object.assign(Object.assign({},nE),e),{metadata:t});return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:i});let a=yield Vk(n,i,s),l=!1,c=Promise.resolve();const u=e=>{const t=c.then(e);return c=t.catch((()=>{})),t},d=null===(t=n.localExtensibility)||void 0===t?void 0:t.disposeLocalExtensibility;return{state:i,get services(){return a},policy:s,createSessionRuntime(){return oE(this,arguments,void 0,(function*(e={}){if(l)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return function(e){return Kk(this,void 0,void 0,(function*(){var t,r,n,i,s,a,l,c;const u={sessionId:null!==(s=null===(t=e.options)||void 0===t?void 0:t.sessionId)&&void 0!==s?s:(0,o.randomUUID)(),createdAt:new Date},d=Object.freeze(Object.assign({},null!==(a=null===(r=e.options)||void 0===r?void 0:r.metadata)&&void 0!==a?a:{})),h={options:null!==(l=e.options)&&void 0!==l?l:{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:u,metadata:d,getAgentSkills:e.workspaceServices.getAgentSkills};let p,f;const m=[];try{p=e.adapters.resourceFactory?yield e.adapters.resourceFactory.createResources(h):void 0,f=p,m.push(p);for(const t of null!==(c=e.adapters.resourceWrappers)&&void 0!==c?c:[])f=yield t.wrapResources(Object.assign(Object.assign({},h),{baseResources:p,resources:f})),m.push(f);yield null===(i=null===(n=e.adapters.lifecycle)||void 0===n?void 0:n.onSessionCreated)||void 0===i?void 0:i.call(n,u)}catch(e){try{yield Zk(m)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let g=!1;return{state:u,resources:{base:p,wrapped:f},metadata:d,workspaceServices:e.workspaceServices,policy:e.policy,dispose(){return Kk(this,void 0,void 0,(function*(){var t,r;if(!g){g=!0;try{yield Zk(m)}finally{yield null===(r=null===(t=e.adapters.lifecycle)||void 0===t?void 0:t.onSessionDisposed)||void 0===r?void 0:r.call(t,u)}}}))}}}))}({options:e,workspaceState:i,workspaceServices:a,policy:s,adapters:n})}))},reload(){return oE(this,void 0,void 0,(function*(){l||(yield u((()=>oE(this,void 0,void 0,(function*(){var e,t;if(l)return;const r=a,o=yield Vk(n,i,s);l?yield Jk(o,{disposeLocalExtensibility:d}):(a=o,yield Jk(r,{preserveSharedContributorsFrom:o,disposeLocalExtensibility:d}),yield null===(t=null===(e=n.lifecycle)||void 0===e?void 0:e.onWorkspaceReload)||void 0===t?void 0:t.call(e,i))})))))}))},dispose(){return oE(this,void 0,void 0,(function*(){l||(l=!0,yield u((()=>oE(this,void 0,void 0,(function*(){var e;try{yield Jk(a,{disposeLocalExtensibility:d})}finally{yield null===(e=n.lifecycle)||void 0===e?void 0:e.dispose()}})))))}))}}}))}var sE=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class aE{requestApproval(e){return sE(this,void 0,void 0,(function*(){return{approved:!0}}))}}class lE{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}getPermissions(){return sE(this,void 0,void 0,(function*(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(yield this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}))}updatePermissions(){return sE(this,void 0,void 0,(function*(){}))}}class cE{open(e,t){return sE(this,void 0,void 0,(function*(){}))}getDiagnostics(e,t){return sE(this,void 0,void 0,(function*(){return[]}))}}class uE{getCodebaseReference(e,t){return sE(this,void 0,void 0,(function*(){}))}}class dE{constructor(e){this.inner=e}getState(e){return sE(this,void 0,void 0,(function*(){const t=yield this.inner.getState(e);return Object.assign(Object.assign({},t),{servers:t.servers.filter((e=>"needsAuth"!==e.status))})}))}}class hE{constructor(e){this.subagents=e.map((e=>new qu.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:qu.b$.DEFAULT,isBackground:!1,source:"sdk"})))}getAllSubagents(){return sE(this,void 0,void 0,(function*(){return this.subagents}))}reload(){return sE(this,void 0,void 0,(function*(){return this.subagents}))}}var pE=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},fE=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),mE=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const gE=vw;function vE(e,t){return mE(this,void 0,void 0,(function*(){const r=(0,a.dirname)(e);yield(0,no.mkdir)(r,{recursive:!0}),yield(0,no.writeFile)(e,t,"utf-8")}))}class yE{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=gE(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=Sb({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,a.join)(this.projectDir,r)}:void 0;this.transcriptStore=new Hb(this.projectDir,e.blobStore,vE,Object.assign({writeText:!1,writeJsonl:!0},t?{pathResolver:t}:{})),this.nestedSubagentTranscriptStore=new Hb(this.projectDir,e.blobStore,vE,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=Sb({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,a.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((()=>mE(this,void 0,void 0,(function*(){try{yield e()}catch(e){Yw.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})))),this.writeChain}writeFromState(e,t){return mE(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>mE(this,void 0,void 0,(function*(){yield this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=yield(0,nr.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))(null==n?void 0:n.conversationState)&&(yield this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t))}))),"[LocalTranscriptWriter] Failed to write transcript:")}))}writeTurnEndedFromState(e,t,r){return mE(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>mE(this,void 0,void 0,(function*(){yield 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=Sb({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,a.join)(this.projectDir,e)}return function(e,t){const r=Sb({conversationId:t,ext:"jsonl",kind:"primary"});return(0,a.join)(gE(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var wE=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const bE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SE="User aborted/interrupted manually.";class kE{constructor(e){var t;this.sessions=new Map,this.backgroundRuns=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=null!==(t=e.mcpTools)&&void 0!==t?t:[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new Yt}createOrResumeSession(e,t){return wE(this,void 0,void 0,(function*(){var e;if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!bE.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&Xt(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=null!=r?r:(0,o.randomUUID)(),i=function(e){const t=new nr.We,r=(0,nr.sh)(e),n=new nr.pH(new nr.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n}(n),s=new yE({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:i.getBlobStore()});return this.sessions.set(n,{agentStore:i,transcriptWriter:s,toolCallId:t.toolCallId}),this.registerParentChildLink(n,t.parentConversationId),null===(e=this.onSessionCreated)||void 0===e||e.call(this,{agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}))}runSession(e,t,r,n){return wE(this,void 0,void 0,(function*(){var n;if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,i]=e.withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),i),{status:"background",backgroundReason:Ze.qLf.AGENT_REQUEST,toolCallCount:0}}const i=yield this.executeSubagent(e,t,r,o);return null===(n=this.onSessionCompleted)||void 0===n||n.call(this,t,i),i}))}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}awaitBackgroundWorkers(){return wE(this,void 0,void 0,(function*(){for(;this.backgroundPromises.size>0;)yield Promise.allSettled([...this.backgroundPromises])}))}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r){const n=this.lifecycleStore.startRun(e,{abort:r}),o=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:n,promise:o};this.backgroundRuns.set(e,i),this.backgroundPromises.add(o),o.then((t=>{var r;this.lifecycleStore.finishRun(e,n);const o=this.backgroundRuns.get(e);if((null==o?void 0:o.runId)===n){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,t),this.maybeCleanupReleasedSession(e);try{null===(r=this.onSessionCompleted)||void 0===r||r.call(this,e,t)}catch(t){Yw.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(o)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){var t;this.pendingReleaseSessions.delete(e);const r=this.sessions.get(e);if(!r)return;const n=this.parentChildIds.get(e);if(n)for(const e of n)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),r.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),null===(t=this.onSessionReleased)||void 0===t||t.call(this,e)}executeSubagent(e,t,r,n){return wE(this,void 0,void 0,(function*(){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}))}executeSubagentWithContinuation(e,t,r,n,o){return wE(this,void 0,void 0,(function*(){const i=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let s=yield this.runContinuationLoop(e,t,r,n,o,i);if(!o.collectBackgroundChildren||"completed"!==s.status)return s;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=yield this.collectAvailableChildCompletions(t,e.signal)}catch(e){return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return s;const l=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(s=yield this.runContinuationLoop(e,t,new Vt.Pw(Object.assign(Object.assign({},r),{prompt:l,resumeAgentId:t,runInBackground:!1})),n,o,i),"completed"!==s.status)return s}return s}))}runContinuationLoop(e,t,r,n,i,s){return wE(this,void 0,void 0,(function*(){var a,l;let c,u,d=0;for(let h=0;h<s;h++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};const s=0===h?r.prompt:this.computeContinuationNudge(i,d,c),p=0===h?new Vt.Pw(Object.assign(Object.assign({},r),{runInBackground:!1})):new Vt.Pw(Object.assign(Object.assign({},r),{prompt:s,resumeAgentId:t,runInBackground:!1}));if(u=yield this.executeSubagentOnce(e,t,p,n),"completed"!==u.status)return u;const f=null!==(a=u.toolCallCount)&&void 0!==a?a:0,m=null!==(l=u.finalMessage)&&void 0!==l?l:"";if(void 0!==c&&m.includes(c))return u;f>0?(d=0,c=void 0):(d+=1,c=d>=i.idleThreshold?`DONE_${(0,o.randomUUID)().replace(/-/g,"").slice(0,8)}`:void 0)}return null!=u?u:{status:"error",error:"Subagent continuation exited unexpectedly"}}))}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}executeSubagentOnce(e,t,r,n){return wE(this,void 0,void 0,(function*(){var o,i,s;let a,l=0;const c=new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:new Ze.RGk({text:r.prompt})})}}),u=new Ze.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(u.credentials=r.credentials);const d=new Vw,h={sendUpdate:(e,r)=>wE(this,void 0,void 0,(function*(){var e,n;"tokenDelta"===r.message.case&&(null===(e=this.onSubagentTokenDelta)||void 0===e||e.call(this,t,r.message.value.tokens)),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||null===(n=this.onInteractionUpdate)||void 0===n||n.call(this,t,r),"toolCallCompleted"===r.message.case&&l++,"textDelta"===r.message.case&&(a=(null!=a?a:"")+r.message.value.text)})),query:(e,t)=>wE(this,void 0,void 0,(function*(){return function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return On(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return jn(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return $n(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new fE.tz({result:{case:"rejected",value:new fE.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return Dn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)}))},p={handleCheckpoint:(e,t)=>wE(this,void 0,void 0,(function*(){yield n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)})),getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const s=null===(o=r.rootParentConversationId)||void 0===o?void 0:o.trim(),f=null===(i=r.parentConversationId)||void 0===i?void 0:i.trim(),m=void 0!==s&&""!==s?s:void 0!==f&&""!==f?f:t,g=yield this.getResources({agentId:t,parentAgentId:r.parentConversationId}),v=r.readonly?new V(g,function(e){const t=[[Tt,(r=e.errorMessage,{execute(e,t){return Rt(this,void 0,void 0,(function*(){return new _t.v3({result:{case:"permissionDenied",value:new _t.U7({path:t.path,error:r,isReadonly:!0})}})}))}})],[se,Nt(e.errorMessage)],[at,$t(e.errorMessage)]];var r;return e.wrapShell&&t.push([Pt,Mt(e.errorMessage)],[It,jt(e.errorMessage)],[ee,Dt(e.errorMessage)]),e.includeWriteBackgroundShellStdin&&t.push([te,Lt(e.errorMessage)]),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):g;return yield this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,u,h,v,n.agentStore.getBlobStore(),d,p,[...this.mcpTools],{conversationGroupId:m,conversationId:t,subagentTypeName:r.subagentType||void 0,headers:this.headers,endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),yield n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:SE}:{status:"success"}),{status:"completed",finalMessage:a,toolCallCount:l}}catch(r){const o=r instanceof Error?r.message:String(r);return Yw.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),yield n.transcriptWriter.writeTurnEndedFromState(e,null!==(s=n.agentStore.getLatestCheckpoint())&&void 0!==s?s:n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:SE}:{status:"error",error:o}}}))}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:SE}:{status:"error",error:t}}isAwaitBackgroundMode(e){var t;if(!Boolean(e.resumeAgentId&&!Xt(e.prompt)&&!0===e.readonly&&!0!==e.runInBackground))return!1;if(0===(null!==(t=e.parentConversationId)&&void 0!==t?t:"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}awaitBackgroundRun(e,t){return wE(this,void 0,void 0,(function*(){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}`}}))}awaitBusyLifecycleRun(e,t){return wE(this,void 0,void 0,(function*(){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);yield new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}))}awaitBackgroundEntry(e,t){return wE(this,void 0,void 0,(function*(){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}))}registerParentChildLink(e,t){var r,n,o,i;const s=null==t?void 0:t.trim();if(!s||s===e||!this.sessions.has(s))return;const a=this.childParentIds.get(e);if(a===s)return;a&&(null===(r=this.parentChildIds.get(a))||void 0===r||r.delete(e),0===(null!==(o=null===(n=this.parentChildIds.get(a))||void 0===n?void 0:n.size)&&void 0!==o?o:0)&&this.parentChildIds.delete(a)),this.childParentIds.set(e,s);const l=null!==(i=this.parentChildIds.get(s))&&void 0!==i?i:new Set;l.add(e),this.parentChildIds.set(s,l)}removeParentChildLink(e){var t;const r=this.childParentIds.get(e);if(!r)return;this.childParentIds.delete(e);const n=this.parentChildIds.get(r);null==n||n.delete(e),0===(null!==(t=null==n?void 0:n.size)&&void 0!==t?t:0)&&this.parentChildIds.delete(r)}enqueueChildCompletion(e,t){var r,n;const o=this.childParentIds.get(e);if(!o)return;const i=null!==(r=this.queuedChildCompletions.get(o))&&void 0!==r?r:[];i.push({agentId:e,success:"completed"===t.status,finalMessage:"completed"===t.status?null!==(n=t.finalMessage)&&void 0!==n?n:"":"error"===t.status?t.error:"Subagent was aborted by the user"}),this.queuedChildCompletions.set(o,i),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(o);if(s){this.childCompletionWaiters.delete(o);for(const e of s)e()}}collectAvailableChildCompletions(e,t){return wE(this,void 0,void 0,(function*(){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(yield this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}))}hasPendingChildSubagents(e){var t,r;return(null!==(r=null===(t=this.parentChildIds.get(e))||void 0===t?void 0:t.size)&&void 0!==r?r:0)>0}drainChildCompletions(e){var t;const r=null!==(t=this.queuedChildCompletions.get(e))&&void 0!==t?t:[];return this.queuedChildCompletions.delete(e),r}waitForChildCompletion(e,t){return wE(this,void 0,void 0,(function*(){if(t.aborted)throw new Error("aborted");yield new Promise(((r,n)=>{var o;const i=null!==(o=this.childCompletionWaiters.get(e))&&void 0!==o?o:new Set,s=()=>{l(),r()},a=()=>{l(),n(new Error("aborted"))},l=()=>{i.delete(s),0===i.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",a)};i.add(s),this.childCompletionWaiters.set(e,i),t.addEventListener("abort",a,{once:!0})}))}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t=e.success?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var EE=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),xE=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),CE=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),_E=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),PE=r("./src/agent/analytics.ts");function IE(e,t){var r,n,o,i,s,a,l,c,u;switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:null!==(i=null===(r=e.message.value.userMessage)||void 0===r?void 0:r.text)&&void 0!==i?i:""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":return{type:"summary-completed"};case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:null!==(s=null===(o=null===(n=e.message.value.event.value)||void 0===n?void 0:n.toJson)||void 0===o?void 0:o.call(n))&&void 0!==s?s:e.message.value.event.value}:{}};case"toolCallStarted":return TE("tool-call-started",e.message.value);case"partialToolCall":return TE("partial-tool-call",e.message.value);case"toolCallCompleted":return TE("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value,r=void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens;return Object.assign({type:"turn-ended"},r&&{usage:Object.assign({inputTokens:Number(null!==(a=t.inputTokens)&&void 0!==a?a:BigInt(0)),outputTokens:Number(null!==(l=t.outputTokens)&&void 0!==l?l:BigInt(0)),cacheReadTokens:Number(null!==(c=t.cacheReadTokens)&&void 0!==c?c:BigInt(0)),cacheWriteTokens:Number(null!==(u=t.cacheWriteTokens)&&void 0!==u?u:BigInt(0))},t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)})})}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==(null==n?void 0:n.delta.case))return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const i=IE(o,t);return null!==i&&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":return!0;default:return!1}}(i)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:i}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"promptSuggestion":case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case void 0:return null;default:return e.message,null}}function TE(e,t){const r=function(e){if(!(null==e?void 0:e.tool))return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"shell",args:Object.assign(Object.assign({command:t.command},t.workingDirectory?{workingDirectory:t.workingDirectory}:{}),t.timeout?{timeout:t.timeout}:{})},r?{result:DE(r)}:{}):null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"delete",args:{path:t.path}},r?{result:NE(r)}:{}):null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"glob",args:Object.assign({globPattern:t.globPattern},t.targetDirectory?{targetDirectory:t.targetDirectory}:{})},r?{result:$E(r)}:{}):null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"grep",args:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({pattern:t.pattern},t.path?{path:t.path}:{}),t.glob?{glob:t.glob}:{}),t.outputMode?{outputMode:t.outputMode}:{}),t.contextBefore?{contextBefore:t.contextBefore}:{}),t.contextAfter?{contextAfter:t.contextAfter}:{}),t.context?{context:t.context}:{}),t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{}),t.type?{type:t.type}:{}),t.headLimit?{headLimit:t.headLimit}:{}),void 0!==t.offset?{offset:t.offset}:{}),t.multiline?{multiline:t.multiline}:{}),t.sort?{sort:t.sort}:{}),t.sortAscending?{sortAscending:t.sortAscending}:{})},r?{result:LE(r)}:{}):null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"read",args:{path:t.path}},r?{result:UE(r)}:{}):null}case"editToolCall":{const{args:t,result:r}=e.tool.value;if(!t)return null;const n={path:t.path};return Object.assign({type:"edit",args:n},r?{result:BE(r)}:{})}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"ls",args:Object.assign({path:t.path},t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{})},r?{result:zE(r)}:{}):null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"readLints",args:{paths:t.paths}},r?{result:HE(r)}:{}):null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"mcp",args:Object.assign(Object.assign(Object.assign({},t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{}),t.toolName?{toolName:t.toolName}:{}),t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{})},r?{result:qE(r)}:{}):null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"generateImage",args:Object.assign({description:t.description},t.filePath?{filePath:t.filePath}:{})},r?{result:VE(r)}:{}):null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"recordScreen",args:{mode:JE(t.mode)}},r?{result:KE(r)}:{}):null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"semSearch",args:Object.assign(Object.assign({query:t.query},t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{}),t.explanation?{explanation:t.explanation}:{})},r?{result:GE(r)}:{}):null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"createPlan",args:{plan:t.plan}},r?{result:ZE(r)}:{}):null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:XE(e.status)})))}},r?{result:YE(r)}:{}):null}case"fetchToolCall":case"switchModeToolCall":case"computerUseToolCall":case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"task",args:RE(t)},r?{result:ME(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"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"piReadToolCall":case"piBashToolCall":case"piEditToolCall":case"piWriteToolCall":case"piGrepToolCall":case"piFindToolCall":case"piLsToolCall":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 RE(e){var t,r;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({description:null!==(t=e.description)&&void 0!==t?t:"",prompt:null!==(r=e.prompt)&&void 0!==r?r:""},e.subagentType?{subagentType:AE(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:OE(e.mode)}:{}),e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{})}function AE(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function OE(e){switch(e){case qu.FL.AGENT:return"agent";case qu.FL.PLAN:return"plan";default:return"unspecified"}}function ME(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>{var t,r;return null!==(r=null===(t=e.toJson)||void 0===t?void 0:t.call(e))&&void 0!==r?r:e}))}:{}),t.agentId?{agentId:t.agentId}:{}),{isBackground:null!==(r=t.isBackground)&&void 0!==r&&r}),void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{}),t.resultSuffix?{resultSuffix:t.resultSuffix}:{}),{backgroundReason:jE(t.backgroundReason)}),t.transcriptPath?{transcriptPath:t.transcriptPath}:{})}}case"error":return{status:"error",error:{message:null!==(n=e.result.value.error)&&void 0!==n?n:"Task failed"}};default:return}}function jE(e){switch(e){case Ze.qLf.AGENT_REQUEST:return"agentRequest";case Ze.qLf.USER_REQUEST:return"userRequest";case Ze.qLf.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function DE(e){var t,r,n,o,i,s,a,l;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:null!==(r=t.exitCode)&&void 0!==r?r:0,signal:null!==(n=t.signal)&&void 0!==n?n:"",stdout:null!==(o=t.stdout)&&void 0!==o?o:"",stderr:null!==(i=t.stderr)&&void 0!==i?i:"",executionTime:null!==(s=t.executionTime)&&void 0!==s?s:0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:null!==(a=e.result.value.reason)&&void 0!==a?a:"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:null!==(l=e.result.value.error)&&void 0!==l?l:"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function NE(e){var t,r,n,o,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(null!==(r=e.result.value.fileSize)&&void 0!==r?r:0)}}:{status:"error",error:{message:null!==(i=null!==(o=null!==(n=e.result.value.error)&&void 0!==n?n:e.result.value.reason)&&void 0!==o?o:e.result.value.clientVisibleError)&&void 0!==i?i:e.result.case,path:e.result.value.path}}}function $E(e){var t,r,n,o,i,s,a;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{files:null!==(r=e.result.value.files)&&void 0!==r?r:[],totalFiles:null!==(n=e.result.value.totalFiles)&&void 0!==n?n:0,clientTruncated:null!==(o=e.result.value.clientTruncated)&&void 0!==o&&o,ripgrepTruncated:null!==(i=e.result.value.ripgrepTruncated)&&void 0!==i&&i}}:{status:"error",error:{message:null!==(a=null!==(s=e.result.value.error)&&void 0!==s?s:e.result.value.reason)&&void 0!==a?a:e.result.case}}}function LE(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=FE(n);return{status:"success",value:Object.assign(Object.assign({},Object.keys(r).length>0?{workspaceResults:r}:{}),t.activeEditorResult?{activeEditorResult:FE(t.activeEditorResult)}:{})}}return{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}}function FE(e){var t,r,n,o,i,s,a,l,c;if(null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"content":return{type:"content",output:{matches:null!==(o=null===(r=e.result.value.matches)||void 0===r?void 0:r.map((e=>Object.assign(Object.assign(Object.assign(Object.assign({file:e.file},void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{}),{line:e.line}),e.beforeContext?{beforeContext:e.beforeContext}:{}),e.afterContext?{afterContext:e.afterContext}:{}))))&&void 0!==o?o:[],totalMatches:null!==(i=e.result.value.totalMatches)&&void 0!==i?i:0}};case"files":return{type:"files",output:{files:null!==(s=e.result.value.files)&&void 0!==s?s:[],count:null!==(a=e.result.value.count)&&void 0!==a?a:0}};case"count":return{type:"count",output:{counts:null!==(l=null===(n=e.result.value.counts)||void 0===n?void 0:n.map((e=>({file:e.file,count:e.count}))))&&void 0!==l?l:[],total:null!==(c=e.result.value.total)&&void 0!==c?c:0}};default:return}}function UE(e){var t,r,n,o,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:null!==(r=e.result.value.totalLines)&&void 0!==r?r:0,fileSize:Number(null!==(n=e.result.value.fileSize)&&void 0!==n?n:0)}}:{status:"error",error:{message:null!==(i=null!==(o=e.result.value.error)&&void 0!==o?o:e.result.value.reason)&&void 0!==i?i:e.result.case,path:e.result.value.path}}}function BE(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:Object.assign(Object.assign(Object.assign({},void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{}),void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{}),e.result.value.diffString?{diffString:e.result.value.diffString}:{})}:{status:"error",error:{message:null!==(n=null!==(r=e.result.value.error)&&void 0!==r?r:e.result.value.reason)&&void 0!==n?n:e.result.case,path:e.result.value.path}}}function zE(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:WE(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function WE(e){var t,r,n,o,i,s,a,l;if(e)return{absPath:null!==(n=e.absPath)&&void 0!==n?n:"",childrenDirs:null!==(o=null===(t=e.childrenDirs)||void 0===t?void 0:t.map(WE))&&void 0!==o?o:[],childrenFiles:null!==(i=null===(r=e.childrenFiles)||void 0===r?void 0:r.map((e=>({name:e.name}))))&&void 0!==i?i:[],childrenWereProcessed:null!==(s=e.childrenWereProcessed)&&void 0!==s&&s,fullSubtreeExtensionCounts:null!==(a=e.fullSubtreeExtensionCounts)&&void 0!==a?a:{},numFiles:null!==(l=e.numFiles)&&void 0!==l?l:0}}function HE(e){var t,r,n,o,i,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:null!==(n=null===(r=e.result.value.fileDiagnostics)||void 0===r?void 0:r.map((e=>{var t,r,n;return{path:e.path,diagnostics:null!==(r=null===(t=e.diagnostics)||void 0===t?void 0:t.map((e=>Object.assign(Object.assign({severity:QE(e.severity)},e.range?{range:Object.assign(Object.assign({},e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{}),e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{})}:{}),{message:e.message,source:e.source,code:e.code}))))&&void 0!==r?r:[],diagnosticsCount:null!==(n=e.diagnosticsCount)&&void 0!==n?n:0}})))&&void 0!==n?n:[],totalFiles:null!==(o=e.result.value.totalFiles)&&void 0!==o?o:0,totalDiagnostics:null!==(i=e.result.value.totalDiagnostics)&&void 0!==i?i:0}}:{status:"error",error:{message:null!==(s=e.result.value.error)&&void 0!==s?s:e.result.case}}}function qE(e){var t,r,n,o,i,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{content:null!==(n=null===(r=e.result.value.content)||void 0===r?void 0:r.map((e=>{var t,r;const n={};return"text"===(null===(t=e.content)||void 0===t?void 0:t.case)?n.text={text:e.content.value.text}:"image"===(null===(r=e.content)||void 0===r?void 0:r.case)&&(n.image=Object.assign({data:e.content.value.data},e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{})),n})))&&void 0!==n?n:[],isError:null!==(o=e.result.value.isError)&&void 0!==o&&o}}:{status:"error",error:{message:null!==(s=null!==(i=e.result.value.error)&&void 0!==i?i:e.result.value.reason)&&void 0!==s?s:e.result.case}}}function GE(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{results:null!==(r=e.result.value.results)&&void 0!==r?r:""}}:{status:"error",error:{message:null!==(n=e.result.value.error)&&void 0!==n?n:e.result.case}}}function VE(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{filePath:null!==(r=e.result.value.filePath)&&void 0!==r?r:""}}:{status:"error",error:{message:null!==(n=e.result.value.error)&&void 0!==n?n:e.result.case}}}function JE(e){switch(e){case Dg.$u.START_RECORDING:return"START_RECORDING";case Dg.$u.SAVE_RECORDING:return"SAVE_RECORDING";case Dg.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function KE(e){var t,r,n,o,i;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:null!==(r=e.result.value.wasPriorRecordingCancelled)&&void 0!==r&&r}};case"saveSuccess":return{status:"success",value:{path:null!==(n=e.result.value.path)&&void 0!==n?n:"",recordingDurationMs:Number(null!==(o=e.result.value.recordingDurationMs)&&void 0!==o?o:0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:null!==(i=e.result.value.error)&&void 0!==i?i:"Unknown error"}};default:return}}function ZE(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function YE(e){var t,r,n,o,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{todos:null!==(n=null===(r=e.result.value.todos)||void 0===r?void 0:r.map((e=>({content:e.content,status:XE(e.status)}))))&&void 0!==n?n:[],totalCount:null!==(o=e.result.value.totalCount)&&void 0!==o?o:0}}:{status:"error",error:{message:null!==(i=e.result.value.error)&&void 0!==i?i:e.result.case}}}function XE(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function QE(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}const ex={type:"object",properties:{},additionalProperties:!0};function tx(e){return{execute(t,r,n){return o=this,i=void 0,a=function*(){const t=r.toolName||function(e){const t=`${rt}-`;return e.startsWith(t)?e.slice(t.length):e}(r.name),n=e[t];if(void 0===n)return new xt.iz({result:{case:"error",value:new xt.Nh({error:`Unknown custom tool: ${t}`})}});try{return function(e){var t;const r=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:nx(e)?e:void 0};var t}(e),n=void 0!==r.structuredContent?ar.Struct.fromJson(r.structuredContent):void 0;return new xt.iz({result:{case:"success",value:new xt.QW({content:r.content.map(rx),isError:null!==(t=r.isError)&&void 0!==t&&t,structuredContent:n})}})}(yield 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 xt.iz({result:{case:"error",value:new xt.Nh({error:e instanceof Error?e.message:String(e)})}})}},new((s=void 0)||(s=Promise))((function(e,t){function r(e){try{l(a.next(e))}catch(e){t(e)}}function n(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s((function(e){e(o)}))).then(r,n)}l((a=a.apply(o,i||[])).next())}));var o,i,s,a}}}function rx(e){var t;return"text"===e.type?new xt._Z({content:{case:"text",value:new xt.zN({text:e.text})}}):new xt._Z({content:{case:"image",value:new xt.do({data:n.Buffer.from(e.data,"base64"),mimeType:null!==(t=e.mimeType)&&void 0!==t?t:""})}})}function nx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var ox=r("./src/agent/errors.ts"),ix=r("./src/agent/executor-common.ts"),sx=r("./src/agent/sdk-config.ts"),ax=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lx=r("./src/agent/utils/logger.ts"),cx=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const ux={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dx=new Map;var hx=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function px(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof Wv))throw new ox.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(at),i=tx(t);e.resources.base.register(at,{execute(e,t,r){return hx(this,void 0,void 0,(function*(){if(function(e){return e.providerIdentifier===rt}(t)){const o=yield df(e,t,Object.assign(Object.assign({},n),{toolDef:{source:"internal"}}));return void 0!==o?o:i.execute(e,t,r)}return o.execute(e,t,r)}))}})}const fx={warn(){},error(){}},mx={log(){}};class gx{requestApproval(e){return hx(this,void 0,void 0,(function*(){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${vx(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 vx(e){switch(e.type){case Ad.Shell:return"this shell command";case Ad.Mcp:return"this MCP tool call";case Ad.Write:return"this file edit";case Ad.Delete:return"this file deletion";default:return"this operation"}}function yx(e){try{const t=(0,i.statSync)(e);return t.isFile()&&("win32"===process.platform||!!(73&t.mode))}catch(e){return!1}}function wx(e){const t=`${process.platform}-${process.arch}`,r=[`@cursor/sdk-${t}`,`@cursor/february-${t}`];if(!process.argv[1])return;let n=(0,a.dirname)((0,a.resolve)(process.argv[1]));const o=(0,a.parse)(n).root;for(;n!==o;){for(const t of r){const r=(0,a.join)(n,"node_modules",t,"bin",e);if(yx(r))return r}n=(0,a.dirname)(n)}}function bx(e){return void 0!==e&&"insecure_none"!==e.type}function Sx(e,t){return hx(this,void 0,void 0,(function*(){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,Qe.q6)().with(h._O,mx);Qk(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}`);Jc=e}((0,sx.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(ix.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const l=performance.now();let u=0,d=0;if(r.apiKey){const e=performance.now();yield Promise.all([(0,ix.ly)(r.apiKey),(0,ix.mU)(r.apiKey)]),u=performance.now()-e}const p=r.workingDirectory||process.cwd(),f=(0,hv.Rv)((0,s.homedir)(),p);let m;const g="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;m=v&&(0,a.isAbsolute)(v)?v:wx(g),m||(m=(0,io.resolveRipgrepFromPath)()),m&&(0,io.configureRipgrepPath)(m);let y,w=cb();if(r.apiKey)try{y=(0,ix.KU)(r.apiKey);const e=(0,lr.createClient)(Ek.I,y),t=performance.now(),n=yield function(e){let t=dx.get(e);return t||(t=function(e){return cx(this,void 0,void 0,(function*(){try{const t=yield function(e){return cx(this,void 0,void 0,(function*(){const t=yield(0,ix.dC)(e,ix.EV);if(!t)return;const r=ix.EV.endsWith("/")?ix.EV.slice(0,-1):ix.EV,n=yield fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,ix.tF)(),"x-ghost-mode":(0,ix.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lx.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=yield n.json();return"string"==typeof o.config&&o.config.length>0?o.config:void 0}))}(e);if(!t)return ux;const r=new ax.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const t=JSON.parse(e);if(t.user)return Object.assign(Object.assign({},t.user),{custom:Object.assign(Object.assign({},t.user.custom),{clientType:"sdk",clientVersion:(0,ix.tF)()})})}catch(e){lx.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,ix.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch(e){return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch(e){return n}}}}catch(e){return lx.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),ux}}))}(e),dx.set(e,t),t.then((r=>{r===ux&&dx.get(e)===t&&dx.delete(e)}),(()=>{dx.get(e)===t&&dx.delete(e)}))),t}(r.apiKey);d=performance.now()-t;const o={getDefaultNetworkAllowlist:()=>hx(this,void 0,void 0,(function*(){return n.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})}))};w=new mw(new fw(e),o,{isMcpAccessNetworkAllowlistEnabled:()=>n.checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:e=>n.checkFeatureGate("mcp_settings_overhaul",e)})}catch(e){lx.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const b=performance.now(),S=r.apiKey?yield(0,io.loadSandboxPolicyFromFileOrUndefined)(`${(0,s.homedir)()}/.cursor/sandbox.json`,(0,s.homedir)()):void 0,k=void 0!==r.apiKey?yield function(e){return hx(this,void 0,void 0,(function*(){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===(null==n?void 0:n.enabled))return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=bx(r)?r:!0===(null==n?void 0:n.enabled)?function(e,t={}){return Object.assign({type:e},t)}("workspace_readwrite",{networkPolicy:(0,io.networkDisabledPolicy)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(){const e=wx("win32"===process.platform?"cursorsandbox.exe":"cursorsandbox");e&&(0,io.configureSandboxPrereqs)({sandboxBinaryPath:e})}(),!(0,io.isSandboxSupported)(void 0,{ctx:e.initializationCtx}))throw new ox.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 i={};i.perUser=o;const{policy:s}=yield(0,io.resolveSandboxPolicyForWorkspace)(t,i);return{defaultSandboxPolicy:s,defaultSandboxPolicySources:i}}))}({cwd:p,perUserSandboxPolicy:S,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,E=performance.now()-b,x=null==k?void 0:k.defaultSandboxPolicy,C=null==k?void 0:k.defaultSandboxPolicySources,_=bx(x),P=performance.now(),I=yield function(e){return sE(this,void 0,void 0,(function*(){var t,r,n,o,i,s,a,l,c;const{workingDirectory:u,projectDir:d}=e,h=Qk(e.settingSources),p=null!==(r=e.teamSettingsService)&&void 0!==r?r:cb(),f=null!==(n=e.defaultSandboxPolicy)&&void 0!==n?n:{type:"insecure_none"},m=null!==(o=e.getSandboxSupported)&&void 0!==o?o:()=>(0,io.isSandboxSupported)(f,{ctx:e.initializationCtx}),g=null!==(i=e.getSandboxEnabled)&&void 0!==i?i:()=>"insecure_none"!==f.type&&m(),v=new Bd,y=new su(v,p,[u]),w=new cE,b=new uE,S=null===(t=e.getSmartModeClassifierAutoModeEnabled)||void 0===t?void 0:t.call(e),k=new lE(S?"allowlist":null!==(s=e.approvalMode)&&void 0!==s?s:"unrestricted",f,p,null!==(a=e.respectAdminControls)&&void 0!==a&&a),E=e.pendingDecisionProvider,x={executeIndexedGrep:void 0},C=()=>!0,_=eE(h,"plugins"),P=null!==(l=e.importThirdPartyPlugins)&&void 0!==l&&l,I=null===(c=e.mcpMetaToolEnabled)||void 0===c||c,T=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,R=void 0!==e.customSubagents&&e.customSubagents.length>0,A=T||eE(h,"project")||eE(h,"user")||_,O=eE(h,"project")||eE(h,"user")||eE(h,"mdm"),M=eE(h,"team"),j=M&&void 0!==e.dashboardTransport,D=eE(h,"project")||eE(h,"user")||M||j||_,N=t=>iE({workingDirectory:u,adapters:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.includeMcp?{mcp:ub({teamSettingsService:p,initializationCtx:e.initializationCtx,importThirdPartyPlugins:P,ignoreApprovals:!0,includeProjectMcp:eE(h,"project"),includeUserMcp:eE(h,"user"),includePluginMcp:_,inlineMcpServers:e.mcpServers})}:{}),_?{pluginBootstrap:Dk({importThirdPartyPlugins:P,dashboardTransport:e.dashboardTransport})}:{}),O?{hooks:kk({includeProjectHooks:eE(h,"project"),includeUserHooks:eE(h,"user"),includeEnterpriseHooks:eE(h,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{}),D?{localExtensibility:_k({includeProjectExtensibility:eE(h,"project"),includeUserExtensibility:eE(h,"user"),includeManagedSkills:j,includeTeamExtensibility:M,includePluginExtensibility:_,teamSettingsService:p,getThirdPartyExtensibilityEnabled:C,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:P})}:{}),{resourceFactory:Uk({ignoreService:y,grepProvider:x,workspacePaths:[u],diagnosticsProvider:w,repositoryProvider:b,projectDir:null!=d?d:u,shellManager:void 0,defaultSandboxPolicy:f,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:g,getSandboxSupported:m,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:I,createMcpStateAccessor:e=>new dE(new rv(e)),createSessionMcpLease:(t,r)=>ub({teamSettingsService:p,initializationCtx:e.initializationCtx,importThirdPartyPlugins:!1,ignoreApprovals:!0,includeProjectMcp:!1,includeUserMcp:!1,includePluginMcp:!1,inlineMcpServers:r}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{var t;const r=null!=E?E:new aE;return{pendingDecisionStore:r,fileChangeTracker:new Fd(u),permissionsService:new uw(y,r,k,p,u,null!==(t=e.respectAdminControls)&&void 0!==t&&t)}}}),resourceWrappers:O?[{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 n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new Sk(new dk(e.resources,n.hookExecutor,(()=>function(e,t){var r,n,o,i;const s=null!==(n=null!==(r=vk(t,yk,"conversationId","conversation_id"))&&void 0!==r?r:e.sessionId)&&void 0!==n?n:"",a=null!==(o=vk(t,yk,"generationId","generation_id"))&&void 0!==o?o:s,l=null!==(i=vk(t,yk,"model"))&&void 0!==i?i:"unknown",c=vk(t,yk,"modelId","model_id"),u=vk(t,bk,"modelParams","model_params");return Object.assign({conversation_id:s,generation_id:a,model:l},Ie({modelId:c,modelParams:u}))}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[]}),R?{workspaceServicesContributors:[{contributeServices:t=>{var r;const n=new hE(null!==(r=e.customSubagents)&&void 0!==r?r:[]),o=t.services.subagentsService;return{subagentsService:void 0===o?n:new td([n,o])}}}]}:{})});if(!A)return N({includeMcp:!1});try{return yield N({includeMcp:!0})}catch(e){return Yw.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:u,projectDir:d,enablePlugins:_,importThirdPartyPlugins:P}),N({includeMcp:!1})}}))}({workingDirectory:p,projectDir:f,teamSettingsService:w,initializationCtx:i,dashboardTransport:y,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:x,defaultSandboxPolicySources:C,approvalMode:_?"allowlist":void 0,pendingDecisionProvider:_||!0===r.autoReview?new gx:void 0,getNetworkAllowlistInfo:_?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),i=[...o.allowlist],s=`${t}/.cursor/sandbox.json`,a=await(0,io.loadSandboxPolicyFromFileOrUndefined)(s,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&i.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,io.loadSandboxPolicyFromFileOrUndefined)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&i.push(...t.networkPolicy.allow)}const l=[...new Set(i)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:l}}(w,(0,s.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),T=performance.now()-P;let R,A;return(0,PE.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(u),bootstrap_statsig_ms:Math.round(d),create_workspace_runtime_ms:Math.round(T),load_sandbox_policy_ms:Math.round(E),total_ms:Math.round(performance.now()-l)}),{run:(e,t,i)=>hx(this,void 0,void 0,(function*(){return function(e,t){return Kw.run(e,t)}(fx,(()=>hx(this,void 0,void 0,(function*(){var s,a,l,u;const d=(0,c.VI)((0,Qe.q6)().withName("sdk.run").with(h._O,mx)),[f,m]=d.ctx.withCancel(),g=null!==(s=t.sessionId)&&void 0!==s?s:(0,o.randomUUID)(),v=t.mcpServersOverride,y=void 0===(w=t.customTools)?[]:Object.entries(w).map((([e,t])=>{var r,n;return{clientKey:rt,providerIdentifier:rt,toolName:e,name:`${rt}-${e}`,description:null!==(r=t.description)&&void 0!==r?r:"",inputSchema:null!==(n=t.inputSchema)&&void 0!==n?n:ex,source:"internal"}}));var w;let b;b=yield I.createSessionRuntime({sessionId:g,mcpServersOverride:v,extraMcpTools:y});const S=new Map;try{const s=b.resources.wrapped;px(b,t.customTools);const c=null!==(a=t.blobStore)&&void 0!==a?a:new nr.ve;let d=null!==(l=t.initialState)&&void 0!==l?l:new Ze.Y9z({});const h=void 0!==t.model?new Ze.G4_({modelId:t.model.id,parameters:(null!==(u=t.model.params)&&void 0!==u?u:[]).map((e=>new Ze.SRo({id:e.id,value:e.value})))}):void 0,w=Array.isArray(e.images)?e.images.map((e=>{const t=(0,o.randomUUID)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),i=(0,ix.v8)(r);return new CE.d(Object.assign(Object.assign({uuid:t},i?{mimeType:i}:{}),{dataOrBlobId:{case:"data",value:r}}))})):[],k=w.length>0?new CE.xv({selectedImages:w}):void 0,E=function(e){switch(e){case"agent":return Ze.xyI.AGENT;case"plan":return Ze.xyI.PLAN;default:return}}(t.mode),x=new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:new Ze.RGk(Object.assign({text:e.text,selectedContext:k},void 0!==E?{mode:E}:{}))})}}),C={sendUpdate:(e,t)=>hx(this,void 0,void 0,(function*(){const e=IE(t,g);null!==e&&(yield i.sendUpdate(e))})),query:(e,t)=>hx(this,void 0,void 0,(function*(){return function(e){var t;switch(e.query.case){case"webSearchRequestQuery":return An(e.id);case"webFetchRequestQuery":return Mn(e.id);case"switchModeRequestQuery":return Nn(e.id);case"askQuestionInteractionQuery":return Dn(e.id,new fE.tz({result:{case:"rejected",value:new fE.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return Ln(e.id,new Cn.bK({result:{case:"success",value:new Cn.Jo},planUri:""}));case"setupVmEnvironmentArgs":return Fn(e.id,new _E.r$({result:{case:"success",value:new _E.JH}}));case"replaceEnvArgs":return Un(e.id,new xE.dV({result:{case:"failure",value:new xE.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return Bn(e.id,new qn.HL({result:{case:"error",value:new qn.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return zn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Wn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Hn(e.id,null===(t=e.query.value.args)||void 0===t?void 0:t.description);case void 0:throw new ox.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new ox.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)}))};if(R!==t.apiKey||!A){yield Promise.all([(0,ix.ly)(t.apiKey),(0,ix.mU)(t.apiKey)]);const e=(0,ix.KU)(t.apiKey),r=Qn((0,lr.createClient)(EE.N,e),{injectTraceHeaders:!0});A=new En(r),R=t.apiKey}const _=(0,ix.Vh)(A,(()=>{const e=(0,ix.KU)(t.apiKey),r=Qn((0,lr.createClient)(EE.N,e),{injectTraceHeaders:!0}),n=new En(r);return A=n,R=t.apiKey,n})),P=new kE({agentClient:_,getResources:e=>hx(this,[e],void 0,(function*({agentId:e}){let r=S.get(e);return r||(r=yield I.createSessionRuntime({sessionId:e,mcpServersOverride:v,extraMcpTools:y}),px(r,t.customTools),r.resources.base.register(Zt,T),S.set(e,r)),r.resources.wrapped})),mcpTools:y,workspacePath:p,parentConversationId:g,onSessionReleased:e=>{const t=S.get(e);t&&(t.dispose(),S.delete(e))}}),T=Kt(P);b.resources.base.register(Zt,T);const O=I.services.hooksRuntime,M=O?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(de.sessionStart)||t.hooksConfigLease.hasHookForStep(de.sessionEnd)||t.hooksConfigLease.hasHookForStep(de.stop)||t.hooksConfigLease.hasHookForStep(de.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{onSessionStart(e){return pE(this,void 0,void 0,(function*(){if(o=e,n.hasHooksForStep(de.sessionStart))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Ie(e)),{is_background_agent:!1}),r=yield n.executeHookForStep(de.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){Yw.warn("[hooks-adapter] sessionStart hook failed:",e)}}))},onSessionEnd(e,t){return pE(this,void 0,void 0,(function*(){var r,i,s;if(n.hasHooksForStep(de.sessionEnd))try{const a=Object.assign(Object.assign({conversation_id:null!==(r=null==o?void 0:o.conversationId)&&void 0!==r?r:"",generation_id:null!==(i=null==o?void 0:o.generationId)&&void 0!==i?i:"",model:null!==(s=null==o?void 0:o.model)&&void 0!==s?s:"unknown"},o?Ie(o):{}),{reason:e,duration_ms:t,is_background_agent:!1,final_status:e});yield n.executeHookForStep(de.sessionEnd,a)}catch(e){Yw.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()}))},onBeforeSubmitPrompt(e){return pE(this,void 0,void 0,(function*(){var t;if(n.hasHooksForStep(de.beforeSubmitPrompt))try{const r=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Ie(e)),{prompt:null!==(t=e.promptText)&&void 0!==t?t:"",attachments:[]});yield n.executeHookForStep(de.beforeSubmitPrompt,r)}catch(e){Yw.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}}))},onTurnCompleted(e){return pE(this,void 0,void 0,(function*(){if(!n.hasHooksForStep(de.stop))return;const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Ie(e)),{status:"completed",loop_count:e.loopCount}),r=yield n.executeHookForStep(de.stop,t),o="string"==typeof(null==r?void 0:r.followup_message)?r.followup_message.trim():"";return o.length>0?o:void 0}))},onTurnError(e){return pE(this,void 0,void 0,(function*(){if(n.hasHooksForStep(de.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Ie(e)),{status:"error",loop_count:e.loopCount});yield n.executeHookForStep(de.stop,t)}catch(e){Yw.warn("[hooks-adapter] onTurnError stop hook failed:",e)}}))},onTurnAborted(e){return pE(this,void 0,void 0,(function*(){if(n.hasHooksForStep(de.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Ie(e)),{status:"aborted",loop_count:e.loopCount});yield n.executeHookForStep(de.stop,t)}catch(e){Yw.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}}))},dispose(){return pE(this,void 0,void 0,(function*(){yield r.dispose()}))}}}({workspaceRuntime:O,sessionState:b.state,metadata:b.metadata}):void 0,j=new yE({workspacePath:p,conversationId:g,blobStore:c}),D=function(e,t,r){const{hooks:n}=r,[o,i]=e.withCancel(),s=new Vw;let a=r.initialState;const l={handleCheckpoint(e,t){return Xw(this,void 0,void 0,(function*(){var e;a=t,yield null===(e=r.onCheckpoint)||void 0===e?void 0:e.call(r,t)}))},getLatestCheckpoint:()=>a};let c="completed";const u=Date.now(),d=(()=>Xw(this,void 0,void 0,(function*(){var e,i,u,d,h,p,f,m,g;const v=eb(r,0,Qw(t));try{const t=yield null===(e=null==n?void 0:n.onSessionStart)||void 0===e?void 0:e.call(n,v);if(null==t?void 0:t.blocked)throw c="error",new Error(null!==(f=t.blockedReason)&&void 0!==f?f:"Session blocked by sessionStart hook")}catch(e){if("completed"!==c)throw e;Yw.warn("[agent-session-runner] sessionStart hook failed:",e)}let y=t,w=0;for(;y;){const e=eb(r,w,Qw(y));try{yield null===(i=null==n?void 0:n.onBeforeSubmitPrompt)||void 0===i?void 0:i.call(n,e)}catch(e){Yw.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}try{yield r.agentClient.run(o,a,y,void 0,r.interactionListener,r.resources,r.blobStore,s,l,null!==(m=r.mcpTools)&&void 0!==m?m:[],Object.assign(Object.assign({conversationId:r.conversationId},r.runOptions),{subagentModelOverrides:null!==(g=null===(u=r.runOptions)||void 0===u?void 0:u.subagentModelOverrides)&&void 0!==g?g:[]}))}catch(t){throw c=tb(t)?"aborted":"error",null==(b="aborted"===c?null===(d=null==n?void 0:n.onTurnAborted)||void 0===d?void 0:d.call(n,e):null===(h=null==n?void 0:n.onTurnError)||void 0===h?void 0:h.call(n,e))||b.catch((e=>{Yw.warn("[agent-session-runner] fire-and-forget hook failed:",e)})),t}let t;try{t=yield null===(p=null==n?void 0:n.onTurnCompleted)||void 0===p?void 0:p.call(n,e)}catch(e){throw c="error",e}const f="string"==typeof t?t.trim():"";0!==f.length?(w+=1,s.resetStream(),S=f,y=new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:new Ze.RGk({text:S})})}})):y=void 0}var b,S})))().finally((()=>Xw(this,void 0,void 0,(function*(){var e,t;const r=Date.now()-u;try{yield null===(e=null==n?void 0:n.onSessionEnd)||void 0===e?void 0:e.call(n,c,r)}catch(e){Yw.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{yield null===(t=null==n?void 0:n.dispose)||void 0===t?void 0:t.call(n)}catch(e){Yw.warn("[agent-session-runner] hooks dispose failed:",e)}}))));return{done:d,abort(){i()}}}(f,x,{agentClient:_,interactionListener:C,resources:s,blobStore:c,initialState:d,conversationId:g,mcpTools:y,runOptions:{generationUUID:t.requestId,requestedModel:h,enableAgentRetries:!1!==r.enableAgentRetries},hooks:M,onCheckpoint(e){return hx(this,void 0,void 0,(function*(){var r;d=e,j.writeFromState(f,e),yield null===(r=t.onCheckpoint)||void 0===r?void 0:r.call(t,e)}))}}),N=D.done.finally((()=>hx(this,void 0,void 0,(function*(){try{yield P.awaitBackgroundWorkers()}finally{yield j.waitForPendingWrites().catch((()=>{}));for(const e of S.values())try{yield e.dispose()}catch(e){lx.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}S.clear(),yield b.dispose()}})))).catch((e=>{throw e}));return{abort(){D.abort(),m()},done:N}}catch(e){for(const e of S.values())try{yield e.dispose()}catch(e){}throw S.clear(),yield b.dispose(),e}}))))})),reload(){return hx(this,void 0,void 0,(function*(){yield I.reload()}))},dispose(){return hx(this,void 0,void 0,(function*(){yield I.dispose()}))}}}))}},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){r.r(t),r.d(t,{buildMcpSandboxPolicy:()=>n.Ico});var n=r("../mcp-core/dist/index.js")},"../mcp-core/dist/index.js"(e,t,r){r.d(t,{B1j:()=>J,c8u:()=>$e,E_S:()=>Le,Ico:()=>Me,O3I:()=>re,tBH:()=>Q,MEY:()=>$,Fmf:()=>Ne,jIB:()=>Te,VDJ:()=>pe,X5z:()=>de,$HQ:()=>B,YaX:()=>H,PKk:()=>Fe,FC3:()=>G,_NE:()=>U,q2e:()=>Y});const n=BigInt(0),o=BigInt(8),i=BigInt(16),s=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<o|BigInt(t)}return{version:4,value:r}}function l(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=a(n);if(!o)return;t.push(Number(o.value>>i&s)),t.push(Number(o.value&s))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function c(e){var t;return null!==(t=a(e))&&void 0!==t?t:function(e){const t=j(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=l(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<i|BigInt(t)),n)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),s=t.slice(r+2),a=l(o),c=l(s);if(!a||!c)return;const u=a.length+c.length;return u>7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...c].reduce(((e,t)=>e<<i|BigInt(t)),n)}}(e)}function u(e,t){const r=j(e),n=j(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=c(t.slice(0,r)),o=c(e);if(!n||!o||n.version!==o.version)return!1;const i=Number(t.slice(r+1)),s=4===n.version?32:128;if(!Number.isInteger(i)||i<0||i>s)return!1;const a=BigInt(s-i);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}const d="Blocked by MCP Network Admin Server Controls";function h(e){return/\s/.test(e)}const p="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",f=new RegExp(`^(?:${p}\\.)*${p}$`),m=new RegExp(`^\\*\\.(?:${p}\\.)*${p}$`),g="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${g}(?:\\.${g}){3}$`),y=/^[0-9a-f:]+$/,w=new RegExp(`^(?:${g}(?:\\.${g}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function b(e){const t=j(e);return t.length>0&&t.length<=253&&f.test(t)}function S(e){const t=j(e);return v.test(t)||function(e){const t=j(e);if(!y.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch(e){return!1}}(t)}function k(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return k(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return k(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(b(t)||S(t))}(t.hostname)}catch(e){return!1}}(e);const t=j(e);return"*"===t||!!m.test(t)||(t.includes("/")?function(e){const t=j(e);if(!w.test(t))return!1;const[r]=t.split("/");return void 0!==r&&u(r,t)}(t):b(t)||S(t))}function C(e){if(P.has(e))return P.get(e);P.size>=_&&P.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 x(e)?e:void 0}if(h(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch(e){return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),i=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===i.length||!x(i)||i!==o&&"*"===i?void 0:i}(e);return P.set(e,t),t}const _=2048,P=new Map,I=new Map;function T(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function R(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function A(e,t){return function(e,t,r){const n=O(t);if(!n)return!1;let o;try{o=new URL(e)}catch(e){return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(i=o.hostname,s=n.hostname,!i.includes("*")&&j(i)===j(s)&&(T(a=o.pathname,l=n.pathname)||T(R(a),R(l)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:T(e,t)}(o.search,n.search,r));var i,s,a,l}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function O(e){const t=e.trim();if(0===t.length||h(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=D(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("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(j(r.hostname)!==j(o))return}return r}}function M(e,t){if(T(e,t))return!0;let r;return I.has(t)?r=I.get(t):(I.size>=_&&I.clear(),r=D(t),I.set(t,r)),!!r&&u(r.hostname,e)}function j(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function D(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch(e){return}}function N(e){return(null!=(t=e.mcpNetworkAllowlist)?t:[]).flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));var t}function $(e,t){var r,n;if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!O(e))return{allowed:!1,message:null!==(r=t.blockMessage)&&void 0!==r?r:d};const o=N(t);return o.length>0&&o.some((t=>function(e,t){const r=O(t);if(!r)return!1;if(!e.includes("://"))return u(j(r.hostname),e);if(A(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch(e){return}}(e);return void 0!==n&&A(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:null!==(n=t.blockMessage)&&void 0!==n?n:d}}function L(e){const t=null==e?void 0:e.trim();return t&&t.length>0?t:void 0}function F(e,t,r){return void 0!==(null==r?void 0:r.command)&&void 0===r.url&&void 0===t&&!0===(null==e?void 0:e.allowUserOverrideMcpServers)}function U({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:i=!0}){const s=null==e?void 0:e.allowedMcpServers,a=function(e){var t;if(!0!==(null==e?void 0:e.allowUserOverrideMcpServers))return;const r=(null!==(t=e.deniedMcpServers)&&void 0!==t?t:[]).flatMap((e=>{const t=L(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(void 0!==r&&r.includes("*")){const e=C(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=C(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const i=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===i||i.includes("@"))return;const s=C(i.replace(/:\d+$/,""));if(void 0!==s)return s;try{return C(new URL(e).hostname)}catch(e){return}}(t);return void 0===r?[]:[r]}));return r.length>0?r:void 0}(e),l=void 0===t?void 0:function(e,t){return null==e?void 0:e.find((e=>function(e,t){const r=L(e.command),n=L(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&T(r,t.command),i=void 0===n||void 0!==t.url&&M(n,t.url);return o&&i}(e,t)))}(s,t),c=F(e,l,t),u=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){var n,o;return void 0===r?(null!==(o=null===(n=null==e?void 0:e.allowedMcpServers)||void 0===n?void 0:n.length)&&void 0!==o?o:0)>0:void 0!==t||F(e,t,r)}({allowedMcpConfiguration:e,matchedServer:l,server:t})||void 0===t&&void 0!==a,d=void 0===t?i?null==s?void 0:s.flatMap((e=>{var t;return null!==(t=e.networkAllowlist)&&void 0!==t?t:[]})):void 0:c?[]:function(e,t,r){var n;return void 0===e?r:[...null!==(n=e.networkAllowlist)&&void 0!==n?n:[],...void 0!==L(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(l,t,o),h=void 0===t?void 0:c?"allow_all":function(e,t){var r,n;if(void 0!==L(null==e?void 0:e.command)&&void 0!==t.command&&void 0===t.url)return null!==(r="allow_all"===(n=null==e?void 0:e.networkMode)||"allowlist"===n||"deny_all"===n||"no_sandbox"===n?n:void 0)&&void 0!==r?r:"no_sandbox"}(l,t),p=void 0===t||c?a:void 0;return Object.assign(Object.assign(Object.assign(Object.assign({enabled:u,mcpNetworkAllowlist:d},void 0!==h?{mcpNetworkMode:h}:{}),void 0!==p?{mcpNetworkDenylist:p}:{}),void 0!==r?{localAgentNetworkAllowlist:r}:{}),void 0!==n?{blockMessage:n}:{})}function B(e){if(!0===(null==e?void 0:e.enabled)&&"no_sandbox"!==e.mcpNetworkMode)return e}function z(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function W(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function H(e,t,r){var n;if(void 0===t)return!0;if(!0===t.disableAll)return!1;const o=null!==(n=t.allowedMcpServers)&&void 0!==n?n:[];return 0===o.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){var n;const o=null!==(n=null==r?void 0:r.matchesServerUrlPattern)&&void 0!==n?n:M;return t.some((t=>{const r=z(t.command),n=W(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&T(r,e.command),s=void 0===n||void 0!==e.url&&o(n,e.url);return i&&s}))}(e,t,r)}(e,o,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){var n;const o=null!==(n=null==r?void 0:r.matchesServerUrlPattern)&&void 0!==n?n:M;return(null!=t?t:[]).some((t=>{const r=z(t.command),n=W(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&T(r,e.command),s=void 0===n||void 0!==e.url&&o(n,e.url);return i&&s}))}(e,t.deniedMcpServers,r)}function q(e){return(null!=e?e:[]).flatMap((e=>{var t,r;const n=null===(t=e.name)||void 0===t?void 0:t.trim();if(void 0===n||0===n.length)return[];const o=(null!==(r=e.toolAllowlist)&&void 0!==r?r:[]).map((e=>e.trim())).filter((e=>e.length>0));return 0===o.length?[`${n}:*`]:o.map((e=>`${n}:${e}`))}))}function G({autoRunControls:e,allowedMcpServers:t,isMcpSettingsOverhaulEnabled:r}){var n;const o=!0===(null==e?void 0:e.enabled)&&null!==(n=e.mcpToolAllowlist)&&void 0!==n?n:[];return i=r?[...q(t),...o]:[...o],[...new Set(i)];var i}var V=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class J{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}get(e){return V(this,void 0,void 0,(function*(){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=(()=>V(this,void 0,void 0,(function*(){try{const r=yield e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch(e){}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})))(),this.refreshInFlight=r}return t}const r=yield e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}))}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}function K(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function Z(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch(e){return{host:null,origin:null,pathname:null}}}(e),n=!1!==(null==t?void 0:t.includePath);return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function Y(e,t){return Z(e,t)}var X=r("crypto");function Q(e,t){const r=null==e?void 0:e.access_token,n="string"==typeof r?r.length:0,o=Boolean(null==e?void 0:e.refresh_token),i="number"==typeof(null==e?void 0:e.expires_in)&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:(null==t?void 0:t.expiresInIsFresh)&&null!==i?Date.now()+Math.round(1e3*i):null,grantedScope:"string"==typeof(null==e?void 0:e.scope)&&e.scope.length>0?e.scope:null}}function ee(e){if(e)return(0,X.createHash)("sha256").update(e).digest("hex").slice(0,12)}function te(e){if(e&&0!==e.length)return ee(JSON.stringify([...e].sort()))}function re(e){var t,r;return{clientIdHash:ee(null==e?void 0:e.client_id),clientSecretHash:ee(null==e?void 0:e.client_secret),redirectUrisHash:te(null==e?void 0:e.redirect_uris),redirectUriCount:null!==(r=null===(t=null==e?void 0:e.redirect_uris)||void 0===t?void 0:t.length)&&void 0!==r?r:0}}function ne(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 oe(e,t){for(const r of t)if("string"==typeof ne(e,r.split(".")))return ne(e,r.split("."))}const ie="[REDACTED]",se=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function ae(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${ie}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${ie}`)}function le(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function ce(e,t){return le(ae(e),null==t?void 0:t.maxLength)}function ue(e){if("string"==typeof e)return le(ae(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")||se.test(t)}(e)?ie:"string"==typeof t?ae(t):t));if(!t)return;return le(t)}catch(e){return}}function de(e){var t,r,n,o,i;const s=e instanceof Error?e.name:null!=e?typeof e:void 0,a=e instanceof Error?e.message:null!=e?String(e):void 0,l=void 0!==a?ce(a):void 0,c=oe(e,["code","cause.code"]),u=null!==(t=function(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}(e))&&void 0!==t?t:oe(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),d=null!==(r=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=ne(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e))&&void 0!==r?r:function(e){var t;if(!e)return;const r=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)/),n=null!==(t=null==r?void 0:r[1])&&void 0!==t?t:null==r?void 0:r[2];if(!n)return;const o=Number.parseInt(n,10);return Number.isNaN(o)?void 0:o}(l),h=ue(null!==(i=null!==(o=null!==(n=ne(e,["response","body"]))&&void 0!==n?n:ne(e,["body"]))&&void 0!==o?o:ne(e,["data"]))&&void 0!==i?i:ne(e,["cause","body"])),p=function(e){var t,r;const n=null===(t=e.message)||void 0===t?void 0:t.toLowerCase(),o=null===(r=e.code)||void 0===r?void 0:r.toLowerCase();return(null==n?void 0:n.includes("timed out"))||(null==n?void 0:n.includes("timeout"))||(null==n?void 0:n.includes("etimedout"))||"etimedout"===o?"timeout":(null==n?void 0:n.includes("enotfound"))||(null==n?void 0:n.includes("eai_again"))||(null==n?void 0:n.includes("dns"))||"enotfound"===o||"eai_again"===o?"dns":(null==n?void 0:n.includes("certificate"))||(null==n?void 0:n.includes("tls"))||(null==n?void 0:n.includes("ssl"))?"tls":(null==n?void 0:n.includes("econnreset"))||(null==n?void 0:n.includes("connection reset"))||"econnreset"===o?"connection_reset":(null==n?void 0:n.includes("econnrefused"))||(null==n?void 0:n.includes("connection refused"))||"econnrefused"===o?"connection_refused":void 0}({message:l,code:c});return K({errorName:s,errorMessage:l,errorType:null!=e?typeof e:void 0,httpStatus:d,oauthErrorCode:u,errorResponseSummary:h,networkClassification:p,sdkErrorKind:u?"oauth_error":p?"auth_transport_error":l?"generic_error":void 0})}const he={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 pe(e){var t,r,n,o,i,s,a,l,c,u;const d=null!==(c=e.message)&&void 0!==c?c:he[e.event],h={event:e.event,cursorMcp:{oauth:K(Object.assign({},e.metadata))}},p=null!==(u=e.level)&&void 0!==u?u:"info";"error"!==p?"warn"!==p?"debug"!==p?null===(l=(a=e.logger).info)||void 0===l||l.call(a,d,h):null===(s=(i=e.logger).debug)||void 0===s||s.call(i,d,h):null===(o=(n=e.logger).warn)||void 0===o||o.call(n,d,h):null===(r=(t=e.logger).error)||void 0===r||r.call(t,d,e.error,h)}var fe=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const me=4096;function ge(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function ve(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function ye(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function we(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function be(e,t){var r,n,o,i,s;if(null==e)return{kind:"none",bytes:0,contentLength:we(t.get("content-length"))};if("string"==typeof e){const n=(new TextEncoder).encode(e).length;return{kind:"text",bytes:n,contentLength:null!==(r=we(t.get("content-length")))&&void 0!==r?r:n}}if(e instanceof URLSearchParams){const r=e.toString(),o=(new TextEncoder).encode(r).length;return{kind:"text",bytes:o,contentLength:null!==(n=we(t.get("content-length")))&&void 0!==n?n:o}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:null!==(o=we(t.get("content-length")))&&void 0!==o?o:e.size}:e instanceof ArrayBuffer?{kind:"binary",bytes:e.byteLength,contentLength:null!==(i=we(t.get("content-length")))&&void 0!==i?i:e.byteLength}:ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:null!==(s=we(t.get("content-length")))&&void 0!==s?s:e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:we(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:we(t.get("content-length"))}}function Se(e,t){var r;if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const n="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch(e){return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch(e){return}}}(t):t instanceof URLSearchParams&&null!==(r=t.get("grant_type"))&&void 0!==r?r:void 0;return n?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"}}(n):void 0}function ke(e){var t,r,n,o;const{input:i,init:s}=e,a=Z(ve(i)),l=function(e,t){const r=new Headers(ge(e)?e.headers:void 0);return new Headers(null==t?void 0:t.headers).forEach(((e,t)=>{r.set(t,e)})),r}(i,s),c=ye(l),u=l.get("content-type"),d=ee(null!==(t=l.get("mcp-session-id"))&&void 0!==t?t:void 0),h=l.get("authorization"),p=h&&null!==(r=h.split(/\s+/,1)[0])&&void 0!==r?r:null;return{method:(null!==(o=null!==(n=null==s?void 0:s.method)&&void 0!==n?n:ge(i)?i.method:void 0)&&void 0!==o?o:"GET").toUpperCase(),url:a,headers:{names:c,count:c.length},contentType:u,body:be(null==s?void 0:s.body,l),sessionIdHash:null!=d?d:null,authorizationScheme:p}}function Ee(e,t){var r,n,o,i,s;const a=ye(e.headers),l=we(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:a,count:a.length},contentType:e.headers.get("content-type"),body:Object.assign({kind:null===e.body?"none":"stream",bytes:null===e.body?0:l,contentLength:l},void 0!==t?{errorSummary:t}:{}),sessionIdHash:null!==(n=ee(null!==(r=e.headers.get("mcp-session-id"))&&void 0!==r?r:void 0))&&void 0!==n?n:null,wwwAuthenticateHash:null!==(i=ee(null!==(o=e.headers.get("www-authenticate"))&&void 0!==o?o:void 0))&&void 0!==i?i:null,mcpProtocolVersion:null!==(s=e.headers.get("mcp-protocol-version"))&&void 0!==s?s:null}}function xe(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 Ce(e,t){return fe(this,void 0,void 0,(function*(){try{const r=yield e.clone().text();return r.length>t?r.slice(0,t):r}catch(e){return}}))}function _e(e){return fe(this,void 0,void 0,(function*(){if(!function(e,t){var r,n;const o=ke({input:e,init:t});if(void 0!==Se(o.contentType,null==t?void 0:t.body))return!0;const i=null!==(n=null===(r=o.url.path)||void 0===r?void 0:r.toLowerCase())&&void 0!==n?n:"";return i.endsWith("/token")||i.includes("/oauth/token")||i.includes("/connect/token")}(e.input,e.init))return;const t=yield Ce(e.response,me);if(void 0!==t)try{return ue(JSON.parse(t))}catch(e){return ce(t,{maxLength:me})}}))}function Pe(e){return fe(this,void 0,void 0,(function*(){const t=yield function(e,t){return fe(this,void 0,void 0,(function*(){var r,n;try{if(t.ok)return;const o=null!==(n=null===(r=t.headers.get("content-type"))||void 0===r?void 0:r.toLowerCase())&&void 0!==n?n:"";if(!o.includes("json")&&!o.includes("text"))return;const i=yield Ce(t,me);if(void 0===i)return;return function(e){if("/mcp"!==(t=Z(ve(e.input)).path)&&!0!==(null==t?void 0:t.endsWith("/mcp")))return ce(e.rawText,{maxLength:me});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,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?ce(r.message,{maxLength:me}):void 0;return void 0!==n||void 0!==o?JSON.stringify(Object.assign(Object.assign({},void 0!==n?{code:n}:{}),void 0!==o?{message:o}:{})):void 0}(t):void 0}catch(e){return}}({input:e,rawText:i})}catch(e){return}}))}(e.input,e.response);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?yield _e({input:e.input,response:e.response,init:e.init}):void 0}}))}function Ie(e,t,r){var n;try{e()}catch(e){null===(n=t.warn)||void 0===n||n.call(t,"MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function Te(e){const{fetch:t,logger:r,metadata:n,logSuccessfulExchanges:o=!0}=e;return(e,i)=>fe(this,void 0,void 0,(function*(){const s=Date.now();try{const a=yield t(e,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:c}=a.ok?{}:yield Pe({input:e,init:i,response:a});return!o&&a.ok||Ie((()=>{!function(e){var t,r;const{logger:n,response:o}=e,i=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:i,responseErrorSummary:s,oauthTokenErrorBodySummary:a}=e,l=ke({input:t,init:r}),c=Se(l.contentType,null==r?void 0:r.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign({},i),{request:l,response:Ee(n,s)}),void 0!==c?{oauth:{grantType:c}}:{}),void 0!==a?{oauthTokenErrorBodySummary:a}:{})}}}(e);o.ok?null===(t=n.info)||void 0===t||t.call(n,"MCP HTTP exchange completed",i):null===(r=n.warn)||void 0===r||r.call(n,"MCP HTTP exchange completed",i)}({logger:r,input:e,init:i,response:a,durationMs:Date.now()-s,metadata:n,responseErrorSummary:l,oauthTokenErrorBodySummary:c})}),r,"success"),a}catch(t){const o=function(e){var t,r;if(!e||"object"!=typeof e)return;const n=[e.response,null===(t=e.cause)||void 0===t?void 0:t.response];for(const e of n)if(e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status&&"headers"in e&&"function"==typeof(null===(r=e.headers)||void 0===r?void 0:r.get))return e}(t),{responseErrorSummary:a,oauthTokenErrorBodySummary:l}=o?yield Pe({input:e,init:i,response:o}):{};throw Ie((()=>{!function(e){var t;const{logger:r}=e;null===(t=r.warn)||void 0===t||t.call(r,"MCP HTTP exchange failed",function(e){var t;const{input:r,init:n,error:o,durationMs:i,metadata:s,responseFromError:a,responseErrorSummary:l,oauthTokenErrorBodySummary:c}=e,u=de(o),d=ke({input:r,init:n}),h=Se(d.contentType,null==n?void 0:n.body),p=void 0!==a?Ee(a,l):{status:null!==(t=u.httpStatus)&&void 0!==t?t:null,ok:null,headers:{names:[],count:0},contentType:null,body:Object.assign({kind:"none",bytes:null,contentLength:null},void 0!==l?{errorSummary:l}:{}),sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null};return{event:"mcp_http_exchange",outcome:"error",durationMs:i,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},s),{request:d,response:p}),void 0!==h?{oauth:{grantType:h}}:{}),void 0!==c?{oauthTokenErrorBodySummary:c}:{}),{error:xe(u)})}}}(e))}({logger:r,input:e,init:i,error:t,durationMs:Date.now()-s,metadata:n,responseFromError:o,responseErrorSummary:a,oauthTokenErrorBodySummary:l})}),r,"failure"),t}}))}new Set(["InvalidGrantError","InvalidRequestError"]),new Set(["SiblingAlreadyRefreshedError","OAuthRefreshTransientError","AbortError","TimeoutError","ServerError","TemporarilyUnavailableError"]);const Re=["0.0.0.0/0","::/0"];function Ae(e){const t=(null!=e?e:[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));return{hasConfiguredEntries:t.length>0,hasInvalidEntries:r.length!==t.length,entries:r}}function Oe(e){const t=Ae(e.mcpNetworkAllowlist),r=Ae(e.mcpNetworkDenylist),n=e.mcpNetworkMode;if("deny_all"===n||r.entries.includes("*")||r.hasInvalidEntries)return{version:1,default:"deny"};if("allow_all"===n)return Object.assign({version:1,default:"deny",allow:[...Re]},r.entries.length>0?{deny:r.entries}:{});if("allowlist"===n||t.hasConfiguredEntries){const e=function(e){return e.entries.includes("*")?[...Re]:e.entries}(t);return e.length>0?Object.assign({version:1,default:"deny",allow:e},r.entries.length>0?{deny:r.entries}:{}):{version:1,default:"deny"}}return Object.assign({version:1,default:"deny",allow:[...Re]},r.entries.length>0?{deny:r.entries}:{})}function Me(e,t){return n=this,o=void 0,s=function*(){const{resolveSandboxPolicyForWorkspace:n}=yield Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),o={type:"workspace_readwrite",sandboxWorkspaceRoot:t,networkPolicy:Oe(e),networkPolicyStrict:!0},{policy:i}=yield n(t,{perUser:o});return i},new((i=void 0)||(i=Promise))((function(e,t){function r(e){try{l(s.next(e))}catch(e){t(e)}}function a(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i((function(e){e(n)}))).then(r,a)}l((s=s.apply(n,o||[])).next())}));var n,o,i,s}const je=["0.0.0.0/0","::/0"];function De(e){const t=(null!=e?e:[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function Ne(e){const t=!0===e.enabled,r=De(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...je];const t=De(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...je]:t.entries;if(!function(e){var t;return(null!==(t=e.mcpNetworkAllowlist)&&void 0!==t?t:[]).some((e=>e.trim().length>0))}(e))return[...je];const r=N(e);return r.includes("*")?[...je]:r}(e):[],i=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:i})}class $e 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)}}function Le(e,t){void 0!==t&&t.length>0&&e.searchParams.set("scope",t.join(" "))}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 n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!(null==n?void 0:n[1]))return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){var t;if(!(e instanceof Error))return!1;const r=e,n=null===(t=e.cause)||void 0===t?void 0:t.code;return"ECONNREFUSED"===r.code||"ECONNREFUSED"===n||e.message.includes("ECONNREFUSED")}(e)}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]),new Set([429,502,503,504]),new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]),Error},"../shell-exec/dist/index.js"(e,t,r){r.r(t),r.d(t,{BashState:()=>yt,INSECURE_NONE_SANDBOX_POLICY:()=>lr,KnownShellExecutor:()=>je,NaiveTerminalExecutor:()=>Ct,OutputSuppressionController:()=>Zt,PowerShellState:()=>Et,SHELL_OUTPUT_SUPPRESSED_NOTICE:()=>Kt,SandboxUnsupportedError:()=>Pe,ZshState:()=>At,configureRipgrepPath:()=>v,configureSandboxPrereqs:()=>Te,createDefaultTerminalExecutor:()=>ar,createIgnoreMapping:()=>rr,createNaiveTerminalExecutor:()=>_t,getLastSandboxFailureReason:()=>_e,getPowerShellExecutable:()=>kt,getRipgrepBinaryPath:()=>S,getSandboxPolicyType:()=>Ke,getShellExecutablePath:()=>nr,getSuggestedShell:()=>sr,isAllowAllNetworkByPolicy:()=>te,isHardcodedWriteProtected:()=>Y,isNetworkEnabledByPolicy:()=>ee,isRipgrepConfigured:()=>k,isSandboxSupported:()=>Oe,loadSandboxPolicyFromFileOrUndefined:()=>er,mergeNetworkPolicies:()=>nt,mergePathsIntersection:()=>Ye,mergePathsUnion:()=>Xe,networkAllowAllPolicy:()=>ne,networkDisabledPolicy:()=>re,parseSandboxPolicyJson:()=>Qt,primeSandboxSupport:()=>Me,resolvePolicyPaths:()=>tr,resolveRipgrepFromPath:()=>g,resolveSandboxPolicyForWorkspace:()=>st,spawnInSandbox:()=>Re,spawnWithSignal:()=>Ne,withConfiguredRipgrepEnv:()=>b});var n=r("node:path"),o=r("node:fs"),i=r("../utils/dist/lru-cache.js");const s="undefined"!=typeof process&&"win32"===process.platform,a=new i.q({max:512});function l(e){try{return o.statSync(e)}catch(e){return null}}function c(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,o=a.get(r);if(void 0!==o)return o;const i=n.join(".",e);if(l(i))return a.set(r,i),i;const c=process.env.PATH.split(s?";":":");for(const o of c){const i=n.join(o,e);if(l(i)&&(!t||t.test(i)))return a.set(r,i),i}return a.set(r,e),e}function u(e,t,r){if("win32"!==process.platform)return{cmd:c(e),args:t};if(!o.existsSync(e)){const n=[".exe",".bat",".cmd",".ps1"],i=e.toLowerCase();if(n.some((e=>i.endsWith(e)))){const n=c(e,r);if(o.existsSync(n))return u(n,t,r)}for(const i of n){const n=c(`${e}${i}`,r);if(o.existsSync(n))return u(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:n.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:n.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");let m;function g(){const e=u("rg",[]).cmd;return"rg"!==e?e:void 0}function v(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");m=e}function y(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 w(e,t){const r=(0,n.dirname)(t);if(!r||"."===r)return e;const o=function(e){const t=y(e);return void 0!==t?e[t]??"":""}(e).split(n.delimiter).filter(Boolean);return function(e,t){const r=y(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...o.filter((e=>e!==r))].join(n.delimiter))}function b(e){return m&&(0,n.isAbsolute)(m)?{...w(e,m),CURSOR_RIPGREP_PATH:m}:e}function S(){if(!m)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return m}function k(){return void 0!==m}var E=r("node:child_process");function x(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;return n}const C=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function _(e){const t={...e};for(const e of C)delete t[e];return t}var P=r("node:crypto");let I;function T(){const e=(0,n.join)((0,h.tmpdir)(),"cursor-sandbox-cache",(I||(I=(0,P.randomBytes)(16).toString("hex")),I));return{NPM_CONFIG_CACHE:(0,n.join)(e,"npm"),PNPM_STORE_PATH:(0,n.join)(e,"pnpm-store"),GOCACHE:(0,n.join)(e,"go-build"),GOMODCACHE:(0,n.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,n.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,n.join)(e,"pip"),UV_CACHE_DIR:(0,n.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,n.join)(e,"bun"),YARN_CACHE_FOLDER:(0,n.join)(e,"yarn"),npm_config_devdir:(0,n.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,n.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,n.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,n.join)(e,"turbo"),GRADLE_USER_HOME:(0,n.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,n.join)(e,"conda"),POETRY_CACHE_DIR:(0,n.join)(e,"poetry"),GEM_SPEC_CACHE:(0,n.join)(e,"gem-specs"),BUNDLE_PATH:(0,n.join)(e,"bundle"),COMPOSER_HOME:(0,n.join)(e,"composer"),HOMEBREW_CACHE:(0,n.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,n.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,n.join)(e,"nx"),NUGET_PACKAGES:(0,n.join)(e,"nuget"),CCACHE_DIR:(0,n.join)(e,"ccache"),CP_HOME_DIR:(0,n.join)(e,"cocoapods")}}var R=r("../context/dist/logger.js"),A=r("../context/dist/core.js"),O=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),M=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class j extends Error{constructor(e,t,r,n,o,i){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=o,this.stderr=i,this.command=r,this.args=n,Error.captureStackTrace&&Error.captureStackTrace(this,j)}}function D(e,t,r){var n;r=null!=r?r:{};const o=new O.Observable((n=>{var o,i;const{encoding:s,timeout:a}=r,l=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(r,["encoding","timeout"]),{cmd:c,args:d}=u(e,t),h=l.stdin;h&&(delete l.stdin,null!==(o=l.stdio)&&void 0!==o||(l.stdio=["pipe","pipe","pipe"])),null!==(i=l.stdio)&&void 0!==i||(l.stdio=["ignore","pipe","pipe"]);const p=(0,E.spawn)(c,d,l);r.processInfo&&void 0!==p.pid&&(r.processInfo.pid=p.pid);let f=null;a&&a>0&&(f=setTimeout((()=>{p.killed||p.kill();const e=new j(`Process timed out after ${a}ms`,-1,c,d);n.error(e)}),a));const m=t=>o=>{if(o.length<1)return;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(o);let i="<< String sent back was too long >>";try{i="string"==typeof o?o.toString():o.toString(s||"utf8")}catch(t){i=`<< Lost chunk of process output for ${e} - length was ${o.length}>>`}n.next({source:t,text:i})},g=new O.Subscription;if(h)if(p.stdin){const e=p.stdin;g.add(h.subscribe({next:t=>e.write(t),error:n.error.bind(n),complete:()=>e.end()}))}else n.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let v=null,y=null,w=!1;return p.stdout?(y=new O.AsyncSubject,p.stdout.on("data",m("stdout")),p.stdout.on("close",(()=>{y.next(!0),y.complete()}))):y=(0,O.of)(!0),p.stderr?(v=new O.AsyncSubject,p.stderr.on("data",m("stderr")),p.stderr.on("close",(()=>{v.next(!0),v.complete()}))):v=(0,O.of)(!0),p.on("error",(e=>{w=!0,f&&clearTimeout(f),n.error(e)})),p.on("close",(e=>{w=!0,f&&clearTimeout(f);const t=(0,O.merge)(y,v).pipe((0,M.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new j(`Process failed with exit code: ${e}`,e,c,d);n.error(t)}))})),g.add(new O.Subscription((()=>{w||(f&&clearTimeout(f),p.kill())}))),g}));let i=o;if(r.retries&&r.retries>0){const e=r.retries,t=null!==(n=r.retryDelay)&&void 0!==n?n:1e3;i=i.pipe((0,M.L5)({count:e,delay:(e,r)=>{if(e instanceof j&&0!==e.exitCode)return(0,O.timer)(t);throw e}}))}return r.split?i:i.pipe((0,M.Tj)((e=>null==e?void 0:e.text)))}function N(e,t,r){return(null==r?void 0:r.split)?(n=D(e,t,Object.assign(Object.assign({},null!=r?r:{}),{split:!0})),new Promise(((e,t)=>{let r="",o="";n.subscribe({next:e=>{"stdout"===e.source?r+=e.text:o+=e.text},error:e=>{if(e instanceof j){const n=new j(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,o);t(n)}else{const n=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(n)}},complete:()=>e([r,o])})}))):function(e){return new Promise(((t,r)=>{let n="";e.subscribe({next:e=>{n+=e},error:e=>{if(e instanceof j){const t=new j(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(D(e,t,Object.assign(Object.assign({},null!=r?r:{}),{split:!1})));var n}var $=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const L=[{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:".ssh"}];function F(e){const t=L.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function U(e){const t=L.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}L.filter((e=>"git"===e.type)).map((e=>e.pattern)),L.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const B=[];let z=null,W=null;let H=null;const q=new Map;const G="win32"===process.platform||"darwin"===process.platform;function V(e){if(!e.endsWith(n.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function J(e){return e.endsWith(n.sep)?e:e+n.sep}function K(e,t){const r=V(t);if(G){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(J(n))}return e===r||e.startsWith(J(r))}function Z(e,t){const r=V(e);return G?(0,n.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,n.relative)(r,t).replace(/\\/g,"/")}async function Y(e,t){if(K(e,t)){const r=Z(t,e);if((null===z&&(z=$({ignoreCase:!0}),z.add(L.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),z).ignores(r))return!0}const{isWorktree:r,gitDirParent:o}=await async function(e){const t=q.get(e);if(t)return t;const r=await(0,d.stat)((0,n.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return q.set(e,t),t}const o=await async function(e){try{const t=await N("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,n.dirname)((0,n.resolve)(e,t.trim()))}catch{return null}}(e),i={isWorktree:!0,gitDirParent:o??e};return q.set(e,i),i}(t);if(K(e,o)){const t=Z(o,e);if((null===W&&(W=$({ignoreCase:!0}),W.add(L.filter((e=>"git"===e.type)).map((e=>e.pattern)))),W).ignores(t))return!0}if(r&&K(e,t)&&".git"===Z(t,e))return!0;for(const t of function(){if(null!==H)return H;const e=h.homedir(),t=[];for(const r of L)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,n.join)(e,r.pattern))}return H=t,t}())if(K(e,t))return!0;return!1}const X=new WeakMap;function Q(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}function ee(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function te(e){return void 0!==e&&"allow"===e.default}function re(){return{version:1,default:"deny"}}function ne(){return{version:1,default:"allow"}}const oe="darwin"===process.platform,ie="linux"===process.platform,se=(0,R.h)("shell-exec:sandbox");function ae(e){const t=P.randomBytes(8).toString("hex"),r=n.join(h.tmpdir(),`sandbox-policy-${t}`);return o.writeFileSync(r,e,{encoding:"utf-8",mode:384}),r}let le;function ce(){return le}function ue(e){"linux"===process.platform&&Object.assign(e,b(e))}let de=null,he=null,pe=null,fe=null,me=!1,ge=null;function ve(e){if(null!==de)return!!de;try{const t=ce();return se.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(de=o.existsSync(t),de?se.info(e,`[checkBinaryAvailable] Binary path exists: ${de}`):(he=new Error(`Sandbox binary not found at ${t}`),se.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!de):(he=new Error("Sandbox binary path was not configured"),de=!1,se.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return he=t,de=!1,se.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function ye(e){if(null!==fe)return fe;const t=e??(0,A.q6)();if(se.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!ve(t)){const e=he?.message||"Binary check failed";return pe=e,se.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),fe=!1,fe}if("win32"===process.platform)return pe="Windows sandbox helper only provides network proxy, not filesystem isolation",se.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),fe=!1,fe;if("darwin"===process.platform)return pe=null,se.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),fe=!0,fe;const{binaryPath:r,args:n,env:o}=be(t,process.cwd());try{return(0,E.execFileSync)(r,n,{stdio:["ignore","ignore","pipe"],timeout:we,env:o,shell:!1}),pe=null,se.info(t,"[isSandboxHelperSupported] Preflight succeeded, sandbox supported!"),fe=!0,fe}catch(e){const r=e;return Se(t,{message:r.message,status:r.status,stderrText:r.stderr?.toString?.()||""})}}const we=15e3;function be(e,t){const r={sandbox:{type:"workspace_readwrite",cwd:t,additionalReadwritePaths:[],networkAccess:!1,disableTmpWrite:!1,ignoreMapping:void 0}},n=String(ce());se.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),se.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return ue(o),{binaryPath:n,args:["--policy",ae(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}function Se(e,t){const{message:r,status:n,stderrText:o}=t;return se.error(e,`[sandboxPreflight] Preflight failed: ${r}`),se.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&se.error(e,`[sandboxPreflight] Stderr: ${o}`),pe=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,fe=!1,!1}function ke(e,t=[],r={},i){const s=(0,A.q6)();if(r.env=x(r.env),!ve(s))throw new Error(`Sandbox binary not available: ${he?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===i.type)return(0,E.spawn)(e,t,r);if("workspace_readwrite"===i.type||"workspace_readonly"===i.type)return function(e,t,r,i){if("workspace_readwrite"!==i.type&&"workspace_readonly"!==i.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=i.sandboxWorkspaceRoot??s;let l,c=e,u=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",u=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",u=["-c",`${e} ${t.join(" ")}`])),i.ignoreMapping&&(l=Ee(i.ignoreMapping));const d=function(e,t,r){const i=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,o.existsSync)(r)&&(0,o.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},s=function(e){let t=n.resolve(e);for(;;){try{const e=n.join(t,".git");if(o.existsSync(e))return!0}catch{}const e=n.dirname(t);if(e===t)return!1;t=e}}(r),a=!ie||s?t??{}:{},l={...i};for(const[e,t]of Object.entries(a))l[e]?l[e]=[...l[e],...t]:l[e]=t;if(0!==Object.keys(l).length)return Ee(l)}(i.additionalReadonlyPaths,i.writeProtectionMapping,a),h=ee(i.networkPolicy),p="workspace_readonly"===i.type?{type:"workspace_readonly",cwd:a,readBoundary:i.readBoundary??"system",additionalReadPaths:i.additionalReadPaths||[],additionalReadonlyPaths:d,networkAccess:h,ignoreMapping:l}:{type:"workspace_readwrite",cwd:a,readBoundary:i.readBoundary??"system",additionalReadPaths:i.additionalReadPaths||[],additionalReadwritePaths:i.additionalReadwritePaths||[],additionalReadonlyPaths:d,networkAccess:h,disableTmpWrite:i.disableTmpWrite||!1,ignoreMapping:l},f=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!ee(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(i),m={sandbox:p};void 0!==f&&(m.networkPolicy=f),!1===i.networkPolicyStrict&&(m.networkPolicyStrict=!1);const g=["--policy",ae(JSON.stringify(m)),"--",c,...u],v={..."linux"===process.platform?_(process.env):process.env,..."linux"===process.platform&&r.env?_(r.env):r.env,CURSOR_SANDBOX:"native"};ue(v);const y={cwd:r.cwd||s,env:v,stdio:r.stdio||["pipe","pipe","pipe"]};try{const e=new Date,t=(0,E.spawn)(String(ce()),g,y);return oe&&t.pid&&function(e,t){X.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${e}`)}}(e,t,r,i);throw new Error(`Unsupported sandbox policy: ${String(i)}`)}function Ee(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?xe(t):t;o[e]=r;const n=Ce(e);n!==e&&(o[n]=r)}return o}function xe(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ce(e){try{return(0,o.realpathSync)(e)}catch{return e}}function _e(){return pe}class Pe extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Ie="darwin"===process.platform;function Te(e){!function(e){S();const{sandboxBinaryPath:t}=e;le||(le=t)}(e)}function Re(e,t=[],r={},n){if(r.env=x(r.env),n.enableSharedBuildCache&&(r={...r,env:{...x(process.env),...T(),...r.env}}),"insecure_none"!==n.type){if(ye())return ke(e,t,r,n);const o=_e();throw new Pe(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r){return(0,E.spawn)(e,t,r)}(e,t,r)}function Ae(e){return Ie?async function(e){const t=X.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,i=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,E.execFile)("/usr/bin/log",i,((t,n,i)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),a=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const i=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(i){const[,e,s,l,c,u,d]=i,h=Number(s);a.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:l.toLowerCase(),decisionCode:Number(c),operation:u,target:d,duplicateCount:1,raw:n,relationship:Q(h,r,o)});continue}const s=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(s){const e=Number(s[1]),i=s[2],l=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(i);if(l){const[,i,s,c,u,d,h]=l,p=Number(s);a.push({timestamp:t.timestamp,processName:i.trim(),pid:p,decision:c.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Q(p,r,o)})}else a.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}a.push({timestamp:t.timestamp,raw:n})}catch{}e(a)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Oe(e,t){if(Ie)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return ye(t?.ctx)}async function Me(e){if(Ie)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return async function(e){return me&&null!==fe?fe:(null!==ge||(ge=async function(e){const t=e.ctx??(0,A.q6)();if(!ie||!ve(t)){const e=ye(t);return me=!0,e}null!==fe&&se.info(t,`[primeSandboxHelperSupport] Re-probing from ${e.workspaceCwd}; the cached verdict (${fe}) was measured from a different directory`);const r=e.timeoutMs??we,{binaryPath:n,args:o,env:i}=be(t,e.workspaceCwd),s=Date.now(),a=await function(e){return new Promise((t=>{let r;try{r=(0,E.spawn)(e.binaryPath,e.args,{stdio:["ignore","ignore","pipe"],env:e.env,shell:!1,detached:!0})}catch(e){return void t({kind:"failed",message:e instanceof Error?e.message:String(e),stderrText:""})}let n="";r.stderr?.on("data",(e=>{n+=e.toString()}));let o=!1;const i=setTimeout((()=>{o||(o=!0,function(e){const t=e.pid;if(void 0!==t)try{process.kill(-t,"SIGKILL")}catch{try{e.kill("SIGKILL")}catch{}}}(r),t({kind:"timeout",stderrText:n}))}),e.timeoutMs);i.unref?.();const s=e=>{o||(o=!0,clearTimeout(i),t(e))};r.on("error",(e=>{s({kind:"failed",message:e.message,stderrText:n})})),r.on("close",((e,t)=>{s(0!==e?{kind:"failed",message:`preflight exited with code ${e}${t?` (signal ${t})`:""}`,status:e,stderrText:n}:{kind:"ok"})}))}))}({binaryPath:n,args:o,env:i,timeoutMs:r}),l=Date.now()-s;if("timeout"===a.kind)return pe=`Linux preflight rooted at ${e.workspaceCwd} did not finish within ${r}ms (sandbox setup for this workspace is slower than the terminal tool will wait). stderr: ${a.stderrText||"none"}`,se.error(t,`[primeSandboxHelperSupport] Preflight timed out after ${r}ms, treating sandbox as unsupported`),fe=!1,me=!0,!1;if("failed"===a.kind){const e=Se(t,{message:a.message,status:a.status,stderrText:a.stderrText});return me=!0,e}return pe=null,se.info(t,`[primeSandboxHelperSupport] Preflight rooted at ${e.workspaceCwd} succeeded in ${l}ms, sandbox supported!`),fe=!0,me=!0,!0}(e).finally((()=>{ge=null}))),ge)}(e)}var je;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(je||(je={}));const De={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Ne(e,t=[],r={},n,o){if(o?.aborted){const e=new Error("Operation was aborted");e.name="AbortError";const t=new(require("node:events").EventEmitter);return process.nextTick((()=>{t.emit("error",e)})),t}const i=Re(e,t,{...r,env:b(r.env??process.env)},n);if(o){const e=()=>{if(i.pid)try{if(r.detached)try{process.kill(-i.pid,"SIGTERM")}catch{i.kill("SIGTERM")}else i.kill("SIGTERM");const e=setTimeout((()=>{if(!i.killed&&i.pid)try{if(r.detached)try{process.kill(-i.pid,"SIGKILL")}catch{i.kill("SIGKILL")}else i.kill("SIGKILL")}catch(e){}}),1e3);i.once("exit",(()=>{clearTimeout(e)}))}catch(e){}};o.addEventListener("abort",e,{once:!0}),i.once("exit",(()=>{o.removeEventListener("abort",e)}))}return i}function $e(e){e?.on("error",(()=>{}))}function Le(e,t){e&&($e(e),e.write(t),e.end())}function Fe(e,t){e&&($e(e),e.on("data",(e=>{t(e.toString())})))}function Ue(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function Be(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}const ze="__CURSOR_BASH_STATE_START__",We="__CURSOR_BASH_STATE_END__",He=50,qe=262144;class Ge{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??He,this.maxBufferedBytes=t?.maxBufferedBytes??qe}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o<e.length;o++){const i=e[o];i.type!==r?(t.push({type:r,data:Buffer.concat(n)}),r=i.type,n=[i.data]):n.push(i.data)}return t.push({type:r,data:Buffer.concat(n)}),t}(e))try{await this.writable.write(t)}catch{}}}function Ve(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 Ge(e.writable,e.outputLimiterOptions);let r;const n=Promise.all([Je(e.stdout,"stdout",t),Je(e.stderr,"stderr",t)]).then((()=>{})).catch((e=>{r=e}));return{async waitForOutput(){if(await n,void 0!==r)throw(e=r)instanceof Error?e:new Error(String(e));var e},async flush(){await t.flush()}}}async function Je(e,t,r){if(e)for await(const n of e)await r.push(t,n)}function Ke(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Ze(...e){return e.some((e=>!0===e))}function Ye(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=rt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(rt);let r=new Set(t[0].map(rt));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(rt));r=new Set([...r].filter((e=>n.has(e))))}return[...r]}function Xe(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(rt(e));return[...t]}const Qe=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]<t[e]?r:e))}}}({defaultValue:"system",rank:{workspace:0,custom:1,system:2}}),et=(...e)=>Ye(...e);function tt(e,t){if("custom"===e)return t??[]}function rt(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function nt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const i=o.size>0?[...o]:void 0;let s;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){s=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==i&&(a.allow=i),n.size>0&&(a.deny=[...n]),void 0!==s&&(a.logging=s),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 ot(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e)){const e=r[t];if(e){const o=new Set(e);for(const e of n)o.has(e)&&o.delete(e),o.add(e);r[t]=[...o]}else r[t]=[...n]}return 0!==Object.keys(r).length?r:void 0}function it(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function st(e,t){if(!t)return{policy:{type:"insecure_none"}};const r=await(0,d.stat)((0,n.join)(e,".git")).then((e=>e),(()=>null)),o=r?.isFile()??!1,i=null!==r;if("workspace_readwrite"===Ke(t)){let r=e;if(o){const o=await N("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,n.resolve)(e,t.trim())),(()=>null));if(o){r=(0,n.dirname)(o);const i=t.perRepo,s=i?.ignoreMapping;t={...t,perRepo:{...i,type:"workspace_readwrite",additionalReadwritePaths:[...i?.additionalReadwritePaths??[],o],ignoreMapping:s,writeProtectionMapping:ot(i?.writeProtectionMapping,U(e))}}}}if(i)return at(t,{workspaceDir:e,gitDirParent:r})}return at(t,{workspaceDir:e})}function at(e,t){const r=function(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const i=o[0].type;for(const e of o)if(e.type!==i)throw new Error(`Cannot merge policies of different types: found "${i}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return i}(e);if(void 0===r)return ut(e,t);switch(r){case"workspace_readwrite":return ut(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=lt(e,t),o={policy:ct({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(e,t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,i=t?.debug,s={type:"insecure_none",allowlistEscalated:Ze(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:it(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:Ze(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:it(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},a=Object.fromEntries(Object.entries(s).filter((([e,t])=>void 0!==t)));a.type="insecure_none";const l={policy:a};return i&&(l.debug={fieldSources:{}}),l}(e,t);default:throw new Error(`Unknown policy type: ${r}`)}}function lt(e,t){const r=t?.debug,{perUser:o,perRepo:i,teamAdmin:s}=e,a=t?.workspaceDir??process.cwd(),l=function(e){const t=function(){if(0!==B.length)return{version:1,deny:[...B]}}(),r=h.homedir(),o=[];for(const e of L)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":o.push(e.pattern);break;case"home":r.length>0&&o.push((0,n.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${t}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:o,writeProtectionMapping:F(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(a),c={},u=[o,i,s],d=["perUser","perRepo","teamAdmin","hardcoded"],p=(e,t)=>{r&&(c[e]=d[t]??"unknown")},f=Ze(o?.disableTmpWrite,i?.disableTmpWrite,s?.disableTmpWrite);for(let e=u.length-1;e>=0;e--)if(!0===u[e]?.disableTmpWrite){p("disableTmpWrite",e);break}const m=Ze(o?.networkPolicyStrict,i?.networkPolicyStrict,s?.networkPolicyStrict,l.networkPolicyStrict);l.networkPolicyStrict&&p("networkPolicyStrict",3);const g=function(...e){return Qe.merge(...e)}(o?.readBoundary,i?.readBoundary,s?.readBoundary),v=function(...e){return et(...e)}(tt(o?.readBoundary,o?.additionalReadPaths),tt(i?.readBoundary,i?.additionalReadPaths),tt(s?.readBoundary,s?.additionalReadPaths)),y="custom"===g?v:void 0,w=Xe(o?.additionalReadonlyPaths,i?.additionalReadonlyPaths,s?.additionalReadonlyPaths,l.additionalReadonlyPaths),b=w.length>0?w:void 0;let S=nt(o?.networkPolicy,i?.networkPolicy,s?.networkPolicy,l.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const E=void 0!==(x=S)?x:{version:1,default:"deny"};var x;const C=it(o?.debugOutputDir,i?.debugOutputDir,s?.debugOutputDir),_=Ze(o?.captureDenies,i?.captureDenies,s?.captureDenies),P=it(o?.enableSharedBuildCache,i?.enableSharedBuildCache,s?.enableSharedBuildCache),I=ot(o?.ignoreMapping,i?.ignoreMapping,s?.ignoreMapping,l.ignoreMapping),T=function(e){const t=L.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:y,additionalReadonlyPaths:b,networkPolicy:E,debugOutputDir:C,captureDenies:_||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:ot(o?.writeProtectionMapping,i?.writeProtectionMapping,s?.writeProtectionMapping,l.writeProtectionMapping,T),fieldSources:c}}function ct(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,i=t?.debug,s=lt(e,t),a=Xe(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),l={policy:ct({type:"workspace_readwrite",disableTmpWrite:s.disableTmpWrite,networkPolicyStrict:s.networkPolicyStrict,readBoundary:s.readBoundary,additionalReadPaths:s.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:s.additionalReadonlyPaths,networkPolicy:s.networkPolicy,debugOutputDir:s.debugOutputDir,captureDenies:s.captureDenies,enableSharedBuildCache:s.enableSharedBuildCache,ignoreMapping:s.ignoreMapping,writeProtectionMapping:s.writeProtectionMapping},"workspace_readwrite")};return i&&(l.debug={fieldSources:s.fieldSources}),l}const dt="win32"===process.platform;function ht(e){return!dt&&!!e?.SUDO_ASKPASS}function pt(e){return ht(e)?"alias sudo='sudo -A'; ":""}function ft(e){const t=[];let r=0;for(;r<e.length;){const n=0===r||"&&"===e.slice(Math.max(0,r-2),r)||"||"===e.slice(Math.max(0,r-2),r)||"|"===e[r-1]||";"===e[r-1],o=Math.max(0,r-10),i=e.slice(o,r),s=/(?:&&|\|\||[|;])\s*$/.test(i)||0===r&&/^\s*$/.test(i);if((n||s)&&"sudo"===e.slice(r,r+4)){const n=r+4;if(n>=e.length||/\s/.test(e[n])){let o=n;for(;o<e.length&&/\s/.test(e[o]);)o++;let i=!1;if(o<e.length&&"-"===e[o]){let t=o+1;for(;t<e.length&&/[^\s]/.test(e[t]);)t++;const r=e.slice(o,t);i=/^-[a-zA-Z]*A[a-zA-Z]*$/.test(r)}i?(t.push("sudo"),r=n):(t.push("sudo -A"),r=n);continue}}t.push(e[r]),r++}return t.join("")}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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function gt(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 vt(e){if("win32"!==process.platform)return e;const t=n.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===n.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}class yt{cwd;state;userTerminalHint;useFileStateTransport;constructor(e,t,r,n=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n}async getCwd(){return this.cwd}clone(e){return new yt(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport)}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,p.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,a=(0,f.Jt)(),l=r?.workingDirectory??this.cwd,c={...process.env,...De,...r?.env};let u='builtin eval "$1"';s||(u+=" < /dev/null");const m=pt(c),g=this.useFileStateTransport;let v,y,w;if(g){v=await(0,d.mkdtemp)(n.join(h.tmpdir(),"cursor-bash-state-")),n.basename(v),y=n.join(v,"state-in"),w=n.join(v,"state-out"),await(0,d.writeFile)(y,this.state,"utf8"),await(0,d.writeFile)(w,"","utf8").catch((()=>{}));const e=vt(y),t=vt(w);c.CURSOR_STATE_INPUT_FILE=e,c.CURSOR_STATE_OUTPUT_FILE=t}const b=["-O","extglob","-c",`${g?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)"} && builtin shopt -s extglob && builtin eval -- "$snap" && { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${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=gt(this.userTerminalHint);if(!S)throw new Error("Can't find Bash");const k=r?.sandboxWorkspaceRoot??l,E=(await st(k,r?.sandboxPolicy)).policy,x="insecure_none"!==E.type?{...E,sandboxWorkspaceRoot:k}:E;let C="";const _=async()=>{if(g){if(!w)return void(C=this.state);try{C=await(0,d.readFile)(w,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),C=this.state}}},P=async()=>{if(v)try{await(0,d.rm)(v,{recursive:!0,force:!0})}catch{}};let I;try{I=Ne(S,b,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:l,detached:!0},x,r?.signal)}catch(e){throw await P(),e}I.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:I.stdin??void 0,pid:I.pid})}catch(e){}}));const T=Ve({stdout:I.stdout,stderr:I.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});I.on("error",(async e=>{await P(),a.throw(e)}));let R=null,A=null,O=!1;const M=async e=>{if(!O){if(O=!0,A&&(clearTimeout(A),A=null),(0,p.HF)(i.ctx,"exit"),e)try{await T.waitForOutput()}catch(e){return await P(),void a.throw(e instanceof Error?e:new Error(String(e)))}if(await T.flush(),!r?.signal?.aborted){await _();const e=`${ze}\n`,t=`${We}\n`;if(C.startsWith(e)&&C.endsWith(t)){let t=C.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=Ue(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(x.captureDenies)try{const e=await Ae(I);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:R,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch{a.close()}await P()}};I.on("exit",((e,t)=>{R=e;const n=r?.closeTimeout??5e3;n>0&&(A=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),M(!1)}),n))})),I.on("close",(async()=>{await M(!0)}));const j=I.stdio[3],D=I.stdio[4];g||(Le(j,this.state),Fe(D,(e=>{C+=e}))),yield*a}catch(e){o.error=e,o.hasError=!0}finally{mt(o)}}}var wt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class bt{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 bt((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,p.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{wt(n)}}}var St=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kt(){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=n.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,o.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}class Et{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Et(e??this.cwd,this.state)}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,p.VI)(e.withName("PowerShellState.execute")),!1),s=r?.pipeStdin??!1,a=r?.workingDirectory??this.cwd,l=(0,f.Jt)(),c={...process.env,...De,...r?.env},u=ht(c)?ft(t):t,m=h.tmpdir(),g=n.join(m,`ps-state-out-${(0,P.randomUUID)()}.txt`),v=((e,t,r,n)=>`\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 -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\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 "${n}"\n\nexit $COMMAND_EXIT_CODE\n`)(this.state,a,u,g),y=n.join(m,`ps-script-${(0,P.randomUUID)()}.ps1`);await async function(e,t){await d.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(y,v);const w=["-ExecutionPolicy","Bypass"];s||w.push("-NonInteractive"),w.push("-File",y);const b=kt(),S="win32"===process.platform,k=r?.sandboxWorkspaceRoot??a,E=(await st(k,r?.sandboxPolicy)).policy,x=Ne(b,w,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe"],cwd:a,detached:!S},"insecure_none"!==E.type?{...E,sandboxWorkspaceRoot:k}:E,r?.signal);x.on("spawn",(async()=>{try{await l.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid})}catch(e){}}));const C=Ve({stdout:x.stdout,stderr:x.stderr,writable:l,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),_=async()=>{try{const e=await d.readFile(g,"utf8"),{cwd:t,rest:r}=Ue(e);this.state=r,this.cwd=t.trim(),await(0,d.rm)(g).catch((()=>{}))}catch(e){}await(0,d.rm)(y).catch((()=>{}))};let I=null,T=null,R=!1;const A=async e=>{if(!R){if(R=!0,T&&(clearTimeout(T),T=null),(0,p.HF)(i.ctx,"exit"),e)try{await C.waitForOutput()}catch(e){return await _(),void l.throw(e instanceof Error?e:new Error(String(e)))}await C.flush();try{await l.write({type:"exit",code:I,data:"",aborted:r?.signal?.aborted??!1}),await _(),l.close()}catch(e){l.close()}}};x.on("exit",((e,t)=>{I=e;const n=r?.closeTimeout??5e3;n>0&&(T=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),A(!1)}),n))})),x.on("close",(async()=>{await A(!0)})),x.on("error",(e=>{_().catch((()=>{})),l.throw(e)})),yield*l}catch(e){o.error=e,o.hasError=!0}finally{St(o)}}}var xt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Ct{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new Ct(e??this.cwd,this.options)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,p.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),i=(0,f.Jt)(),s=r?.pipeStdin??!1,a={...process.env,...De,...r?.env},l=ht(a)?ft(t):t,c=r?.workingDirectory??this.cwd,u=r?.sandboxWorkspaceRoot??c,d=(await st(u,r?.sandboxPolicy)).policy,h="insecure_none"!==d.type?{...d,sandboxWorkspaceRoot:u}:d,m=Ne(this.options?.shell||process.env.SHELL||"/bin/sh",[...this.options?.shellArgs??[],"-c",l],{env:a,cwd:c,stdio:[s?"pipe":"ignore","pipe","pipe"]},h,r?.signal);m.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:m.stdin??void 0,pid:m.pid})}catch(e){}}));const g=Ve({stdout:m.stdout,stderr:m.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});m.on("error",(e=>{i.throw(e)})),m.on("exit",(async e=>{if((0,p.HF)(o.ctx,"exit"),await g.flush(),h.captureDenies)try{const e=await Ae(m);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:e,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}})),yield*i}catch(e){n.error=e,n.hasError=!0}finally{xt(n)}}}function _t(e){const t="win32"===process.platform,r=e?.shell??(t?kt():void 0),n=process.cwd();return new Ct(n,{...e,shell:r})}const Pt="__CURSOR_ZSH_STATE_START__",It="__CURSOR_ZSH_STATE_END__";var Tt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Rt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class At{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new At(e??this.cwd,this.state)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,p.VI)(e.withName("ZshState.execute")),!1),i=r?.pipeStdin??!1,s=(0,f.Jt)(),a=r?.workingDirectory??this.cwd,l={...process.env,...De,...r?.env};let c='builtin eval "$1"';i||(c+=" < /dev/null");const u=["-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; builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${pt(l)}${c}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],d=r?.sandboxWorkspaceRoot??a,h=(await st(d,r?.sandboxPolicy)).policy,m="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:d}:h,g=Ne(Rt(),u,{env:l,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:a,detached:!0},m,r?.signal);let v="";g.on("spawn",(async()=>{try{await s.write({type:"stdin_ready",stdin:g.stdin??void 0,pid:g.pid})}catch(e){}}));const y=Ve({stdout:g.stdout,stderr:g.stderr,writable:s,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});g.on("error",(e=>{s.throw(e)}));let w=null,b=null,S=!1;const k=async e=>{if(!S){if(S=!0,b&&(clearTimeout(b),b=null),(0,p.HF)(o.ctx,"exit"),e)try{await y.waitForOutput()}catch(e){return void s.throw(e instanceof Error?e:new Error(String(e)))}if(await y.flush(),!r?.signal?.aborted){const e=`${Pt}\n`,t=`${It}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=Ue(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(m.captureDenies)try{const e=await Ae(g);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:w,data:"",aborted:r?.signal?.aborted??!1}),s.close()}catch(e){s.close()}}};g.on("exit",((e,t)=>{w=e;const n=r?.closeTimeout??5e3;n>0&&(b=setTimeout((()=>{S||(console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Killing detached process group.`),function(e,t){if(e)try{process.kill(-e,t)}catch{return}}(g.pid,"SIGKILL"),k(!1))}),n))})),g.on("close",(async()=>{await k(!0)}));const E=g.stdio[3],x=g.stdio[4];Le(E,this.state),Fe(x,(e=>{v+=e})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Tt(n)}}}const Ot="__CURSOR_ZSH_STATE_LIGHT_VALID__",Mt='#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state_light.zsh\n# dump_zsh_state_light\n# Or execute directly (captures a subshell\'s state):\n# ./dump_zsh_state_light.zsh\n\n# Lightweight version that skips function tracking for better performance\n\n# Define a function so sourcing won\'t alter caller state; emulate locally inside\nfunction dump_zsh_state_light() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=${EPOCHREALTIME}\n typeset step_start=${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf \'cursor_snap_%s=$(command base64 -d <<\'\'\'CURSOR_SNAP_EOF_%s\'\'\'\n\' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d \'\n\'\n builtin printf \'\nCURSOR_SNAP_EOF_%s\n\' "$var_name"\n builtin printf \')\n\'\n builtin printf \'eval "$cursor_snap_%s"\n\' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n # Emit validity marker so we can detect if dump_zsh_state_light completed\n _emit "__CURSOR_ZSH_STATE_LIGHT_VALID__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump (light) generated on $(command date +\'%Y-%m-%d %H:%M:%S %z\')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\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_AGENT_STORE\' || true)\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 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 n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Dt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class Nt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Nt(e??this.cwd,this.state)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,p.VI)(e.withName("ZshLightState.execute")),!1),i=r?.pipeStdin??!1,s=(0,f.Jt)(),a=r?.workingDirectory??this.cwd,l={...process.env,...De,...r?.env};let c='builtin eval "$1"';i||(c+=" < /dev/null");const u=pt(l),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; ${Mt} builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${u}${c}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],h=r?.sandboxWorkspaceRoot??a,m=(await st(h,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,v=Ne(Dt(),d,{env:l,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:a,detached:!0},g,r?.signal);let y="";v.on("spawn",(async()=>{try{await s.write({type:"stdin_ready",stdin:v.stdin??void 0,pid:v.pid})}catch(e){}}));const w=Ve({stdout:v.stdout,stderr:v.stderr,writable:s,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});v.on("error",(e=>{s.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)(o.ctx,"exit"),e)try{await w.waitForOutput()}catch(e){return void s.throw(e instanceof Error?e:new Error(String(e)))}if(await w.flush(),!r?.signal?.aborted){const e=`${Ot}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=Ue(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await Ae(v);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:b,data:"",aborted:r?.signal?.aborted??!1}),s.close()}catch(e){s.close()}}};v.on("exit",((e,t)=>{b=e;const n=r?.closeTimeout??5e3;n>0&&(S=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),E(!1)}),n))})),v.on("close",(async()=>{await E(!0)}));const x=v.stdio[3],C=v.stdio[4];Le(x,this.state),Fe(C,(e=>{y+=e})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{jt(n)}}}var $t,Lt,Ft=r("node:perf_hooks");!function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}($t||($t={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(Lt||(Lt={}));const Ut={eventLoopDelayP95Ms:0,eventLoopUtilization:0};let Bt,zt=0;class Wt{eventLoopMonitor;sampleTimer;lastEventLoopUtilization=Ft.performance.eventLoopUtilization();latestSnapshot=Ut;constructor(){this.eventLoopMonitor=(0,Ft.monitorEventLoopDelay)({resolution:Lt.EventLoopResolutionMs}),this.lastEventLoopUtilization=Ft.performance.eventLoopUtilization(),this.eventLoopMonitor.enable(),this.sample(),this.sampleTimer=setInterval((()=>{this.sample()}),Lt.SampleIntervalMs),this.sampleTimer.unref?.()}dispose(){void 0!==this.sampleTimer&&(clearInterval(this.sampleTimer),this.sampleTimer=void 0,this.eventLoopMonitor.disable(),this.latestSnapshot=Ut,this.lastEventLoopUtilization=Ft.performance.eventLoopUtilization())}isUnderPressure(){return this.latestSnapshot.eventLoopDelayP95Ms>=$t.EventLoopDelayP95Ms||this.latestSnapshot.eventLoopUtilization>=$t.EventLoopUtilization}formatSuppressionSection(){const e=this.latestSnapshot,t=[`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms (threshold ${$t.EventLoopDelayP95Ms}ms)`,`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% (threshold ${(100*$t.EventLoopUtilization).toFixed(1)}%)`].join(", "),r=this.getPressureTriggerReasons(e);return`event loop pressure gate enabled; ${r.length>0?`event loop under pressure (${r.join(", ")})`:"event loop not under pressure"}; event loop metrics: ${t}`}getPressureTriggerReasons(e){const t=[];return e.eventLoopDelayP95Ms>=$t.EventLoopDelayP95Ms&&t.push(`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms >= ${$t.EventLoopDelayP95Ms}ms`),e.eventLoopUtilization>=$t.EventLoopUtilization&&t.push(`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% >= ${(100*$t.EventLoopUtilization).toFixed(1)}%`),t}sample(){this.latestSnapshot={eventLoopDelayP95Ms:this.computeEventLoopDelayP95Ms(),eventLoopUtilization:this.computeEventLoopUtilization()}}computeEventLoopDelayP95Ms(){const e=this.eventLoopMonitor.percentile(95);if(this.eventLoopMonitor.reset(),!Number.isFinite(e))return 0;const t=e/1e6;return Math.max(0,t-Lt.EventLoopResolutionMs)}computeEventLoopUtilization(){const e=Ft.performance.eventLoopUtilization(),t=e.active-this.lastEventLoopUtilization.active,r=t+(e.idle-this.lastEventLoopUtilization.idle);return this.lastEventLoopUtilization=e,r<=0||!Number.isFinite(r)?0:t/r}}const Ht=6e4,qt=65536,Gt=2097152,Vt=262144,Jt=1e3,Kt="\n[This shell is producing too much output to stream. The command will still run.]\n";class Zt{bucketChars;bucketStarts;totalChars=0;outputSuppressed=!1;noticeSent=!1;windowMs;minimumThresholdCharsPerSecond;thresholdCharsPerSecondWithoutPressure;minChars;eventLoopPressureTracker;disposed=!1;constructor(e){this.windowMs=e?.windowMs??Ht,this.minimumThresholdCharsPerSecond=e?.minimumThresholdCharsPerSecond??qt,this.thresholdCharsPerSecondWithoutPressure=e?.thresholdCharsPerSecondWithoutPressure??Gt,this.minChars=e?.minChars??Vt;const t=Math.ceil(this.windowMs/Jt)+1;this.bucketChars=new Uint32Array(t),this.bucketStarts=new Float64Array(t)}record(e,t=Date.now()){if(this.disposed)return{shouldForward:!this.outputSuppressed,noticeJustTriggered:!1,charsPerSecond:0,thresholdCharsPerSecond:this.minimumThresholdCharsPerSecond};this.recordChars(e,t);const r=this.getEventLoopPressureTracker().isUnderPressure(),n=this.getCharsInWindow(t),o=this.getAverageCharsPerSecond(t),i=this.getPeakBucketCharsPerSecond(t),s=Math.max(o,i),a=n>=this.minChars,l=a&&s>=this.thresholdCharsPerSecondWithoutPressure,c=a&&r&&o>=this.minimumThresholdCharsPerSecond,u=l?this.thresholdCharsPerSecondWithoutPressure:r?this.minimumThresholdCharsPerSecond:this.thresholdCharsPerSecondWithoutPressure,d=l?s:o;this.outputSuppressed||!l&&!c||(this.outputSuppressed=!0);const h=this.outputSuppressed&&!this.noticeSent;return h&&(this.noticeSent=!0,console.warn("[OutputSuppressionController] Suppressing shell output:",`volume thresholds met (${[`output volume ${(p={charsInWindow:n,charsPerSecond:d,minChars:this.minChars,triggeredThresholdCharsPerSecond:u,suppressWithoutPressure:l,eventLoopPressureTracker:this.getEventLoopPressureTracker()}).charsInWindow} chars in window >= min ${p.minChars}`,`output rate ${Math.round(p.charsPerSecond)} chars/s >= threshold ${p.triggeredThresholdCharsPerSecond} chars/s`].join("; ")}); ${p.suppressWithoutPressure?"event loop pressure gate bypassed due to extreme output rate":p.eventLoopPressureTracker.formatSuppressionSection()}`)),{shouldForward:!this.outputSuppressed,noticeJustTriggered:h,charsPerSecond:d,thresholdCharsPerSecond:u};var p}reset(){this.disposed||(this.bucketChars.fill(0),this.bucketStarts.fill(0),this.totalChars=0,this.outputSuppressed=!1,this.noticeSent=!1)}dispose(){this.disposed||(this.disposed=!0,this.eventLoopPressureTracker?.dispose(),this.eventLoopPressureTracker=void 0)}getEventLoopPressureTracker(){return void 0===this.eventLoopPressureTracker&&(this.eventLoopPressureTracker=function(){zt++,void 0===Bt&&(Bt=new Wt);const e=Bt;let t=!1;return{isUnderPressure:()=>e.isUnderPressure(),formatSuppressionSection:()=>e.formatSuppressionSection(),dispose:()=>{t||(t=!0,zt--,0===zt&&void 0!==Bt&&(Bt.dispose(),Bt=void 0))}}}()),this.eventLoopPressureTracker}recordChars(e,t){if(this.prune(t),e<=0)return;const r=Math.floor(t/Jt)*Jt,n=Math.floor(r/Jt)%this.bucketChars.length;this.bucketStarts[n]!==r&&(this.totalChars-=this.bucketChars[n],this.bucketStarts[n]=r,this.bucketChars[n]=0),this.bucketChars[n]+=e,this.totalChars+=e}getAverageCharsPerSecond(e){if(this.prune(e),0===this.totalChars)return 0;const t=e-this.windowMs;let r=e;for(let e=0;e<this.bucketStarts.length;e++)this.bucketChars[e]>0&&this.bucketStarts[e]>=t&&(r=Math.min(r,this.bucketStarts[e]));const n=Math.max(Jt,Math.min(this.windowMs,e-r+Jt));return this.totalChars/(n/1e3)}getPeakBucketCharsPerSecond(e){this.prune(e);const t=e-this.windowMs;let r=0;for(let e=0;e<this.bucketChars.length;e++)this.bucketStarts[e]>=t&&(r=Math.max(r,this.bucketChars[e]));return r/1}getCharsInWindow(e){return this.prune(e),this.totalChars}prune(e){const t=e-this.windowMs;for(let e=0;e<this.bucketStarts.length;e++)0!==this.bucketStarts[e]&&this.bucketStarts[e]<t&&(this.totalChars-=this.bucketChars[e],this.bucketStarts[e]=0,this.bucketChars[e]=0)}}var Yt=r("../utils/dist/path-utils.js");function Xt(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 Qt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:Xt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}async function er(e,t){const r=await async function(e,t){try{const r=await(0,d.readFile)(e,"utf-8"),n=JSON.parse(r),o=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 n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary&&"custom"!==t.readBoundary)return'Invalid readBoundary: expected "system", "workspace", or "custom"';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"}}(n);if(o)return{success:!1,error:`Invalid sandbox policy: ${o}`};let i=Qt(n);return t&&(i=tr(i,t)),{success:!0,policy:i}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function tr(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Yt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Yt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Yt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}function rr(e,t){if(!e||0===e.length)return{};const r=e.map((e=>e.trim())).filter((e=>""!==e&&!e.startsWith("#")));return 0===r.length?{}:{[t]:r}}function nr(e){switch(e){case je.Zsh:case je.ZshLight:return u("zsh",[]).cmd;case je.Bash:return u("bash",[]).cmd;case je.PowerShell:return kt();default:return process.env.SHELL||"/bin/sh"}}function or(e){try{return u(e,[]).cmd!==e}catch(e){return!1}}function ir(){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=n.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?n.win32.join(t,"bash.exe"):n.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 sr(e){if(e===je.ZshLight)return je.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?ir():void 0,o=void 0!==n||/git.*bash\.exe$/i.test(t)||/program.*git.*bin.*bash\.exe$/i.test(t),i=!r||o;return t.includes("zsh")?je.Zsh:t.includes("bash")&&i?je.Bash:t.includes("pwsh")||t.includes("powershell")?je.PowerShell:n?je.Bash:r&&(or("pwsh")||or("powershell"))?je.PowerShell:or("zsh")?je.Zsh:or("bash")&&i?je.Bash:or("pwsh")||or("powershell")?je.PowerShell:je.Naive}function ar(e){let t=e;if(!e?.userTerminalHint){const r=ir();r&&(t={...e,userTerminalHint:r})}switch(sr(t?.userTerminalHint??"")){case je.Zsh:return new bt((()=>async function(e){const t={...process.env,...De,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state.zsh\n# dump_zsh_state\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state.zsh\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:functions p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_ZSH_STATE_START__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\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_AGENT_STORE' || true)\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`],o=Ne(Rt(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=Be(i,r),a=`${Pt}\n`,l=`${It}\n`;let c;s.startsWith(a)&&s.endsWith(l)?(c=s.slice(a.length),c=c.slice(0,-25)):c=`${process.cwd()}\n`;const{cwd:u,rest:d}=Ue(c);return new At(u,d)}(t)));case je.Bash:return new bt((()=>async function(e){const t={...process.env,...De,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Require base64 for safe encoding of emitted sections\n if ! command -v base64 >/dev/null 2>&1; then\n echo "Error: base64 command is required" >&2\n return 1\n fi\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # Environment variables (export statements)\n # Filter out: proxy settings 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_AGENT_STORE' || true)\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`],o=gt(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const i=Ne(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal);let s="";i.stdout?.on("data",(e=>{s+=e.toString()})),await new Promise((e=>{i.on("close",(()=>{e(void 0)}))}));const a=Be(s,r),l=`${ze}\n`,c=`${We}\n`;let u;a.startsWith(l)&&a.endsWith(c)?(u=a.slice(l.length),u=u.slice(0,-26)):u=`${process.cwd()}\n`;const{cwd:d,rest:h}=Ue(u),p="win32"===process.platform,f="win32"===process.platform?process.cwd():d;return new yt(f,h,e?.userTerminalHint,p)}(t)));case je.PowerShell:return new bt((()=>async function(){return new Et(process.cwd(),"")}()));case je.ZshLight:return new bt((()=>async function(e){const t={...process.env,...De,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`${Mt} builtin printf '${r}\\n'; dump_zsh_state_light`],o=Ne(Dt(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=Be(i,r),a=`${Ot}\n`,l=s.startsWith(a)?s.slice(a.length):s,{cwd:c,rest:u}=Ue(l);return new Nt(c,u)}(t)));default:return _t(t)}}process.platform;const lr={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){r.d(t,{q:()=>he});var n,o,i,s,a,l,c,u,d,h,p,f,m,g,v,y,w,b,S,k,E,x,C,_,P,I,T,R,A,O,M,j,D,N,$,L,F,U,B,z,W,H,q,G,V,J,K,Z,Y,X,Q=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},ee=function(e,t,r,n,o){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?o.call(e,r):o?o.value=r:t.set(e,r),r},te=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const re="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,ne=new Set,oe="object"==typeof process&&process?process:{},ie=(e,t,r,n)=>{"function"==typeof oe.emitWarning?oe.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let se=globalThis.AbortController,ae=globalThis.AbortSignal;if(void 0===se){ae=class{constructor(){this._onabort=[],this.aborted=!1}addEventListener(e,t){this._onabort.push(t)}},se=class{constructor(){this.signal=new ae,t()}abort(e){var t,r;if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);null===(r=(t=this.signal).onabort)||void 0===r||r.call(t,e)}}};let e="1"!==(null===(n=oe.env)||void 0===n?void 0:n.LRU_CACHE_IGNORE_AC_WARNING);const t=()=>{e&&(e=!1,ie("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 le=e=>e&&e===Math.floor(e)&&e>0&&Number.isFinite(e),ce=e=>le(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ue:null:null;class ue extends Array{constructor(e){super(e),this.fill(0)}}class de{static create(e){const t=ce(e);if(!t)return[];ee(o,o,!0,"f",i);const r=new o(e,t);return ee(o,o,!1,"f",i),r}constructor(e,t){if(!te(o,o,"f",i))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=de,i={value:!1};class he{get perf(){return te(this,f,"f")}static unsafeExposeInternals(e){return{starts:te(e,P,"f"),ttls:te(e,I,"f"),sizes:te(e,_,"f"),keyMap:te(e,v,"f"),keyList:te(e,y,"f"),valList:te(e,w,"f"),next:te(e,b,"f"),prev:te(e,S,"f"),get head(){return te(e,k,"f")},get tail(){return te(e,E,"f")},free:te(e,x,"f"),isBackgroundFetch:t=>te(e,s,"m",V).call(e,t),backgroundFetch:(t,r,n,o)=>te(e,s,"m",G).call(e,t,r,n,o),moveToTail:t=>te(e,s,"m",K).call(e,t),indexes:t=>te(e,s,"m",z).call(e,t),rindexes:t=>te(e,s,"m",W).call(e,t),isStale:t=>te(e,$,"f").call(e,t)}}get max(){return te(this,a,"f")}get maxSize(){return te(this,l,"f")}get calculatedSize(){return te(this,g,"f")}get size(){return te(this,m,"f")}get fetchMethod(){return te(this,h,"f")}get memoMethod(){return te(this,p,"f")}get dispose(){return te(this,c,"f")}get onInsert(){return te(this,u,"f")}get disposeAfter(){return te(this,d,"f")}constructor(e){s.add(this),a.set(this,void 0),l.set(this,void 0),c.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),v.set(this,void 0),y.set(this,void 0),w.set(this,void 0),b.set(this,void 0),S.set(this,void 0),k.set(this,void 0),E.set(this,void 0),x.set(this,void 0),C.set(this,void 0),_.set(this,void 0),P.set(this,void 0),I.set(this,void 0),T.set(this,void 0),R.set(this,void 0),A.set(this,void 0),O.set(this,void 0),j.set(this,(()=>{})),D.set(this,(()=>{})),N.set(this,(()=>{})),$.set(this,(()=>!1)),F.set(this,(e=>{})),U.set(this,((e,t,r)=>{})),B.set(this,((e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0})),this[X]="LRUCache";const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:i,updateAgeOnHas:z,allowStale:W,dispose:H,onInsert:q,disposeAfter:G,noDisposeOnSet:V,noUpdateTTL:J,maxSize:K=0,maxEntrySize:Z=0,sizeCalculation:Y,fetchMethod:Q,memoMethod:oe,noDeleteOnFetchRejection:se,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:ue,allowStaleOnFetchAbort:pe,ignoreFetchAbort:fe,perf:me}=e;if(void 0!==me&&"function"!=typeof(null==me?void 0:me.now))throw new TypeError("perf option must have a now() method if specified");if(ee(this,f,null!=me?me:re,"f"),0!==t&&!le(t))throw new TypeError("max option must be a nonnegative integer");const ge=t?ce(t):Array;if(!ge)throw new Error(`invalid max value: ${t}`);if(ee(this,a,t,"f"),ee(this,l,K,"f"),this.maxEntrySize=Z||te(this,l,"f"),this.sizeCalculation=Y,this.sizeCalculation){if(!te(this,l,"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!==oe&&"function"!=typeof oe)throw new TypeError("memoMethod must be a function if defined");if(ee(this,p,oe,"f"),void 0!==Q&&"function"!=typeof Q)throw new TypeError("fetchMethod must be a function if specified");if(ee(this,h,Q,"f"),ee(this,R,!!Q,"f"),ee(this,v,new Map,"f"),ee(this,y,new Array(t).fill(void 0),"f"),ee(this,w,new Array(t).fill(void 0),"f"),ee(this,b,new ge(t),"f"),ee(this,S,new ge(t),"f"),ee(this,k,0,"f"),ee(this,E,0,"f"),ee(this,x,de.create(t),"f"),ee(this,m,0,"f"),ee(this,g,0,"f"),"function"==typeof H&&ee(this,c,H,"f"),"function"==typeof q&&ee(this,u,q,"f"),"function"==typeof G?(ee(this,d,G,"f"),ee(this,C,[],"f")):(ee(this,d,void 0,"f"),ee(this,C,void 0,"f")),ee(this,T,!!te(this,c,"f"),"f"),ee(this,O,!!te(this,u,"f"),"f"),ee(this,A,!!te(this,d,"f"),"f"),this.noDisposeOnSet=!!V,this.noUpdateTTL=!!J,this.noDeleteOnFetchRejection=!!se,this.allowStaleOnFetchRejection=!!ue,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!fe,0!==this.maxEntrySize){if(0!==te(this,l,"f")&&!le(te(this,l,"f")))throw new TypeError("maxSize must be a positive integer if specified");if(!le(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");te(this,s,"m",L).call(this)}if(this.allowStale=!!W,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!z,this.ttlResolution=le(n)||0===n?n:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!le(this.ttl))throw new TypeError("ttl must be a positive integer if specified");te(this,s,"m",M).call(this)}if(0===te(this,a,"f")&&0===this.ttl&&0===te(this,l,"f"))throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!te(this,a,"f")&&!te(this,l,"f")){const e="LRU_CACHE_UNBOUNDED";(e=>!ne.has(e))(e)&&(ne.add(e),ie("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,he))}}getRemainingTTL(e){return te(this,v,"f").has(e)?1/0:0}*entries(){for(const e of te(this,s,"m",z).call(this))void 0===te(this,w,"f")[e]||void 0===te(this,y,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield[te(this,y,"f")[e],te(this,w,"f")[e]])}*rentries(){for(const e of te(this,s,"m",W).call(this))void 0===te(this,w,"f")[e]||void 0===te(this,y,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield[te(this,y,"f")[e],te(this,w,"f")[e]])}*keys(){for(const e of te(this,s,"m",z).call(this)){const t=te(this,y,"f")[e];void 0===t||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield t)}}*rkeys(){for(const e of te(this,s,"m",W).call(this)){const t=te(this,y,"f")[e];void 0===t||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield t)}}*values(){for(const e of te(this,s,"m",z).call(this))void 0===te(this,w,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield te(this,w,"f")[e])}*rvalues(){for(const e of te(this,s,"m",W).call(this))void 0===te(this,w,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield te(this,w,"f")[e])}[(a=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,v=new WeakMap,y=new WeakMap,w=new WeakMap,b=new WeakMap,S=new WeakMap,k=new WeakMap,E=new WeakMap,x=new WeakMap,C=new WeakMap,_=new WeakMap,P=new WeakMap,I=new WeakMap,T=new WeakMap,R=new WeakMap,A=new WeakMap,O=new WeakMap,j=new WeakMap,D=new WeakMap,N=new WeakMap,$=new WeakMap,F=new WeakMap,U=new WeakMap,B=new WeakMap,s=new WeakSet,M=function(){const e=new ue(te(this,a,"f")),t=new ue(te(this,a,"f"));ee(this,I,e,"f"),ee(this,P,t,"f"),ee(this,N,((r,n,o=te(this,f,"f").now())=>{if(t[r]=0!==n?o:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{te(this,$,"f").call(this,r)&&te(this,s,"m",Z).call(this,te(this,y,"f")[r],"expire")}),n+1);e.unref&&e.unref()}}),"f"),ee(this,j,(r=>{t[r]=0!==e[r]?te(this,f,"f").now():0}),"f"),ee(this,D,((o,i)=>{if(e[i]){const s=e[i],a=t[i];if(!s||!a)return;o.ttl=s,o.start=a,o.now=r||n();const l=o.now-a;o.remainingTTL=s-l}}),"f");let r=0;const n=()=>{const e=te(this,f,"f").now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>{r=0}),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=o=>{const i=te(this,v,"f").get(o);if(void 0===i)return 0;const s=e[i],a=t[i];return s&&a?s-((r||n())-a):1/0},ee(this,$,(o=>{const i=t[o],s=e[o];return!!s&&!!i&&(r||n())-i>s}),"f")},L=function(){const e=new ue(te(this,a,"f"));ee(this,g,0,"f"),ee(this,_,e,"f"),ee(this,F,(t=>{ee(this,g,te(this,g,"f")-e[t],"f"),e[t]=0}),"f"),ee(this,B,((e,t,r,n)=>{if(te(this,s,"m",V).call(this,t))return 0;if(!le(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!le(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r}),"f"),ee(this,U,((t,r,n)=>{if(e[t]=r,te(this,l,"f")){const r=te(this,l,"f")-e[t];for(;te(this,g,"f")>r;)te(this,s,"m",q).call(this,!0)}ee(this,g,te(this,g,"f")+e[t],"f"),n&&(n.entrySize=r,n.totalCalculatedSize=te(this,g,"f"))}),"f")},z=function*({allowStale:e=this.allowStale}={}){if(te(this,m,"f"))for(let t=te(this,E,"f");te(this,s,"m",H).call(this,t)&&(!e&&te(this,$,"f").call(this,t)||(yield t),t!==te(this,k,"f"));)t=te(this,S,"f")[t]},W=function*({allowStale:e=this.allowStale}={}){if(te(this,m,"f"))for(let t=te(this,k,"f");te(this,s,"m",H).call(this,t)&&(!e&&te(this,$,"f").call(this,t)||(yield t),t!==te(this,E,"f"));)t=te(this,b,"f")[t]},H=function(e){return void 0!==e&&te(this,v,"f").get(te(this,y,"f")[e])===e},Symbol.iterator)](){return this.entries()}find(e,t={}){for(const r of te(this,s,"m",z).call(this)){const n=te(this,w,"f")[r],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,te(this,y,"f")[r],this))return this.get(te(this,y,"f")[r],t)}}forEach(e,t=this){for(const r of te(this,s,"m",z).call(this)){const n=te(this,w,"f")[r],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,te(this,y,"f")[r],this)}}rforEach(e,t=this){for(const r of te(this,s,"m",W).call(this)){const n=te(this,w,"f")[r],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,te(this,y,"f")[r],this)}}purgeStale(){let e=!1;for(const t of te(this,s,"m",W).call(this,{allowStale:!0}))te(this,$,"f").call(this,t)&&(te(this,s,"m",Z).call(this,te(this,y,"f")[t],"expire"),e=!0);return e}info(e){const t=te(this,v,"f").get(e);if(void 0===t)return;const r=te(this,w,"f")[t],n=te(this,s,"m",V).call(this,r)?r.__staleWhileFetching:r;if(void 0===n)return;const o={value:n};if(te(this,I,"f")&&te(this,P,"f")){const e=te(this,I,"f")[t],r=te(this,P,"f")[t];if(e&&r){const t=e-(te(this,f,"f").now()-r);o.ttl=t,o.start=Date.now()}}return te(this,_,"f")&&(o.size=te(this,_,"f")[t]),o}dump(){const e=[];for(const t of te(this,s,"m",z).call(this,{allowStale:!0})){const r=te(this,y,"f")[t],n=te(this,w,"f")[t],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;if(void 0===o||void 0===r)continue;const i={value:o};if(te(this,I,"f")&&te(this,P,"f")){i.ttl=te(this,I,"f")[t];const e=te(this,f,"f").now()-te(this,P,"f")[t];i.start=Math.floor(Date.now()-e)}te(this,_,"f")&&(i.size=te(this,_,"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=te(this,f,"f").now()-e}this.set(t,r.value,r)}}set(e,t,r={}){var n,o,i,l,h,p,f,g;if(void 0===t)return this.delete(e),this;const{ttl:k=this.ttl,start:_,noDisposeOnSet:P=this.noDisposeOnSet,sizeCalculation:j=this.sizeCalculation,status:$}=r;let{noUpdateTTL:L=this.noUpdateTTL}=r;const z=te(this,B,"f").call(this,e,t,r.size||0,j);if(this.maxEntrySize&&z>this.maxEntrySize)return $&&($.set="miss",$.maxEntrySizeExceeded=!0),te(this,s,"m",Z).call(this,e,"set"),this;let W=0===te(this,m,"f")?void 0:te(this,v,"f").get(e);if(void 0===W)W=0===te(this,m,"f")?te(this,E,"f"):0!==te(this,x,"f").length?te(this,x,"f").pop():te(this,m,"f")===te(this,a,"f")?te(this,s,"m",q).call(this,!1):te(this,m,"f"),te(this,y,"f")[W]=e,te(this,w,"f")[W]=t,te(this,v,"f").set(e,W),te(this,b,"f")[te(this,E,"f")]=W,te(this,S,"f")[W]=te(this,E,"f"),ee(this,E,W,"f"),ee(this,m,(g=te(this,m,"f"),++g),"f"),te(this,U,"f").call(this,W,z,$),$&&($.set="add"),L=!1,te(this,O,"f")&&(null===(n=te(this,u,"f"))||void 0===n||n.call(this,t,e,"add"));else{te(this,s,"m",K).call(this,W);const r=te(this,w,"f")[W];if(t!==r){if(te(this,R,"f")&&te(this,s,"m",V).call(this,r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||P||(te(this,T,"f")&&(null===(o=te(this,c,"f"))||void 0===o||o.call(this,t,e,"set")),te(this,A,"f")&&(null===(i=te(this,C,"f"))||void 0===i||i.push([t,e,"set"])))}else P||(te(this,T,"f")&&(null===(l=te(this,c,"f"))||void 0===l||l.call(this,r,e,"set")),te(this,A,"f")&&(null===(h=te(this,C,"f"))||void 0===h||h.push([r,e,"set"])));if(te(this,F,"f").call(this,W),te(this,U,"f").call(this,W,z,$),te(this,w,"f")[W]=t,$){$.set="replace";const e=r&&te(this,s,"m",V).call(this,r)?r.__staleWhileFetching:r;void 0!==e&&($.oldValue=e)}}else $&&($.set="update");te(this,O,"f")&&(null===(p=this.onInsert)||void 0===p||p.call(this,t,e,t===r?"update":"replace"))}if(0===k||te(this,I,"f")||te(this,s,"m",M).call(this),te(this,I,"f")&&(L||te(this,N,"f").call(this,W,k,_),$&&te(this,D,"f").call(this,$,W)),!P&&te(this,A,"f")&&te(this,C,"f")){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(f=te(this,d,"f"))||void 0===f||f.call(this,...t)}return this}pop(){var e;try{for(;te(this,m,"f");){const e=te(this,w,"f")[te(this,k,"f")];if(te(this,s,"m",q).call(this,!0),te(this,s,"m",V).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}return}finally{if(te(this,A,"f")&&te(this,C,"f")){const t=te(this,C,"f");let r;for(;r=null==t?void 0:t.shift();)null===(e=te(this,d,"f"))||void 0===e||e.call(this,...r)}}}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,o=te(this,v,"f").get(e);if(void 0!==o){const e=te(this,w,"f")[o];if(te(this,s,"m",V).call(this,e)&&void 0===e.__staleWhileFetching)return!1;if(!te(this,$,"f").call(this,o))return r&&te(this,j,"f").call(this,o),n&&(n.has="hit",te(this,D,"f").call(this,n,o)),!0;n&&(n.has="stale",te(this,D,"f").call(this,n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=te(this,v,"f").get(e);if(void 0===n||!r&&te(this,$,"f").call(this,n))return;const o=te(this,w,"f")[n];return te(this,s,"m",V).call(this,o)?o.__staleWhileFetching:o}fetch(e){return Q(this,arguments,void 0,(function*(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=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:g=!1,status:y,signal:b}=t;if(!te(this,R,"f"))return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:y});const S={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:y,signal:b},k=te(this,v,"f").get(e);if(void 0===k){y&&(y.fetch="miss");const t=te(this,s,"m",G).call(this,e,k,S,m);return t.__returned=t}{const t=te(this,w,"f")[k];if(te(this,s,"m",V).call(this,t)){const e=r&&void 0!==t.__staleWhileFetching;return y&&(y.fetch="inflight",e&&(y.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=te(this,$,"f").call(this,k);if(!g&&!o)return y&&(y.fetch="hit"),te(this,s,"m",K).call(this,k),n&&te(this,j,"f").call(this,k),y&&te(this,D,"f").call(this,y,k),t;const i=te(this,s,"m",G).call(this,e,k,S,m),a=void 0!==i.__staleWhileFetching&&r;return y&&(y.fetch=o?"stale":"refresh",a&&o&&(y.returnedStale=!0)),a?i.__staleWhileFetching:i.__returned=i}}))}forceFetch(e){return Q(this,arguments,void 0,(function*(e,t={}){const r=yield this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}))}memo(e,t={}){const r=te(this,p,"f");if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o}=t,i=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(t,["context","forceRefresh"]),s=this.get(e,i);if(!o&&void 0!==s)return s;const a=r(e,s,{options:i,context:n});return this.set(e,a,i),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=te(this,v,"f").get(e);if(void 0!==a){const t=te(this,w,"f")[a],l=te(this,s,"m",V).call(this,t);return i&&te(this,D,"f").call(this,i,a),te(this,$,"f").call(this,a)?(i&&(i.get="stale"),l?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(o||te(this,s,"m",Z).call(this,e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),l?t.__staleWhileFetching:(te(this,s,"m",K).call(this,a),n&&te(this,j,"f").call(this,a),t))}i&&(i.get="miss")}delete(e){return te(this,s,"m",Z).call(this,e,"delete")}clear(){te(this,s,"m",Y).call(this,"delete")}}X=Symbol.toStringTag,q=function(e){var t,r,n;const o=te(this,k,"f"),i=te(this,y,"f")[o],a=te(this,w,"f")[o];return te(this,R,"f")&&te(this,s,"m",V).call(this,a)?a.__abortController.abort(new Error("evicted")):(te(this,T,"f")||te(this,A,"f"))&&(te(this,T,"f")&&(null===(t=te(this,c,"f"))||void 0===t||t.call(this,a,i,"evict")),te(this,A,"f")&&(null===(r=te(this,C,"f"))||void 0===r||r.push([a,i,"evict"]))),te(this,F,"f").call(this,o),e&&(te(this,y,"f")[o]=void 0,te(this,w,"f")[o]=void 0,te(this,x,"f").push(o)),1===te(this,m,"f")?(ee(this,k,ee(this,E,0,"f"),"f"),te(this,x,"f").length=0):ee(this,k,te(this,b,"f")[o],"f"),te(this,v,"f").delete(i),ee(this,m,(n=te(this,m,"f"),--n),"f"),o},G=function(e,t,r,n){const o=void 0===t?void 0:te(this,w,"f")[t];if(te(this,s,"m",V).call(this,o))return o;const i=new se,{signal:a}=r;null==a||a.addEventListener("abort",(()=>i.abort(a.reason)),{signal:i.signal});const l={signal:i.signal,options:r,context:n},c=(n,o=!1)=>{const{aborted:a}=i.signal,c=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(a&&!o?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,c&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),a&&!c&&!o)return u(i.signal.reason);const h=d,p=te(this,w,"f")[t];return(p===d||c&&o&&void 0===p)&&(void 0===n?void 0!==h.__staleWhileFetching?te(this,w,"f")[t]=h.__staleWhileFetching:te(this,s,"m",Z).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,l.options))),n},u=n=>{const{aborted:o}=i.signal,a=o&&r.allowStaleOnFetchAbort,l=a||r.allowStaleOnFetchRejection,c=l||r.noDeleteOnFetchRejection,u=d;if(te(this,w,"f")[t]===d&&(c&&void 0!==u.__staleWhileFetching?a||(te(this,w,"f")[t]=u.__staleWhileFetching):te(this,s,"m",Z).call(this,e,"fetch")),l)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const d=new Promise(((t,n)=>{var s;const a=null===(s=te(this,h,"f"))||void 0===s?void 0:s.call(this,e,o,l);a&&a instanceof Promise&&a.then((e=>t(void 0===e?void 0:e)),n),i.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))}))})).then(c,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),p=Object.assign(d,{__abortController:i,__staleWhileFetching:o,__returned:void 0});return void 0===t?(this.set(e,p,Object.assign(Object.assign({},l.options),{status:void 0})),t=te(this,v,"f").get(e)):te(this,w,"f")[t]=p,p},V=function(e){if(!te(this,R,"f"))return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof se},J=function(e,t){te(this,S,"f")[t]=e,te(this,b,"f")[e]=t},K=function(e){e!==te(this,E,"f")&&(e===te(this,k,"f")?ee(this,k,te(this,b,"f")[e],"f"):te(this,s,"m",J).call(this,te(this,S,"f")[e],te(this,b,"f")[e]),te(this,s,"m",J).call(this,te(this,E,"f"),e),ee(this,E,e,"f"))},Z=function(e,t){var r,n,o,i,a;let l=!1;if(0!==te(this,m,"f")){const o=te(this,v,"f").get(e);if(void 0!==o)if(l=!0,1===te(this,m,"f"))te(this,s,"m",Y).call(this,t);else{te(this,F,"f").call(this,o);const i=te(this,w,"f")[o];if(te(this,s,"m",V).call(this,i)?i.__abortController.abort(new Error("deleted")):(te(this,T,"f")||te(this,A,"f"))&&(te(this,T,"f")&&(null===(r=te(this,c,"f"))||void 0===r||r.call(this,i,e,t)),te(this,A,"f")&&(null===(n=te(this,C,"f"))||void 0===n||n.push([i,e,t]))),te(this,v,"f").delete(e),te(this,y,"f")[o]=void 0,te(this,w,"f")[o]=void 0,o===te(this,E,"f"))ee(this,E,te(this,S,"f")[o],"f");else if(o===te(this,k,"f"))ee(this,k,te(this,b,"f")[o],"f");else{const e=te(this,S,"f")[o];te(this,b,"f")[e]=te(this,b,"f")[o];const t=te(this,b,"f")[o];te(this,S,"f")[t]=te(this,S,"f")[o]}ee(this,m,(a=te(this,m,"f"),--a),"f"),te(this,x,"f").push(o)}}if(te(this,A,"f")&&(null===(o=te(this,C,"f"))||void 0===o?void 0:o.length)){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(i=te(this,d,"f"))||void 0===i||i.call(this,...t)}return l},Y=function(e){var t,r,n;for(const n of te(this,s,"m",W).call(this,{allowStale:!0})){const o=te(this,w,"f")[n];if(te(this,s,"m",V).call(this,o))o.__abortController.abort(new Error("deleted"));else{const i=te(this,y,"f")[n];te(this,T,"f")&&(null===(t=te(this,c,"f"))||void 0===t||t.call(this,o,i,e)),te(this,A,"f")&&(null===(r=te(this,C,"f"))||void 0===r||r.push([o,i,e]))}}if(te(this,v,"f").clear(),te(this,w,"f").fill(void 0),te(this,y,"f").fill(void 0),te(this,I,"f")&&te(this,P,"f")&&(te(this,I,"f").fill(0),te(this,P,"f").fill(0)),te(this,_,"f")&&te(this,_,"f").fill(0),ee(this,k,0,"f"),ee(this,E,0,"f"),te(this,x,"f").length=0,ee(this,g,0,"f"),ee(this,m,0,"f"),te(this,A,"f")&&te(this,C,"f")){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(n=te(this,d,"f"))||void 0===n||n.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){r.d(t,{DN:()=>l,PS:()=>h,ZU:()=>c,fl:()=>p,o1:()=>a,oL:()=>d,yn:()=>s});var n=r("node:fs/promises"),o=r("node:os"),i=r("node:path");function s(e,t){return void 0!==e&&("win32"===process.platform?(0,i.normalize)(e).toLowerCase()===(0,i.normalize)(t).toLowerCase():e===t)}function a(e,t){const r=function(e){return e.replace(/^~(?=$|\/|\\)/,(0,o.homedir)())}(e);return t&&!(0,i.isAbsolute)(r)?(0,i.resolve)(t,r):(0,i.resolve)(r)}function l(e,t){return r=this,o=void 0,l=function*(){const r=a(e,t);let o=r;for(;;)try{const e=yield(0,n.realpath)(o);return(0,i.resolve)(e,(0,i.relative)(o,r))}catch(e){if("ENOENT"!==e.code)return null;const t=(0,i.dirname)(o);if(t===o)return r;o=t}},new((s=void 0)||(s=Promise))((function(e,t){function n(e){try{a(l.next(e))}catch(e){t(e)}}function i(e){try{a(l.throw(e))}catch(e){t(e)}}function a(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(n,i)}a((l=l.apply(r,o||[])).next())}));var r,o,s,l}function c({basePath:e,targetPath:t}){const r=(0,i.resolve)(e),n=(0,i.resolve)(e,t);return r===(0,i.parse)(r).root?(0,i.parse)(n).root===r&&(n===r||n.length>r.length):n===r||n.startsWith(r+i.sep)}function u(e,t){for(const r of t)if(c({basePath:r,targetPath:e}))return!0;return!1}function d(e){return e.replace(/\\/g,"/")}const h="You cannot search other worktrees for this repository, stay within your workspace paths.";function p(e){const{targetPath:t,workspacePaths:r,mainWorktreePath:n}=e;if(void 0===t)return!1;if(0===r.length)return!1;if(!r.every((e=>function(e){return d(e).includes(".cursor/worktrees")}(e))))return!1;if(u(t,r))return!1;const o=(0,i.isAbsolute)(t)?[(0,i.resolve)(t)]:r.map((e=>(0,i.resolve)(e,t))),s=r.map((e=>function(e){var t;const r=d(e),n=r.indexOf("/.cursor/worktrees/");if(-1===n)return;const o=r.slice(n+19).split("/");if(o.length<2)return;const i=null!==(t=o[0])&&void 0!==t?t:"";return 0!==i.length?r.slice(0,n+19+i.length):void 0}(e))).filter((e=>void 0!==e));return!!(s.length>0&&o.some((e=>u(e,s))))||!(void 0===n||!o.some((e=>u(e,[n]))))}},"../utils/dist/writable-iterable.js"(e,t,r){r.d(t,{F8:()=>i,Jt:()=>s,W2:()=>o});var n=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class o extends Error{constructor(e){super(e),this.name="WriteIterableClosedError"}}class i{constructor(e,t){this.writable=e,this.map=t,this.closed=!1}write(e){return n(this,void 0,void 0,(function*(){if(this.closed)throw new o("WritableIterable is closed");const t=this.map(e);yield this.writable.write(t)}))}close(){this.closed||(this.closed=!0)}}function s(){const e=[],t=[];let r,i=!1,s=()=>{},a=()=>{};const l=()=>{const e=new Promise(((e,t)=>{s=e,a=t}));return e.catch((()=>{})),e};let c=l();function u(t,r){for(;e.length>0;){const n=e.shift();r?n.reject(r):n.resolve(t)}}function d(e){t.length=0,a(e),c=Promise.reject(e),c.catch((()=>{}))}return{write(s){return n(this,void 0,void 0,(function*(){if(i)throw null!=r?r:new o("WritableIterable is closed");const n=e.shift();if(n){if(n.resolve({done:!1,value:s}),e.length>0)return}else t.push(s);const a=t.length+1;for(let e=0;e<a;e++)yield c}))},throw(e){i||(i=!0,r=e,d(e),u({done:!0,value:void 0},e))},close(){i||(i=!0,t.length=0,s(),c=Promise.reject(new o("WritableIterable is closed")),c.catch((()=>{})),u({done:!0,value:void 0}))},[Symbol.asyncIterator]:()=>({next(){s(),c=l();const n=t.shift();return void 0!==n?Promise.resolve({done:!1,value:n}):i?r?Promise.reject(r):Promise.resolve({done:!0,value:void 0}):new Promise(((t,r)=>{e.push({resolve:t,reject:r})}))},throw:e=>(i=!0,r=e,t.length=0,d(e),u({done:!0,value:void 0},e),Promise.resolve({done:!0,value:void 0})),return:()=>(i=!0,t.length=0,s(),c=Promise.reject(new Error("Iterator was closed")),c.catch((()=>{})),u({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))})}}}};
|