@cursor/sdk 1.0.29 → 1.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundled/index.js +234 -236
- package/dist/cjs/525.js +1 -0
- package/dist/cjs/executor-common.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/esm/357.js +1 -1
- package/dist/esm/executor-common.d.ts.map +1 -1
- package/dist/esm/index.js +1 -1
- package/package.json +6 -6
- package/dist/cjs/988.js +0 -1
package/dist/cjs/988.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
exports.id=988,exports.ids=[988],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>CC});var n=r("node:buffer"),o=r("node:crypto"),i=r("node:os"),s=r("node:path"),a=r.t(s,2),l=r("../context/dist/otel.js"),c=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 u{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 c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,l.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(c,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{c(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 d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function v(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),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 y=/ \[git: ([^\]]*)\]/;function w(e,t,r){if("object"!=typeof t||null===t)return e;if(y.test(e))return e;const n=t,o=[];if("string"==typeof n.gitErrorCode&&n.gitErrorCode.length>0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let 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(m,v),s.length<=2048?s:`${s.slice(0,2048)}… [truncated to 2048 chars]`}`),i}var b=function(e){return this instanceof b?(this.v=e,this):new b(e)},S=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 b?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])}},k=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 E=(0,d.h)("SimpleControlledExecManager"),x=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),_=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]});class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function I(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class T{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 S(this,arguments,(function*(){const i=performance.now(),s=[],a=yield b(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 b(l)}))}(this)}}class R{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return function(r){return S(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,f=!0,m=k(d);!(i=(h=yield b(m.next())).done);f=!0){l=h.value,f=!1;const e=l,t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-c)),yield yield b(t)}}catch(e){s={error:e}}finally{try{f||i||!(a=m.return)||(yield b(a.call(m)))}finally{if(s)throw s.error}}}finally{const e=u.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield yield b(new p.yT({id:n,hookAdditionalContexts:e})))}}))}(this)}}class A{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,f.Jt)();let a;const l=()=>{a=setTimeout((()=>{s.write(new p.$Y({message:{case:"heartbeat",value:new p.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,m=k(o);!(e=(d=yield m.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=m.return)||(yield l.call(m))}finally{if(r)throw r.error}}yield s.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),C.increment(n,1,{exec_case:i})}catch(e){if(e instanceof f.W2)return;_.increment(n,1,{exec_case:i}),yield s.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:I(e)})}}))}finally{const e=performance.now()-c;x.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 E.error(e,s,{messageCase:t.message.case}),_.increment(e,1,{exec_case:i}),function(){return S(this,arguments,(function*(){yield yield b(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:s})}})),yield yield b(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}}))}))}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var O=function(e){return this instanceof O?(this.v=e,this):new O(e)};function M(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 O?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 O(t.next());if(e.done)return yield O(void 0);yield yield O(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 j=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())}))},D=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=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(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 L=(0,d.h)("ExecutorResource"),U=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}execute(e,t,r){return j(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=D(n,(0,l.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,l.mJ)(i),a=s?new p.Kg(s):void 0,c=this.execManager.createExecInstance(i,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,machineId:null==r?void 0:r.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==(null==r?void 0:r.hookContextCollector)})})),u=yield M(c);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const f=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)U.increment(i,1,{hook_event_name:t.hookEventName})}};f(d);let m=this.deserializeResult(d);for(;void 0===m;){const e=yield M(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,f(d),m=this.deserializeResult(d)}return(()=>j(this,void 0,void 0,(function*(){var e,t,r,n;try{try{for(var o,s=!0,a=$(h);!(e=(o=yield a.next()).done);s=!0)n=o.value,s=!1,f(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){L.info(i,"Ignoring exec stream shutdown during detached drain",{error:e})}})))().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{N(n)}}))}}class z{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=D(a,(0,l.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,f=(0,l.mJ)(h),m=f?new p.Kg(f):void 0,g=this.execManager.createExecInstance(h,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,machineId:null==r?void 0:r.machineId,spanContext:m,acceptHookAdditionalContexts:void 0!==(null==r?void 0:r.hookContextCollector)||!0===(null==r?void 0:r.deliverAgentStoreConflictNotices)})}));try{for(var c,u=!0,d=$(g);!(n=(c=yield F(d.next())).done);u=!0){s=c.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{N(a)}}))}}function W(e,t){return{symbol:Symbol(),remoteImplementation:e,registerControlledImplementation:t}}class H{constructor(e,t){this.resource=e,this.value=t}}class q{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new H(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 G{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 V(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function J(e){return t=>{if(t.message.case===e)return t.message.value}}function K(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function Z(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}W((e=>new B(e,V("adoptArgs"),J("adoptResult"))),((e,t)=>{t.register(new T(e,Z("adoptArgs"),K("adoptResult")))}));const Y=W((e=>new B(e,V("agentStoreConflictArgs"),J("agentStoreConflictResult"))),((e,t)=>{t.register(new T(e,Z("agentStoreConflictArgs"),K("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","gap"]);class X{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}}W((e=>new X),((e,t)=>{}));const Q=W((e=>new B(e,V("backgroundShellSpawnArgs"),J("backgroundShellSpawnResult"))),((e,t)=>{t.register(new T(e,Z("backgroundShellSpawnArgs"),K("backgroundShellSpawnResult")))})),ee=W((e=>new B(e,V("writeShellStdinArgs"),J("writeShellStdinResult"))),((e,t)=>{t.register(new T(e,Z("writeShellStdinArgs"),K("writeShellStdinResult")))}));function te(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 re="local",ne=W((e=>new B(e,V("canvasDiagnosticsArgs"),J("canvasDiagnosticsResult"))),((e,t)=>{t.register(new T(e,Z("canvasDiagnosticsArgs"),K("canvasDiagnosticsResult")))}));Error;const oe=W((e=>new B(e,V("computerUseArgs"),J("computerUseResult"))),((e,t)=>{t.register(new T(e,Z("computerUseArgs"),K("computerUseResult")))})),ie=(W((e=>new B(e,V("conversationSearchArgs"),J("conversationSearchResult"))),((e,t)=>{t.register(new T(e,Z("conversationSearchArgs"),K("conversationSearchResult")))})),W((e=>new B(e,V("deleteArgs"),J("deleteResult"))),((e,t)=>{t.register(new T(e,Z("deleteArgs"),K("deleteResult")))}))),se=W((e=>new B(e,V("diagnosticsArgs"),J("diagnosticsResult"))),((e,t)=>{t.register(new T(e,Z("diagnosticsArgs"),K("diagnosticsResult")))})),ae=W((e=>new B(e,V("fetchArgs"),J("fetchResult"))),((e,t)=>{t.register(new T(e,Z("fetchArgs"),K("fetchResult")))})),le=W((e=>new B(e,V("gitDiffRequest"),J("gitDiffResponse"))),((e,t)=>{t.register(new T(e,Z("gitDiffRequest"),K("gitDiffResponse")))})),ce=W((e=>new B(e,V("grepArgs"),J("grepResult"))),((e,t)=>{t.register(new T(e,Z("grepArgs"),K("grepResult")))})),ue={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"},de={PreToolUse:ue.preToolUse,PermissionRequest:null,PostToolUse:ue.postToolUse,UserPromptSubmit:ue.beforeSubmitPrompt,Stop:ue.stop,SubagentStop:ue.subagentStop,SessionStart:ue.sessionStart,SessionEnd:ue.sessionEnd,PreCompact:ue.preCompact,Notification:null},he=Object.fromEntries(Object.entries(de).filter((e=>null!==e[1])).map((([e,t])=>[t,e]))),pe={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},fe=["Glob"],me=["Notification","PermissionRequest"],ge={warn:()=>{},info:()=>{}};function ve(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 ye(e,t,r=ge){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=ge){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=pe[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):fe.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=ve(t,o);e&&n.push(e)}return n}function we(e,t=ge){const r={};for(const[n,o]of Object.entries(e)){const e=n;if(me.includes(e)){t.warn(`Claude Code event "${e}" is not supported in Cursor and will be ignored`);continue}const i=de[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=ye(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 be(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 Se=e=>"string"==typeof e,ke=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ee=(e,t=[])=>({isValid:e,errors:t});function xe(e,t,r){void 0===e||Se(e)||r.push(`${t} must be a string if provided`)}const Ce=e=>{const t=[];return ke(e)?Ee(!0):(t.push("Expected an object"),Ee(!1,t))},_e=e=>{const t=[],r=Ce(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"),Ee(0===t.length,t)};function Pe(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 Ie=new Set([ue.sessionStart,ue.beforeSubmitPrompt,ue.preToolUse,ue.postToolUse,ue.postToolUseFailure]);function Te(e){return"prompt"===e.type}function Re(e){return"command"===e.type||void 0===e.type}const Ae={[ue.beforeShellExecution]:_e,[ue.beforeMCPExecution]:_e,[ue.afterShellExecution]:e=>{const t=Ce(e);return t.isValid,t},[ue.afterMCPExecution]:e=>{const t=Ce(e);return t.isValid,t},[ue.beforeReadFile]:e=>{const t=[],r=Ce(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"),Ee(0===t.length,t)},[ue.afterFileEdit]:e=>{const t=Ce(e);return t.isValid,t},[ue.beforeTabFileRead]:e=>{const t=[],r=Ce(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"),Ee(0===t.length,t)},[ue.afterTabFileEdit]:e=>Ce(e),[ue.beforeSubmitPrompt]:e=>{const t=Ce(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||Se(e.additional_context)||r.push("additional_context must be a string if provided"),Ee(0===r.length,r)},[ue.stop]:e=>{const t=Ce(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"),Ee(0===r.length,r)},[ue.afterAgentResponse]:e=>{const t=Ce(e);return t.isValid,t},[ue.afterAgentThought]:e=>{const t=Ce(e);return t.isValid,t},[ue.sessionStart]:e=>{const t=Ce(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(ke(e.env))for(const[t,n]of Object.entries(e.env))Se(t)||r.push(`env key "${t}" must be a string`),Se(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||Se(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||Se(e.user_message)||r.push("user_message must be a string if provided"),Ee(0===r.length,r)},[ue.sessionEnd]:e=>{const t=Ce(e);return t.isValid?Ee(!0,[]):t},[ue.preCompact]:e=>{const t=Ce(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Ee(!0,[]);const r=[];if(!ke(e))return r.push("PreCompact response must be an object"),Ee(!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"),Ee(0===r.length,r)},[ue.subagentStart]:e=>{const t=Ce(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||Se(n.user_message)||r.push("user_message must be a string if provided"),Ee(0===r.length,r)},[ue.subagentStop]:e=>{const t=Ce(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"),Ee(0===r.length,r)},[ue.preToolUse]:e=>{const t=[],r=Ce(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"),xe(e.additional_context,"additional_context",t),Ee(0===t.length,t)},[ue.postToolUse]:e=>{const t=[],r=Ce(e);return r.isValid?(xe(e.additional_context,"additional_context",t),Ee(0===t.length,t)):r},[ue.postToolUseFailure]:e=>{const t=Ce(e);if(!t.isValid)return t;const r=[];return xe(e.additional_context,"additional_context",r),Ee(0===r.length,r)},[ue.workspaceOpen]:e=>{const t=Ce(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{Se(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")),Ee(0===r.length,r)}},Oe=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===ue.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===ue.stop?qe(t,r,"Stop"):e===ue.subagentStop?qe(t,r,"SubagentStop"):t,function(e,t,r,n){var o;if(!Ie.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=he[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=[ue.beforeShellExecution,ue.beforeMCPExecution,ue.beforeReadFile,ue.beforeTabFileRead,ue.subagentStart,ue.preToolUse],je=[ue.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 Fe({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:Le(e,i),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:i,shouldNotifyUser:o&&!r}}function Le(e,t){return $e(e)?{permission:"deny",user_message:t}:e===ue.beforeSubmitPrompt||e===ue.sessionStart?{continue:!1,user_message:t}:e===ue.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(!ke(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)"),Ee(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Se(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&&(Se(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)=>{Se(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(Se(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),Ee(0===t.length,t)},Je=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Ee(!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 Ee(0===r.length,r)},Ke=e=>{const t=[];if(!ke(e))return t.push("Hooks config must be an object"),Ee(!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"),!ke(e.hooks))return t.push("Config hooks must be an object"),Ee(!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(ue),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 Ee(0===t.length,t)};var Ze=r("../proto/dist/generated/agent/v1/hooks_pb.js");const Ye=W((e=>new B(e,V("executeHookArgs"),J("executeHookResult"))),((e,t)=>{t.register(new T(e,Z("executeHookArgs"),K("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,f,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 p.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:""},Pe(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(ue.preCompact,o);return new p.S1({response:new p.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:""},Pe(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(ue.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new Ze.W0({permission:null==r?void 0:r.permission,userMessage:null==r?void 0:r.user_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"subagentStop":{const e=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:""},Pe(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(ue.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new Ze.AH({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(ue.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!==(f=e.model)&&void 0!==f?f:""},Pe(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 p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new Ze.u1({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(ue.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:""},Pe(e)),{text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0})),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new Ze.FW}})})}case"afterAgentThought":{const e=M.request.value;return yield this.hookExecutor.executeHookForStep(ue.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:""},Pe(e)),{text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0})),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new Ze.H}})})}case"stop":{const e=M.request.value,t=yield this.hookExecutor.executeHookForStep(ue.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:""},Pe(e)),{status:e.status,loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}));return new p.S1({response:new p.w5({response:{case:"stop",value:new Ze.rT({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!==_?_:""},Pe(e)),{tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd}),n=yield this.hookExecutor.executeHookForStep(ue.preToolUse,r);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new Ze.Wn({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:""},Pe(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(ue.postToolUse,r);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new Ze.uB({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:""},Pe(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(ue.postToolUseFailure,r);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new Ze.U1({additionalContext:null==n?void 0:n.additional_context})}})})}default:return new p.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=W((e=>new B(e,V("lsArgs"),J("lsResult"))),((e,t)=>{t.register(new T(e,Z("lsArgs"),K("lsResult")))})),rt="cursor-ide-browser",nt="cursor-dev-control",ot="custom-user-tools",it=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",rt,nt,ot,"fsd"]);function st(e){return!it.has(e)}const at=new Set([nt,rt]);function lt(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 ct;function ut(e){return void 0===e||void 0===e.serverIdentifiers}function dt(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}!function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(ct||(ct={}));const ht=W((e=>new B(e,V("mcpArgs"),J("mcpResult"))),((e,t)=>{t.register(new T(e,Z("mcpArgs"),K("mcpResult")))})),pt=W((e=>new B(e,V("listMcpResourcesExecArgs"),J("listMcpResourcesExecResult"))),((e,t)=>{t.register(new T(e,Z("listMcpResourcesExecArgs"),K("listMcpResourcesExecResult")))})),ft=W((e=>new B(e,V("readMcpResourceExecArgs"),J("readMcpResourceExecResult"))),((e,t)=>{t.register(new T(e,Z("readMcpResourceExecArgs"),K("readMcpResourceExecResult")))})),mt=W((e=>new B(e,V("mcpStateExecArgs"),J("mcpStateExecResult"))),((e,t)=>{t.register(new T(e,Z("mcpStateExecArgs"),K("mcpStateExecResult")))})),gt=W((e=>new B(e,V("mcpAllowlistPrecheckArgs"),J("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new T(e,Z("mcpAllowlistPrecheckArgs"),K("mcpAllowlistPrecheckResult")))})),vt=W((e=>new B(e,V("miniSweAgentBashArgs"),J("miniSweAgentBashResult"))),((e,t)=>{t.register(new T(e,Z("miniSweAgentBashArgs"),K("miniSweAgentBashResult")))})),yt=W((e=>new B(e,V("piBashArgs"),J("piBashResult"))),((e,t)=>{t.register(new T(e,Z("piBashArgs"),K("piBashResult")))})),wt=W((e=>new B(e,V("piEditArgs"),J("piEditResult"))),((e,t)=>{t.register(new T(e,Z("piEditArgs"),K("piEditResult")))})),bt=W((e=>new B(e,V("piFindArgs"),J("piFindResult"))),((e,t)=>{t.register(new T(e,Z("piFindArgs"),K("piFindResult")))})),St=W((e=>new B(e,V("piGrepArgs"),J("piGrepResult"))),((e,t)=>{t.register(new T(e,Z("piGrepArgs"),K("piGrepResult")))})),kt=W((e=>new B(e,V("piLsArgs"),J("piLsResult"))),((e,t)=>{t.register(new T(e,Z("piLsArgs"),K("piLsResult")))})),Et=W((e=>new B(e,V("piReadArgs"),J("piReadResult"))),((e,t)=>{t.register(new T(e,Z("piReadArgs"),K("piReadResult")))})),xt=W((e=>new B(e,V("piWriteArgs"),J("piWriteResult"))),((e,t)=>{t.register(new T(e,Z("piWriteArgs"),K("piWriteResult")))})),Ct=W((e=>new B(e,V("readArgs"),J("readResult"))),((e,t)=>{t.register(new T(e,Z("readArgs"),K("readResult")))})),_t=W((e=>new B(e,V("redactedReadArgs"),J("redactedReadResult"))),((e,t)=>{t.register(new T(e,Z("redactedReadArgs"),K("redactedReadResult")))}));var Pt=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),It=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),Tt=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),Rt=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),At=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Ot=W((e=>new B(e,V("shellArgs"),J("shellResult"))),((e,t)=>{t.register(new T(e,Z("shellArgs"),K("shellResult")))})),Mt=W((e=>new z(e,V("shellStreamArgs"),J("shellStream"))),((e,t)=>{t.register(new R(e,Z("shellStreamArgs"),K("shellStream")))})),jt=W((e=>new B(e,V("writeArgs"),J("writeResult"))),((e,t)=>{t.register(new T(e,Z("writeArgs"),K("writeResult")))}));var Dt=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())}))},Nt=function(e){return this instanceof Nt?(this.v=e,this):new Nt(e)};function $t(e,t){var r,n;return new Rt.jn({command:null!==(r=t.command)&&void 0!==r?r:"",workingDirectory:null!==(n=t.workingDirectory)&&void 0!==n?n:"",error:e,isReadonly:!0})}function Ft(e){return{execute(t,r){return Dt(this,void 0,void 0,(function*(){return new Rt.W4({result:{case:"permissionDenied",value:$t(e,r)}})}))}}}function Lt(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 Nt?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 Nt(new Rt.FI({event:{case:"permissionDenied",value:$t(e,r)}}))}))}}}function Ut(e){return{execute(t,r){return Dt(this,void 0,void 0,(function*(){return new Pt.Lt({result:{case:"permissionDenied",value:$t(e,r)}})}))}}}function Bt(e){return{execute(t,r){return Dt(this,void 0,void 0,(function*(){return new It.Pi({result:{case:"permissionDenied",value:new It.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}))}}}function zt(e){return{execute(t,r){return Dt(this,void 0,void 0,(function*(){return new Tt.iz({result:{case:"permissionDenied",value:new Tt.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}))}}}function Wt(e){return{execute(t,r){return Dt(this,void 0,void 0,(function*(){return new Pt.nt({result:{case:"error",value:new Pt.Gv({error:e})}})}))}}}const Ht=W((e=>new B(e,V("recordScreenArgs"),J("recordScreenResult"))),((e,t)=>{t.register(new T(e,Z("recordScreenArgs"),K("recordScreenResult")))})),qt=W((e=>new B(e,V("requestContextArgs"),J("requestContextResult"))),((e,t)=>{t.register(new T(e,Z("requestContextArgs"),K("requestContextResult")))}));var Gt=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const Vt=W((e=>new B(e,V("shellAllowlistPrecheckArgs"),J("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new T(e,Z("shellAllowlistPrecheckArgs"),K("shellAllowlistPrecheckResult")))})),Jt=W((e=>new B(e,V("forceBackgroundShellArgs"),J("forceBackgroundShellResult"))),((e,t)=>{t.register(new T(e,Z("forceBackgroundShellArgs"),K("forceBackgroundShellResult")))}));function Kt(e,t){e.hookApprovalRequirement=void 0!==t?new Rt.In(t):void 0}function Zt(e){return e.hookApprovalRequirement}function Yt(e){return(null==e?void 0:e.kind)===Rt.b.FORCE_PROMPT}W((e=>new B(e,V("smartModeClassifierArgs"),J("smartModeClassifierResult"))),((e,t)=>{t.register(new T(e,Z("smartModeClassifierArgs"),K("smartModeClassifierResult")))}));var Xt=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),Qt=r("../proto/dist/generated/agent/v1/subagents_pb.js");class er 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 tr(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 Xt.vS({result:{case:"error",value:new Xt.od({agentId:l,error:a.error})}}):"aborted"===a.status?new Xt.vS({result:{case:"error",value:new Xt.od({agentId:l,error:null!==(o=a.error)&&void 0!==o?o:"Subagent was aborted by the user"})}}):"background"===a.status?new Xt.vS({result:{case:"success",value:new Xt.HJ({agentId:l,finalMessage:a.finalMessage,toolCallCount:null!==(i=a.toolCallCount)&&void 0!==i?i:0,backgroundReason:a.backgroundReason,transcriptPath:a.transcriptPath})}}):new Xt.vS({result:{case:"success",value:new Xt.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 er&&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 Xt.vS({result:{case:"error",value:new Xt.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 rr=W((e=>new B(e,V("subagentArgs"),J("subagentResult"))),((e,t)=>{t.register(new T(e,Z("subagentArgs"),K("subagentResult")))}));W((e=>new B(e,V("subagentAwaitArgs"),J("subagentAwaitResult"))),((e,t)=>{t.register(new T(e,Z("subagentAwaitArgs"),K("subagentAwaitResult")))})),W((e=>new B(e,V("forceBackgroundSubagentArgs"),J("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new T(e,Z("forceBackgroundSubagentArgs"),K("forceBackgroundSubagentResult")))}));class nr{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 or(e){return"string"==typeof e&&e.trim().length>0}const ir=W((e=>new B(e,V("webFetchAllowlistPrecheckArgs"),J("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new T(e,Z("webFetchAllowlistPrecheckArgs"),K("webFetchAllowlistPrecheckResult")))})),sr=e=>String(e).replace(/[\r\n]/g,""),ar="x-inference-authentication-jwt";var lr=r("../proto/dist/generated/agent/v1/agent_pb.js");const cr={textDelta:(e,t)=>new lr.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new lr.Pt({text:e})}}),toolCallStarted:(e,t,r)=>new lr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new lr.xu({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new lr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new lr.LL({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new lr.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new lr.I0({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new lr.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new lr.cH({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t)=>new lr.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new lr.tr({thinkingDurationMs:e})}}),userMessageAppended:e=>new lr.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new lr.v$({userMessage:e})}}),partialToolCall:(e,t,r)=>new lr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new lr.fx({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new lr.Uq({message:{case:"tokenDelta",value:new lr.Fy({tokens:e})}}),summary:e=>new lr.Uq({message:{case:"summary",value:new lr.EC({summary:e})}}),summaryStarted:()=>new lr.Uq({message:{case:"summaryStarted",value:new lr.lW}}),heartbeat:()=>new lr.Uq({message:{case:"heartbeat",value:new lr.ih}}),summaryCompleted:(e,t)=>new lr.Uq({message:{case:"summaryCompleted",value:new lr.ZM({hookMessage:e,failed:t})}}),shellOutputDelta:e=>new lr.Uq({message:{case:"shellOutputDelta",value:new lr.Nn({event:e})}}),turnEnded(e){var t;return new lr.Uq({message:{case:"turnEnded",value:new lr.lJ(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 lr.Uq({message:{case:"stepStarted",value:new lr.dw({stepId:BigInt(e)})}}),stepCompleted:(e,t)=>new lr.Uq({message:{case:"stepCompleted",value:new lr.Lr({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),promptSuggestion:e=>new lr.Uq({message:{case:"promptSuggestion",value:new lr.yf({suggestion:e})}}),activeBranchChange:(e,t)=>new lr.Uq({message:{case:"activeBranchChange",value:new lr.PS({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new lr.Uq({message:{case:"feedbackRequest",value:new lr.ap({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};var ur=r("../agent-kv/dist/index.js");function dr(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 hr=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),pr=r("../proto/dist/generated/agent/v1/mcp_pb.js"),fr=r("@bufbuild/protobuf"),mr=r("@connectrpc/connect"),gr=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_ef7275568c8b1f1f499006dc986c70d2/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),vr=r("../proto/dist/generated/aiserver/v1/utils_pb.js");class yr 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 wr extends yr{get kind(){return"RetriableError"}}class br extends yr{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Sr extends yr{get kind(){return"NonRetriableError"}}class kr extends yr{get kind(){return"CancelledError"}}const Er=new Set([vr.yM.NOT_LOGGED_IN,vr.yM.AGENT_REQUIRES_LOGIN,vr.yM.AUTH_TOKEN_NOT_FOUND,vr.yM.AUTH_TOKEN_EXPIRED,vr.yM.INVALID_AUTH_ID,vr.yM.UNAUTHORIZED,vr.yM.GITHUB_NO_USER_CREDENTIALS,vr.yM.GITHUB_USER_NO_ACCESS]),xr=new Set([vr.yM.FREE_USER_USAGE_LIMIT,vr.yM.FREE_USER_RATE_LIMIT_EXCEEDED,vr.yM.PRO_USER_ONLY,vr.yM.PRO_USER_USAGE_LIMIT,vr.yM.PRO_USER_RATE_LIMIT_EXCEEDED,vr.yM.RATE_LIMITED,vr.yM.RATE_LIMITED_CHANGEABLE,vr.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Cr=new Set([vr.yM.USAGE_PRICING_REQUIRED,vr.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),_r=new Set([vr.yM.BAD_API_KEY,vr.yM.BAD_USER_API_KEY,vr.yM.OUTDATED_CLIENT]),Pr=new Set([vr.yM.USER_ABORTED_REQUEST,vr.yM.DEBOUNCED]),Ir=new Set([vr.yM.CUSTOM_MESSAGE]),Tr=["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"],Rr=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH"]),Ar=new RegExp(`\\b(${[...Rr].join("|")})\\b`),Or=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"];function Mr(e,t={}){const{requestId:r}=t;if(e instanceof yr)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(vr.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,vr.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===mr.Code.Canceled||e.code===mr.Code.Aborted)return Dr(e)?new wr(e.message,h):new kr(e.message,h);if(void 0!==(null==u?void 0:u.error)){const t=u.error;if(Pr.has(t))return new kr(jr(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 br(jr(e,u),r,h);if(Er.has(t))return new br(jr(e,u),"login",h);if(xr.has(t))return new br(jr(e,u),"upgrade",h);if(Cr.has(t))return new br(jr(e,u),"payment",h);if(_r.has(t))return new br(jr(e,u),"config",h);if(Ir.has(t)&&!0!==(null===(a=u.details)||void 0===a?void 0:a.isRetryable))return new Sr(jr(e,u),h);if(!1===(null===(l=u.details)||void 0===l?void 0:l.isRetryable))return new Sr(jr(e,u),h)}return e.code===mr.Code.Unauthenticated?new br(e.message,"login",h):new wr(e.message,h)}(e,r);const n=(0,ur.y_)(e);if(void 0!==n)return new Sr(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 kr(e.message,{cause:e,requestId:r});if("AgentWebSocketDeliveryAmbiguousError"===e.name)return new wr(e.message,{cause:e,requestId:r,isTransport:!0});if(Dr(e))return new wr(e.message,{cause:e,requestId:r})}const o=e instanceof Error?e.message:String(e);return new wr(o,{cause:e instanceof Error?e:void 0,requestId:r})}function jr(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 Dr(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(Tr.some((t=>e.includes(t)))||Ar.test(e))return!0;const n=r.code;if("string"==typeof n&&(Tr.some((e=>n.includes(e)))||Rr.has(n)))return!0;r=r.cause}return!1}function Nr(e){return!0===e.isTransport||(e.cause instanceof Error?Dr(e.cause):Tr.some((t=>e.message.includes(t)))||Ar.test(e.message))}var $r=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())}))},Fr=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},Lr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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}),Ur=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 Br extends Error{constructor(e){super(e),this.name="LostConnection"}}class zr{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}run(e){return $r(this,void 0,void 0,(function*(){var t,r,n,o;const i={stack:[],error:void 0,hasError:!1};try{Fr(i,(0,l.VI)(e.withName("ClientExecController.run")),!1);const u=[];try{try{for(var s,a=!0,c=Ur(this.serverStream);!(t=(s=yield c.next()).done);a=!0){o=s.value,a=!1;const t=o;if((0,fr.isMessage)(t,p.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const r=(()=>$r(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,l.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:null!==(s=r.traceFlags)&&void 0!==s?s:1},"exec.handle",e),p=(0,l.fU)(h)}else h=e;Fr(a,p?new l.r2(h,p):void 0,!1);const f=this.controlledExecManager.handle(h,t);try{for(var c,u=!0,d=Ur(f);!(r=(c=yield d.next()).done);u=!0){i=c.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{Lr(a)}})))();u.push(r)}}catch(e){r={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(r)throw r.error}}yield Promise.all(u)}catch(e){if(e instanceof mr.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Br(e.message);if(e instanceof mr.ConnectError&&e.code===mr.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 Br(e.message)}else{if(e instanceof f.W2)throw new Br(e.message);if(e instanceof mr.ConnectError&&e.code===mr.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Br(e.message)}}throw e}}catch(e){i.error=e,i.hasError=!0}finally{Lr(i)}}))}}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())}))},Hr=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 qr=(0,d.h)("ClientInteractionController"),Gr=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Vr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}run(e){return Wr(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,l.VI)(e.withName("ClientInteractionController.run")),!1);e=u.ctx;let d,h=Promise.resolve();try{for(var s,a=!0,c=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 c.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=>{qr.error(e,"Error handling interaction update",t),null!=d||(d=t)})))}}catch(e){r={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(r)throw r.error}}if(yield h,void 0!==d)throw d}catch(e){i.error=e,i.hasError=!0}finally{Hr(i)}}))}handleInteractionUpdate(e,t){return Wr(this,void 0,void 0,(function*(){yield this.interactionListener.sendUpdate(e,t)}))}handleInteractionQuery(e,t){var r;const n=void 0!==t.query.case&&Gr.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=>{qr.error(e,"Error handling interaction query",t)})).finally(i)}}var Jr=r("../utils/dist/promise-extras.js");function Kr(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 Gt.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Gt.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:null===(t=e.skillOptions)||void 0===t?void 0:t.clone()}),subagents:new Gt.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Gt.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,ur.Bk)(i),(0,ur.Bk)(s),(0,ur.Bk)(a),(0,ur.Bk)(l)]),f=[{blobId:u,blobData:i},{blobId:d,blobData:s},{blobId:h,blobData:a},{blobId:p,blobData:l}],m=new Gt.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 Zr=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 Yr=15728640,Xr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Qr=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),en=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});class tn{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,ur.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,ur.nj)(t),r);return this.transientBytes=o,!0}has(e){return this.transientBlobs.has((0,ur.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}getBlob(e,t){return Zr(this,void 0,void 0,(function*(){const r=(0,ur.nj)(t),n=this.transientBlobs.get(r);return void 0===n?yield this.parent.getBlob(e,t):n}))}persistForRemoteRead(e,t){return Zr(this,void 0,void 0,(function*(){const r=(0,ur.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(yield(0,Jr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}))}setBlob(e,t,r){return Zr(this,void 0,void 0,(function*(){yield this.parent.setBlob(e,t,r)}))}setBlobLocallyOnly(e,t,r){return Zr(this,void 0,void 0,(function*(){yield this.parent.setBlobLocallyOnly(e,t,r)}))}flush(e){return Zr(this,void 0,void 0,(function*(){yield this.parent.flush(e)}))}}function rn(e){const t=void 0===(null==(r=e.tokenDetails)?void 0:r.promptContextUsageTree)?r:new lr.VN(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=rn(n);s!==n&&(o||(i=Object.assign({},e.subagentStates),o=!0),i[t]=new lr.aK(Object.assign(Object.assign({},r),{conversationState:s})))}return n||o?new lr.Y9(Object.assign(Object.assign({},e),{tokenDetails:t,subagentStates:i})):e}const nn=(0,d.h)("@anysphere/agent-client:stall-detector"),on=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type"]}),sn=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type"]}),an=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall"}),ln=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored"});class cn{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 un{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(),ln.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(vn),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"});nn.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(vn);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(nn.warn(this.ctx,d,o),on.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,an.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});nn.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"),sn.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 dn=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 hn=(0,d.h)("@anysphere/agent-client:turn-runner");var pn=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())}))},fn=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},mn=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}),gn=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 vn=(0,Qe.cF)(Symbol("agentStreamMetadata"),void 0),yn=(0,d.h)("@anysphere/agent-client:abort"),wn=(0,d.h)("@anysphere/agent-client:retry"),bn=(0,d.h)("@anysphere/agent-client:request-context-blob");function Sn(e){return pn(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 Zr(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 Zr(this,arguments,void 0,(function*({ctx:e,resources:t,notesSessionId:r}){const n=t.get(qt),o=yield n.execute(e,new Gt._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),Yr),m=yield Kr({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,Xr.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,Xr.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 Xr.increment(e,1,{mode:o,outcome:h?"hydrated":"inline"}),Qr.histogram(e,g,{mode:o}),en.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:Yr,maxInlineDynamicBytes:null!==(c=o.requestContextDynamicInlineMaxBytes)&&void 0!==c?c:1048576,notesSessionId:o.conversationId})}catch(r){t.requestContextParts=void 0,bn.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 kn=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 En(e,t,r){return pn(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c;try{for(n=!0,o=gn(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,cr.shellOutputDelta({case:"stdout",value:new Rt.o0({data:t.event.value.data})}));break;case"stderr":yield r.sendUpdate(e,cr.shellOutputDelta({case:"stderr",value:new Rt.Db({data:t.event.value.data})}));break;case"exit":yield r.sendUpdate(e,cr.shellOutputDelta({case:"exit",value:new Rt.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 xn=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0;function Cn(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function _n(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}function Pn(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 In(e){return e instanceof Error?e.name:void 0}function Tn(e){const t={errorName:In(e)};let r=e;for(let e=0;e<10&&void 0!==r;e++){if(Cn(r)){const e=_n(r),n=Pn(e),o=In(e);return Object.assign(Object.assign({},t),{underlyingConnectError:{code:r.code,codeName:mr.Code[r.code],cause:void 0!==n||void 0!==o?{code:n,name:o}:void 0}})}r=_n(r)}return t}class Rn{constructor(e,t){this.client=e,this.endpointUrl=t,this.hasStartedStream=!1}run(e,t,r,n,o,i,s,a,c,u,d){return pn(this,void 0,void 0,(function*(){var h,p;const f={stack:[],error:void 0,hasError:!1};try{const m=new tn(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){wn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const S=fn(f,(0,l.VI)(e.withName("networkPhase")),!1);e=S.ctx,yield function(e){return dn(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 dn(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 kr("Cancelled during backoff"));const n=setTimeout((()=>{null==t||t.removeEventListener("abort",o),e()}),i+s);function o(){clearTimeout(n),r(new kr("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,N=0,$=!1;const F=()=>{var e;D&&(null===(e=S.onConnectionStateChange)||void 0===e||e.call(S,{state:"connected"}),D=!1)},L=()=>{$=!0,F()},U={handleCheckpoint:(e,t,r)=>dn(this,void 0,void 0,(function*(){var n;$=!0,yield b.handleCheckpoint(e,t,r),P=t,I=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible",F()})),getLatestCheckpoint:()=>b.getLatestCheckpoint()};for(;;){if(w.canceled)throw x.toCancelledError(void 0,O);if(P=void 0,I=void 0,$=!1,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&&hn.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&&hn.info(w,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:A,reason:"resume_action"}))):(e.logging&&hn.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&&hn.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:U,attempt:A,attemptRequestId:O,notifyConnected:F,notifyApplicationProgress:L}),F(),void(e.logging&&hn.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));let n=E.classify(t,{attempt:A,attemptRequestId:O,originalRequestId:C,serverErrorRetries:M,transportErrorRetries:j,endlessRetries:r});if("retry"===n.action&&(void 0!==P?N=0:"resumeAction"===R.action.case&&$&&(N++,N>=2&&(e.logging&&hn.warn(w,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:N,attempt:A,requestId:O,originalRequestId:C,errorName:t instanceof Error?t.name:typeof t}),n={action:"throw",error:new wr("Agent turn stopped after repeated resume attempts made no progress",{cause:t instanceof Error?t:void 0,requestId:O,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}})}))),e.logging){const o="retry"===n.action?`RETRY (countAsServerError=${n.countAsServerError}, countAsTransportError=${n.countAsTransportError})`:`THROW ${n.error.kind}`;hn.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&&hn.warn(w,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(t),requestId:O,originalRequestId:C})}}throw e.logging&&hn.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&&hn.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 lr.QF({action:{case:"resumeAction",value:new lr.qK}}),null===(p=E.onResumeFromCheckpoint)||void 0===p||p.call(E)),yield _(A,w.signal)}}}))}({ctx:e,state:t,action:r,checkpointHandler:c,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},Tn(e))},cancellation:{toCancelledError:()=>new kr("Request cancelled")},hooks:{beginAttempt:()=>{v.value=!1,y.sources=[],y.abortReasonName=void 0,y.abortReasonMessage=void 0,b=++w},runAttempt:t=>pn(this,[t],void 0,(function*({state:t,action:r,checkpointHandler:s,attempt:l,attemptRequestId:c,notifyConnected:h,notifyApplicationProgress:p}){const f=function(e,t,r){return{sendUpdate:(n,o)=>pn(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)&&wn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})})),query:(n,o)=>pn(this,void 0,void 0,(function*(){if(t!==r())throw new kr("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,f,i,m,a,s,u,d,c,g,v,y,h,p,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 yr?e:Mr(e,{requestId:o}),p=(e,t)=>u?!s&&n>=d?{action:"throw",error:e()}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:t()},f=()=>new wr("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}});if(h instanceof kr&&!l){if(t)return p((()=>new wr("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}})),(()=>new wr("Connection stalled",{cause:h.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0}})));if(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(Cn(t)&&(t.code===mr.Code.Canceled||t.code===mr.Code.Aborted))return!0;t=_n(t)}return!1}(h))return p(f,(()=>h))}return a&&(h instanceof br||h instanceof Sr)&&function(e){var t;const r=null===(t=e.displayInfo)||void 0===t?void 0:t.inferenceRequestErrorType;return void 0!==r&&!Or.some((e=>e===r))}(h)?!s&&r>=3?{action:"throw",error:h}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:h instanceof kr||h instanceof br||h instanceof Sr?{action:"throw",error:h}:h instanceof wr&&Nr(h)?p(f,(()=>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.some((e=>"stall_detector"!==e)),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=Tn(e),a=e instanceof yr?e:Mr(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{mn(f)}}))}runInternal(e,t,r,n,o,i,s,a,c,d,h,m,g,v,y,w,b,S){return pn(this,arguments,void 0,(function*(e,t,r,n,o,i,s,a,c,d,h,m,g,v,y,w,b,S,k="agent.request.attempt"){var E,x,C,_,P,I,T;const R={stack:[],error:void 0,hasError:!1};try{const O=e,M=fn(R,(0,l.VI)(e.withName(k)),!1);M.span.setAttribute("agent.attempt",S),M.span.setAttribute("agent.request_id",m),M.span.setAttribute("agent.original_request_id",g),e=M.ctx,e=(0,l.Mf)(e,"agent.request_id",m),e=(e=(0,l.Mf)(e,"agent.original_request_id",g)).with(vn,{requestId:m,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const j=new Set(y.sources);let D=void 0!==y.abortReasonName||void 0!==y.abortReasonMessage;const N=(t,r)=>{if(j.has(t))return;j.add(t),y.sources=[...j];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);D||void 0===n||(D=!0,y.abortReasonName=n.abortReasonName,y.abortReasonMessage=n.abortReasonMessage),yn.error(e,"Agent client stream abort",new Error(t),Object.assign({abortSource:t,requestId:m,conversationId:h.conversationId},null!=r?r:{}))};if(e.signal.aborted){const t=e.signal.reason;N("ctx_signal_abort",dr(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;N("ctx_signal_abort",dr(t))}),{once:!0});const[$,F]=e.withCancel();if(null===(E=a.signal)||void 0===E?void 0:E.aborted){const e=null===(C=a.signal)||void 0===C?void 0:C.reason;N("conversation_action_abort",dr(e)),F()}else null===(x=a.signal)||void 0===x||x.addEventListener("abort",(()=>{var e;const t=null===(e=a.signal)||void 0===e?void 0:e.reason;N("conversation_action_abort",dr(t)),F()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw N("pre_run_cancel",t),new kr("User aborted request")}const L=(0,l.VI)(e.withName("createControlledExecManager")),U=A.fromResources(i);L[Symbol.dispose]();const[B,z]=e.withCancel(),W=new cn,{failThresholdMs:H,advisoryThresholdMs:q}=(e=>{var t;const r=null!==(t=xn(null==e?void 0:e.failTimeoutMs))&&void 0!==t?t:3e4,n=xn(null==e?void 0:e.advisoryTimeoutMs);return{failThresholdMs:r,advisoryThresholdMs:void 0!==n&&n>0&&(r<=0||n<r)?n:void 0}})(h.stallDetectorConfig),G=fn(R,new un(B,{thresholdMs:H,advisoryThresholdMs:q,onStall:()=>{v.value=!0,N("stall_detector",{thresholdMs:H,advisoryThresholdMs:q}),z()},onStallCallback:h.onStall,handlerTracker:W}),!1);let V,J;const K=(0,gr.Jt)(),Z=new f.F8(K,(e=>(G.reset("outbound_write",kn(e)),e))),Y=fn(R,(0,l.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=d.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?fr.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0}))),ee=null!==(P=h.requestContextBlobTransportMode)&&void 0!==P?P:"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===ee&&te?"dual":ee;yield Sn({ctx:e,action:r,resources:i,blobStore:s,options:h,source:"run_request",transportMode:re});const ne=void 0===h.mintLlmGatewayCredential?void 0:yield function(e,t){return r=this,n=void 0,i=function*(){let r;try{r=yield e(t.signal)}catch(e){if(t.isCanceled())throw new kr("User aborted request");throw new Sr("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Sr("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Sr("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new lr.Ib({bearerToken:r.bearerToken})},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.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:m}),oe=new lr.Mp({conversationState:rn(t),action:r,modelDetails:n,requestedModel:h.requestedModel,clientLlmGatewayCredential:ne,mcpTools:new pr.Or({mcpTools:Q}),conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,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!==(I=h.subagentModelOverrides)&&void 0!==I?I:[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsPreviewCard:h.clientSupportsPreviewCard,startedAsNewProject:h.startedAsNewProject,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsPromptContextUsageRpc:h.clientSupportsPromptContextUsageRpc,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,runId:g});if(X=Z.write(new hr.KS({message:{case:"runRequest",value:oe}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw N("post_write_cancel",t),Y[Symbol.dispose](),new kr("User aborted request")}const ie=Object.assign(Object.assign(Object.assign({"x-request-id":m,"x-original-request-id":g},function(e){return Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.parentRequestId?{"x-parent-request-id":sr(e.parentRequestId)}:{}),void 0!==e.rootParentRequestId?{"x-root-parent-request-id":sr(e.rootParentRequestId)}:{}),void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":sr(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("$")?{}:{[ar]:n}}()),null!==(T=h.headers)&&void 0!==T?T:{});V=(0,l.VI)(e.withName("handshakeEstablishment")),V.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const se=this.client.run(V.ctx,K,{signal:B.signal,headers:ie,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===J&&(J=performance.now())}}),ae=performance.now(),le=e=>{var t,r;V&&(V.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==J&&V.span.setAttribute("handshake.preNetworkMs",J-ae),V[Symbol.dispose](),V=void 0),w();const n=performance.now();null===(t=h.onFirstMessage)||void 0===t||t.call(h,n-ae),void 0!==J&&(null===(r=h.onFirstMessageNetwork)||void 0===r||r.call(h,n-J))},ce=()=>{var e;b(),null===(e=h.onFirstNonHeartbeatResponse)||void 0===e||e.call(h,performance.now()-ae,S)},ue=h.onTtftBreakdown?e=>{h.onTtftBreakdown(e,S)}:void 0,{interactionStream:de,execStream:he,checkpointStream:pe,kvStream:fe,done:me}=function(e,t,r,n,o,i,s,a){const l=(0,gr.Jt)(),c=(0,gr.Jt)(),u=(0,gr.Jt)(),d=(0,gr.Jt)();let h=!1,p=!1;return{interactionStream:l,execStream:c,checkpointStream:u,kvStream:d,done:function(){return pn(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=gn(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){wn.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){wn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",kn(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 yr?e:Mr(e);return t instanceof wr&&Nr(t)}(y)&&(wn.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}`;wn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===y?(wn.warn(e,t),w=new wr(t,{isTransport:!0})):y instanceof Error&&"[aborted] aborted"===y.message?(wn.warn(e,`${t}; retrying caught [aborted] aborted error`),w=new wr(t,{cause:y,isTransport:!0})):wn.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,se,G,le,$.signal,e.signal,ce,ue);let ge;const ve={handleCheckpoint:(e,t,r)=>pn(this,void 0,void 0,(function*(){var n;yield c.handleCheckpoint(e,t,r),ge=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"})),getLatestCheckpoint:()=>c.getLatestCheckpoint()};Y[Symbol.dispose]();const ye=5e3;let we;const be=()=>{we=setTimeout((()=>{Z.write(new hr.KS({message:{case:"clientHeartbeat",value:new hr.kA}})).then((()=>G.onClientSentHeartbeat()),(()=>{})),be()}),ye)},Se=()=>{void 0!==we&&(clearTimeout(we),we=void 0)};be();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,s=new Rt.a({command:(null===(_=n.shellCommand)||void 0===_?void 0:_.command)||"",parsingResult:new Rt.HO,skipApproval:!0}),a=i.get(Mt).execute(e,s,{execId:n.execId}),l=new Vr(de,o,new f.F8(Z,(e=>new hr.KS({message:{case:"interactionResponse",value:e}}))),G);t={run:e=>pn(this,void 0,void 0,(function*(){yield Promise.all([W.track("handleShellStream",En(e,a,o)),W.track("interactionController",l.run(e))])}))}}else{const e=new Vr(de,o,new f.F8(Z,(e=>new hr.KS({message:{case:"interactionResponse",value:e}}))),G);t={run:t=>pn(this,void 0,void 0,(function*(){yield W.track("interactionController",e.run(t))}))}}void 0!==X&&(yield Promise.race([X,me.catch((()=>{}))]));const l=new f.F8(Z,(e=>{if((0,fr.isMessage)(e,p.yT))return new hr.KS({message:{case:"execClientMessage",value:e}});if((0,fr.isMessage)(e,p.$Y))return new hr.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,fr.isMessage)(e)?e.getType().typeName:typeof e})`)})),c=new zr(he,l,U),S=new ur.hC(fe,new f.F8(Z,(e=>new hr.KS({message:{case:"kvClientMessage",value:e}}))),s,{beforeGetBlob:(e,t)=>pn(this,void 0,void 0,(function*(){return s.persistForRemoteRead(e,t)}))}),k=new u(pe,ve,e);let E,x;const C={promise:new Promise(((e,t)=>{E=e,x=t})),resolve:E,reject:x};$.canceled?(C.resolve(),de.close()):$.signal.addEventListener("abort",(()=>{C.resolve(),de.close()}),{once:!0}),c.run($).then(C.resolve).catch(C.reject);const P=Promise.allSettled([W.track("streamSplitter",me.finally((()=>{Se(),a.close(),l.close()}))),W.track("execHandler",C.promise),t.run(e),W.track("checkpointController",k.run()),W.track("kvHandler",S.run(e)),W.track("conversationActionManager",a.run(e,{write:t=>pn(this,void 0,void 0,(function*(){yield Sn({ctx:e,action:t,resources:i,blobStore:s,options:h,source:"queued_action"}),yield Z.write(new hr.KS({message:{case:"conversationAction",value:t}}))}))}))]);let I,T;const R={promise:new Promise(((e,t)=>{I=e,T=t})),resolve:I,reject:T};P.then(R.resolve).catch(R.reject),e.canceled?R.reject(new kr("User aborted request")):e.signal.addEventListener("abort",(()=>R.reject(new kr("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?z():function(e){var t;const r=null!==(t=e.lingerMs)&&void 0!==t?t:6e3;return new Promise((t=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout((()=>o("linger_timed_out")),r);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:me,lingerMs:h.softCancelLingerMs}).then((t=>{wn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:m}),z()}))};$.canceled?(A(),R.reject(new kr("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),R.reject(new kr("User aborted request"))}),{once:!0});const M=yield R.promise,j=M[0],D=M[1],N=M[3],F=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===N.status)throw new Sr("Checkpoint persistence failed",{cause:N.reason instanceof Error?N.reason:void 0,requestId:m,displayInfo:{title:"Checkpoint persistence failed",detail:F(N),isRetryable:!1}});const L="ineligible_terminal_turn"===ge;if(L){const t=Object.assign(Object.assign({},"rejected"===j.status?{streamSplitter:F(j)}:{}),"rejected"===D.status?{execHandler:F(D)}:{});Object.keys(t).length>0&&wn.warn(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===j.status&&!L)throw j.reason;if("rejected"===D.status&&!L)throw D.reason;$.canceled||(yield this.processUnprocessedMessages(O,a,ve,n,o,i,s,d,h,m,g,v,y,G,w,b))}finally{Se(),V&&(V[Symbol.dispose](),V=void 0)}}catch(e){R.error=e,R.hasError=!0}finally{mn(R)}}))}processUnprocessedMessages(e,t,r,n,o,i,s,a,l,c,u,d,h,p,f,m){return pn(this,void 0,void 0,(function*(){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),p[Symbol.dispose]();const w=r.getLatestCheckpoint();try{yield this.runInternal(e,v,new lr.QF({action:{case:"userMessageAction",value:new lr.Vt({userMessage:y})}}),n,o,i,s,t,r,a,l,c,u,d,h,f,m,0,"agent.request.queuedMessage")}catch(e){throw w===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}))}}var An=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),On=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),Mn=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),jn=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Dn=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Nn=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),$n=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");Error;const Fn=e=>new lr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new $n.lI({result:{case:"approved",value:new $n.XJ}})}}),Ln=(e,t)=>new lr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new $n.lI({result:{case:"rejected",value:new $n.yc({reason:null!=t?t:""})}})}}),Un=e=>new lr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Nn.fS({result:{case:"approved",value:new Nn.Hs}})}}),Bn=(e,t)=>new lr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Nn.fS({result:{case:"rejected",value:new Nn.m$({reason:null!=t?t:""})}})}}),zn=(e,t)=>new lr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new lr.zT({result:t})}}),Wn=e=>new lr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Dn.w$({result:{case:"approved",value:new Dn.q5}})}}),Hn=(e,t)=>new lr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Dn.w$({result:{case:"rejected",value:new Dn.rA({reason:null!=t?t:""})}})}}),qn=(e,t)=>new lr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new On.gz({result:t})}}),Gn=(e,t)=>new lr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Vn=(e,t)=>new lr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),Jn=(e,t)=>new lr.Y5({id:e,result:{case:"prManagementResult",value:t}}),Kn=(e,t)=>new lr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new jn.h({result:{case:"rejected",value:new jn.OI({reason:null!=t?t:"Authentication was rejected"})}})}}),Zn=(e,t)=>new lr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new An.qG({result:{case:"rejected",value:new An.lB({reason:null!=t?t:"Connecting GitHub was skipped"})}})}}),Yn=(e,t)=>new lr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Mn.vW({result:{case:"approved",value:new Mn.l3({description:null!=t?t:""})}})}});var Xn=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js");Error;var Qn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),eo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),to=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 ro=(0,mr.createContextKey)(void 0,{description:"anysphere.callerContext"});function no(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function oo(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:Qn.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):null==t||t.setStatus({code:Qn.s.OK}),null==t||t.end(),null==r||r())};return{next(){return to(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 to(this,void 0,void 0,(function*(){return i(),n.return?n.return(e):{done:!0,value:void 0}}))},throw(e){return to(this,void 0,void 0,(function*(){if(i(e),n.throw)return n.throw(e);throw e}))}}}}}function io(...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 so(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,c={})=>{var u;const d=(0,l.fR)(s.withName(`rpc.${String(o)}`),{kind:eo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),h=(0,l.fU)(d);let p;try{let o;if(r&&(o=function(e){var t,r;const n=new Headers;try{const o=(0,l.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=io(o,e))}const s=io(c.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,c.signal):{signal:c.signal,cleanup:void 0};p=g;const v=(null!==(u=c.contextValues)&&void 0!==u?u:(0,mr.createContextValues)()).set(ro,d),y=Object.assign(Object.assign({},c),{headers:s,signal:m,contextValues:v}),w=i.call(e,a,y);return no(w)?oo(w,h,p):null!==(f=w)&&"object"==typeof f&&"then"in f&&"function"==typeof f.then?w.then((e=>no(e)?oo(e,h,p):(null==h||h.setStatus({code:Qn.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:Qn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e})):(null==h||h.setStatus({code:Qn.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:Qn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e}var f}}})}var ao=r("../utils/dist/workspace-paths.js");function lo(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return(null==e?void 0:e.trim())?e:(0,s.join)((0,i.homedir)(),".cursor")}(),"projects")}function co(e){return(0,s.join)(lo(),(0,ao.r_)(e))}var uo=r("node:fs/promises"),ho=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),po=r("node:fs"),fo=r("../shell-exec/dist/index.js"),mo=r("./src/agent/native/tree-sitter.webpack.cjs"),go=r("./src/agent/native/tree-sitter-bash.webpack.cjs");let vo;const yo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function bo(e){const t=function(){if(void 0!==vo)return vo;try{const e=new mo;e.setLanguage(go),vo=e}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;vo=null,console.warn("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return vo}();if(null===t)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=t.parse(e),n=new WeakSet;let o=!1,i=!0;const s={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},l=e=>{o=!0,a.hasRedirects=!0,i=i&&e},c=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,i=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>c(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),s=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),l={operator:n,destinationFds:i,targetNodeType:o?.type??""};if(void 0!==s&&(l.targetText=s),a.redirects.push(l),">&"===n){const e=c(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of i)t.fdTargets.set(e,"unsafe");return!1}for(const e of i)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=c(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of i)t.fdTargets.set(e,"unsafe");return!1}for(const e of i)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of i)t.fdTargets.set(e,"unsafe");return!1}for(const e of i)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<<?<?/.test(t)&&(s.hasInputRedirect=!0),(/(^|\s)[0-9]*>>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(s.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(s.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void l(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void l(!1);l(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)yo.has(r.type)&&h(r,t)})(t),yo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{s.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of t.childrenForFieldName("argument"))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||s.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?s.simpleCommands.includes(e.text)||s.simpleCommands.push(e.text):s.simpleCommands.push(t.text)}}else s.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=i),{legacy:s,structured:a}}var So=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),ko=r("../utils/dist/path-utils.js");const Eo=async e=>{const t=(0,ko.o1)(e);try{return await(0,uo.realpath)(t)}catch{return t}},xo="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Co="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",_o=/\$\(|`|<\(|>\(/,Po=/[;&|]/;let Io,To,Ro,Ao;function Oo(){if(void 0===Io){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Io=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Io}function Mo(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 jo(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Do(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 No(){if(void 0===Ao){const e=(process.env[xo]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xo} (expected "allow" or "deny"); using "deny".`);const r=jo("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Co]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=jo(Co)),Ao={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:jo("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Do("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ao}function $o(e,t,r={}){const n=[Mo(e),Mo(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 Fo(e,t){const r=function(){const e=No();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===To&&(To=$o("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),To);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(_o.test(e))return r;const i=(void 0===Ro&&(Ro=$o("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ro);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||i?.test(t)||Po.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=No();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 Lo=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Uo(e){if(!e)return;let t;return"allow"===e.default?t=Lo.h1.ALLOW:"deny"===e.default&&(t=Lo.h1.DENY),new Lo.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Lo.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function Bo(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 Lo.h1.ALLOW:t.default="allow";break;case Lo.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,fo.networkAllowAllPolicy)():(0,fo.networkDisabledPolicy)())}function zo(e){switch(e){case"system":return Lo.Sz.SYSTEM;case"workspace":return Lo.Sz.WORKSPACE;default:return Lo.Sz.UNSPECIFIED}}function Wo(e){const t=function(e){switch(e){case Lo.Sz.SYSTEM:return"system";case Lo.Sz.WORKSPACE:return"workspace";case Lo.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function Ho(e){if(!e)return{type:"insecure_none"};switch(e.type){case Lo.vc.INSECURE_NONE:case Lo.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Lo.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:Bo(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,...Wo(e)};case Lo.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Bo(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...Wo(e)};default:return{type:"insecure_none"}}}function qo(e){if(e)return"insecure_none"===e.type?new Lo.Mw({type:Lo.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Lo.Mw({type:Lo.vc.WORKSPACE_READWRITE,networkAccess:(0,fo.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:Uo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:zo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Lo.Mw({type:Lo.vc.WORKSPACE_READONLY,networkAccess:(0,fo.isNetworkEnabledByPolicy)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Uo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:zo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Lo.Mw({type:Lo.vc.INSECURE_NONE})}function Go(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||""===e||""===e||""===e||"\ufeff"===e}function Vo(e){let t="",r=!1;for(const n of e)Go(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function Jo(e){return e.length>0&&[...e].every((e=>"*"===e))}function Ko(e){const t=e.indexOf(":");if(t<=0)return;const r=e.slice(0,t).trim();return[...r].some((e=>0===e.trim().length))?void 0:{executablePattern:r,argsPattern:e.slice(t+1).trim()}}function Zo(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}}function Yo({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const Xo={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function Qo(e){let t="",r="plain",n=0;for(;n<e.length;){const o=e[n];if("plain"===r){"$"===o&&"'"===e[n+1]?(r="ansi",n+=2):"$"===o&&'"'===e[n+1]?(r="double",n+=2):"'"===o?(r="single",n++):'"'===o?(r="double",n++):"\\"===o&&n+1<e.length?("\n"!==e[n+1]&&(t+=e[n+1]),n+=2):(t+=o,n++);continue}if("single"===r){"'"===o?r="plain":t+=o,n++;continue}if("double"===r){if('"'===o){r="plain",n++;continue}if("\\"===o&&n+1<e.length){const r=e[n+1];if("$"===r||"`"===r||'"'===r||"\\"===r||"\n"===r){"\n"!==r&&(t+=r),n+=2;continue}}t+=o,n++;continue}if("'"===o){r="plain",n++;continue}if("\\"!==o||n+1>=e.length){t+=o,n++;continue}const i=e[n+1],s=Xo[i];if(void 0!==s){t+=s,n+=2;continue}const a="x"===i?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===i?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===i?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],l="u"===i||"U"===i,c="x"===i||l?16:8;if(void 0!==a){const e=Number.parseInt(a,c);if(!l||e<=1114111){t+=l?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===c?2:1);continue}}t+=i,n+=2}return Vo(t)}function ei({rule:e,command:t}){const r=Vo(e).trim();return 0!==r.length&&(null!==function(e){const t=Vo(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Jo(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=Ko(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Jo(e)&&(0===t.length||Jo(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Vo(t).trim(),Qo(t).trim()].some((e=>function(e,t){const r=Ko(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),i=-1===o?t:t.slice(0,o),s=-1===o?"":t.slice(o+1).trim();if(Zo(e,i)&&Zo(n,s))return!0}return e.includes("*")?Zo(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ti({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>ei({rule:e,command:t}))))return e}function ri(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ni({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ti({matchForms:Yo({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:ri(n)}var oi=r("../utils/dist/lru-cache.js"),ii=r("node:util"),si=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),ai=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");const li="utf8",ci="utf8bom",ui="latin1",di={"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 hi(e){const t=e.toLowerCase();return"latin-1"===t?ui:"utf-8"===t?li:"utf-8-bom"===t||"utf-8 bom"===t?ci:t}var pi,fi=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())}))},mi=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)}))}}},gi=function(e){return this instanceof gi?(this.v=e,this):new gi(e)},vi=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:gi(e[n](t)),done:!1}:o?o(t):t}:o}};!function(e){e.CRLF="CRLF",e.LF="LF"}(pi||(pi={}));const yi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],wi=new Set(yi),bi=new ii.TextDecoder("utf-8",{fatal:!0}),Si=new ii.TextDecoder("latin1"),ki=Buffer.from([239,187,191]),Ei=new Map,xi=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...yi]),Ci=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i;function _i(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Pi(e){const t=_i(e);return wi.has(t)}function Ii(e){const t=_i(e);return{encoding:"binary",lineEnding:pi.LF,isBinaryFile:!0,isImageFile:Ci.test(t),isVideoFile:wi.has(t)}}function Ti(e,t){return fi(this,void 0,void 0,(function*(){const r=yield(0,uo.readFile)(e),n=Mi(r);if(n.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const o=Ei.get(e);let i;i=t||o||n.encoding;const{text:s,encoding:a}=function(e,t){const r=hi(t);if(r===li||r===ci||"ascii"===r){const t=Li(e);return r===ci&&t.encoding===li?{text:t.text,encoding:ci}:t}if(r===ui)return{text:Si.decode(e),encoding:ui};try{const t=function(e){return di[e]||e}(r);if(si.encodingExists(t))return{text:si.decode(e,t),encoding:r}}catch(e){}return Li(e)}(r,i),l=function(e){return e.startsWith("\ufeff")?e.slice(1):e}(s);return Fi(e,a===li&&Ui(r)?ci:a),n.lineEnding===pi.CRLF?l.replaceAll("\r\n","\n"):l}))}function Ri(e,t,r,n){return fi(this,void 0,void 0,(function*(){let o;try{o=r?yield function(e,t){return fi(this,void 0,void 0,(function*(){try{return yield Ai(e)}catch(e){}const r=_i(e);if(xi.has(r))return Ii(e);try{return yield function(e){return fi(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=mi(Ni(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 Ai(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:$i()}))}(t)}catch(e){return $i()}}))}(e,r):yield Ai(e)}catch(t){const r=_i(e);o=xi.has(r)?Ii(e):$i()}const i=Ei.get(e);if(!o.isBinaryFile){let t;t=hi(n||i||o.encoding);const r=t===ci||t===li&&!n&&(yield function(e){return fi(this,void 0,void 0,(function*(){try{return Ui(yield Di(e))}catch(e){return!1}}))}(e));o=Object.assign(Object.assign({},o),{encoding:r?ci:t}),Fi(e,o.encoding)}const s=Oi(t);if(o.lineEnding===pi.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===ci?Buffer.concat([ki,si.encode(t,li,{defaultEncoding:li})]):si.encode(t,o.encoding,{defaultEncoding:li}),format:o}}))}function Ai(e){return fi(this,void 0,void 0,(function*(){const t=Mi(yield Di(e));return t.isBinaryFile?Object.assign(Object.assign({},t),{isVideoFile:Pi(e)}):Object.assign(Object.assign({},t),{isVideoFile:!1})}))}function Oi(e){if(""===e)return 1;let t=1;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}function Mi(e){if(0===e.length)return $i();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:ji(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:ji(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:pi.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:ji(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=ai.detect(e);let s=i.confidence>.7?i.encoding:"utf-8";return"ascii"===s&&(s="utf-8"),{encoding:null!=s?s:"utf-8",lineEnding:ji(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function ji(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?pi.LF:t/(t+r)*100>=5?pi.CRLF:pi.LF}function Di(e){return fi(this,void 0,void 0,(function*(){const t=yield(0,uo.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 Ni(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 gi?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 gi((0,uo.readdir)(e,{withFileTypes:!0}));for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield gi(yield*vi(mi(Ni(r))))):n.isFile()&&(yield yield gi(r))}}catch(e){return yield gi(void 0)}}))}function $i(){return{encoding:li,lineEnding:"win32"===process.platform?pi.CRLF:pi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Fi(e,t){if(Ei.has(e)&&Ei.delete(e),Ei.set(e,t),Ei.size<=100)return;const r=Ei.keys().next().value;void 0!==r&&Ei.delete(r)}function Li(e){try{return{text:bi.decode(e),encoding:li}}catch(t){return{text:Si.decode(e),encoding:ui}}}function Ui(e){return e.length>=ki.length&&e[0]===ki[0]&&e[1]===ki[1]&&e[2]===ki[2]}var Bi=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),zi=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class Wi{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.ttlMs="function"==typeof e?e:Wi.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 Hi=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 qi(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:o=[],caseSensitive:s=!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,i.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),c&&h.push("--no-ignore-vcs"),s&&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,fo.spawnInSandbox)((0,fo.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{Hi(r)}}(),didTimeout:g}}let Gi;function Vi({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 Ji{constructor(e=()=>function(e=process.env){if(void 0!==Gi)return Gi;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 Wi({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(Vi(e))}walk(e,t){const r=Vi(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=qi(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 Ki(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}async function Zi(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Yi(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 Xi(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 Qi=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],es=[".gitignore",".cursorignore"];async function ts(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ko.DN)(e);return null===t?null:t}async function rs(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}class ns{constructor(e,t,r){this.ignoreServicePromise=is.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()))}getShellSandboxIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getShellSandboxIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}}const os=Math.min(8,Math.max(1,Math.floor(i.availableParallelism()/2)));class is{constructor(e,t,r,n,o){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.gitIgnoreCache=new oi.q({max:2e3}),this.cursorIgnoreCache=new oi.q({max:2e3}),this.gitRootCache=new oi.q({max:1e3}),this.gitRemoteUrlCache=new oi.q({max:200}),this.hasGitDirCache=new oi.q({max:1e3}),this.gitParsedIgnoreCache=new Map,this.cursorParsedIgnoreCache=new Map}static getRipwalkCache(){return is.ripwalkCache??=new Ji,is.ripwalkCache}getIgnoreInstance(e,t,r){let n=r.get(e);return n||(n=Bi().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,ko.DN)(e)??(0,ko.o1)(e)}static async init(e,t,r,n){const o=await(0,Jr.PH)(r,(async e=>{const t=await(0,ko.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),i={},s={},a=(await(0,Jr.PH)(o,(r=>Ki(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([is.initializeIgnoreMapping(a,".gitignore",i),is.initializeIgnoreMapping(o,".cursorignore",s)]),new is(t,i,s,n,o)}static async preloadHierarchy(e,t,r,n){let o=(0,ko.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await is.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,uo.access)(n,uo.constants.F_OK);const t=await Ti(n),o=is.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=is.deduplicateRootDirectories(e),o=await is.promiseQueue.enqueueList(n,(e=>is.findFilesWithRipgrep(e,t))),i=Array.from(o.values()).flat();await Promise.all(i.map((async e=>{try{const t=await Ti(e),n=is.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const a=new Set;for(const e of n)await is.preloadHierarchy(e,t,r,a)}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:es.map((e=>`**/${e}`)),excludeGlobs:Qi,source:"ignore_scan"},i=is.getRipwalkCache().walk(r,o);for await(const r of i.lines)(0,s.basename)(r)===t&&n.push((0,s.join)(e,r));return n}async handleManualLookupWhenNoWorkspaceDirs(e,t){const r={};let n=(0,s.dirname)(e);const o=(0,s.parse)(n).root;for(;;){const e=(0,s.join)(n,t);try{const t=await Ti(e),o=is.parseIgnoreRules(t);o.length>0&&(r[n]=o)}catch{}if(n===o)break;n=(0,s.dirname)(n)}return this.testIgnored(e,r,((e,t)=>Bi().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,s.dirname)((0,ko.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){if(this.rootDirectories.some((e=>(0,ko.ZU)({basePath:e,targetPath:n})))){n=(0,s.dirname)(n);continue}if(void 0!==r[n])break;o.push(n);const e=(0,s.dirname)(n);if(e===n)break;n=e}o.length>0&&(await is.promiseQueue.enqueueList(o,(e=>is.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,ko.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ko.oL)(t),l=i.test(a);if(l.ignored&&!l.unignored)return!0;const c=i.test(`${a}/`);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,ko.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,uo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(){const e={...this.cursorIgnoreMapping};for(const t of this.rootDirectories){const r=await this.getRepoBlockExcludeGlobs(t);if(0===r.length)continue;const n=e[t];e[t]=n?[...n,...r]:r}return e}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ko.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,s.dirname)(e),r=await Ti(e),n=is.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Ti(e),n=is.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ko.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const l=(0,s.parse)(a).root;for(;a!==l;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,uo.access)((0,s.join)(e,".git"),uo.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),r=await(this.teamSettingsService?.getTeamRepos());if(!r)return!1;const n=r.repos??[],o=r.disableLocalExecAllowlistEnforcement?[]:r.allowedRepos??[];if(0===n.length&&0===o.length)return!1;if(0===t.length)return this.checkNonRepoPathBlockedByAllowlist(e,o);let i=0===o.length,a=!1;for(const r of t){let t;if(this.gitRemoteUrlCache.has(r)?t=this.gitRemoteUrlCache.get(r):(t=await Zi((0,Qe.q6)(),this.gitExecutor,r),void 0!==t&&this.gitRemoteUrlCache.set(r,t)),void 0===t)continue;const l=t,c=(0,s.relative)(r,e)||".";for(const e of n)if(this.doesRepoUrlMatch(e.url,l))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,c))return!0;o.length>0&&!a&&(a=!0,i=o.some((e=>this.doesRepoUrlMatch(e.url,l)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,c))))))}return!i}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,ko.ZU)({basePath:r,targetPath:e}))return!1;const n=this.getWorkspaceRelativePath(e);for(const e of t)if(this.isWildcardUrl(e.url)){if((e.patterns||[]).some((e=>this.matchGlob(e.pattern,n))))return!1}else if(this.isPathPatternUrl(e.url)&&this.matchGlob(e.url,n))return!1;return!0}isWildcardUrl(e){return"*"===e.trim()}isPathPatternUrl(e){return!(e.includes("://")||e.includes("github.com")||e.includes("gitlab.com")||e.includes("bitbucket.org")||e.includes("@"))}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ko.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ko.oL)((0,s.relative)(t,e)):(0,ko.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(i.homedir(),".cursor");return await(0,ko.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){if(e.trim().toLowerCase().replace(/\.git$/i,""),e.includes("*")){if("*"===e.trim())return!0;const r=Xi(e).toLowerCase(),n=Xi(t).toLowerCase();return this.matchRepoUrlGlob(r,n)}return Xi(e).toLowerCase()===Xi(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return zi(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),a=this.normalizePathForComparison(r);let l=!1,c="";if(a.startsWith(n)?(l=!0,c=""):n.startsWith(a)&&(l=!0,c=(0,s.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,s.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,ko.o1)(e);try{await(0,uo.access)((0,s.join)(o,".git"),uo.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,s.dirname)(o);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,uo.access)((0,s.join)(i,".git"),uo.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:r,noIgnoreVcs:!0,source:"ignore_scan"},i=is.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,s.join)(o,e),n=(0,s.dirname)(r),i=(0,s.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Zi(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}async function ss(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(ri(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function as(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return ri(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ls(e,t,r){return"permissionsConfig"===r.type&&r.isReadonly?{case:"permissionDenied",value:new Rt.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:!0})}:{case:"rejected",value:new Rt.pZ({command:e,workingDirectory:t,reason:as(r)})}}is.promiseQueue=new Jr.TJ({max:os});var cs=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 us=(0,d.h)("local-exec:background-shell");function ds(e,t,r){return new Pt.Lt({result:ls(e,t,r)})}class hs{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 ps(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 fs(e){e().catch((()=>{}))}const ms=65536;class gs{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.startedAtMs=Date.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=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>ms){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=ms)this.observe(e.slice(t,t+ms));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(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Date.now()-this.startedAtMs}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:Date.now()-this.startedAtMs}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,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"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&us.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class vs{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new gs({shellId:t,outputPath:i,config:o,conversationId:r??re,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&us.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 ys{async spawn(e,t){const r=new AbortController,n=new hs(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,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 fo.SandboxUnsupportedError)throw e}return fs((()=>ps(n,o))),n}async adopt(e){const t=new hs(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,fs((()=>ps(t,e.eventIterator))),t}}function ws(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function bs(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: ${ws(e.cwd)}\n`,n+=`command: ${ws(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${ws(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}class Ss{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,uo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,l,c,u=!1,d=!1;const h=Date.now(),p=new Date(h).toISOString();let f,m="running",g=!1,v=Promise.resolve();const y=async e=>{if(l)try{await l.write(e)}catch(e){}},w=t.shellId,b=s.join(r,`${w}.txt`),S=async()=>{if(!a)return;const e=Date.now()-h,r=bs({pid:f,cwd:t.workingDirectory,command:t.command,title:t.description,status:m,startedAt:p,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},k=()=>(v=v.then(S).catch((()=>{})),v),E=()=>{void 0!==c&&(clearInterval(c),c=void 0)},x=async e=>{if(d)return;d=!0,f=e;const r=Date.now()-h,n=bs({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:m,startedAt:p,runningForMs:r});await(0,uo.writeFile)(b,n,"utf8"),c=setInterval((()=>{k()}),5e3)},C=async()=>{a||(a=await po.promises.open(b,"r+")),l||(l=await po.promises.open(b,"a"))},_=async(e,t)=>{if(!g){if(g=!0,E(),d||await x(),await C(),void 0!==t){const e=Date.now()-h,r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await y(r)}m=e,await k()}};try{for await(const t of o(e,i)){if("stdout"===t.type)d||(await x(),await C()),await y(t.data);else if("stderr"===t.type)d||(await x(),await C()),await y(t.data);else if("stdin_ready"!==t.type||u)"exit"===t.type&&await _(t.aborted?"aborted":0===t.code?"succeeded":"failed",`exit_code: ${t.code??"unknown"}`);else{u=!0,d||(await x(t.pid),await C());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`;y(`[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(!g){const e=i.signal?.aborted??!1;await _(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=ws(e instanceof Error?e.message:"Unknown error");if(await _(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(E(),await v,a)try{await a.close()}catch{}if(l)try{await l.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,uo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let i="running";const a=Date.now()-n,l=bs({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:a})+(e.initialOutput??"");await(0,uo.writeFile)(r,l,"utf8");const c=await po.promises.open(r,"r+");let u;try{u=await po.promises.open(r,"a")}catch(e){throw await c.close(),e}let d=!1,h=!1,p=Promise.resolve();const f=async()=>{const t=Date.now()-n,r=bs({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:t});try{await c.write(r,0,"utf8")}catch{}},m=()=>(p=p.then(f).catch((()=>{})),p);let g=setInterval((()=>{m()}),5e3);const v=()=>{void 0!==g&&(clearInterval(g),g=void 0)},y=async()=>{if(!d){d=!0,v(),await p;try{await c.close()}catch{}try{await u.close()}catch{}}},w=async e=>{try{await u.write(e)}catch(e){}},b=async(t,r)=>{if(!h){if(h=!0,v(),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 w(o)}i=t,await m()}},S={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await b(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await w(e.data):"exit"===e.type&&(await b(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await y())}return t.done&&await y(),t}catch(t){const r=e.abortController.signal.aborted;throw await b(r?"aborted":"failed"),await y(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await b(t?"aborted":"failed")}return await y(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:S})}}class ks{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:te(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??re,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 Es{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class xs{constructor(e,t,r,n,o,i,s){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=i&&void 0!==s?new Es(i,s):i,l=o??function(e){const t=new ys;return new Ss(t,e)}(n),c=new vs(l,n,a);this.backgroundShellManager=new ks(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,l.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Ho(t.sandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(),s=(0,ko.o1)(i),a=new Rt.HO(bo(n).structured),c=ni({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Pt.Lt({result:{case:"rejected",value:new Rt.pZ({command:n,workingDirectory:s,reason:c})}});let u=o;if(us.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:s,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId},o);if("block"===r.kind)return us.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),ds(n,s,r.reason);us.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:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Zt(t)},o);if("block"===r.kind)return us.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),ds(n,s,r.reason);u=r.policy,us.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(Oo()&&(u=Fo(n,a),"insecure_none"!==u.type)){const e=await rs(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=u?{perRepo:u}:void 0,i={ctx:e,command:n,workingDirectory:s,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(i,this.coreExecutor);return new Pt.Lt({result:{case:"success",value:new Pt.Po({shellId:r,command:n,workingDirectory:s,pid:a.pid})}})}catch(r){if(r instanceof fo.SandboxUnsupportedError){const o=u?.type??"unknown";return us.warn(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Pt.Lt({result:{case:"sandboxUnsupported",value:new Rt.rI({command:n,workingDirectory:s,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Pt.Lt({result:{case:"error",value:new Pt.Of({command:n,workingDirectory:s,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{cs(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var Cs=r("node:async_hooks"),_s=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js"),Ps=r("zod");const Is={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ts=Ps.z.object({command:Ps.z.string().optional(),args:Ps.z.array(Ps.z.string()).optional(),env:Ps.z.record(Ps.z.string(),Ps.z.string()).optional(),url:Ps.z.string().optional(),headers:Ps.z.record(Ps.z.string(),Ps.z.string()).optional(),cwd:Ps.z.string().optional(),envFile:Ps.z.string().optional(),auth:Ps.z.object({CLIENT_ID:Ps.z.string(),CLIENT_SECRET:Ps.z.string().optional(),scopes:Ps.z.array(Ps.z.string()).optional()}).optional(),enabledTools:Ps.z.array(Ps.z.string()).optional()}),Rs=Ps.z.object({mcpServers:Ps.z.record(Ps.z.string(),Ts).optional()}),As=Ps.z.enum(["canvas"]),Os=Ps.z.array(As).transform((e=>[...new Set(e)].sort()));class Ms extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function js(e){const t=e.trim();if(!t)throw new Ms("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Ms("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Ms("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Ms("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 Ms("Missing plugin name before @",e);if(!i)throw new Ms("Missing source after @",e);if(!r.test(o))throw new Ms("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Ms("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 Ms("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 Ms("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 Ms("Missing Git URL after 'url:'",e);try{new URL(t)}catch(t){throw new Ms("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 Ms("Missing marketplace name",e);if(!r.test(a))throw new Ms("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:l,raw:e}}function Ds(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 Ns(e){return e.sourceInfo.name}function $s(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Fs(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function Ls(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const Us=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Bs(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Us.has(e)))}const zs=/\$\{([A-Z][A-Z0-9_]*)(?::-([^}]*))?\}/g,Ws=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Hs=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function qs(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Hs.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Gs(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Gs(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Gs(r,t)}else for(const[,r,n]of e.matchAll(zs))Ws.has(r)||t.has(r)||t.set(r,n)}function Vs(e){if(void 0===(null==e?void 0:e.mcpServers))return;const t=new Map;if(Gs(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);r[e]=Object.assign({type:"string",title:qs(e),description:void 0===n||0===n.length?`Referenced as \`\${${e}}\` in this plugin's MCP configuration.`:`Referenced as \`\${${e}}\` in this plugin's MCP configuration. Defaults to \`${n}\` when left blank.`},Bs(e)?{writeOnly:!0}:{})}return{type:"object",properties:r}}var Js=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const Ks=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Zs=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Ys(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 Xs(e){let t;try{t=new URL(e).pathname.split("/")}catch(r){t=e.split("/")}for(const e of t){const t=Zs.exec(e);if(null!==t)return t[1]}}function Qs(e){var t;return void 0===e?{kind:"absent"}:Ks.has(e)?{kind:"supported",id:e,version:null!==(t=Xs(e))&&void 0!==t?t:e}:{kind:"unsupported",id:e}}const ea=10485760,ta=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,ra=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],na=[".cursor-plugin",".claude-plugin"],oa=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ia=Ps.z.object({source:Ps.z.literal("github"),repo:Ps.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Ps.z.string().optional(),sha:Ps.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),sa=Ps.z.object({source:Ps.z.literal("url"),url:Ps.z.string().url().endsWith(".git","URL must end with .git"),ref:Ps.z.string().optional(),sha:Ps.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),aa=Ps.z.object({source:Ps.z.literal("git-subdir"),url:Ps.z.string().url().endsWith(".git","URL must end with .git"),path:Ps.z.string().min(1),ref:Ps.z.string().optional(),sha:Ps.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),la=Ps.z.union([Ps.z.string(),ia,sa,aa]),ca=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,ua=Ps.z.object({cursor:Ps.z.string().regex(ca,"Must be a semver version (X.Y.Z)").optional(),sand:Ps.z.string().regex(ca,"Must be a semver version (X.Y.Z)").optional()}),da=Ps.z.object({name:Ps.z.string().min(1,"Author name is required"),email:Ps.z.string().email().optional()}),ha=Ps.z.enum(["string","number","integer","boolean","object","array","null"]),pa=Ps.z.union([ha,Ps.z.array(ha).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Ps.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function fa(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Ps.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:Ps.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:Ps.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:Ps.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:Ps.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:Ps.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:Ps.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const ma=Ps.z.lazy((()=>Ps.z.object({type:pa.optional(),title:Ps.z.string().optional(),description:Ps.z.string().optional(),format:Ps.z.string().optional(),writeOnly:Ps.z.boolean().optional(),default:Ps.z.unknown().optional(),enum:Ps.z.array(Ps.z.any()).nonempty().optional(),const:Ps.z.unknown().optional(),properties:Ps.z.record(Ps.z.string(),ma).optional(),required:Ps.z.array(Ps.z.string()).optional(),additionalProperties:Ps.z.union([Ps.z.boolean(),ma]).optional(),items:Ps.z.union([ma,Ps.z.array(ma)]).optional(),minLength:Ps.z.number().int().nonnegative().optional(),maxLength:Ps.z.number().int().nonnegative().optional(),minimum:Ps.z.number().optional(),maximum:Ps.z.number().optional(),exclusiveMinimum:Ps.z.number().optional(),exclusiveMaximum:Ps.z.number().optional(),multipleOf:Ps.z.number().positive().optional(),minItems:Ps.z.number().int().nonnegative().optional(),maxItems:Ps.z.number().int().nonnegative().optional(),uniqueItems:Ps.z.boolean().optional(),minProperties:Ps.z.number().int().nonnegative().optional(),maxProperties:Ps.z.number().int().nonnegative().optional()}).strict().superRefine(fa)));function ga(e){const t=ma.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:Ps.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 va=Ps.z.unknown().superRefine(((e,t)=>{const r=ga(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),ya=(Ps.z.object({name:Ps.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>ta.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ps.z.string().optional(),source:la,description:Ps.z.string().optional(),version:Ps.z.string().optional(),author:da.optional(),publisher:Ps.z.string().min(1).optional(),homepage:Ps.z.string().url().optional(),repository:Ps.z.string().url().optional(),license:Ps.z.string().optional(),keywords:Ps.z.array(Ps.z.string()).optional(),capabilities:Os.optional(),logo:Ps.z.string().optional(),category:Ps.z.string().optional(),tags:Ps.z.array(Ps.z.string()).optional(),minClientVersions:ua.optional(),strict:Ps.z.boolean().default(!0),commands:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),agents:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),skills:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),rules:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),hooks:Ps.z.union([Ps.z.string(),Ps.z.record(Ps.z.unknown())]).optional(),variables:va.optional(),mcpServers:Ps.z.union([Ps.z.string(),Ps.z.record(Ps.z.unknown()),Ps.z.array(Ps.z.union([Ps.z.string(),Ps.z.record(Ps.z.unknown())]))]).optional()}),Ps.z.object({description:Ps.z.string().optional(),version:Ps.z.string().optional(),pluginRoot:Ps.z.string().optional()}),Ps.z.object({name:Ps.z.string().min(1).regex(ta,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ps.z.string().optional(),description:Ps.z.string().optional(),version:Ps.z.string().optional(),author:da.optional(),publisher:Ps.z.string().min(1).optional(),homepage:Ps.z.string().url().optional(),repository:Ps.z.string().url().optional(),license:Ps.z.string().optional(),logo:Ps.z.string().optional(),keywords:Ps.z.array(Ps.z.string()).optional(),capabilities:Os.optional(),minClientVersions:ua.optional(),commands:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),agents:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),skills:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),rules:Ps.z.union([Ps.z.string(),Ps.z.array(Ps.z.string())]).optional(),hooks:Ps.z.union([Ps.z.string(),Ps.z.record(Ps.z.unknown())]).optional(),variables:va.optional(),mcpServers:Ps.z.union([Ps.z.string(),Ps.z.record(Ps.z.unknown()),Ps.z.array(Ps.z.union([Ps.z.string(),Ps.z.record(Ps.z.unknown())]))]).optional()}));function wa(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ba(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Sa(e,t){if(wa(e)&&"string"==typeof e.name){const t=ba(e.name);if(t.length>0)return t}return function(e){var t;const r=void 0!==e.repoName?ba(e.repoName):"";return r.length>0?r:`cursor-marketplace-${null!==(t=e.fallbackId)&&void 0!==t?t:(0,o.randomUUID)()}`}(t)}function ka(e){if(wa(e)&&wa(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 Ea(e){return"string"==typeof e?e:void 0}function xa(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Ca(e){return"string"==typeof e?e:xa(e)}function _a(e){if(!wa(e)||!wa(e.metadata))return;const t={description:Ea(e.metadata.description),version:Ea(e.metadata.version),pluginRoot:Ea(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Pa(e){if(!wa(e))return;const t=Ea(e.name);if(void 0===t||0===t.length)return;const r=Ea(e.email);return Object.assign({name:t},void 0!==r?{email:r}:{})}function Ia(e){if("string"==typeof e||wa(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||wa(e)));return t.length>0?t:void 0}}function Ta(e){if("string"==typeof e||wa(e))return e}function Ra(e){if(void 0===e)return;const t=ga(e);return t.success?t.data:void 0}function Aa(e,t={}){if(e.length>ea)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(!wa(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(!wa(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:wa(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Ea(n.ref),sha:Ea(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Ea(n.ref),sha:Ea(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:Ea(n.ref),sha:Ea(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Ea(n.ref),sha:Ea(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Ea(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?ba(e.name):"")||function(e){var t;if("string"==typeof e){const t=ba((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const r=ba(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=ba((0,s.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=ba((0,s.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=Os.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,l=function(e){const t=ua.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand))return t.data}(e.minClientVersions);return{entry:Object.assign(Object.assign({name:o,displayName:Ea(e.displayName),source:r,description:Ea(e.description),version:Ea(e.version),author:Pa(e.author),publisher:Ea(e.publisher),homepage:Ea(e.homepage),repository:Ea(e.repository),license:Ea(e.license),keywords:xa(e.keywords),logo:Ea(e.logo),category:Ea(e.category),tags:xa(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Ca(e.commands),agents:Ca(e.agents),skills:Ca(e.skills),rules:Ca(e.rules),hooks:Ta(e.hooks),variables:Ra(e.variables),mcpServers:Ia(e.mcpServers)},void 0!==a&&{capabilities:a}),void 0!==l&&{minClientVersions:l})}}(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:Sa(r,t),owner:ka(r),description:Ea(r.description),plugins:n,metadata:_a(r),skippedPluginEntries:o}}}function Oa(e){if(e.length>ea)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=Qs(Ys(t)),n=ya.safeParse(t);return n.success?Object.assign({success:!0,data:n.data},"unsupported"===r.kind&&{unrecognizedSchemaId:r.id}):{success:!1,error:`Invalid plugin manifest: ${n.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Ma(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 ja(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function Da(e,t){var r,n;if((null!==(r=e.disabledEnvironments)&&void 0!==r?r:[]).includes(t))return!1;const o=null!==(n=e.environments)&&void 0!==n?n:[];return 0===o.length||o.includes(t)}new Js.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Na=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const $a=/\$\{([^:}]+)(?::-([^}]*))?\}/g;function Fa(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 La(e,r)}function La(e,t){if("string"==typeof e)return e.replace($a,((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=>La(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=La(o,t);return r}return e}function Ua(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}var Ba=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 za=[".mcp.json","mcp.json"],Wa=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Ha(e,t){if(!function(e){return Wa.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 qa(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Ga(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return za.map((e=>void 0!==t?`${t}/${e}`:e))}function Va(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=Ua(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ua(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?Ua(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ua(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 Fa(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 Ja(e,t,r){var n;try{const o=(0,Na.qg)(e),i=Ys(o);if(void 0!==i){const e=null!==(n=null==r?void 0:r.log)&&void 0!==n?n:Is;"unsupported"===Qs(i).kind?e.log("warn",`mcp.json declares an unrecognized $schema, loading anyway: ${i}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Xs(e),n=Xs(t);return void 0!==r&&void 0!==n&&r!==n}(null==r?void 0:r.pluginSchemaId,i)&&e.log("warn",`mcp.json $schema ${i} disagrees with plugin.json $schema ${null==r?void 0:r.pluginSchemaId}, loading anyway`)}const s=Rs.safeParse(o),a=!0===(null==r?void 0:r.skipExpansion);if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return a?s.data:Va(s.data,t,r);const l={};for(const[e,t]of Object.entries(o))"mcpServers"!==e&&!Ha(e,t)&&qa(t)&&(l[e]=t);if(Object.keys(l).length>0){const e=Rs.safeParse({mcpServers:l});if(e.success)return a?e.data:Va(e.data,t,r)}return null}catch(e){return null}}function Ka(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}function Za(e,t,r){return Ba(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:za,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=Ja(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 Ba(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=>Ba(this,void 0,void 0,(function*(){const n=e.replace(/^\.\//,"");if(!ja(n))return;const o=yield t(n);if(null===o)return;const l=Ja(o,s,r.parserOptions);(null==l?void 0:l.mcpServers)&&Object.keys(l.mcpServers).length>0&&Ka(a,l.mcpServers,i(n))})),c=e=>{var t;const n=Ja(JSON.stringify(e),s,r.parserOptions);(null==n?void 0:n.mcpServers)&&Object.keys(n.mcpServers).length>0&&Ka(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 Ya(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 Xa=r("node:stream"),Qa=r("node:stream/promises"),el=r("node:zlib");function tl(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 rl(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var nl=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js"),ol=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 il=".cache-complete";function sl(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function al(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function ll(e){return rl(e)}function cl(e,t){return function(e,t,r,n){const o=[e,t,r];return void 0!==n&&o.push(n),(0,s.join)(...o)}(e,sl(t.marketplaceSlug),al(t.pluginId),void 0!==t.version?ll(t.version):void 0)}class ul{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,s.join)(o,".cursor","plugins/cache")}getCacheDir(e){return cl(this.cacheRoot,e)}isCached(e){return ol(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{const e=(0,s.join)(t,il);return(yield(0,uo.stat)(e)).isFile()}catch(e){return!1}}))}extractToCache(e){return ol(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,uo.mkdir)(t,{recursive:!0});const r=Xa.Readable.from(e.tarball);return yield(0,Qa.pipeline)(r,(0,el.createGunzip)(),(0,nl.o6)({cwd:t,strip:1})),yield this.markCacheComplete(e),t}))}listCachedVersions(e){return ol(this,void 0,void 0,(function*(){const t=sl(e.marketplaceSlug),r=al(e.pluginId),n=(0,s.join)(this.cacheRoot,t,r);try{return(yield(0,uo.readdir)(n,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(e){return[]}}))}removeVersion(e){return ol(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{yield(0,uo.rm)(t,{recursive:!0,force:!0})}catch(e){}}))}removeAllVersions(e){return ol(this,void 0,void 0,(function*(){const t=cl(this.cacheRoot,e);yield(0,uo.rm)(t,{recursive:!0,force:!0})}))}pruneOldVersions(e){return ol(this,void 0,void 0,(function*(){const t=yield this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>ll(e))));for(const n of t)r.has(n)||(yield this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n}))}))}markCacheComplete(e){return ol(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,uo.writeFile)((0,s.join)(t,il),"")}))}}function dl(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 hl=r("node:child_process");const pl=[["safe.bareRepository","explicit"],["core.fsmonitor","false"],["core.hooksPath",i.devNull],["core.attributesFile",i.devNull]];var fl=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 ml=(0,ii.promisify)(hl.execFile);function gl(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 vl(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),n=new Set;for(let e=0;e<t;e++){const t=r[`GIT_CONFIG_KEY_${e}`];for(const[o,i]of pl)t===o&&(r[`GIT_CONFIG_VALUE_${e}`]=i,n.add(o))}let o=t;for(const[e,t]of pl)n.has(e)||(r[`GIT_CONFIG_KEY_${o}`]=e,r[`GIT_CONFIG_VALUE_${o}`]=t,o++);return o!==t&&(r.GIT_CONFIG_COUNT=String(o)),r}(t)}({command:gl(e),optionsEnv:t})}function yl(e,t,r){return n=this,o=void 0,s=function*(){const n=null!=r?r:{},{env:o,encoding:i="utf8"}=n,s=fl(n,["env","encoding"]),a=yield ml(e,t,Object.assign(Object.assign({},s),{encoding:i,env:vl(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 wl(e,t,r){const n=null!=r?r:{},{env:o}=n,i=fl(n,["env"]);return(0,hl.spawn)(e,t,Object.assign(Object.assign({},i),{env:vl(t,o)}))}function bl(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Sl(e){return"function"==typeof e?e():e}function kl(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 yl("git",[...bl(),...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 El=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 xl=/^[0-9a-f]{7,40}$/i,Cl=/^[0-9a-f]{40}$/i;function _l(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 Pl(e,t,r){return El(this,void 0,void 0,(function*(){const n=t.trim();if(Cl.test(n))return{fullSha:n.toLowerCase()};if(xl.test(n)){try{const t=yield function(e,t,r){return El(this,void 0,void 0,(function*(){var n;const{stdout:o}=yield kl(["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=_l(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 kl(["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=_l(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 kl(["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=_l(o);if(!i)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:i.toLowerCase()}}))}var 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 Tl=oa.map((e=>e.split("/")[0]));let Rl;function Al(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 Ol(e){const t=[];for(const r of e){const e=Al(r);if(null===e)return"all";t.push(e)}return t}function Ml(e,t){return Il(this,void 0,void 0,(function*(){const r="all"===e?"all":Ol(e),n=t&&"all"!==r&&(yield function(){return process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(null!=Rl||(Rl=(()=>Il(this,void 0,void 0,(function*(){try{const{stdout:e}=yield kl(["--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}})))()),Rl)}());return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Tl,...o])]):[]};var o}))}function jl(e){return e.toLowerCase().includes("filtering not recognized by server")}function Dl(e,t,r){return Il(this,void 0,void 0,(function*(){yield kl(["sparse-checkout","set","--cone","--",...t],Object.assign(Object.assign({},r),{cwd:e}))}))}function Nl(e){return Il(this,void 0,void 0,(function*(){try{yield(0,uo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch(e){return!1}try{const{stdout:t}=yield kl(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch(e){return!1}}))}function $l(e,t,r){return Il(this,void 0,void 0,(function*(){if("all"!==t&&0===t.length)return;if(!(yield Nl(e)))return;const n=Object.assign(Object.assign({},r),{cwd:e,sshBatchMode:!0});if("all"===t)return void(yield kl(["sparse-checkout","disable"],n));const o=Ol(t);"all"!==o?yield kl(["sparse-checkout","add","--",...o],n):yield kl(["sparse-checkout","disable"],n)}))}const Fl=/\.git$/i,Ll=new Set(["account","dashboard"]);function Ul(e){return e.replace(Fl,"")}function Bl(e){let t;try{t=decodeURIComponent(e)}catch(e){return}return t.length>0&&!t.includes("/")?t:void 0}function zl(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Wl(e){return e.toLowerCase().split(".").includes("gitlab")}function Hl(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function ql(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map;const Gl=new Map;function Vl(e){if(void 0===e)return;if(Gl.has(e))return Gl.get(e);const t=function(e){var t,r;const n=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===n||!ql(n.hostname))return;const o=function(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}(n.pathname).split("/").filter(Boolean),i=3===o.length&&"git"===(null===(t=o[0])||void 0===t?void 0:t.toLowerCase()),s=2===o.length&&"git"!==(null===(r=o[0])||void 0===r?void 0:r.toLowerCase());if(!i&&!s)return;const a=i?o[1]:o[0],l=i?o[2]:o[1];return a&&l?Object.freeze({hostname:n.hostname,owner:a,name:l}):void 0}(e);return Gl.size>=2048&&Gl.clear(),Gl.set(e,t),t}function Jl(e){return void 0!==function(e){const t=Vl(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}function Kl(e){const t=e.toLowerCase();return Wl(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Zl(e){return zl(e)?"github":Wl(e)?"gitlab":Hl(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Yl(e){var t;let r;try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;r=new URL(t.includes("://")?t:`https://${t}`)}catch(e){return null}const n=r.hostname;let o=r.pathname.split("/").filter(Boolean);ql(n)&&"git"===(null===(t=o[0])||void 0===t?void 0:t.toLowerCase())&&(o=o.slice(1)),o.length>=3&&"scm"===o[0].toLowerCase()&&(o=o.slice(1));const i=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Ul(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(o);return void 0===i?null:{provider:Zl(n),owner:i.owner,repo:i.repo,host:n}}function Xl(e){const t=Ql(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean);return r.length>=3&&"scm"===r[0].toLowerCase()}function Ql(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch(e){return null}}function ec(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Yl(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Wl(r.host)){const e=Ql(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=Ul(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=Ql(e.trim());if(null!==t&&Hl(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Bl(t),o=Bl(r);if(void 0===n||void 0===o||Ll.has(n.toLowerCase()))return;const i=Ul(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=Ql(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=Ul(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!ql(e.host)&&null===Kl(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=rc(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Xl(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=Kl(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function tc(e){const t=ec(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 rc(e){return zl(e)?"github.com":e}new RegExp("^tmp-[0-9a-f]{16}$");function nc(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,i.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function oc(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function ic(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}var sc=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 ac=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 lc(e){const t=rl(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":ac.has(t.toLowerCase())?`_${t}`:t}const cc=18e5,uc=6e5,dc={recursive:!0,force:!0,maxRetries:3},hc=["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"],pc=["enotempty: directory not empty, rename","/_staging/"],fc=["upload-pack: not our ref","server does not allow request for unadvertised object"];function mc(e){const t=String(e).toLowerCase().replaceAll("\\","/");return hc.some((e=>t.includes(e)))?"user_git_access":pc.every((e=>t.includes(e)))?"local_cache_race":fc.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function gc(e){return"object"==typeof e&&null!==e&&(!0===e.killed||gc(e.cause))}function vc(e){return gc(e)?"killed_by_budget":mc(e)}function yc(e){const t=ec(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=Yl(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:rc(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const wc=new Map;class bc{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?cc:void 0}localTimeoutMs(){return this.sparsePluginClones?uc:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}cloneResolvedRef(e,t,r,n){return sc(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({},Sl(null===(o=this.options)||void 0===o?void 0:o.extraGitConfig)),{"safe.directory":e})},{sparse:l,sparseDirs:c}=yield Ml(null!==(s=null==n?void 0:n.materialize)&&void 0!==s?s:"all",this.sparsePluginClones);yield kl(["init"],Object.assign(Object.assign({},a),{timeoutMs:this.localTimeoutMs()})),l&&(yield Dl(e,c,{sshBatchMode:null==n?void 0:n.sshBatchMode,extraGitConfig:Sl(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.localTimeoutMs()}));const{stderr:u}=yield kl(["fetch","--depth","1",...l?["--filter=blob:none"]:[],t,r],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()}));return yield kl(["checkout","FETCH_HEAD"],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()})),{strategy:l?"sparse":"full",filterIgnoredByServer:l&&jl(null!=u?u:"")}}))}createStagingDir(){return sc(this,void 0,void 0,(function*(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,o.randomUUID)());return yield(0,uo.mkdir)(e,{recursive:!0}),e}))}moveToCanonicalDir(e,t){return sc(this,void 0,void 0,(function*(){return yield(0,uo.mkdir)((0,s.dirname)(t),{recursive:!0}),yield(0,uo.rm)(t,dc),yield(0,uo.rename)(e,t),t}))}cleanStaleStagingDirs(){return sc(this,void 0,void 0,(function*(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=yield(0,uo.readdir)(e,{withFileTypes:!0}),r=Date.now();yield Promise.all(t.filter((e=>e.isDirectory())).map((t=>sc(this,void 0,void 0,(function*(){try{const n=(0,s.join)(e,t.name),o=yield(0,uo.stat)(n);r-o.mtimeMs>bc.STALE_STAGING_THRESHOLD_MS&&(yield(0,uo.rm)(n,dc))}catch(e){}})))))}catch(e){}}))}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,lc(e),lc(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=yc(e);return(0,s.join)(this.cacheRoot,lc(r),...n.map(lc),lc(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=yc(e);return(0,s.join)(this.cacheRoot,lc(t),...r.map(lc))}pruneSiblingCloneDirs(e,t,r){return sc(this,void 0,void 0,(function*(){const n=this.getCanonicalRepoRootDir(e),o=lc(t);try{const e=yield(0,uo.readdir)(n,{withFileTypes:!0});yield Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,uo.rm)((0,s.join)(n,e.name),dc))))}catch(e){}if(void 0!==r)try{yield(0,uo.rm)(r,dc)}catch(e){}}))}ensureCloned(e,t,r){return sc(this,arguments,void 0,(function*(e,t,r,n=Is,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,Jr.wj)(i,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}))}ensureMaterialized(e,t){return sc(this,arguments,void 0,(function*(e,t,r=Is){const n=this.serializedOnRepo((0,s.dirname)(e),(()=>sc(this,void 0,void 0,(function*(){var n;const o=performance.now();try{yield $l(e,t,{extraGitConfig:Sl(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:vc(n)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:vc(n)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o,{outcome:"error"}),n}}))));return this.sparsePluginClones?n:(0,Jr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}))}serializedOnRepo(e,t){return sc(this,void 0,void 0,(function*(){const r=`${this.cacheRoot}:${e}`,n=wc.get(r),o=(null!=n?n:Promise.resolve()).catch((()=>{})).then(t);wc.set(r,o);try{return yield o}finally{wc.get(r)===o&&wc.delete(r)}}))}ensureClonedImpl(e,t,r,n,o){return sc(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:tc(t);if(null!==d)try{u=(yield Pl(d,c,{sshBatchMode:!0,extraGitConfig:Sl(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&gc(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:mc(e)}),d=null,u=(yield Pl(t,c,{extraGitConfig:Sl(null===(s=this.options)||void 0===s?void 0:s.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else u=(yield Pl(t,c,{extraGitConfig:Sl(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 Nl(h);return e&&(yield $l(h,o,{extraGitConfig:Sl(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 sc(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,uo.utimes)(u,e,e).catch((()=>{}))}),bc.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&&gc(e))throw e;s.log("error","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:i,error:String(e),errorCategory:vc(e)}),yield(0,uo.rm)(u,dc),yield(0,uo.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=vc(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,uo.rm)(u,dc)}catch(e){}}}))}isCloneComplete(e){return sc(this,void 0,void 0,(function*(){try{if(!(yield(0,uo.stat)(e)).isDirectory())return!1;const t=yield(0,uo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(yield(0,uo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch(e){return!1}}catch(e){return!1}}))}getPluginDir(e,t){return ic(e,t)}copyPluginToDir(e,t){return sc(this,void 0,void 0,(function*(){yield(0,uo.mkdir)(t,{recursive:!0}),yield(0,uo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}))}readManifest(e){return sc(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 sc(this,arguments,void 0,(function*(e,t={}){for(const r of oa){const n=(0,s.join)(e,r);let o;try{o=yield(0,uo.readFile)(n,"utf-8")}catch(e){continue}const i=Aa(o,t);if(i.success)return i.data}return null}))}(e,t);return this.manifestCache.set(n,o),o}))}resolvePluginPath(e,t){return sc(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=Ma(o.source,null===(r=n.metadata)||void 0===r?void 0:r.pluginRoot);return i&&ja(i)?i:null}))}discoverPlugins(e){return sc(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=Ma(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":ja(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):[]}))}}bc.STALE_STAGING_THRESHOLD_MS=3e5,bc.STAGING_HEARTBEAT_INTERVAL_MS=6e4;var Sc=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 kc=(0,ii.debuglog)("cursor-plugins");function Ec(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 xc(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 Cc(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)&&!Nc(e,t.gitUrl)?e:n:e}function _c(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 Pc(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=xc(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 Ic="backend-git://";function Tc(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Ic}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Rc(e){if(!e.startsWith(Ic))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 Ac="backend-release://";function Oc(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${Ac}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Mc(e){if(!e.startsWith(Ac))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 jc=/^[0-9a-f]{7,40}$/i;function Dc(e){let t;try{t=yc(e)}catch(e){return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Nc(e,t){if(e.trim()===t.trim())return!0;const r=Dc(e),n=Dc(t);return null!==r&&r===n}const $c=104857600;function Fc(e,t,r,n,a,l){return Sc(this,void 0,void 0,(function*(){const c=yield function(e){return Sc(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>$c)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||!Lc(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||!Lc(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>$c)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:a,githubToken:l}),u=c.byteLength;yield(0,uo.mkdir)(n,{recursive:!0});const d=yield(0,uo.mkdtemp)((0,s.join)((0,i.tmpdir)(),"release-asset-")),h=(0,s.join)(d,"asset.tar.gz"),p=(0,s.join)(d,"extracted");try{yield(0,uo.writeFile)(h,c),yield(0,uo.mkdir)(p,{recursive:!0});let e=0,t=0;yield nl.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,uo.readdir)(p,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=p;if(1===o.length&&0===i.length){const e=(0,s.join)(p,o[0].name);(yield(0,uo.readdir)(e)).some((e=>na.includes(e)))&&(a=e)}const l=yield(0,uo.readdir)(a);yield Promise.all(l.map((e=>(0,uo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{yield(0,uo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}))}function Lc(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Uc{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:Is,this.extraGitConfig=h.extraGitConfig,this.awaitAuthReady=h.awaitAuthReady,this.githubToken=h.githubToken,this.sparsePluginClones=null!==(l=h.sparsePluginClones)&&void 0!==l&&l,this.marketplaceCache=h.marketplaceCacheRoot?new bc(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 Sc(this,void 0,void 0,(function*(){var e,t,r,n,i,s,a,l,c,u,d,h,p,f,m,g;const v=yield this.getEffectiveUserPlugins(),y=null!==(t=v.plugins)&&void 0!==t?t:[],w=null!==(r=v.marketplaces)&&void 0!==r?r:[],b=[],S=[],k=new Map,E=(e,t)=>Sc(this,void 0,void 0,(function*(){const r=`${e}\0${t}`;let n=k.get(r);if(!n){const o=Sl(this.extraGitConfig),i=this.sparsePluginClones?3e4:void 0,s=e.startsWith("git@")||e.startsWith("ssh://")?null:tc(e),a=(e,r)=>Sc(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 Pl(e,t,n):yield Pl(e,t)).fullSha}));if(null!==s)try{n=yield a(s,!0)}catch(t){if(this.sparsePluginClones&&gc(t))throw t;n=yield a(e,!1)}else n=yield a(e,!1);k.set(r,n)}return n})),x=e=>Sc(this,void 0,void 0,(function*(){const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&(yield this.awaitAuthReady());const e=`${t}\0${n}`,i=!k.has(e);let s;i&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{s={sha:yield E(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 E(r,n),gitUrl:r}}));for(const t of y){if(!t.isEnabled||!(null===(e=t.plugin)||void 0===e?void 0:e.name))continue;const r=t.plugin,v=xc(r,w);if(!this.isMarketplaceAllowed(v)){this.pluginLogger.log("info",`Skipping plugin ${r.name} because marketplace ${null!==(n=null==v?void 0:v.name)&&void 0!==n?n:"<none>"} is not allowed`,{pluginId:r.name,marketplaceName:null==v?void 0:v.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const y=Ec({name:r.name,pluginId:void 0!==r.id?String(r.id):null!==(i=r.name)&&void 0!==i?i:""}),k=y;if(!r.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${y} without gitUrl (enableInlinePlugins=false)`,{pluginId:k});continue}const e=t.inlineContentJson;if(!e){this.pluginLogger.log("info",`Skipping DB-inline plugin ${y}: no inline content provided`,{pluginId:k});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==v?void 0:v.name)?{id:void 0!==v.id?`${v.name}-${v.id}`:`${v.name}-inline`,name:v.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${k}`,{pluginId:k,marketplaceId:null!==(l=null==i?void 0:i.id)&&void 0!==l?l:"unknown",version:n}),b.push({pluginId:k,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:y,version:n,downloadUrl:`inline://${null!==(c=r.id)&&void 0!==c?c:k}`,marketplaceDbId:void 0!==(null==v?void 0:v.id)?String(v.id):void 0,marketplace:i,inlineContentJson:e});continue}const E=r.gitUrl,C=Cc(E,v),_=Pc(t,w),P=dl(r,_),I=null!==(u=null==v?void 0:v.gitRef)&&void 0!==u?u:_;let T,R,A=C;try{if(void 0!==P)T=`release/${P.releaseTag}`;else{const e=yield x({preferredGitUrl:C,sourceGitUrl:E,gitRef:_,pluginId:k});T=e.sha,A=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${y}@${_}, skipping plugin`,{pluginId:k,ref:_,error:String(e)});const t=e instanceof Error?e.message:String(e);S.push({pluginName:y,pluginId:k,pluginDbId:void 0!==r.id?String(r.id):void 0,marketplaceName:null==v?void 0:v.name,errorMessage:t,errorType:/timed?\s*out/i.test(t)?"timeout":"clone"});continue}R=void 0!==P?Oc({repo:P.releaseRepo,asset:P.releaseAsset,tag:P.releaseTag}):Tc(A,_,null!==(d=r.gitPath)&&void 0!==d?d:void 0);const O=_c(v);let M=O,j=null==v?void 0:v.gitUrl,D=I;if((null==v?void 0:v.gitUrl)&&O){const e=Nc(E,v.gitUrl),t=e?A:O,r=e?E:v.gitUrl,n=e?_:I;j=r;try{const e=yield x({preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:k});D=e.sha,M=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 ${y} from ${t}@${n}, falling back to raw ref`,{pluginId:k,cacheRepoUrl:t,cacheRef:n,error:String(e)}),M=r}}const N=(null==v?void 0:v.name)?Object.assign({id:void 0!==v.id?`${v.name}-${v.id}`:`${v.name}-${encodeURIComponent(null!==(h=v.gitUrl)&&void 0!==h?h:"project")}`,name:v.name},M&&{gitUrl:M,gitRef:D}):void 0,$=void 0!==P||A===E&&M===j?void 0:{downloadUrl:Tc(E,_,null!==(p=r.gitPath)&&void 0!==p?p:void 0),marketplaceGitUrl:j};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${k} from ${D} at ${r.gitPath}`,{pluginId:k,marketplaceId:null!==(f=null==N?void 0:N.id)&&void 0!==f?f:"unknown",gitPath:null!==(m=r.gitPath)&&void 0!==m?m:void 0,gitRef:D}),b.push({pluginId:k,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:y,version:T,downloadUrl:R,marketplaceDbId:void 0!==(null==v?void 0:v.id)?String(v.id):void 0,marketplace:N,gitPath:null!==(g=r.gitPath)&&void 0!==g?g:void 0,isOriginBacked:void 0===P&&A!==E||void 0,originSourceFallback:$})}return{plugins:b,listFailures:S}}))}isDirectInstallSameFetch(e){const t=e.marketplace;if(!(null==t?void 0:t.gitUrl)||!t.gitRef)return!1;const r=Rc(e.downloadUrl);return!(!r||!Nc(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}installPlugin(e,t){return Sc(this,void 0,void 0,(function*(){var r;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,a=JSON.parse(o);yield(0,uo.mkdir)(n,{recursive:!0});const l={};if(a.rules&&a.rules.length>0){const e=(0,s.join)(n,"rules");yield(0,uo.mkdir)(e,{recursive:!0});const t=[];for(const r of a.rules){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${rl(r.name)}.md`,o=[];o.push(`description: ${oc(r.name)}`),r.globs&&r.globs.length>0&&o.push(`globs: ${oc(r.globs.join(", "))}`),o.push(`alwaysApply: ${!0===r.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;yield(0,uo.writeFile)((0,s.join)(e,n),i+r.content,"utf-8"),t.push(`rules/${n}`)}t.length>0&&(l.rules=t)}if(a.commands&&a.commands.length>0){const e=(0,s.join)(n,"commands");yield(0,uo.mkdir)(e,{recursive:!0});const t=[];for(const r of a.commands){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${rl(r.name)}.md`,o=r.description?`---\ndescription: ${oc(r.description)}\n---\n\n`:"";yield(0,uo.writeFile)((0,s.join)(e,n),o+r.content,"utf-8"),t.push(`commands/${n}`)}t.length>0&&(l.commands=t)}if(a.hooks&&a.hooks.length>0){const e=(0,s.join)(n,"hooks");yield(0,uo.mkdir)(e,{recursive:!0});const o={};for(const e of a.hooks){const n=e.hookStep;n&&!1!==e.isActive&&nc(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,uo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:o},null,2),"utf-8")}if(a.mcpServers&&a.mcpServers.length>0){const e={};for(const t of a.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&(yield(0,uo.writeFile)((0,s.join)(n,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8"))}const c=Object.assign({name:i},l),u=(0,s.join)(n,".cursor-plugin");yield(0,uo.mkdir)(u,{recursive:!0}),yield(0,uo.writeFile)((0,s.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{e.isOriginBacked&&void 0!==this.awaitAuthReady&&(yield this.awaitAuthReady());try{return void(yield this.installFromEntryUrls(e,t))}catch(n){const o=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r=Object.assign(Object.assign({},r),{gitUrl:t.marketplaceGitUrl});else{const{gitUrl:e,gitRef:t}=r;r=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,["gitUrl","gitRef"])}return Object.assign(Object.assign({},e),{downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0})}(e);if(void 0===o)throw n;this.pluginLogger.captureException(n,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:o.downloadUrl,sourceMarketplaceGitUrl:null===(r=o.marketplace)||void 0===r?void 0:r.gitUrl,error:String(n)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),yield(0,uo.rm)(t,{recursive:!0,force:!0});try{yield this.installFromEntryUrls(o,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}))}installFromEntryUrls(e,t){return Sc(this,void 0,void 0,(function*(){if(null===Mc(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)&&gc(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 Sc(this,arguments,void 0,(function*(e,t,r=Is,n,o){var a;const l=null!==(a=null==o?void 0:o.sparsePluginClones)&&void 0!==a&&a,c=l?cc:void 0,u=Mc(e.downloadUrl);if(u){if(e.gitPath){const r=yield(0,uo.mkdtemp)((0,s.join)((0,i.tmpdir)(),"release-plugin-"));try{yield Fc(u.repo,u.asset,u.tag,r,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);const n=ic(r,e.gitPath);yield(0,uo.mkdir)(t,{recursive:!0}),yield(0,uo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,uo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else yield Fc(u.repo,u.asset,u.tag,t,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);return}const d=Rc(e.downloadUrl);if(!d)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const h=yield(0,uo.mkdtemp)((0,s.join)((0,i.tmpdir)(),"backend-plugin-"));try{let o;if(yield function(e,t,r){return Sc(this,arguments,void 0,(function*(e,t,r,n=Is,o,i="all",s=!1){const a=performance.now(),l=jc.test(t),c="HEAD"===t.toUpperCase(),u=Object.assign(Object.assign({},o),{"safe.directory":r}),d=s?cc:void 0,h=s?uc:void 0,{sparse:p,sparseDirs:f}=yield Ml(i,s),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,v=e=>Sc(this,void 0,void 0,(function*(){p&&(yield Dl(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0}))})),y=(e,n)=>Sc(this,void 0,void 0,(function*(){let o="";return c?(({stderr:o}=yield kl(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield v(d)):l?(yield kl(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield kl(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield v(h),({stderr:o}=yield kl(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield kl(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=yield kl(["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:tc(e);let b="";if(null!==w)try{b=yield y(w,!0)}catch(t){if(s&&gc(t))throw t;yield(0,uo.rm)(r,{recursive:!0,force:!0}),yield(0,uo.mkdir)(r,{recursive:!0}),b=yield y(e,g)}else b=yield y(e,g);p&&jl(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);kc("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?Ol([d.gitPath]):[],l),d.gitPath)o=ic(h,d.gitPath);else{const t=yield function(e,t){return Sc(this,void 0,void 0,(function*(){var r;for(const n of oa){const o=(0,s.join)(e,n);let i;try{i=yield(0,uo.readFile)(o,"utf-8")}catch(e){continue}const a=Aa(i);if(!a.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${n}: ${a.error}`};const l=a.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=Ma(c.source,null===(r=l.metadata)||void 0===r?void 0:r.pluginRoot);return u&&ja(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 $l(h,Ol([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=ic(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 $l(h,"all",{extraGitConfig:n,timeoutMs:c}),o=h}}yield(0,uo.mkdir)(t,{recursive:!0}),yield(0,uo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,uo.rm)(h,{recursive:!0,force:!0}).catch((()=>{}))}}))}(e,t,this.pluginLogger,Sl(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){}}prewarmMarketplaceClones(e){return Sc(this,void 0,void 0,(function*(){var t;const r=this.marketplaceCache;if(!r)return;const n=new Map;for(const r of e){const e=r.marketplace;if(!(null==e?void 0:e.gitUrl))continue;const o=null!==(t=e.gitRef)&&void 0!==t?t:"main",i=`${e.id}\0${e.gitUrl}\0${o}`;let s=n.get(i);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:o,gitPaths:[]},n.set(i,s)),r.gitPath&&s.gitPaths.push(r.gitPath)}for(const e of n.values()){const t=Ol(e.gitPaths),n=performance.now();try{yield r.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:t}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===t?"all":t.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===t?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}))}tryInstallFromMarketplaceCache(e,t){return Sc(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?Ol([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,Ol([c]),this.pluginLogger));const u=s.getPluginDir(l,c);return yield s.copyPluginToDir(u,t),!0}))}discoverMarketplacePlugins(e,t,r){return Sc(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 Bc(e,t,r,n,o){return new Uc(e,t,r,n,o)}var zc=r("node:url"),Wc=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Hc=()=>({});function qc(e,t){return Wc(e,Object.assign(Object.assign({},t),{engines:Object.assign(Object.assign({},null==t?void 0:t.engines),{js:Hc,javascript:Hc})}))}function Gc(e,t,r){return Wc.stringify({content:e,data:{}},t,r)}function Vc(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Jc(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?Vc(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)&&(Vc(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}var Kc=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs"),Zc=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 Yc=[".md",".mdc",".markdown"],Xc=[...Yc,".txt"],Qc=/^---\s*\n([\s\S]*?)\n---/,eu="";function tu(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function ru(e){var t,r;const n=e.match(Qc);if(!n)return{};try{const e=Kc.Ay.load(n[1],{schema:Kc.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const o=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,i=nu(null!==(t=e.environments)&&void 0!==t?t:null==o?void 0:o.environments);return{disabledEnvironments:nu(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 nu(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 ou(e){return tu((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function iu(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 su{constructor(e){this.fetcher=e}discoverComponents(){return Zc(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=za.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,Yc,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,Yc,i):l.has("agents")?this.discoverMarkdownComponents(`${o}agents`,Yc,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,Xc,i):l.has("commands")?this.discoverMarkdownComponents(`${o}commands`,Xc,i):Promise.resolve([]),void 0!==(null==s?void 0:s.rules)?this.discoverFromManifestPaths(o,s.rules,!1,Yc,i):l.has("rules")?this.discoverMarkdownComponents(`${o}rules`,Yc,i):Promise.resolve([]),this.discoverMcpServers(o,null==s?void 0:s.mcpServers,c)]);return{skills:iu(d?[d,...h]:h),agents:iu(p),hooks:f,commands:iu(m),rules:iu(g),mcpServers:v.servers,mcpVariables:v.variables}}))}discoverHooksFromJson(e){return Zc(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:tu(r),path:e,description:t?eu:`Hook: ${r}`})))}catch(e){return[]}}))}discoverHooksFromManifest(e,t){return Zc(this,arguments,void 0,(function*(e,t,r=!1){var n;if("string"==typeof t){if(!ja(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:tu(e),path:"manifest",description:r?eu:`Hook: ${e}`})))}))}discoverFromManifestPaths(e,t){return Zc(this,arguments,void 0,(function*(e,t,r=!1,n=Yc,o=!1){var i,s;if("string"==typeof t){if(!ja(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(!ja(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=ou(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t),n=o?eu:void 0;if(!o){const{content:t}=yield this.fetcher.fetchFile(e),o=ru(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:tu(r),path:e};void 0!==n&&(t.description=n),a.push(t)}continue}if(r){const t={name:tu(r),path:e};void 0!==n&&(t.description=n),a.push(t)}}else{if(!(yield this.fetcher.fileExists(t)))continue;let e=ou(t),r=o?eu:void 0;if(!o){const{content:n}=yield this.fetcher.fetchFile(t),o=ru(n);e=null!==(s=o.name)&&void 0!==s?s:e,r=o.description}if(e){const n={name:tu(e),path:t};void 0!==r&&(n.description=r),a.push(n)}}}catch(e){}return a}))}discoverMarkdownComponents(e){return Zc(this,arguments,void 0,(function*(e,t=Yc,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=>Zc(this,void 0,void 0,(function*(){try{let t=ou(e.name),n=r?eu:void 0;if(!r){const{content:r}=yield this.fetcher.fetchFile(e.path),o=ru(r);t=o.name?tu(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 Zc(this,arguments,void 0,(function*(e,t=!1){try{const r=`${e}SKILL.md`,n=(0,s.basename)(e.replace(/[\\/]+$/,""));let o=tu(t?n||ou(r):n),i=t?eu:void 0;if(!t){const{content:e}=yield this.fetcher.fetchFile(r),t=ru(e);if(o=t.name?tu(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 Zc(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=>Zc(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=tu(e.name);return t?{name:t,path:r,description:eu}:null}const{content:n}=yield this.fetcher.fetchFile(r),o=ru(n),i=o.name?tu(o.name):tu(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 Zc(this,void 0,void 0,(function*(){const n=new Map,o=t=>Zc(this,void 0,void 0,(function*(){const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o})),i=n=>Zc(this,void 0,void 0,(function*(){return Za(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}})})),s=yield i("fill");if(void 0===(null==s?void 0:s.mcpServers))return{servers:[],variables:void 0};const a=void 0===t?s:yield i("override");return{servers:Object.keys(s.mcpServers).map((e=>{var t,r;return{name:tu(e),path:null!==(r=null===(t=s.mcpServerSourcePaths)||void 0===t?void 0:t[e])&&void 0!==r?r:"manifest"}})),variables:Vs(null!=a?a:s)}}))}}var au=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 lu(e){var t;const r=null!==(t=null!=e?e:process.env.HOME)&&void 0!==t?t:"";return(0,s.join)(r,".claude")}function cu(e){return au(this,void 0,void 0,(function*(){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yield(0,uo.readFile)(n,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch(e){}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yield(0,uo.readFile)(o,"utf-8"),n=JSON.parse(e);n.enabledPlugins&&(Object.assign(t.enabledPlugins,n.enabledPlugins),r=!0)}catch(e){}return r?t:null}))}var uu=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 du(e){return uu(this,void 0,void 0,(function*(){try{return(yield(0,uo.lstat)(e)).isSymbolicLink()}catch(e){return!1}}))}function hu(e){return uu(this,void 0,void 0,(function*(){if(yield du(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,uo.readFile)(e,"utf-8")}))}function pu(e){return uu(this,void 0,void 0,(function*(){if((yield(0,uo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}))}function fu(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 mu(e){return uu(this,arguments,void 0,(function*({installPath:e,logo:t}){const r=null==t?void 0:t.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=yield(0,uo.realpath)(e),n=ic(t,r),o=yield(0,uo.realpath)(n);if(ic(t,o),!(yield(0,uo.stat)(o)).isFile())return;return yield pu(o),(0,zc.pathToFileURL)(o).href}catch(e){return}}))}function gu(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function vu(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function yu(e,t){var r,n,o;return gu({version:null!==(r=e.version)&&void 0!==r?r:null==t?void 0:t.version,homepage:null!==(n=e.homepage)&&void 0!==n?n:null==t?void 0:t.homepage,repository:null!==(o=e.repository)&&void 0!==o?o:null==t?void 0:t.repository})}function wu(e,t,r){return uu(this,void 0,void 0,(function*(){var n;let o;for(const i of ra){const a=(0,s.join)(e,i);let l;try{if(yield du(a))continue;if(!(yield(0,uo.stat)(a)).isFile())continue;yield pu(a),l=yield hu(a)}catch(e){continue}const c=Oa(l);if(!c.success)continue;const u=c.data,d=u.commands,h=u.agents,p=u.skills,f=u.rules,m=u.hooks,g=u.mcpServers,v=void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m||void 0!==g,y="string"==typeof u.displayName?u.displayName:void 0,w="string"==typeof u.description?u.description:void 0,b=null===(n=u.author)||void 0===n?void 0:n.name,S=yield mu({installPath:e,logo:u.logo}),k=gu(u),E=u.variables,x=u.capabilities,C=void 0!==y||void 0!==w||void 0!==b||void 0!==S||void 0!==E||void 0!==x;if(!v&&!C&&!vu(k))continue;if(!v&&!C){o=o?Object.assign(Object.assign({},o),{fields:yu(o.fields,k)}):{fields:k,path:a,relPath:i,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("warn",`${t}: ${i} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const _=yu(k,null==o?void 0:o.fields),P=C||vu(_);return Object.assign(Object.assign({manifestFilePath:a},v&&{manifestOptions:{commands:d,agents:h,skills:p,rules:f,hooks:m,mcpServers:g}}),P&&{metadata:Object.assign(Object.assign({displayName:y,description:w,authorName:b,logoUrl:S},_),{variables:E,capabilities:x})})}if(void 0!==o)return void 0!==o.unrecognizedSchemaId&&r.log("warn",`${t}: ${o.relPath} declares an unrecognized $schema, loading anyway: ${o.unrecognizedSchemaId}`),{manifestFilePath:o.path,metadata:o.fields}}))}function bu(e,t){return uu(this,void 0,void 0,(function*(){const r=function(e,t){var r;const n=new Map,o=(0,s.resolve)(e),i=(0,s.resolve)(null!==(r=null==t?void 0:t.symlinkTargetRoot)&&void 0!==r?r:o),a=(0,uo.realpath)(i).catch((()=>i));function l(e){const t=(0,s.resolve)(e);try{return ic(o,t)}catch(t){throw new Error(`Path escapes plugin directory: ${e}`)}}function c(e){return uu(this,void 0,void 0,(function*(){const t=l(e),r=yield a,n=yield(0,uo.realpath)(t);try{return ic(r,n)}catch(t){throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}))}return{listDirectory(t,r){return uu(this,void 0,void 0,(function*(){const n=l(t?(0,s.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,uo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=yield c(r);o=(yield(0,uo.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 uu(this,void 0,void 0,(function*(){const r=n.get(t);if(void 0!==r)return{content:r};const o=l((0,s.join)(e,t)),i=yield c(o);yield pu(i);const a=yield(0,uo.readFile)(i,"utf-8");return n.set(t,a),{content:a}}))},fileExists(t){return uu(this,void 0,void 0,(function*(){try{const r=l((0,s.join)(e,t)),n=yield c(r);return(yield(0,uo.stat)(n)).isFile()}catch(e){return!1}}))}}}(e),n=new su(r),o=yield n.discoverComponents({manifest:t}),[i,a,l,c]=yield Promise.all([Su(r,o.skills,e),Eu(r,o.agents,e),xu(r,o.commands,e),ku(r,o.rules,e)]);return{skills:i,agents:a,commands:l,rules:c}}))}function Su(e,t,r){return uu(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=_u({content:Ua(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function ku(e,t,r){return uu(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=_u({content:Ua(t,r),relativePath:o.path});i&&n.push(Object.assign(Object.assign({},i),{name:o.name}))}catch(e){}return n}))}function Eu(e,t,r){return uu(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=Pu({content:Ua(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function xu(e,t,r){return uu(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=Iu({content:Ua(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function Cu(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o<e.length;o++){const i=e[o];if("{"===i)n++;else if("}"===i&&n>0)n--;else if(","===i&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function _u({content:e,relativePath:t}){var r,n,o,i,s;try{const a=qc(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=nu(null!==(i=a.data.environments)&&void 0!==i?i:null===(r=a.data.metadata)||void 0===r?void 0:r.environments),m=nu(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:Cu(a.data.globs),alwaysApply:!0===a.data.alwaysApply,content:e,environments:f,disabledEnvironments:m}}catch(e){return null}}function Pu({content:e,relativePath:t}){var r,n;try{const o=qc(e),i=o.content.trim();if(!i)return null;let a;"string"==typeof o.data.tools?a=o.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(o.data.tools)&&(a=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,s.basename)(t);return{path:t,name:"string"==typeof o.data.name?o.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof o.data.description?o.data.description:void 0,tools:a,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 Iu({content:e,relativePath:t}){try{const r=qc(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch(e){return null}}function Tu(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}function Ru(e,t,r){return uu(this,void 0,void 0,(function*(){const n=null!=r?r:Tu(t);return function(e){return Ba(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 ra){const r=yield e(t);if(null===r)continue;let a;try{a=JSON.parse(r)}catch(e){continue}s=Ys(a);const l=Oa(r);if(l.success){void 0!==l.data.mcpServers&&(o=l.data.mcpServers,i=n(t));break}}return Za(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=>uu(this,void 0,void 0,(function*(){if(!ja(t))return null;const r=(0,s.join)(e,t);try{return(yield du(r))?null:(yield(0,uo.stat)(r)).isFile()?(yield pu(r),yield hu(r)):null}catch(e){return null}}))}(e),{fallbackFileNames:Ga(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}))}function Au(e,t,r){return uu(this,void 0,void 0,(function*(){var n;const o=yield Ru(e,void 0,{log:r});if(o)return o;for(const o of oa){const i=(0,s.join)(e,o);try{if(!(yield(0,uo.stat)(i)).isFile())continue;const o=yield(0,uo.readFile)(i,"utf-8"),a=JSON.parse(o).plugins;if(!Array.isArray(a))continue;const l=t.name,c=a.find((e=>e.name===l));if(!(null===(n=null==c?void 0:c.mcpServers)||void 0===n?void 0:n.length))continue;for(const t of c.mcpServers){const n=t.replace(/^\.\//,"");if(!ja(n))continue;const o=(0,s.join)(e,n);try{yield pu(o);const t=Ja(yield hu(o),e,{log:r});if((null==t?void 0:t.mcpServers)&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return Object.assign(Object.assign({},t),{mcpServerSourcePaths:e})}}catch(e){}}return null}catch(e){}}return null}))}function Ou(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:Ua(e.command,t)}):"prompt"in e&&"string"==typeof e.prompt?Object.assign(Object.assign({},e),{prompt:Ua(e.prompt,t)}):e)));return Object.assign(Object.assign({},e),{hooks:r})}function Mu(e,t,r,n){return uu(this,void 0,void 0,(function*(){if("object"==typeof r){const o=ju(r,t);return o&&"config"in o?Object.assign({config:Ou(o.config,e)},void 0!==n&&{sourcePath:n}):o}let o,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!ja(t))return;o=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else o=(0,s.join)(e,"hooks","hooks.json");try{if(yield du(o))return;if(!(yield(0,uo.stat)(o)).isFile())return}catch(e){return}try{yield pu(o),i=yield(0,uo.readFile)(o,"utf-8")}catch(e){return}try{a=JSON.parse(i)}catch(e){return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const l=ju(a,t);return l&&"config"in l?{config:Ou(l.config,e),sourcePath:o}:l}))}function ju(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=we(r),o=Ke(n);return o.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}}function Du(e,t,r,n){return uu(this,void 0,void 0,(function*(){var o,i,s,a,l,c,u,d,h,p,f,m,g;const v=null!==(f=null==n?void 0:n.log)&&void 0!==f?f:Is,y=yield wu(e,t,v),w=Object.assign(Object.assign({},null!==(m=Tu(r))&&void 0!==m?m:(null==n?void 0:n.configuredVariables)?{configuredVariables:n.configuredVariables}:void 0),{log:v}),[b,S,k]=yield Promise.all([bu(e,null==y?void 0:y.manifestOptions),Ru(e,r,w),Mu(e,t,null===(o=null==y?void 0:y.manifestOptions)||void 0===o?void 0:o.hooks,null==y?void 0:y.manifestFilePath)]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},b),void 0!==(null===(i=null==y?void 0:y.metadata)||void 0===i?void 0:i.displayName)&&{displayName:y.metadata.displayName}),void 0!==(null===(s=null==y?void 0:y.metadata)||void 0===s?void 0:s.description)&&{description:y.metadata.description}),void 0!==(null===(a=null==y?void 0:y.metadata)||void 0===a?void 0:a.authorName)&&{authorName:y.metadata.authorName}),void 0!==(null===(l=null==y?void 0:y.metadata)||void 0===l?void 0:l.logoUrl)&&{logoUrl:y.metadata.logoUrl}),void 0!==(null===(c=null==y?void 0:y.metadata)||void 0===c?void 0:c.version)&&{version:y.metadata.version}),void 0!==(null===(u=null==y?void 0:y.metadata)||void 0===u?void 0:u.homepage)&&{homepage:y.metadata.homepage}),void 0!==(null===(d=null==y?void 0:y.metadata)||void 0===d?void 0:d.repository)&&{repository:y.metadata.repository}),{variablesSchema:null===(h=null==y?void 0:y.metadata)||void 0===h?void 0:h.variables,mcpConfig:S,capabilities:null!==(g=null===(p=null==y?void 0:y.metadata)||void 0===p?void 0:p.capabilities)&&void 0!==g?g:[],hooks:k})}))}function Nu(e,t,r){return uu(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c,u,d,h,p;const f=null!==(h=null==r?void 0:r.log)&&void 0!==h?h:Is,m=yield wu(e,t.raw,f),[g,v,y]=yield Promise.all([bu(e,null==m?void 0:m.manifestOptions),Au(e,t,f),Mu(e,t.raw,null===(n=null==m?void 0:m.manifestOptions)||void 0===n?void 0:n.hooks,null==m?void 0:m.manifestFilePath)]),w={source:"claude-plugin",sourceInfo:t};return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:w,installPath:e},void 0!==(null===(o=null==m?void 0:m.metadata)||void 0===o?void 0:o.displayName)&&{displayName:m.metadata.displayName}),void 0!==(null===(i=null==m?void 0:m.metadata)||void 0===i?void 0:i.description)&&{description:m.metadata.description}),void 0!==(null===(s=null==m?void 0:m.metadata)||void 0===s?void 0:s.authorName)&&{authorName:m.metadata.authorName}),void 0!==(null===(a=null==m?void 0:m.metadata)||void 0===a?void 0:a.logoUrl)&&{logoUrl:m.metadata.logoUrl}),void 0!==(null===(l=null==m?void 0:m.metadata)||void 0===l?void 0:l.version)&&{version:m.metadata.version}),void 0!==(null===(c=null==m?void 0:m.metadata)||void 0===c?void 0:c.homepage)&&{homepage:m.metadata.homepage}),void 0!==(null===(u=null==m?void 0:m.metadata)||void 0===u?void 0:u.repository)&&{repository:m.metadata.repository}),g),{mcpConfig:null!=v?v:void 0,capabilities:null!==(p=null===(d=null==m?void 0:m.metadata)||void 0===d?void 0:d.capabilities)&&void 0!==p?p:[],hooks:y})}))}function $u(e,t,r,n){return uu(this,void 0,void 0,(function*(){const o=`${r.name}@${r.version}`,{displayName:i,description:s,authorName:a,logoUrl:l,version:c,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:v,capabilities:y,hooks:w}=yield Du(e,o,r,{log:null==n?void 0:n.log}),b={source:t,sourceInfo:r};return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:b,installPath:e},void 0!==i&&{displayName:i}),void 0!==s&&{description:s}),void 0!==a&&{authorName:a}),void 0!==l&&{logoUrl:l}),void 0!==c&&{version:c}),void 0!==u&&{homepage:u}),void 0!==d&&{repository:d}),{variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:null!=v?v:void 0,capabilities:y,hooks:w})}))}function Fu(e,t){return uu(this,arguments,void 0,(function*(e,t,r={}){var n,o;const i=null!==(n=r.log)&&void 0!==n?n:Is,a=performance.now(),l=yield function(e){return au(this,void 0,void 0,(function*(){const t=lu(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yield(0,uo.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()-a).toFixed(1)}ms)`),[];const c=yield function(e){return au(this,void 0,void 0,(function*(){const t=lu(e),r=(0,s.join)(t,"settings.json");try{const e=yield(0,uo.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir),u=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),d=function(e,t,r){var n;if(0===r.length)return Jc(e,t,null,void 0);const o=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(null!==(n=null==e?void 0:e.enabledPlugins)&&void 0!==n?n:{}))!1===r&&o.add(t);const i=new Set,s=[];for(const{workspacePath:n,settings:a}of r){const r=Jc(e,t,a,n);for(const e of r)i.has(e.pluginId)||o.has(e.pluginId)||(i.add(e.pluginId),s.push(e))}return s}(l,c,yield(0,Jr.PH)(u,(e=>uu(this,void 0,void 0,(function*(){return{workspacePath:e,settings:yield cu(e)}}))),{max:8})),h=[],p=r.onError;for(const{pluginId:e,installPath:t}of d)try{const r=performance.now(),n=js(e),o=yield Nu(t,n,{log:i});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(js(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()-a).toFixed(1)}ms (${d.length} resolved, ${h.length} loaded)`),h}))}Error;function Lu(e){return uu(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:Is,u=performance.now(),{client:d,userId:h,teamId:p,onCursorError:f,pruneOldVersions:m,pluginFilter:g,onPluginsListed:v}=e,y=[],w=null!==(l=e.cacheManager)&&void 0!==l?l:new ul(e.userHomeDir),b=performance.now();let S;try{S=yield d.listEnabledPlugins(h,p)}catch(e){return c.captureException(e,{error_type:"list_enabled_plugins"}),c.increment("marketplace.source_unavailable",1),c.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-b).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}c.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-b).toFixed(1)}ms (${S.plugins.length} plugins)`),v&&(yield v(S.plugins));const k=[];if(S.listFailures){y.push(...S.listFailures);for(const e of S.listFailures)k.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 E=new Map;for(const e of S.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`);y.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=E.get(s);if(l||(l={slug:i,pluginId:e.pluginId,versions:[]},E.set(s,l)),l.versions.push(e.version),yield w.isCached({marketplaceSlug:i,pluginId:e.pluginId,version:e.version}))a=w.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=w.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,uo.mkdir)(t,{recursive:!0});try{yield d.installPlugin(e,t),yield w.markCacheComplete({marketplaceSlug:i,pluginId:e.pluginId,version:e.version})}catch(e){try{yield(0,uo.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 $u(a,h,p,{log:c});k.push(m);try{yield w.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));y.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:null===(i=e.marketplace)||void 0===i?void 0:i.name,errorMessage:r.message,errorType:fu(r)});const n=null===(s=e.marketplace)||void 0===s?void 0:s.name,o=void 0!==n&&"cursor-public"!==n&&n.length>0;k.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 E.values())try{yield w.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch(e){}return c.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-u).toFixed(1)}ms (${k.length} plugins loaded, ${y.length} failures)`),{plugins:k,failures:y,sourceUnavailable:!1}}))}function Uu(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 Bu(e){var t;return null!==(t=Uu(e))&&void 0!==t?t:`path:${e.installPath}`}function zu(e,t={}){return Object.assign(Object.assign({},e),{model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools})}function Wu(e,t){const r=[];for(const o of e){const e=Ds(o.identifier),i=`plugin:${e}`,a=Ns(o.identifier),l=$s(o.identifier),c=Fs(o.identifier),u=Ls(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:l,pluginId:c,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}(0,s.join)((0,i.homedir)(),".claude","plugins","marketplaces");const Hu=Ps.z.object({path:Ps.z.string(),name:Ps.z.string().optional(),description:Ps.z.string().optional(),globs:Ps.z.array(Ps.z.string()).optional(),alwaysApply:Ps.z.boolean().optional(),content:Ps.z.string(),environments:Ps.z.array(Ps.z.string()).optional(),disabledEnvironments:Ps.z.array(Ps.z.string()).optional()}),qu=Hu.extend({name:Ps.z.string()}),Gu=Ps.z.object({path:Ps.z.string(),name:Ps.z.string(),description:Ps.z.string().optional(),tools:Ps.z.array(Ps.z.string()).optional(),model:Ps.z.string().optional(),prompt:Ps.z.string(),permissionMode:Ps.z.enum(["default","readonly"]).optional()}),Vu=Ps.z.object({path:Ps.z.string(),name:Ps.z.string(),description:Ps.z.string().optional(),argumentHint:Ps.z.string().optional(),content:Ps.z.string()}),Ju=Ps.z.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),Ku=Ps.z.object({config:Ju,sourcePath:Ps.z.string().optional()}),Zu=Ps.z.custom((e=>"object"==typeof e&&null!==e));Ps.z.object({schemaVersion:Ps.z.number().int(),displayName:Ps.z.string().optional(),description:Ps.z.string().optional(),authorName:Ps.z.string().optional(),skills:Ps.z.array(Hu),rules:Ps.z.array(qu),agents:Ps.z.array(Gu),commands:Ps.z.array(Vu),mcpConfig:Rs.extend({mcpServerSourcePaths:Ps.z.record(Ps.z.string(),Ps.z.string()).optional()}).optional(),hooks:Ku.optional(),hooksError:Ps.z.string().optional(),capabilities:Ps.z.array(Ps.z.string()),variablesSchema:Zu.optional()}),Error;var Yu=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 Xu(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 Qu extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function ed(e){return 65279===e.charCodeAt(0)?e.slice(1):e}function td(e){return Yu(this,void 0,void 0,(function*(){try{return ed(yield(0,uo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}))}function rd(e){return Yu(this,void 0,void 0,(function*(){const t=yield td(e);return void 0===t?[]:function(e){const t=function(e){const t=ed(e);if(0===t.trim().length)return{};const r=[],n=(0,Na.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Na._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Qu(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof n||null===n||Array.isArray(n))return{};const o=n;return void 0===o.plugins||"object"==typeof o.plugins&&null!==o.plugins&&!Array.isArray(o.plugins)?o:{}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||Xu(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}))}function nd(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var od=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),id=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const sd={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},ad=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},sd],ld=(new Set(ad.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function cd(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return ad.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&ld.has(o)}function ud(e){return{dirPath:(0,s.join)(e,sd.configDir,sd.subdir),scope:"builtin",source:"builtin"}}function dd(e){return ad.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function hd(e,t){return dd(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function pd(e,t){return dd(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var fd=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 md(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const gd=ad.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${md(e)}[/\\\\]${md(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),vd=/[/\\]\.cursor[/\\]rules[/\\]/i,yd=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],wd=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function bd(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(wd.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(vd.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of gd)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of yd)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Sd{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Sd.ripwalkCache??=new Ji,Sd.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,l.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]};if((0,s.resolve)(this.root)===(0,s.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 Ki(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const o=this.getThirdPartyExtensibilityEnabled(),i=this.buildIncludeGlobs(o),a={root:this.root,includeGlobs:i,excludeGlobs:Qi,followSymlinks:!0,source:"nested_extensibility"},c={rules:[],skills:[],markdown:[],agents:[]},u=Sd.getRipwalkCache();try{const e=u.walk(r.ctx,a);try{for await(const t of e.lines){const e=bd(t,o);e&&c[e].push((0,s.resolve)(this.root,t))}}finally{u.delete(a)}}catch{}return r.span.setAttribute("nested_extensibility.rules",c.rules.length),r.span.setAttribute("nested_extensibility.skills",c.skills.length),r.span.setAttribute("nested_extensibility.markdown",c.markdown.length),r.span.setAttribute("nested_extensibility.agents",c.agents.length),c}catch(e){t.error=e,t.hasError=!0}finally{fd(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const kd=new Set(["node_modules","__pycache__","dist","build"]);async function Ed({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,l=void 0!==n?await(0,uo.realpath)(n):null,c=e=>{if(null===l)return!0;const t=(0,s.relative)(l,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:l}=e;if(l>r)continue;try{const e=await(0,uo.realpath)(n);if(!c(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,uo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),c=e.isFile();if(e.isSymbolicLink())try{const e=await(0,uo.stat)(r);a=e.isDirectory(),c=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||kd.has(u))continue;i.push({dir:r,depth:l+1})}else c&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const xd={agentStoreSkillsDirs:[],userHomeDirectory:""};function Cd(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function _d(e,t){const r=Cd(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Cd(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Pd(e),inAgentStore:!1}}function Pd(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),i=r.indexOf("/.codex/"),s=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+8)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Id(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:i}=_d(o.fullPath,t),s=r.get(e);void 0!==s?i&&!n[s].inAgentStore&&(n[s]={item:o,inAgentStore:i}):(r.set(e,n.length),n.push({item:o,inAgentStore:i}))}return n.map((e=>e.item))}var Td=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},Rd=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 Ad=(0,d.h)("local-exec:cursor-rules");async function Od(e){return await Ed({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Md(e){const t=await Eo(e);try{return{...await Ud(e),realSkillFilePath:t}}catch(r){return{skillFilePath:e,realSkillFilePath:t,error:r instanceof Error?r.message:String(r)}}}function jd(e){return $d(e.data?.environments??e.data?.metadata?.environments)??[]}function Dd(e){return $d(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Nd(e){return $d(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function $d(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 Fd(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 Ld(e){return e.slice(0,1536)}async function Ud(e){const t=await Ti(e);return{skillFilePath:e,content:t,parsed:qc(t)}}function Bd(e){return!0===e.data?.alwaysApply}function zd({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---`:Gc("",null!==(n=e.data)&&void 0!==n?n:{}).trim()}(e)}(r);if(Bd(r))return new id.DX({fullPath:e,content:t,frontmatter:n,type:new id.f5({type:{case:"global",value:new id.i9}}),environments:jd(r),disabledEnvironments:Dd(r),scopedTo:Nd(r)});const o="string"==typeof r.data?.description?Ld(r.data.description):void 0;return o?new id.DX({fullPath:e,content:t,frontmatter:n,type:new id.f5({type:{case:"agentFetched",value:new id.Xo({description:o})}}),environments:jd(r),disabledEnvironments:Dd(r),scopedTo:Nd(r)}):new id.DX({fullPath:e,parseError:"Description is required",frontmatter:n,scopedTo:Nd(r),type:new id.f5({type:{case:"agentFetched",value:new id.Xo}})})}function Wd({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?Ld(r.data.description):"",o=Cu(r.data?.paths??r.data?.globs);return new od.N({fullPath:e,content:t,description:n,globs:o??[],parseError:n?void 0:"Description is required",environments:jd(r),disabledEnvironments:Dd(r),scopedTo:Nd(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function Hd({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new id.DX({fullPath:e,parseError:t,type:new id.f5({type:{case:"agentFetched",value:new id.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new od.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`}))}function qd(e,t,r){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void Hd({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Fd(t.parsed,r)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(zd(t)),Bd(t.parsed)||e.agentSkills.push(Wd(t)))}function Gd(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}function Vd(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Jd(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=Vd(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=Vd(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 Kd{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Td(t,(0,l.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,ii.debuglog)("Failed to load cursor rules from service:",e),[])))));return Id((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Rd(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()}),Kd.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()}}Kd.CHANGE_COALESCE_MS=1e3;class Zd{constructor(e,t,r,n,o,a,c,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=o,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Sd(r,t,(0,i.homedir)(),o),this.ignoreService=c??new ns(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{Ad.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,ii.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,Qe.q6)(),n=Td(t,(0,l.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return Zd.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Rd(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,ii.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return Zd.ripwalkCache??=new Ji,Zd.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Td(r,(0,l.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,ii.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{Rd(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=Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ki(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=Jd(await Ti(t));if(e)return[{filename:(0,s.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Rd(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=Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ki(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=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([a,c,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{Rd(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,uo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Ti(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Td(t,(0,l.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Rd(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new id.i9};else{const r=Cu(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new id.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new id.Xo({description:Ld(e.frontmatter.description)})}:{case:"manuallyAttached",value:new id._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 id.DX({fullPath:e.path,content:e.body,type:new id.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=Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const l=(0,s.dirname)(i);if(l===i)break;i=l}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Td(n,(0,l.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,uo.stat)(e)).isFile()){const t=await Ti(e);return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Rd(n)}}async isCursorIgnored(e){try{const t=await ts((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=Jd(await Ti(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=Zd.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,s.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{Rd(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Td(r,(0,l.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,uo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}}class Yd{constructor(e,t,r,n,o,i,s=()=>!0,a=Promise.resolve(),l="ide",c,u=()=>[]){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.getAgentStoreSkillRoots=u,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 Sd(e,n,r,s))):[],this.foldersToWatch=this.computeFoldersToWatch();const d=performance.now(),h=this.loadAll(e,c).then((t=>{try{Ad.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,ii.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map})));this._loaded=h,this.setupWatchers(this.foldersToWatch)}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of hd(r,e))t.add(n.dirPath)}for(const r of pd(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(ud(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=Td(t,(0,l.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Rd(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._loaded).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,this._loaded=this.loadAll(e).catch((e=>((0,ii.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map})));for(const e of this.onChangeCallbacks)e()}reloadSkillRoots(e){const t=e.filter((e=>""!==e.trim()));if(0===t.length)return;const r=this._loaded;this._loaded=(async()=>{const e=await r,n=(await Promise.all(t.map((e=>Od(e))))).flat().filter((e=>!cd(e))),o=new Set([...e.realSkillFilePathsByFullPath.keys()].filter((e=>t.some((t=>function(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}(e,t))))));for(const e of n)o.add(e);const i=Gd(e,o),s=new Set(i.realSkillFilePathsByFullPath.values()),a=await Promise.all(n.map((e=>Md(e))));for(const e of a)s.has(e.realSkillFilePath)||(s.add(e.realSkillFilePath),qd(i,e,this.surface));return i})().catch((e=>((0,ii.debuglog)("Failed to reload Agent Skills at roots:",e),r)));for(const e of this.onChangeCallbacks)e()}isPrunedByExtensibilityScan(e){const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Td(r,(0,l.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md"),i=this._loaded,a=(async()=>{const e=await i,{realSkillFilePathsByFullPath:t}=e,r=Gd(e,new Set([o]));if(cd(o)||this.isPrunedByExtensibilityScan(o))return r;const s=t.get(o);if(void 0===s){try{await(0,uo.stat)(o)}catch{return r}return await this.loadAll(n.ctx)}let a;try{a=await(0,uo.realpath)(o)}catch{return await this.loadAll(n.ctx)}if(a!==s)return await this.loadAll(n.ctx);try{return qd(r,{...await Ud(o),realSkillFilePath:a},this.surface),r}catch{return await this.loadAll(n.ctx)}})().catch((e=>((0,ii.debuglog)("Failed to load Agent Skills at path:",e),{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map})));this._loaded=a;for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}async getAllAgentSkills(e){return(await this._loaded).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=Td(r,(0,l.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],i=[],s=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{(0,ii.debuglog)("cursor-rules-service")("Failed to discover nested agent skills: %O",e)}))))),c=await Promise.all(this.foldersToWatch.map((async e=>{const t=(await Od(e)).filter((e=>!cd(e)));return Promise.all(t.map((e=>Md(e))))}))),u=new Set;for(const e of c)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)s.set(t.skillFilePath,t.realSkillFilePath),Hd({rules:o,agentSkills:i,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Fd(t.parsed,this.surface))continue;s.set(t.skillFilePath,t.realSkillFilePath),o.push(zd(t)),Bd(t.parsed)||i.push(Wd(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!cd(e))),h=await Promise.all(d.map((e=>Eo(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Md(e))));for(const e of f)if("error"in e)s.set(e.skillFilePath,e.realSkillFilePath),Hd({rules:o,agentSkills:i,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Fd(e.parsed,this.surface))continue;s.set(e.skillFilePath,e.realSkillFilePath),o.push(zd(e)),Bd(e.parsed)||i.push(Wd(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",i.length),{rules:o,agentSkills:i,realSkillFilePathsByFullPath:s}}catch(e){r.error=e,r.hasError=!0}finally{Rd(r)}}}function Xd(e){let t;switch(e.type){case"global":t=new id.f5({type:{case:"global",value:new id.i9}});break;case"fileGlobbed":t=new id.f5({type:{case:"fileGlobbed",value:new id.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new id.f5({type:{case:"agentFetched",value:new id.Xo({description:Ld(e.description??"")})}});break;case"manuallyAttached":t=new id.f5({type:{case:"manuallyAttached",value:new id._u}});break;default:e.type,t=new id.f5({type:{case:"manuallyAttached",value:new id._u}})}return new id.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 Qd{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{Ad.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,ii.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,ii.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=Td(r,(0,l.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 Wu(e,(e=>e.skills))}(e),a=function(e){return Wu(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(Xd(e));for(const t of e){const e=`plugin:${Ds(t.identifier)}`,r=Ns(t.identifier),n=$s(t.identifier),o=Fs(t.identifier),a=Ls(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===qc(l.content).data?.["disable-model-invocation"]}catch{}i.push(new od.N({fullPath:(0,s.join)(t.installPath,l.path),content:l.content,description:Ld(l.description??""),environments:l.environments??[],disabledEnvironments:l.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,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{Rd(r)}}}const eh=(0,ii.debuglog)("local-subagents");class th{async getAllSubagents(){return[]}async reload(){return[]}}function rh(e){return"true"===(e??"").trim().toLowerCase()}function nh(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",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=rh(o["force-default-model"]),c="true"===(o.readonly??"").trim().toLowerCase()?Qt.b$.READONLY:Qt.b$.DEFAULT,u=rh(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 oh(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function ih(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function sh(e,t){return await Ed({rootDir:e,includeFile:oh,containmentRootDir:t})}class ah{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=>(eh("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(eh("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await sh(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,uo.stat)(r)).isFile())continue}catch(e){eh("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=nh(await Ti(r));if(!o)continue;t.push(new Qt.zz({fullPath:r,name:o.name||ih(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){eh("Failed to parse subagent file %s: %o",r,e)}}}return t}}const lh=new Set(["claude-code-tutor"]);class ch{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(eh("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)lh.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 uh{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&&(eh("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=Ns(o.identifier),i=$s(o.identifier),a=Fs(o.identifier),l=Ls(o.identifier);for(const c of o.agents){const u=zu(c,t),d=(0,s.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:a,marketplaceId:l})}}return n}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Qt.b$.READONLY:Qt.b$.DEFAULT;t.push(new Qt.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 dh=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");function hh(e,t,r){return new Promise(((n,o)=>{const i={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0};(0,hl.execFile)(e,t.map(String),{...i,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}dh.w3.UNSPECIFIED,dh.w3.LEFT,dh.w3.MIDDLE,dh.w3.RIGHT,dh.w3.BACK,dh.w3.FORWARD,dh.Dh.UNSPECIFIED,dh.Dh.UP,dh.Dh.DOWN,dh.Dh.LEFT,dh.Dh.RIGHT,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use");const ph=(0,ii.promisify)(hl.execFile);function fh(e,t){const r=e/t;return{display:{width:e,height:t},api:{width:1280,height:Math.round(1280/r)}}}async function mh(e){const{stdout:t}=await ph("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:fh(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}var gh,vh,yh,wh,bh;!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"}(gh||(gh={})),fr.proto3.util.setEnumType(gh,"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"}(vh||(vh={})),fr.proto3.util.setEnumType(vh,"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"}(yh||(yh={})),fr.proto3.util.setEnumType(yh,"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"}(wh||(wh={})),fr.proto3.util.setEnumType(wh,"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"}(bh||(bh={})),fr.proto3.util.setEnumType(bh,"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 Sh extends fr.Message{constructor(e){super(),this.executionTimestampMs=fr.protoInt64.zero,this.commandDurationMs=fr.protoInt64.zero,this.cursorTypeAfter=gh.UNSPECIFIED,fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Sh).fromBinary(e,t)}static fromJson(e,t){return(new Sh).fromJson(e,t)}static fromJsonString(e,t){return(new Sh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Sh,e,t)}}Sh.runtime=fr.proto3,Sh.typeName="agent.v1.InputEvent",Sh.fields=fr.proto3.util.newFieldList((()=>[{no:1,name:"execution_timestamp_ms",kind:"scalar",T:3},{no:2,name:"action",kind:"message",T:dh.ho},{no:3,name:"command_duration_ms",kind:"scalar",T:3},{no:4,name:"position_before",kind:"message",T:dh.xp},{no:5,name:"position_after",kind:"message",T:dh.xp},{no:6,name:"cursor_type_after",kind:"enum",T:fr.proto3.getEnumType(gh)}]));class kh extends fr.Message{constructor(e){super(),this.videoTimestampMs=fr.protoInt64.zero,this.x=0,this.y=0,this.cursorType=gh.UNSPECIFIED,this.velocity=0,fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new kh).fromBinary(e,t)}static fromJson(e,t){return(new kh).fromJson(e,t)}static fromJsonString(e,t){return(new kh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(kh,e,t)}}kh.runtime=fr.proto3,kh.typeName="agent.v1.CursorPathKeyframe",kh.fields=fr.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:fr.proto3.getEnumType(gh)},{no:5,name:"velocity",kind:"scalar",T:2}]));class Eh extends fr.Message{constructor(e){super(),this.style=vh.UNSPECIFIED,this.keyframes=[],fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Eh).fromBinary(e,t)}static fromJson(e,t){return(new Eh).fromJson(e,t)}static fromJsonString(e,t){return(new Eh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Eh,e,t)}}Eh.runtime=fr.proto3,Eh.typeName="agent.v1.CursorPath",Eh.fields=fr.proto3.util.newFieldList((()=>[{no:1,name:"style",kind:"enum",T:fr.proto3.getEnumType(vh)},{no:2,name:"keyframes",kind:"message",T:kh,repeated:!0}]));class xh extends fr.Message{constructor(e){super(),this.startMs=fr.protoInt64.zero,this.endMs=fr.protoInt64.zero,this.centerX=0,this.centerY=0,this.suggestedZoom=0,this.actionType="",this.actionIndex=0,this.importanceScore=0,this.context="",fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new xh).fromBinary(e,t)}static fromJson(e,t){return(new xh).fromJson(e,t)}static fromJsonString(e,t){return(new xh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(xh,e,t)}}xh.runtime=fr.proto3,xh.typeName="agent.v1.ZoomCandidate",xh.fields=fr.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 Ch extends fr.Message{constructor(e){super(),this.startMs=fr.protoInt64.zero,this.endMs=fr.protoInt64.zero,this.durationMs=fr.protoInt64.zero,this.classification=yh.UNSPECIFIED,this.suggestedSpeed=0,this.precedingActionType="",this.followingActionType="",fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ch).fromBinary(e,t)}static fromJson(e,t){return(new Ch).fromJson(e,t)}static fromJsonString(e,t){return(new Ch).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Ch,e,t)}}Ch.runtime=fr.proto3,Ch.typeName="agent.v1.IdlePeriod",Ch.fields=fr.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:fr.proto3.getEnumType(yh)},{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 _h extends fr.Message{constructor(e){super(),this.videoTimestampMs=fr.protoInt64.zero,this.x=0,this.y=0,this.clickType=wh.UNSPECIFIED,this.actionIndex=0,this.hasModifiers=!1,fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new _h).fromBinary(e,t)}static fromJson(e,t){return(new _h).fromJson(e,t)}static fromJsonString(e,t){return(new _h).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(_h,e,t)}}_h.runtime=fr.proto3,_h.typeName="agent.v1.ClickEffectKeyframe",_h.fields=fr.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:fr.proto3.getEnumType(wh)},{no:5,name:"action_index",kind:"scalar",T:5},{no:6,name:"has_modifiers",kind:"scalar",T:8}]));class Ph extends fr.Message{constructor(e){super(),this.videoTimestampMs=fr.protoInt64.zero,this.displayText="",this.eventType=bh.UNSPECIFIED,this.displayDurationMs=fr.protoInt64.zero,this.actionIndex=0,fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ph).fromBinary(e,t)}static fromJson(e,t){return(new Ph).fromJson(e,t)}static fromJsonString(e,t){return(new Ph).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Ph,e,t)}}Ph.runtime=fr.proto3,Ph.typeName="agent.v1.KeystrokeEvent",Ph.fields=fr.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:fr.proto3.getEnumType(bh)},{no:4,name:"display_duration_ms",kind:"scalar",T:3},{no:5,name:"action_index",kind:"scalar",T:5}]));class Ih extends fr.Message{constructor(e){super(),this.videoPath="",this.videoDurationMs=fr.protoInt64.zero,this.videoWidth=0,this.videoHeight=0,this.actionCount=0,this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.cursorPaths=[],fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ih).fromBinary(e,t)}static fromJson(e,t){return(new Ih).fromJson(e,t)}static fromJsonString(e,t){return(new Ih).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Ih,e,t)}}Ih.runtime=fr.proto3,Ih.typeName="agent.v1.DecisionInput",Ih.fields=fr.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:xh,repeated:!0},{no:11,name:"idle_periods",kind:"message",T:Ch,repeated:!0},{no:12,name:"click_effects",kind:"message",T:_h,repeated:!0},{no:13,name:"keystroke_events",kind:"message",T:Ph,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:Eh,repeated:!0}]));class Th extends fr.Message{constructor(e){super(),this.candidateIndex=0,fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Th).fromBinary(e,t)}static fromJson(e,t){return(new Th).fromJson(e,t)}static fromJsonString(e,t){return(new Th).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Th,e,t)}}Th.runtime=fr.proto3,Th.typeName="agent.v1.ZoomSelection",Th.fields=fr.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 Rh extends fr.Message{constructor(e){super(),this.candidateIndex=0,fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Rh).fromBinary(e,t)}static fromJson(e,t){return(new Rh).fromJson(e,t)}static fromJsonString(e,t){return(new Rh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Rh,e,t)}}Rh.runtime=fr.proto3,Rh.typeName="agent.v1.SpeedupSelection",Rh.fields=fr.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"speed_override",kind:"scalar",T:2,opt:!0}]));class Ah extends fr.Message{constructor(e){super(),this.cursorStyle=vh.UNSPECIFIED,this.selectedZooms=[],this.selectedSpeedups=[],this.showClickEffects=!1,this.selectedClickEffects=[],this.showKeystrokes=!1,this.cuts=[],fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ah).fromBinary(e,t)}static fromJson(e,t){return(new Ah).fromJson(e,t)}static fromJsonString(e,t){return(new Ah).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Ah,e,t)}}Ah.runtime=fr.proto3,Ah.typeName="agent.v1.DecisionOutput",Ah.fields=fr.proto3.util.newFieldList((()=>[{no:1,name:"cursor_style",kind:"enum",T:fr.proto3.getEnumType(vh)},{no:2,name:"selected_zooms",kind:"message",T:Th,repeated:!0},{no:3,name:"selected_speedups",kind:"message",T:Rh,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:Oh,repeated:!0}]));class Oh extends fr.Message{constructor(e){super(),this.startMs=fr.protoInt64.zero,this.endMs=fr.protoInt64.zero,this.reason="",fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Oh).fromBinary(e,t)}static fromJson(e,t){return(new Oh).fromJson(e,t)}static fromJsonString(e,t){return(new Oh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Oh,e,t)}}Oh.runtime=fr.proto3,Oh.typeName="agent.v1.VideoCut",Oh.fields=fr.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 Mh extends fr.Message{constructor(e){super(),this.rawVideoPath="",this.durationMs=fr.protoInt64.zero,this.displayWidth=0,this.displayHeight=0,this.apiWidth=0,this.apiHeight=0,this.recordingStartEpochMs=fr.protoInt64.zero,this.inputEvents=[],this.cursorPaths=[],this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.polishedVideoPath="",fr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Mh).fromBinary(e,t)}static fromJson(e,t){return(new Mh).fromJson(e,t)}static fromJsonString(e,t){return(new Mh).fromJsonString(e,t)}static equals(e,t){return fr.proto3.util.equals(Mh,e,t)}}Mh.runtime=fr.proto3,Mh.typeName="agent.v1.RecordingDataPackage",Mh.fields=fr.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:Sh,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:Eh,repeated:!0},{no:30,name:"zoom_candidates",kind:"message",T:xh,repeated:!0},{no:31,name:"idle_periods",kind:"message",T:Ch,repeated:!0},{no:32,name:"click_effects",kind:"message",T:_h,repeated:!0},{no:33,name:"keystroke_events",kind:"message",T:Ph,repeated:!0},{no:40,name:"decision_input",kind:"message",T:Ih},{no:41,name:"decision_output",kind:"message",T:Ah},{no:50,name:"polished_video_path",kind:"scalar",T:9}]));class jh{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 Dh={left_ptr:gh.ARROW,arrow:gh.ARROW,default:gh.ARROW,top_left_arrow:gh.ARROW,hand:gh.POINTER,hand1:gh.POINTER,hand2:gh.POINTER,pointer:gh.POINTER,pointing_hand:gh.POINTER,xterm:gh.TEXT,ibeam:gh.TEXT,text:gh.TEXT,watch:gh.WAIT,wait:gh.WAIT,progress:gh.WAIT,left_ptr_watch:gh.WAIT,crosshair:gh.CROSSHAIR,cross:gh.CROSSHAIR,tcross:gh.CROSSHAIR,move:gh.MOVE,fleur:gh.MOVE,size_all:gh.MOVE,sb_v_double_arrow:gh.RESIZE_NS,v_double_arrow:gh.RESIZE_NS,ns_resize:gh.RESIZE_NS,row_resize:gh.RESIZE_NS,top_side:gh.RESIZE_NS,bottom_side:gh.RESIZE_NS,sb_h_double_arrow:gh.RESIZE_EW,h_double_arrow:gh.RESIZE_EW,ew_resize:gh.RESIZE_EW,col_resize:gh.RESIZE_EW,left_side:gh.RESIZE_EW,right_side:gh.RESIZE_EW,top_left_corner:gh.RESIZE_NWSE,bottom_right_corner:gh.RESIZE_NWSE,nwse_resize:gh.RESIZE_NWSE,size_fdiag:gh.RESIZE_NWSE,top_right_corner:gh.RESIZE_NESW,bottom_left_corner:gh.RESIZE_NESW,nesw_resize:gh.RESIZE_NESW,size_bdiag:gh.RESIZE_NESW,not_allowed:gh.NOT_ALLOWED,no_drop:gh.NOT_ALLOWED,forbidden:gh.NOT_ALLOWED,circle:gh.NOT_ALLOWED,grab:gh.GRAB,openhand:gh.GRAB,grabbing:gh.GRABBING,closedhand:gh.GRABBING};class Nh{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 jh(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=gh.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 hh("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 hh("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Dh[t]??gh.ARROW}try{const e=await hh("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Dh))if(e.toLowerCase().includes(t))return r}catch{}return gh.ARROW}catch{return gh.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");const $h=1048576,Fh=52428800;var Lh;!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lh||(Lh={}));var Uh=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 Bh{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,l.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path,o=(0,ko.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ss(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new It.Pi({result:{case:"rejected",value:new It.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new It.Pi({result:{case:"permissionDenied",value:new It.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const s=await this.pendingDecisionProvider.requestApproval({type:Lh.Delete,details:{path:o},toolCallId:t.toolCallId});if(!s.approved)return new It.Pi({result:{case:"rejected",value:new It.iq({path:o,reason:s.reason||""})}});let a;try{a=await(0,uo.stat)(o)}catch(e){return"ENOENT"===e.code?new It.Pi({result:{case:"fileNotFound",value:new It.n0({path:o})}}):new It.Pi({result:{case:"error",value:new It.GU({path:o,error:e.message})}})}if(!a.isFile()){const e=a.isDirectory()?"directory":"other";return new It.Pi({result:{case:"notFile",value:new It.LX({path:o,actualType:e})}})}const c=a.size;let u;if(c<=Fh)try{u=await Ti(o)}catch{}const d=u??"";try{await(0,uo.unlink)(o)}catch(e){return"EACCES"===e.code?new It.Pi({result:{case:"permissionDenied",value:new It.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new It.Pi({result:{case:"fileBusy",value:new It.vX({path:o})}}):new It.Pi({result:{case:"error",value:new It.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 It.Pi({result:{case:"success",value:new It.fl({path:o,deletedFile:o,fileSize:BigInt(c),prevContent:d})}})}catch(e){r.error=e,r.hasError=!0}finally{Uh(r)}}}class zh{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===ot));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 pr.I0({serverIdentifier:ot,serverName:ot,instructions:`User-defined tools for this session (server "${ot}"). 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 Wh extends zh{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Hh=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),qh=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 Gh{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,l.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 Hh.uN({result:{case:"success",value:new Hh.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Hh.uN({result:{case:"error",value:new Hh.fk({url:n,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{qh(r)}}}class Vh{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,uo.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 fi(this,void 0,void 0,(function*(){const{buffer:o}=yield Ri(e,t,r,n);yield(0,uo.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 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});class Kh{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,l.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:s}=await yl("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{Jh(o)}}}var Zh=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const Yh=-(2**31),Xh=2**31-1;function Qh(e){return Number.isNaN(e)?0:e<Yh?Yh:e>Xh?Xh:e}function ep(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Qh(Math.trunc(e))}const tp="agent-tools",rp=51380224;var np=r("../mcp-core/dist/index.js"),op=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())}))},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});class sp extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class ap extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class lp{constructor(e){this.disabledService=e}load(e,t,r,n,o){return op(this,void 0,void 0,(function*(){if(yield this.disabledService.isServerDisabled(t))throw new sp(t);return yield o(e,r)}))}}class cp{constructor(e){this.approvalService=e}load(e,t,r,n,o){return op(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,l.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!(yield this.approvalService.isServerApproved(t,r,n)))throw new ap(t);return yield o(e,r)}catch(e){i.error=e,i.hasError=!0}finally{ip(i)}}))}}class up{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}isServerApproved(e,t,r){return op(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 op(this,void 0,void 0,(function*(){try{const e=yield(0,uo.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 op(this,void 0,void 0,(function*(){return this.approvalsPromise}))}addApproval(e){return op(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise;t.includes(e)||(t.push(e),yield this.saveApprovals(t))}))}addApprovals(e){return op(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 op(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 op(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 op(this,void 0,void 0,(function*(){yield(0,uo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),yield(0,uo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}))}saveApprovals(e){return op(this,void 0,void 0,(function*(){yield this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}))}}var dp=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())}))},hp=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},pp=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 fp{load(e,t,r,n,o){return dp(this,void 0,void 0,(function*(){const n=o(e,r);return new gp(e,t,n,r)}))}}function mp(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class gp{constructor(e,t,r,n){var o,i;this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=null===(i=null===(o=(0,l.fU)(e))||void 0===o?void 0:o.spanContext())||void 0===i?void 0:i.traceId,this.toolsPromise=this.clientPromise.then((t=>dp(this,void 0,void 0,(function*(){return null===t?[]:yield t.getTools(e)})))),this.resourcesPromise=this.clientPromise.then((t=>dp(this,void 0,void 0,(function*(){return null===t?[]:(yield t.listResources(e)).resources})))),this.promptsPromise=this.clientPromise.then((t=>dp(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 dp(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=hp(r,(0,l.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=mp(this.toolsPromise);return void 0!==o?o:yield this.toolsPromise}catch(e){r.error=e,r.hasError=!0}finally{pp(r)}}))}callTool(e,t,r,n,o){return dp(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const s=hp(i,(0,l.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{pp(i)}}))}getInstructions(e){return dp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=hp(t,(0,l.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{pp(t)}}))}getClient(e){return dp(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=hp(r,(0,l.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{pp(r)}}))}listResources(e){return dp(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=hp(r,(0,l.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=mp(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:yield this.resourcesPromise}}catch(e){r.error=e,r.hasError=!0}finally{pp(r)}}))}readResource(e,t){return dp(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=hp(r,(0,l.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{pp(r)}}))}listPrompts(e){return dp(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=hp(r,(0,l.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=mp(this.promptsPromise);return void 0!==o?o:yield this.promptsPromise}catch(e){r.error=e,r.hasError=!0}finally{pp(r)}}))}getPrompt(e,t,r){return dp(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=hp(n,(0,l.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{pp(n)}}))}getState(e){return dp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=hp(t,(0,l.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{pp(t)}}))}close(){return dp(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 vp(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 yp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function wp(e,t){if("string"==typeof e)return function(e,t){return e.replace(yp,((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=>wp(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=wp(o,t);return r}return e}const bp=Ps.z.object({type:Ps.z.literal("stdio").optional(),command:Ps.z.string(),args:Ps.z.array(Ps.z.string()).optional(),env:Ps.z.record(Ps.z.string(),Ps.z.string()).optional(),cwd:Ps.z.string().optional()}),Sp=Ps.z.object({CLIENT_ID:Ps.z.string(),CLIENT_SECRET:Ps.z.string().optional(),scopes:Ps.z.array(Ps.z.string()).optional()}),kp=Ps.z.object({caBundle:Ps.z.string().trim().min(1).max(131072)}).strict(),Ep=Ps.z.object({type:Ps.z.enum(["http","sse"]).optional(),url:Ps.z.string(),headers:Ps.z.record(Ps.z.string(),Ps.z.string()).optional(),auth:Sp.optional(),tls:kp.optional()}),xp=Ps.z.union([bp,Ep]),Cp=Ps.z.object({mcpServers:Ps.z.record(Ps.z.string(),xp)});function _p(e){return t=this,r=arguments,o=function*(e,t=e=>process.env[e]){try{const r=yield(0,uo.readFile)(e,"utf8"),n=wp((0,Na.qg)(r),t);return Cp.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 Pp=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js"),Ip=r("../constants/dist/mcp.js");function Tp(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,po.writeFileSync)(`/proc/${e}/oom_score_adj`,"0")}catch(e){}}var Rp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),Ap=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Op=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Mp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),jp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),Dp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Np="mcpStdioStderrTail";function $p(e){if(!(e instanceof Error))return;const t=e[Np];return"string"==typeof t?t:void 0}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())}))},Lp=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},Up=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Bp=["authorization_code","refresh_token"],zp=["code"];class Wp{constructor(e){var t;this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,!0===(null===(t=e.restMcpProviderMetadata)||void 0===t?void 0:t.omitResourceIndicator)&&(this.validateResourceURL=()=>Fp(this,void 0,void 0,(function*(){}))),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,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 Fp(this,void 0,void 0,(function*(){this._clientInformation=e,yield this._saveClientInformation(e)}))}tokens(){return this._tokens}saveTokens(e){return Fp(this,void 0,void 0,(function*(){this._tokens=e,yield this._saveTokens(e)}))}prepareForRefresh(){return Fp(this,void 0,void 0,(function*(){var e;yield null===(e=this._prepareForRefresh)||void 0===e?void 0:e.call(this)}))}releaseRefreshLeaseOnError(e){return Fp(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 Fp(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){var t,r;(0,np.E_S)(e,this._scopes),void 0!==this._serverUrl&&(0,Ip.uS)(e,this._serverUrl);for(const[n,o]of Object.entries(null!==(r=null===(t=this._restMcpProviderMetadata)||void 0===t?void 0:t.authorizationParams)&&void 0!==r?r:{}))e.searchParams.set(n,o);this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}saveCodeVerifier(e){return Fp(this,void 0,void 0,(function*(){this._codeVerifier=e}))}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}function Hp(e){return Fp(this,void 0,void 0,(function*(){var t,r;const{serverName:n,config:o,tokenStorage:i,authRedirectUrl:s}=e,a=function(e,t){if(e)return Object.assign(Object.assign({client_id:e.CLIENT_ID},e.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{}),{redirect_uris:(0,Ip.RJ)(t),grant_types:[...Bp],response_types:[...zp],token_endpoint_auth_method:"none"})}(o.auth,s),l=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 i.loadClientInformation(),staticClientInformation:a}),c=yield(0,np.Ezk)(o.url,e.fetchImpl);return new Wp({identifier:n,redirectUrl:s,serverUrl:o.url,restMcpProviderMetadata:c,clientMetadata:{redirect_uris:(0,Ip.RJ)(s),token_endpoint_auth_method:"none",grant_types:[...Bp],response_types:[...zp],client_name:"Cursor",logo_uri:Ip.G$},scopes:null===(t=o.auth)||void 0===t?void 0:t.scopes,tokens:yield i.loadTokens(),clientInformation:l,saveTokens:e=>i.saveTokens(e),prepareForRefresh:()=>{var e,t;return null!==(t=null===(e=i.prepareForRefresh)||void 0===e?void 0:e.call(i))&&void 0!==t?t:Promise.resolve()},releaseRefreshLeaseOnError:e=>{var t,r;return null!==(r=null===(t=i.releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(i,e))&&void 0!==r?r:Promise.resolve()},invalidateCredentials:i.invalidateCredentials?e=>i.invalidateCredentials(e):void 0,saveClientInformation:e=>i.saveClientInformation(e),addClientAuthentication:null===(r=i.tokenEndpointAuth)||void 0===r?void 0:r.call(i,{clientId:null==l?void 0:l.client_id})})}))}const qp=new Set;let Gp=!1;function Vp(){for(const e of qp)try{process.kill(e,"SIGKILL")}catch(e){}}class Jp{constructor(e,t,r){this._callToolLock=Promise.resolve(),this._stateEnteredAtMs=Date.now(),this.serverName=e,this.client=t,this.tools=new np.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,np.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 Ap.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}setupElicitationHandler(){this.client.setRequestHandler(Dp.$9,(e=>Fp(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 Fp(this,void 0,void 0,(function*(){const l=new URL(t.url);o=null!=o?o:Ip.tl;const c=yield r.loadTokens(),u=yield Hp({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:i}),d=(0,np.mtU)(t.url,n),h=d.headers,p=null!=i?i:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,f=void 0!==d.cursorAuthHeaderValue&&void 0!==d.cursorAuthOrigin&&void 0!==p?(0,np.utF)((()=>d.cursorAuthHeaderValue),d.cursorAuthOrigin,p):p,m=e=>void 0===f||void 0===s?f:(0,np.jIB)({fetch:f,logger:s.logger,metadata:Object.assign(Object.assign({},s.metadata),{transportType:e})}),g=Jp.createClient(),v=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 Jp(e,g,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:s,callback:t=>Fp(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,Rp.j2)(u,Object.assign({serverUrl:l.toString(),authorizationCode:t},void 0!==f?{fetchFn:f}:{})),a&&(0,np.VDJ)({logger:a,event:"mcp_oauth_callback_completion",metadata:Object.assign(Object.assign({identifier:e},(0,np.q2e)(l.toString())),(0,np.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},y=()=>Fp(this,void 0,void 0,(function*(){const r=new Op.A(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=h?h:{})},fetch:m("sse")});try{return yield g.connect(r),new Jp(e,g,{initialState:{kind:"ready"},authProvider:u,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof Rp.D_)return a&&(0,np.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,np.q2e)(l.toString())),(0,np.X5z)(t))}),v();throw t}}));if("sse"===t.type)return y();const w=new jp.j(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=h?h:{})},fetch:m("streamableHttp")});try{return yield g.connect(w),new Jp(e,g,{initialState:{kind:"ready"},authProvider:u,sessionId:w.sessionId,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof Rp.D_)return a&&(0,np.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,np.q2e)(l.toString())),(0,np.X5z)(t))}),v(w.sessionId);if((0,np.PKk)(t))return y();throw t}}))}static fromCachedSession(e,t,r,n,o){return Fp(this,arguments,void 0,(function*(e,t,r,n,o,i=Ip.tl,s,a,l){const c=new URL(t.url),u=yield Hp({serverName:e,config:t,tokenStorage:n,authRedirectUrl:i,fetchImpl:s}),d=(0,np.mtU)(t.url,o),h=d.headers,p=null!=s?s:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,f=void 0!==d.cursorAuthHeaderValue&&void 0!==d.cursorAuthOrigin&&void 0!==p?(0,np.utF)((()=>d.cursorAuthHeaderValue),d.cursorAuthOrigin,p):p,m=new jp.j(c,{authProvider:u,sessionId:r.sessionId,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=h?h:{})},fetch:void 0!==f&&void 0!==a?(0,np.jIB)({fetch:f,logger:a.logger,metadata:Object.assign(Object.assign({},a.metadata),{transportType:"streamableHttp"})}):f}),g=Jp.createClient();return yield g.connect(m),new Jp(e,g,{initialState:{kind:"ready"},authProvider:u,sessionId:m.sessionId,config:t,oauthLifecycleLogger:l})}))}get sessionId(){return this._sessionId}static fromCommand(e,t,r,n,o){return Fp(this,void 0,void 0,(function*(){var i,s,a;const c={stack:[],error:void 0,hasError:!1};try{Lp(c,(0,l.VI)(e.withName("McpSdkClient.fromCommand")),!1);const d=function(e){if("linux"!==process.platform)return e;const t=null!=e?e:(e,t,r)=>(0,hl.spawn)(e,t,r);return(e,r,n)=>{const o=t(e,r,n);return Tp(o.pid),o}}(null==o?void 0:o.spawn),h=new Mp.oQ(Object.assign({command:r.command,args:null!==(i=r.args)&&void 0!==i?i:[],env:n,cwd:r.cwd,stderr:"pipe"},d&&{spawn:d})),p=function(e){let t="",r=null===e;return null!==e&&(e.on("data",(e=>{const r=np.uOd-t.length;r<=0||(t+=e.toString().slice(0,r))})),e.once("end",(()=>{r=!0}))),{read:()=>(0,np.eaG)(t.replace(/\s+/g," ").trim(),{maxLength:np.uOd}),waitForFlush:()=>{return t=this,n=void 0,i=function*(){r||null===e||(yield new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)})))},new((o=void 0)||(o=Promise))((function(e,r){function s(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(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(t,n||[])).next())}));var t,n,o,i}}}(h.stderr),f=Jp.createClient(),m=f.connect(h),g=null!==(s=null==o?void 0:o.connectTimeoutMs)&&void 0!==s?s:6e4;let v;const y=new Promise(((e,r)=>{v=setTimeout((()=>r(new Error(`MCP server connection timed out after ${g}ms: ${t}`))),g)}));try{yield Promise.race([m,y])}catch(e){throw m.catch((()=>{})),yield h.close().catch((()=>{})),yield p.waitForFlush(),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Object.defineProperty(r,Np,{value:t,enumerable:!1,configurable:!0,writable:!0}),r}(e,p.read())}finally{void 0!==v&&clearTimeout(v)}const w=null!==(a=h.pid)&&void 0!==a?a:void 0;return"number"==typeof w&&(u=w,qp.add(u),Gp||(Gp=!0,process.on("exit",Vp))),new Jp(t,f,{initialState:{kind:"ready"},config:r,stdioChildPid:w})}catch(e){c.error=e,c.hasError=!0}finally{Up(c)}var u}))}close(){return Fp(this,void 0,void 0,(function*(){var e;void 0!==this._stdioChildPid&&(e=this._stdioChildPid,qp.delete(e)),yield this.client.close()}))}getTools(e){return Fp(this,void 0,void 0,(function*(){var t,r,n;const o={stack:[],error:void 0,hasError:!1};try{if(Lp(o,(0,l.VI)(e.withName("McpSdkClient.getTools")),!1),"requires_authentication"===this.stateValue.kind)return[];try{return yield this.tools.get((()=>Fp(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 Rp.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=>Fp(this,void 0,void 0,(function*(){}))},this._logStateTransition(o,this.stateValue,"runtime_unauthorized",Object.assign({},(0,np.X5z)(e))),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){o.error=e,o.hasError=!0}finally{Up(o)}}))}callTool(e,t,r,n,o){return Fp(this,void 0,void 0,(function*(){var i,s,a;const c={stack:[],error:void 0,hasError:!1};try{Lp(c,(0,l.VI)(e.withName("McpSdkClient.callTool")),!1).span.setAttribute("toolName",t);const u=this._callToolLock;let d;this._callToolLock=new Promise((e=>{d=e}));try{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:!0===e.isError}}catch(e){if(e instanceof Rp.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=>Fp(this,void 0,void 0,(function*(){}))},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",Object.assign({},(0,np.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){c.error=e,c.hasError=!0}finally{Up(c)}}))}getInstructions(e){return Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(Lp(t,(0,l.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{Up(t)}}))}listResources(e){return Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(Lp(t,(0,l.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();if(!(null==r?void 0:r.resources))return{resources:[]};let 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{Up(t)}}))}readResource(e,t){return Fp(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{return Lp(r,(0,l.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{Up(r)}}))}listPrompts(e){return Fp(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{if(Lp(r,(0,l.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind)return[];if(!(null!==(t=this.client.getServerCapabilities())&&void 0!==t?t:{prompts:!1}).prompts)return[];const 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{Up(r)}}))}getPrompt(e,t,r){return Fp(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{return Lp(n,(0,l.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{Up(n)}}))}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}getState(e){return Fp(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 Kp extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function Zp(e){if(e instanceof Kp)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}class Yp 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 Xp{constructor(e){this.tools=e}execute(e,t,r,n){return Fp(this,void 0,void 0,(function*(){const o=this.tools[e];if(!o)throw new Kp(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 Qp{getClients(e){return Fp(this,void 0,void 0,(function*(){return{}}))}getClient(e,t){return Fp(this,void 0,void 0,(function*(){}))}getInstructions(e){return Fp(this,void 0,void 0,(function*(){return[]}))}getToolSet(e){return Fp(this,void 0,void 0,(function*(){return new Xp({})}))}getTools(e){return Fp(this,void 0,void 0,(function*(){return[]}))}getToolsForServers(e,t){return Fp(this,void 0,void 0,(function*(){return[]}))}}class ef{constructor(e){this.manager=e}getClients(e){return Fp(this,void 0,void 0,(function*(){return this.manager.getClients()}))}getClient(e,t){return Fp(this,void 0,void 0,(function*(){return this.manager.getClient(t)}))}getInstructions(e){return Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Lp(t,(0,l.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return yield this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Up(t)}}))}getToolSet(e){return Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Lp(t,(0,l.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return yield this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Up(t)}}))}getTools(e){return Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Lp(t,(0,l.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(yield this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{Up(t)}}))}getToolsForServers(e,t){return Fp(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 Fp(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 tf{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 Fp(this,void 0,void 0,(function*(){const e=Object.values(this.clients);yield Promise.all(e.map((e=>Fp(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 Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Lp(t,(0,l.VI)(e.withName("McpManager.getToolSet")),!1),n=yield(0,Jr.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)=>Fp(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 Xp(i)}catch(e){t.error=e,t.hasError=!0}finally{Up(t)}}))}getInstructions(e){return Fp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Lp(t,(0,l.VI)(e.withName("McpManager.getInstructions")),!1),n=yield(0,Jr.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new pr.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{Up(t)}}))}}Error;var rf=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 nf(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 of{constructor(e){this.options=e,(0,np.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,np.q2e)(this.options.serverUrl)}:{})}loadTokens(){return rf(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadTokens();return(0,np.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,np.tBH)(e))}),e}))}saveTokens(e){return rf(this,void 0,void 0,(function*(){yield this.options.inner.saveTokens(e),(0,np.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,np.tBH)(e,{expiresInIsFresh:!0}))})}))}prepareForRefresh(){return rf(this,void 0,void 0,(function*(){var e,t;(0,np.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 rf(this,void 0,void 0,(function*(){var t,r;(0,np.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:Object.assign(Object.assign({},this.baseMetadata),(0,np.X5z)(e))}),yield null===(r=(t=this.options.inner).releaseRefreshLeaseOnError)||void 0===r?void 0:r.call(t,e)}))}loadClientInformation(){return rf(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadClientInformation();return(0,np.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,np.O3I)(e))}),e}))}saveClientInformation(e){return rf(this,void 0,void 0,(function*(){yield this.options.inner.saveClientInformation(e),(0,np.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,np.O3I)(e))})}))}invalidateCredentials(e){return rf(this,void 0,void 0,(function*(){void 0!==this.options.inner.invalidateCredentials&&((0,np.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))}))}tokenEndpointAuth(e){var t,r;return null===(r=(t=this.options.inner).tokenEndpointAuth)||void 0===r?void 0:r.call(t,e)}}class sf{constructor(e,t){this.storage=e,this.identifier=t}loadTokens(){return rf(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.identifier)}))}saveTokens(e){return rf(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.identifier,e)}))}loadClientInformation(){return rf(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.identifier)}))}saveClientInformation(e){return rf(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.identifier,e)}))}}class af{constructor(e){this.inner=e}loadTokens(){return rf(this,void 0,void 0,(function*(){}))}loadClientInformation(){return rf(this,void 0,void 0,(function*(){}))}saveTokens(e){return rf(this,void 0,void 0,(function*(){return this.inner.saveTokens(e)}))}saveClientInformation(e){return rf(this,void 0,void 0,(function*(){return this.inner.saveClientInformation(e)}))}invalidateCredentials(e){return rf(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 lf=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())}))},cf=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},uf=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 df=(0,d.h)("DefinitionMcpLoader");function hf(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(i.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(null!=r?r:process.cwd(),t):t}function pf(e){return"function"==typeof e.getMcpNetworkControlsConfig}function ff(e){var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0}function mf(e){if(void 0!==e)return(0,o.createHash)("sha256").update((0,np.Fmf)(e)).digest("hex")}class gf{constructor(e){this.configPath=e,this.configPromise=_p(e)}clearCache(){this.configPromise=_p(this.configPath)}getDefinitions(e){return lf(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 vf{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}load(e){return lf(this,arguments,void 0,(function*(e,t=!0){var r,n,o;const i={stack:[],error:void 0,hasError:!1};try{cf(i,(0,l.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,Jr.PH)([...s],(r=>lf(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){df.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r),stderrTail:$p(r)})}(e,r,t)}}))),{max:null!==(o=this.options.maxConcurrency)&&void 0!==o?o:Math.max(s.length,1)}),new tf(a,this.options.elicitationFactory)}catch(e){i.error=e,i.hasError=!0}finally{uf(i)}}))}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}evictClientsOnSandboxPolicyChange(e,t){return lf(this,void 0,void 0,(function*(){const r=this.middlewares.find(pf);if(!r)return;let n;try{n=JSON.stringify(yield Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((e=>lf(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,np.Fmf)(o)]}))))))}catch(e){return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(df.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),yield this.closeAllCachedClients())}))}closeAllCachedClients(){return lf(this,void 0,void 0,(function*(){const e=[...this.clientCache.values()];this.clientCache.clear(),yield(0,Jr.PH)(e,(e=>lf(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 lf(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{cf(n,(0,l.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{uf(n)}}))}loadDefinitionClient(e,t,n){return lf(this,void 0,void 0,(function*(){var o,i;const s=null!==(o=t.authStorageKey)&&void 0!==o?o:t.identifier,a=new sf(this.tokenStorage,s),c=nf(e,df),u=new of({inner:a,logger:c,identifier:s,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),d=n?new af(u):u;return function(e,t,n,o){return lf(this,arguments,void 0,(function*(e,t,n,o,i={middlewares:[],configPath:""},s){const a={stack:[],error:void 0,hasError:!1};try{const{middlewares:c,configPath:u}=i,d=cf(a,(0,l.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let h=(e,n)=>lf(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const a=cf(i,(0,l.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=c.find(pf);return yield function(e,t,n,o){return lf(this,void 0,void 0,(function*(){var i,s,a;const l=n.cwd?hf({filePath:n.cwd}):void 0;let c,u;if(n.args&&n.args.length>0)c=hf({filePath:n.command,baseDir:l}),u=n.args.map((e=>hf({filePath:e,baseDir:l})));else{const e=(0,Pp.A)(n.command);c=hf({filePath:e[0],baseDir:l}),u=e.slice(1).map((e=>hf({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,np.$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);df.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=${ff(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${ff(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${ff(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist)}, sandboxPolicyHash=${null!==(a=mf(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:ff(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist),mcpNetworkDenylistCount:ff(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist),localAgentNetworkAllowlistCount:ff(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist),sandboxPolicyHash:mf(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:p}));try{return yield Jp.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 np.c8u(t,e);throw e}}return!0===(null==h?void 0:h.enabled)&&"no_sandbox"===h.mcpNetworkMode&&df.info(e,`Starting local MCP server "${t}" without MCP sandboxing`),Jp.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 lf(this,void 0,void 0,(function*(){const i=nf(e,df),s=function(e,t){return{logger:{debug:(t,r)=>df.debug(e,t,r),info:(t,r)=>df.info(e,t,r),warn:(t,r)=>df.warn(e,t,r),error:(t,r,n)=>df.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t);return Jp.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{uf(i)}}));for(const e of c){const r=h;h=(n,o)=>lf(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{uf(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){df.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 sp||e instanceof ap||e instanceof yf}(r)}}class yf 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 wf{constructor(e){this.blockingService=e}getMcpNetworkControlsConfig(e){return lf(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 lf(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 yf(t,null!==(l=u.reason)&&void 0!==l?l:"teamPolicy",u.message);return o(e,r)}))}}class bf extends vf{constructor(e,t,r=[],n,o){super(new gf(e),t,r,{authRedirectUrlGenerator:n,elicitationFactory:o}),this.configPath=e,this.elicitationFactory=o}static init(e,t,r=[]){return new bf(t,e,r)}}function Sf(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 kf=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 Ef{constructor(e){this.mcpAuthPath=e;const t=Ef.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,Ef.mcpAuthPromises.set(e,t),t.catch((()=>{Ef.mcpAuthPromises.get(e)===t&&Ef.mcpAuthPromises.delete(e)}))}Ef.saveLocks.has(e)||Ef.saveLocks.set(e,Promise.resolve())}loadMcpAuth(){return kf(this,void 0,void 0,(function*(){try{const e=yield(0,uo.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 kf(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 kf(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>kf(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 kf(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 kf(this,void 0,void 0,(function*(){var t;const r=null!==(t=Ef.saveLocks.get(this.mcpAuthPath))&&void 0!==t?t:Promise.resolve();let n;Ef.saveLocks.set(this.mcpAuthPath,new Promise((e=>{n=e})));try{return yield r,yield e()}finally{n()}}))}saveClientInformation(e,t){return kf(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>kf(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 kf(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>kf(this,void 0,void 0,(function*(){const t=yield this.mcpAuthPromise;e in t&&(delete t[e],yield this.saveMcpAuth(t))}))))}))}saveMcpAuth(e){return kf(this,void 0,void 0,(function*(){yield(0,uo.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),yield(0,uo.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}))}}Ef.mcpAuthPromises=new Map,Ef.saveLocks=new Map;var xf=r("../proto/dist/generated/agent/v1/utils_pb.js");let Cf;function _f(){if(void 0===Cf){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 Cf===e&&(Cf=void 0),t}));Cf=e}return Cf}const Pf=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},If=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Tf=e=>Pf().encode(e);var Rf=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 Af=1048576,Of=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Mf=(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}},jf=(e,t)=>Rf(void 0,void 0,void 0,(function*(){if(If(e))return((e,t)=>Rf(void 0,void 0,void 0,(function*(){const r=(e=>{if(!If(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!==r&&!Mf(r.width,r.height,1280).needsResize&&e.length<=Af)return{data:Of(e),mimeType:"image/webp"};if("passthrough"===(null==t?void 0:t.webpWithoutCodec))return{data:Of(e),mimeType:"image/webp"};const n=yield(o=e,Pf().decode(o));var o;const i=(yield _f()).fromBitmap({data:Buffer.from(n.data),width:n.width,height:n.height});let{width:s,height:a,needsResize:l}=Mf(i.bitmap.width,i.bitmap.height,1280);l&&i.resize({w:s,h:a});let c=yield Tf({data:i.bitmap.data,width:i.bitmap.width,height:i.bitmap.height});for(;c.length>Af&&s>1&&a>1;)s=Math.max(1,Math.round(.8*s)),a=Math.max(1,Math.round(.8*a)),i.resize({w:s,h:a}),c=yield Tf({data:i.bitmap.data,width:i.bitmap.width,height:i.bitmap.height});return{data:Of(c),mimeType:"image/webp"}})))(e,t);const r=yield _f(),n=yield r.read(e),o=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(n),{width:i,height:s,needsResize:a}=Mf(n.width,n.height);if(!a&&e.length<=Af)return{data:Of(e),mimeType:o};let l=i,c=s;a&&n.resize({w:l,h:c});let u=yield n.getBuffer(o);for(;u.length>Af&&l>1&&c>1;)l=Math.max(1,Math.round(.8*l)),c=Math.max(1,Math.round(.8*c)),n.resize({w:l,h:c}),u=yield n.getBuffer(o);return{data:Of(u),mimeType:o}}));function Df(e){if(void 0!==e&&0!==e.length)try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch(e){}}function Nf(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=e.title.slice(0,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return 0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}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},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});const Lf=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),Uf=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),Bf=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),zf=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),Wf=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),Hf=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),qf=(0,d.h)("McpFileSystemWriter"),Gf="mcpFsStructuredLogOptIn";function Vf(e,t){return t?.includeStructuredLogs?{...e??{},[Gf]:!0}:e}const Jf={debug(e,t,r,n){qf.debug(e,t,Vf(r,n))},info(e,t,r,n){qf.info(e,t,Vf(r,n))},warn(e,t,r,n){qf.warn(e,t,Vf(r,n))},error(e,t,r,n,o){qf.error(e,t,r,Vf(n,o))}},Kf="mcps",Zf="tools",Yf="~staging",Xf="~prev",Qf="mcp_auth",em="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.",tm="# >>> CURSOR MANAGED BLOCK >>>",rm="# <<< CURSOR MANAGED BLOCK <<<",nm=["# 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 om(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function im(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function sm(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function am(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 lm(e){if(Array.isArray(e))return e.map((e=>lm(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,lm(t)]));return Object.fromEntries(t)}return e}function cm(e){return JSON.stringify(lm(e))}function um(e){const t=e.map((e=>({value:e,key:cm(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function dm(e){const t=um(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=um(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=um(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return cm({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 hm{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=>{Jf.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),Jf.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${tm}\n${nm}\n${rm}\n`;let n;await(0,uo.mkdir)(e,{recursive:!0});try{n=await(0,uo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==e?.code)throw e}if(void 0===n)return void await(0,uo.writeFile)(t,r);const o=n.indexOf(tm),i=n.indexOf(rm,o+30);if(-1===o||-1===i)await(0,uo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,uo.writeFile)(t,e)}})((0,s.join)((0,i.homedir)(),".cursor")).catch((e=>{Jf.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,Kf);try{const e=await(0,uo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(Yf))).map((e=>(0,uo.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==e?.code&&Jf.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:ut(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:ut(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){Jf.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(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return sm(this.mcpAuthCopyOverrides?.authToolDescription)??em}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&st(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return sm(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=sm(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:Qf},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&st(e)?this.getNeedsAuthStatusMessage(e):sm(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){Jf.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${n}`);const o=await this.mcpLease.getTools(e).catch((e=>(Jf.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 Jf.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 om(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||Jf.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?om(r.getTools(e),[]).then((e=>(0===e.length&&Jf.info(o,`Direct client getTools() returned 0 tools for "${t}" (state=${i.kind})`),e))):Promise.resolve([]),s?om(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?om(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?om(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:am(i)}}buildServerDataMap(e,t,r,n,o){const i=new Map(r.map((e=>[e.clientKey,e.clientTools]))),a=new Map;for(const e of r){const t=wm(e.clientKey);a.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,Kf,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const e of t){let t=a.get(e.clientKey);if(!t){const r=wm(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,s.join)(this.projectDir,Kf,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},a.set(e.clientKey,t)}t.tools.push(e)}for(const[t,r]of a)if(0===r.tools.length){const 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){Jf.info(e,`Skipping direct client tool fallback for "${t}": settings report 0 enabled tools`);continue}Jf.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(a.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(a.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of a.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===Qf))||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:Qf,name:Qf,description:l.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var l;return a}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)?Jf.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):Jf.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===Qf))){const t=e.tools.find((e=>e.toolName===Qf));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??[])];Jf.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=>(Jf.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 Jf.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=>{Jf.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):Jf.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)),Jf.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=wm(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{$f(r,(0,l.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!ut(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=>(Jf.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(Jf.warn(n,`getClients() threw, defaulting to {}: ${e}`),{}))),this.getEnabledToolsByServer(e)]),a=Object.keys(i);Jf.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){Jf.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{Ff(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,Zf,`${im(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{$f(n,(0,l.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const i=this.getLogContext(e),a=(0,s.join)(this.projectDir,Kf);await(0,uo.mkdir)(a,{recursive:!0});const c=new Map;for(const e of t)try{c.set(e.serverIdentifier,dm(e))}catch(t){Jf.error(i,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),c.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const u=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==c.get(e.serverIdentifier)&&(u.push(e),void 0!==t&&Jf.info(i,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!u.includes(e))try{await(0,uo.stat)((0,s.join)(a,e.sanitizedId))}catch{Jf.info(i,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),u.push(e)}const d=new Set;for(const[e]of this.cachedFingerprints)if(!c.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??wm(e);r.has(n)?(Jf.info(i,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),c.set(e,this.cachedFingerprints.get(e))):(Jf.info(i,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),d.add(n))}const h=void 0===this.cachedServerData;if(h)try{const e=await(0,uo.readdir)(a),t=new Set(e.filter((e=>!e.endsWith(Yf)&&!e.endsWith(Xf))));for(const r of e)if(r.endsWith(Yf))await(0,uo.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else if(r.endsWith(Xf)){const e=r.slice(0,-5);if(t.has(e))await(0,uo.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else try{await(0,uo.rename)((0,s.join)(a,r),(0,s.join)(a,e)),t.add(e)}catch{await(0,uo.rm)((0,s.join)(a,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);c.has(t)||c.set(t,`__preserved_${e}`)}else d.add(e)}catch(e){Jf.error(i,"Error clearing mcps directory",e)}const p=Array.from(d);if(u.length>0||d.size>0){const e=u.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));Jf.info(i,`Incremental write: ${u.length} changed, ${d.size} removed, ${t.length-u.length} unchanged`,{changedServerCount:u.length,changedServers:e,removedServerCount:d.size,removedServerSanitizedIds:p,unchangedServerCount:t.length-u.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:h,projectDirHash:(0,o.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const f=await Promise.allSettled(u.map((t=>this.writeServerAtomic(e,t,a))));for(let t=0;t<u.length;t++){const r=f[t];if("rejected"===r.status){const n=u[t],o=this.cachedFingerprints.get(n.serverIdentifier);void 0!==o?c.set(n.serverIdentifier,o):c.delete(n.serverIdentifier),Jf.error(e,"Error writing server directory",r.reason,{serverIdentifier:n.serverIdentifier,sanitizedId:n.sanitizedId},{includeStructuredLogs:!0})}}const m=await Promise.allSettled(p.map((e=>(0,uo.rm)((0,s.join)(a,e),{recursive:!0,force:!0}))));for(let r=0;r<m.length;r++){const n=m[r];if("rejected"===n.status){const o=p[r];Jf.error(e,"Error removing server directory",n.reason,{sanitizedId:o,removalIndex:r,removalAttemptCount:m.length,removedServerCount:p.length,removedServerSanitizedIds:p,changedServerCount:u.length,unchangedServerCount:t.length-u.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=c}catch(e){n.error=e,n.hasError=!0}finally{Ff(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{$f(n,(0,l.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=`${t.sanitizedId}${Yf}`,i=`${t.sanitizedId}${Xf}`,a=(0,s.join)(r,o),c=(0,s.join)(r,i),u=(0,s.join)(r,t.sanitizedId);await(0,uo.rm)(a,{recursive:!0,force:!0});try{await(0,uo.rename)(c,u)}catch{await(0,uo.rm)(c,{recursive:!0,force:!0})}await this.writeServerDirectory(e,t,{basePath:r,dirName:o});try{try{await(0,uo.rename)(u,c)}catch{}await(0,uo.rename)(a,u)}catch(r){Jf.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0});try{await(0,uo.rename)(c,u)}catch{}throw await(0,uo.rm)(a,{recursive:!0,force:!0}),r}await(0,uo.rm)(c,{recursive:!0,force:!0}).catch((()=>{}))}catch(e){n.error=e,n.hasError=!0}finally{Ff(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{$f(n,(0,l.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,uo.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,Zf);await(0,uo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=im(r.toolName),n=(0,s.join)(e,`${t}.json`),o=lt(r);await(0,uo.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,uo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=im(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,uo.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,uo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=im(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,uo.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,uo.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,uo.writeFile)(e,r)}const i=(0,s.join)(o,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,uo.writeFile)(i,JSON.stringify(a,null,2))}catch(e){n.error=e,n.hasError=!0}finally{Ff(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;$f(r,(0,l.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&&Jf.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=im(t.toolName),n=(0,s.join)(e.folderPath,Zf,`${r}.json`);return new pr.E$({toolName:t.toolName,definitionPath:n,...Nf(t.annotations)})}));return new pr.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 pr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{Ff(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&&Jf.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){Jf.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&Jf.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){Jf.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{$f(t,(0,l.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,Kf),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=wm(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=im(e.name);return new pr.E$({toolName:e.name,definitionPath:(0,s.join)(r,Zf,`${t}.json`),...Nf(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===Qf))){const e=im(Qf);n.push(new pr.E$({toolName:Qf,definitionPath:(0,s.join)(r,Zf,`${e}.json`)}))}return new pr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return Jf.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new pr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{Ff(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<hm.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{Jf.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,Kf),i=new Set,a=new Map;for(const e of t){const t=wm(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let l=[];try{l=await(0,uo.readdir)(o),l=l.filter((e=>!e.endsWith(Yf)&&!e.endsWith(Xf)))}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++,Lf.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),Jf.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++,Lf.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=a.get(t)??0,d=(0,s.join)(o,t,Zf);let h=0;try{h=(await(0,uo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==l&&(u=!1,p++,Lf.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),Jf.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}))}Uf.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),Bf.gauge(e,i.size,this.getMetricTags({mcp_source:r})),zf.gauge(e,c.size,this.getMetricTags({mcp_source:r})),Wf.gauge(e,d,this.getMetricTags({mcp_source:r})),Hf.gauge(e,p,this.getMetricTags({mcp_source:r})),Jf.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||Jf.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())}}hm.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var pm=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},fm=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 mm=(0,d.h)("local-exec:mcp");function gm(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function vm(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function ym(e){return new Tt._Z({content:{case:"text",value:new Tt.zN({text:e})}})}function wm(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 bm(e,t,r){const n=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t,r.toolDef?.annotations);if(n)return await ss(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Tt.iz({result:{case:"error",value:new Tt.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lh.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 Tt.iz({result:{case:"approved",value:new Tt.Ke}}):null:new Tt.iz({result:{case:"rejected",value:new Tt.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Tt.iz({result:{case:"error",value:new Tt.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new Tt.iz({result:{case:"permissionDenied",value:new Tt.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}})??void 0}class Sm{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 describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[i,s]=o;let a;try{a=await s.getState(e)}catch{return}if("ready"===a.kind)return;const l=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(dt(a));return void 0!==l?`MCP server "${i}" has no callable tools right now. ${l}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=pm(r,(0,l.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(n,[i]));const a=await this.toolSet.getTools(n),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),u=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),d=await bm(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(Zp(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new Yp(t.providerIdentifier,c)),r instanceof Yp){const e=await this.describeDisconnectedServer(n,[i,t.providerIdentifier]);return void 0!==e?new Tt.iz({result:{case:"error",value:new Tt.Nh({error:e})}}):new Tt.iz({result:{case:"serverNotFound",value:new Tt.JL({name:r.serverName,availableServers:r.availableServers})}})}if(Zp(r))return new Tt.iz({result:{case:"toolNotFound",value:new Tt.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(ym(t.text))}else if("resource"===t){const t=e;t.resource?.text&&f.push(ym(t.resource.text))}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),n=await jf(r);f.push(new Tt._Z({content:{case:"image",value:new Tt.do({data:n.data,mimeType:n.mimeType})}}))}else if("image"!==t){const t=vp(e);f.push(ym(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 Tt._Z({content:{case:"text",value:new Tt.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=s.join(t,tp),n=s.join(r,`${(0,o.randomUUID)()}.txt`);await(0,uo.mkdir)(s.dirname(n),{recursive:!0});const i=e.slice(0,rp),a=i.split("\n").length,l=Buffer.byteLength(i,"utf8");return await(0,uo.writeFile)(n,i,"utf8"),new xf.pV({filePath:n,sizeBytes:BigInt(l),lineCount:BigInt(a)})}(e,this.projectDir)});if(void 0===m)throw new Error("Failed to materialize MCP text output");const g=p.structuredContent&&"object"==typeof p.structuredContent&&!Array.isArray(p.structuredContent)?fr.Struct.fromJson(p.structuredContent):void 0,v=new Tt.QW({content:m,isError:p.isError,structuredContent:g});return new Tt.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{fm(r)}}}class km{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=pm(r,(0,l.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 Tt.kP({result:{case:"error",value:new Tt.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Tt.kP({result:{case:"success",value:new Tt.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 Tt.kP({result:{case:"success",value:new Tt.T2({resources:i})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Tt.kP({result:{case:"error",value:new Tt.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{fm(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 Tt.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class Em{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=pm(r,(0,l.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Tt.ZD({result:{case:"error",value:new Tt.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lh.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:fr.Value.fromJson(t.server),uri:fr.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:fr.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Tt.ZD({result:{case:"rejected",value:new Tt.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Tt.ZD({result:{case:"error",value:new Tt.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Tt.ZD({result:{case:"error",value:new Tt.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Tt.ZD({result:{case:"notFound",value:new Tt.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,uo.realpath)(r),o=s.resolve(r,t.replace(/^\/+/,""));if(!gm(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.dirname(o);for(;;)try{if(!gm(n,await(0,uo.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==vm(e))throw e;const t=s.dirname(i);if(t===i)throw e;i=t}if(await(0,uo.mkdir)(s.dirname(o),{recursive:!0}),!gm(n,await(0,uo.realpath)(s.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,uo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==vm(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,uo.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,uo.writeFile)(e,t)}return new Tt.ZD({result:{case:"success",value:new Tt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType})}})}if(r.text)return new Tt.ZD({result:{case:"success",value:new Tt.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 Tt.ZD({result:{case:"success",value:new Tt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"blob",value:e}})}})}return new Tt.ZD({result:{case:"error",value:new Tt.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return mm.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Tt.ZD({result:{case:"error",value:new Tt.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{fm(r)}}}async function xm(e,t){const r=wm(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,uo.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,uo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Cm=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),_m="/mcps/",Pm=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Im=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Tm=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Rm=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),Am=new Map;function Om(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Mm({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 Cm.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=s.servers.find((e=>wm(e.serverIdentifier)===n));if(void 0===a)return;let l;try{l=await o(r,a.serverIdentifier)}catch(t){return void Cm.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"};Pm.increment(e,1,{...c,outcome:l}),Im.histogram(e,s.length,c),Tm.histogram(e,a.length,c),Rm.histogram(e,s.length+a.length,c),"mismatch"===l&&Cm.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 jm(e,t,r,n=xm){if(void 0===r||(void 0===(o=r)||!Om(o).includes(_m)))return;var o;const i=function(e){const t=Om(e),r=t.indexOf(_m);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=Am.get(s);void 0!==c&&clearTimeout(c);const u=e,d=setTimeout((()=>{Am.delete(s),(async()=>{if(l){const e=await t.getState(u);for(const r of e.servers){const o=wm(r.serverIdentifier);await Mm({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Mm({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Cm.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);Am.set(s,d)}var Dm=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},Nm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 $m(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}function Fm(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ko.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}const Lm=(0,d.h)("local-exec/grep");function Um(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function Bm(e){try{return(0,po.existsSync)(e)}catch{return"check_failed"}}function zm(e,t,r,n){return{...Hm(e),...n,cwd:t,cwdExists:Bm(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function Wm(e){return new Error(`Path does not exist: ${e}`)}function Hm(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,po.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,po.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,po.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,po.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,po.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,po.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,po.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,po.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,po.existsSync)(n),t.asarUnpackedDirExists){const e=(0,s.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,po.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class qm{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,this.permissionsService=n?.permissionsService}computeRelativeTarget(e,t){const r=(0,ko.o1)(e,this.singleWorkspacePath);return r===t?".":(0,s.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=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),n=[];for(const o of e){const e=(0,ko.o1)(o.file,t),i=await ts(e);null===i||await this.isPostRipgrepBlocked(i)||void 0!==r&&await r(e,i)||n.push(o)}return n}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=Dm(i,(0,l.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),a=await this.buildArgs(t,r,"files_with_matches"),c=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==c.stderr||2===c.exitCode)&&""===c.stdout.trim())throw new Error(c.stderr||`ripgrep exited with code ${c.exitCode}`);const{files:u,totalFiles:d,clientTruncated:h,ripgrepTruncated:p}=function(e,t,r){const n=e.trim(),o=""!==n?$m(n):[],i=o.length,s=o.slice(0,t),a=o.length>t;return{files:s,totalFiles:Qh(i),clientTruncated:a,ripgrepTruncated:i>=r}}(c.stdout,qm.CLIENT_LIMIT_LINES,qm.HARD_MAX_OUTPUT_LINES),f=(await this.filterBlockedFiles(u.map((e=>({file:e}))),t)).map((({file:e})=>e)),m=u.length-f.length,g=new Zh.T7({files:f,totalFiles:Qh(d-m),clientTruncated:h,ripgrepTruncated:p});return new Zh.vD({result:{case:"files",value:g}})}catch(e){i.error=e,i.hasError=!0}finally{Nm(i)}}async runCountMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=Dm(i,(0,l.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),a=await this.buildArgs(t,r,"count"),c=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==c.stderr||2===c.exitCode)&&""===c.stdout.trim())throw new Error(c.stderr||`ripgrep exited with code ${c.exitCode}`);const{counts:u,totalFiles:d,totalMatches:h,clientTruncated:p,ripgrepTruncated:f}=function(e,t,r){const n=e.trim(),o=""!==n?$m(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:Qh(s),totalMatches:Qh(a),clientTruncated:c,ripgrepTruncated:s>=r}}(c.stdout,qm.CLIENT_LIMIT_LINES,qm.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 Zh.xA({counts:m.map((e=>new Zh.sS({file:e.file,count:Qh(e.count)}))),totalFiles:Qh(d-v),totalMatches:Qh(h-y),clientTruncated:p,ripgrepTruncated:f});return new Zh.vD({result:{case:"count",value:w}})}catch(e){i.error=e,i.hasError=!0}finally{Nm(i)}}async runContentMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=Dm(i,(0,l.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),a=await this.buildArgs(t,r,"content"),c=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==c.stderr||2===c.exitCode)&&""===c.stdout.trim())throw new Error(c.stderr||`ripgrep exited with code ${c.exitCode}`);const{byFile:u,totalLines:d,totalMatchedLines:h,clientTruncated:p,ripgrepTruncated:f}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{Dm(o,(0,l.VI)(n.withName("parseContentOutput")),!1);const i=""===e.trim()?[]:$m(e);i.length>0&&""===i[i.length-1]&&i.pop();const s=new Map,a=new Set;let c=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],l=o[2],d=o[3]??"",h=parseInt(i,10);if(!Number.isFinite(h))continue;const p="-"===l;if(!1===p&&c++,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:Qh(i.length),totalMatchedLines:Qh(c),totalFiles:Qh(d),clientTruncated:u>=t,ripgrepTruncated:i.length>=r}}catch(e){o.error=e,o.hasError=!0}finally{Nm(o)}}(c.stdout,qm.CLIENT_LIMIT_LINES,qm.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 Zh.Zp({matches:g.map((e=>new Zh.uI({file:e.file,matches:e.matches.map((e=>new Zh.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Qh(d-y),totalMatchedLines:Qh(h-w),clientTruncated:p,ripgrepTruncated:f});return new Zh.vD({result:{case:"content",value:b}})}catch(e){i.error=e,i.hasError=!0}finally{Nm(i)}}async executeIndexedGrepWithTimeout(e,t,r,n){if(void 0===this.grepProvider.executeIndexedGrep)return;const[o,i]=e.withTimeoutAndCancel(qm.INDEXED_GREP_CONTEXT_TIMEOUT_MS),s={phase:"provider"},a=performance.now();try{return await(0,Jr.wj)(this.grepProvider.executeIndexedGrep(o,t,r,s),qm.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${qm.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Jr.MU)return void Lm.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,l.VI)(e.withName("LocalGrepExecutor.executeRg")),a="utf8",c=8388608;return n=n??qm.HARD_MAX_OUTPUT_LINES,new Promise(((l,u)=>{let d=!1,h=!1;const p=()=>{h||(h=!0,s.span.end())};let f,m;try{const e=o;f=(0,fo.spawnInSandbox)((0,fo.getRipgrepBinaryPath)(),r,{cwd:t},e),0}catch(r){if(p(),Um(r)){const n=r,o=(0,fo.getRipgrepBinaryPath)();if(Lm.error(e,"rg_diagnostics.spawn_throw",void 0,zm(o,t,n,i)),!1===Bm(t))return u(Wm(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 ${qm.MAIN_TIMEOUT_MS/1e3}s`)),f.kill()}catch{}}),qm.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<=c&&g.push(o)}else!0!==S&&y<=c&&g.push(e)})),f.stderr?.on("data",(e=>{w+=e.length,w<=c&&v.push(e)})),f.on("error",(r=>{if(clearTimeout(m),p(),Um(r)){const n=(0,fo.getRipgrepBinaryPath)(),o=r;if(Lm.error(e,"rg_diagnostics.spawn_enoent",void 0,zm(n,t,o,i)),!1===Bm(t))return void u(Wm(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(),l({stdout:t,stderr:r,exitCode:e??0})}))}))}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const i=Dm(n,(0,l.VI)(e.withName("LocalGrepExecutor.execute")),!1),a=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],c=t.outputMode??"content",u={toolCallId:t.toolCallId,execId:r?.execId,outputMode:c,targetPath:t.path,workspacePaths:a},d=Ho(t.sandboxPolicy);try{const r=this.grepProvider.getWorktreeGuardInfo?.(a);if((0,ko.fl)({targetPath:t.path,workspacePaths:a,mainWorktreePath:r?.mainWorktreePath}))return new Zh.Ud({result:{case:"error",value:new Zh.ts({error:ko.PS})}});if(t.path){const r=await ts((0,ko.o1)(t.path,this.singleWorkspacePath));if(null===r)return new Zh.Ud({result:{case:"error",value:new Zh.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 Zh.Ud({result:{case:"error",value:new Zh.ts({error:`Path '${t.path}' is filtered out by .cursorignore`})}});void 0!==this.mcpStateAccessor&&jm(e,this.mcpStateAccessor,r)}let n={};const l=await this.executeIndexedGrepWithTimeout(i.ctx,a,t,u);if(void 0!==l){n=l;for(const[e,t]of Object.entries(n)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else for(const e of a){if(!1===Bm(e))return new Zh.Ud({result:{case:"error",value:new Zh.ts({error:`Path does not exist: ${e}`})}});let r;if("content"===c)r=await this.runContentMode(i.ctx,e,t,d,u);else if("files_with_matches"===c)r=await this.runFilesMode(i.ctx,e,t,d,u);else{if("count"!==c)throw new Error(`Unknown output mode: ${c}`);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,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>Fm(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);n[t]=new Zh.vD({result:{case:"content",value:new Zh.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-o),totalMatchedLines:Math.max(0,e.totalMatchedLines-s)})}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e)));n[t]=new Zh.vD({result:{case:"files",value:new Zh.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;n[t]=new Zh.vD({result:{case:"count",value:new Zh.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,a),p=new Zh._0({pattern:t.pattern,path:t.path,outputMode:c,workspaceResults:h});return new Zh.Ud({result:{case:"success",value:p}})}catch(e){if(t.path){const e=(0,ko.o1)(t.path,this.singleWorkspacePath);try{await(0,uo.stat)(e)}catch(t){return new Zh.Ud({result:{case:"error",value:new Zh.ts({error:`Path does not exist: ${e}`})}})}}return new Zh.Ud({result:{case:"error",value:new Zh.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{Nm(n)}var o}}qm.MAIN_TIMEOUT_MS=25e3,qm.INDEXED_GREP_TIMEOUT_MS=25e3,qm.INDEXED_GREP_CONTEXT_TIMEOUT_MS=qm.INDEXED_GREP_TIMEOUT_MS+100,qm.HARD_MAX_OUTPUT_LINES=1e4,qm.CLIENT_LIMIT_LINES=2e3;var Gm=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),Vm=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},Jm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Km{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{Vm(r,(0,l.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ko.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,uo.stat)(n)}catch(e){return"ENOENT"===e.code?function(e){const t=tl(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new Gm.fv({result:{case:"error",value:new Gm.uj({path:n,error:"No active terminals."})}}):new Gm.fv({result:{case:"error",value:new Gm.uj({path:n,error:`Path does not exist: ${n}`})}}):new Gm.fv({result:{case:"error",value:new Gm.uj({path:n,error:e.message})}})}if(!r.isDirectory())return new Gm.fv({result:{case:"error",value:new Gm.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Ho(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 Gm.fv({result:{case:"timeout",value:new Gm.ze({directoryTreeRoot:a})}}):new Gm.fv({result:{case:"success",value:new Gm.PC({directoryTreeRoot:a})}})}catch(e){return new Gm.fv({result:{case:"error",value:new Gm.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Jm(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return Vm(o,(0,l.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{Jm(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{Vm(i,(0,l.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new Gm.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(a,c);const d={charactersUsed:a.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=qi(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,s.resolve)(t,e),n=await ts(r);null===n||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,u,d,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await g}}catch(e){i.error=e,i.hasError=!0}finally{Jm(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const l=r.get(a);if(!l)return;const c=i.length;if(!n.budgetExceeded&&n.charactersUsed+c<=o){const e=new Gm.ur({name:i});l.childrenFiles.push(e),n.charactersUsed+=c}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}const o=(0,s.extname)(e);let i=a;for(;i.startsWith(t);){const e=r.get(i);e&&(e.fullSubtreeExtensionCounts[o]??=0,e.fullSubtreeExtensionCounts[o]=Qh(e.fullSubtreeExtensionCounts[o]+1),e.numFiles??=0,e.numFiles=Qh(e.numFiles+1));const t=(0,s.dirname)(i);if(t===i)break;i=t}}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new Gm.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}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});const Ym=1e4,Xm={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class Qm{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<Ym){const r=Math.min(e.length,Ym-t);this.fullOutput+=e.slice(0,r)}this.totalChars>Ym&&(this.fullOutput="")}getOutput(){return this.totalChars<=Ym?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=Ym))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-Ym}}}function eg(e,t){const r=$h-e.length;return r<=0?e:e+t.slice(0,r)}function tg(e,t){return null!==e?e:null===t?-1:-i.constants.signals[t]}class rg{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 Rt.xC({...o,aborted:i,abortReason:r.abortReason})}:{case:"success",value:new Rt.QR(o)};return new Rt.W4({result:s,sandboxPolicy:qo(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const i=performance.now(),s=this.defaultCwd,a=(await(0,fo.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 Qm;let a,c,u="",d="",h=!1,p=!1,f="",m=()=>{};const g=(0,fo.withConfiguredRipgrepEnv)({...process.env,...Xm,CURSOR_AGENT:"1"}),v={shell:!0,cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform},y="insecure_none"===l.type?(0,hl.spawn)(t.command,[],v):(0,fo.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:ep(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=Rt.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=Rt.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=eg(u,t),s.append(t)})),y.stderr?.on("data",(e=>{const t=e.toString();d=eg(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:tg(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,l.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,l.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,i=(0,ko.o1)(t.workingDirectory||this.defaultCwd),s=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new Rt.W4({result:{case:"spawnError",value:new Rt.mJ({command:o,workingDirectory:i,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?Ho(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:i,timeout:s,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new Rt.W4({result:{case:"permissionDenied",value:new Rt.jn({command:o,workingDirectory:i,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Rt.W4({result:{case:"rejected",value:new Rt.pZ({command:o,workingDirectory:i,reason:as(c.reason)})}});a=c.policy,Oo()&&(a=Fo(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{Zm(r)}}}var ng=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),og=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const ig=51200;function sg(e){return Buffer.byteLength(e,"utf8")}function ag(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function lg(e){return new og.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 cg(e,t){const r=t?.maxLines??2e3,n=t?.maxBytes??ig,o=e.split("\n"),i=o.length;if(sg(o[0]??"")>n)return{content:"",truncation:lg({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=sg(t)+i;if(l+c>n){a="bytes";break}s.push(t),l+=c}return{content:s.join("\n"),truncation:lg({truncated:void 0!==a,truncatedBy:a,totalLines:i,outputLines:s.length,outputBytes:l,maxLines:r,maxBytes:n})}}function ug(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var dg=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 hg(e){const{content:t,truncation:r}=function(e){const t=ig,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=sg(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=sg(o[0]),a=!0}break}o.unshift(n),s+=c}return{content:o.join("\n"),truncation:lg({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,uo.mkdtemp)((0,s.join)((0,i.tmpdir)(),"pi-bash-")),o=(0,s.join)(n,"output.log");await(0,uo.writeFile)(o,e,"utf8");const a=r.totalLines-r.outputLines+1,l=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${ag(r.outputBytes)} of line ${l} (${ag(ig)} limit). Full output: ${o}]`:`[Showing lines ${a}-${l} of ${r.totalLines}. Full output: ${o}]`}`,fullOutputPath:o,truncation:r}}class pg{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,l.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 Rt.a({command:e.command,timeout:r,toolCallId:t?.execId??"",fileOutputThresholdBytes:BigInt(0),parsingResult:new Rt.HO({parsingFailed:!1,executableCommands:[{name:n,fullText:e.command,args:[]}]})})}(t,r),r);switch(i.result.case){case"success":{const e=await hg(`${i.result.value.stdout}${i.result.value.stderr}`);return new ng.AH({result:{case:"success",value:new ng.cV(e)}})}case"failure":{const e=await hg(`${i.result.value.stdout}${i.result.value.stderr}`);return new ng.AH({result:{case:"success",value:new ng.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{dg(n)}}error(e){return new ng.AH({result:{case:"error",value:new ng.bD({error:e})}})}}var fg=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function mg(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;case"adminCommandDenylist":return ri(e.pattern);case"userRejected":return e.reason??"User rejected the operation";case"permissionsConfig":return e.isReadonly?"Blocked by readonly permissions configuration":"Blocked by permissions configuration";case"cursorFiles":return"Path is blocked because it is a Cursor internal file";case"unsafeResolution":return e.message;case"needsApproval":return e.approvalReason}}var gg=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function vg(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function yg(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 wg(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 bg(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 Sg=new Map;async function kg(e,t){const r=await async function(e){try{return await(0,uo.realpath)(e)}catch{return e}}(e),n=Sg.get(r)??Promise.resolve();let o;const i=new Promise((e=>{o=e})),s=n.then((()=>i));Sg.set(r,s),await n;try{return await t()}finally{o(),Sg.get(r)===s&&Sg.delete(r)}}function Eg(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,zc.fileURLToPath)(r)),("~"===r||r.startsWith("~/"))&&(r=(0,s.join)((0,i.homedir)(),r.slice(2))),(0,s.normalize)((0,s.isAbsolute)(r)?r:(0,s.resolve)(t??process.cwd(),r))}var xg=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 Cg{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,l.VI)(e.withName("LocalPiEditExecutor.execute")),!1),i=Eg(t.path,this.workspacePath);return kg(i,(async()=>{const e=await this.permissionsService.shouldBlockRead(i);if(e)return this.error(`Read blocked: ${mg(e)}`);try{if((await(0,uo.stat)(i)).isDirectory())return this.error(`Path is a directory: ${i}`);const e=(await(0,uo.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=vg(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=vg(o.oldText),i=wg(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:vg(o.newText)})}if(!n)return{matches:r,matchedContent:e};const o=yg(e),i=[];for(const e of t){const t=yg(vg(e.oldText)),r=wg(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:yg(vg(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,gg.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:h,patch:h,firstChangedLine:bg(a,u)}}(t.path,e,t.edits),s=await this.writeExecutor.execute(o.ctx,new At.hY({path:i,fileText:n.newContent,toolCallId:r?.execId??""}),r);switch(s.result.case){case"success":return new fg.u7({result:{case:"success",value:new fg.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 fg.u7({result:{case:"rejected",value:new fg.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{xg(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 fg.u7({result:{case:"error",value:new fg.Nd({error:e})}})}}var _g=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),Pg=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 Ig(e){return e.split(s.sep).join("/")}class Tg{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,l.VI)(e.withName("LocalPiFindExecutor.execute")),!1);const n=Eg(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Find blocked: ${mg(o)}`);try{if(!(await(0,uo.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,uo.readdir)(o,{withFileTypes:!0});for(const a of i){if(n.length>=t)return;if(".git"===a.name||"node_modules"===a.name)continue;const i=(0,s.join)(o,a.name);await r(i)&&(n.push(i+(a.isDirectory()?s.sep:"")),a.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:Ig((0,s.relative)(n,e))}))).filter((({relative:e})=>(0,_s.xF)(e,o,{dot:!0})));if(0===i.length)return this.success("No files found matching pattern");const a=cg(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`),a.truncation.truncated&&c.push(`${ag(ig)} limit reached`),this.success(c.length>0?`${a.content}\n\n[${c.join(". ")}]`:a.content,{resultLimitReached:l,truncation:a.truncation.truncated?a.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown find error")}}catch(e){r.error=e,r.hasError=!0}finally{Pg(r)}}success(e,t){return new _g.bT({result:{case:"success",value:new _g.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new _g.bT({result:{case:"error",value:new _g.Uy({error:e})}})}}var Rg=r("node:readline"),Ag=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),Og=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 Mg{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,l.VI)(e.withName("LocalPiGrepExecutor.execute")),!1);const n=Eg(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Search blocked: ${mg(o)}`);try{const e=(await(0,uo.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,hl.spawn)((0,fo.getRipgrepBinaryPath)(),r,{stdio:["ignore","pipe","pipe"]}),i=[];let s="",a=!1;const l=Math.max(1,t.limit??100),c=(0,Rg.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=cg(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(`${ag(ig)} 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{Og(r)}}async formatMatches(e,t,r,n){const o=[];let i=!1;for(const a of e){const e=r?(0,s.relative)(t,a.filePath):(0,s.basename)(a.filePath);if(0===n&&void 0!==a.lineText){const t=ug(a.lineText);i=i||t.wasTruncated,o.push(`${e}:${a.lineNumber}: ${t.text}`);continue}const l=(await(0,uo.readFile)(a.filePath,"utf8")).replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n"),c=Math.max(1,a.lineNumber-n),u=Math.min(l.length,a.lineNumber+n);for(let t=c;t<=u;t++){const r=ug(l[t-1]??"");i=i||r.wasTruncated,o.push(t===a.lineNumber?`${e}:${t}: ${r.text}`:`${e}-${t}- ${r.text}`)}}return{output:o.join("\n"),linesTruncated:i}}success(e,t){return new Ag.mr({result:{case:"success",value:new Ag.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new Ag.mr({result:{case:"error",value:new Ag.hP({error:e})}})}}var jg=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),Dg=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 Ng{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,l.VI)(e.withName("LocalPiLsExecutor.execute")),!1);const n=Eg(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`List blocked: ${mg(o)}`);try{if(!(await(0,uo.stat)(n)).isDirectory())return this.error(`Not a directory: ${n}`);const e=Math.max(1,t.limit??500),r=(await(0,uo.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,s.join)(n,t);if(await this.permissionsService.shouldBlockRead(e))continue;const r=await(0,uo.stat)(e);o.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===o.length)return this.success("(empty directory)");const a=cg(o.join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=[];return i&&l.push(`${e} entries limit reached. Use limit=${2*e} for more`),a.truncation.truncated&&l.push(`${ag(ig)} limit reached`),this.success(l.length>0?`${a.content}\n\n[${l.join(". ")}]`:a.content,{entryLimitReached:i?e:void 0,truncation:a.truncation.truncated?a.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown ls error")}}catch(e){r.error=e,r.hasError=!0}finally{Dg(r)}}success(e,t){return new jg.pX({result:{case:"success",value:new jg.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new jg.pX({result:{case:"error",value:new jg.iG({error:e})}})}}var $g=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),Fg=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 Lg{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,l.VI)(e.withName("LocalPiReadExecutor.execute")),!1);const n=function(e,t){const r=Eg(e,t);if((0,po.existsSync)(r))return r;for(const e of function(e){const t=(0,s.dirname)(e),r=e.slice(t.length+1),n=new Set;return n.add(e),n.add((0,s.join)(t,r.normalize("NFD"))),n.add((0,s.join)(t,r.replace(/'/g,"’"))),n.add((0,s.join)(t,r.replace(/ /g," "))),n.add((0,s.join)(t,r.replace(/'/g,"’").normalize("NFD"))),[...n]}(r))if((0,po.existsSync)(e))return e;return r}(t.path,this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Read blocked: ${mg(o)}`);try{if((await(0,uo.stat)(n)).isDirectory())return this.error(`Path is a directory: ${n}`);const e=(await(0,uo.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}=cg(o),a=r+1;let l=i;if(s.firstLineExceedsLimit)l=`[Line ${a} is ${ag(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${ag(ig)} 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 $g.Q({result:{case:"success",value:new $g.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{Fg(r)}}error(e){return new $g.Q({result:{case:"error",value:new $g.tB({error:e})}})}}var Ug=r("../proto/dist/generated/agent/v1/pi_write_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});class zg{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,l.VI)(e.withName("LocalPiWriteExecutor.execute")),!1),i=Eg(t.path,this.workspacePath);return kg(i,(async()=>{const e=await this.writeExecutor.execute(o.ctx,new At.hY({path:i,fileText:t.content,toolCallId:r?.execId??""}),r);switch(e.result.case){case"success":return new Ug.hO({result:{case:"success",value:new Ug.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new Ug.hO({result:{case:"rejected",value:new Ug.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new Ug.hO({result:{case:"error",value:new Ug.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new Ug.hO({result:{case:"error",value:new Ug.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){n.error=e,n.hasError=!0}finally{Bg(n)}}}var Wg=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function Hg(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class qg{constructor(e){this.drainer=e}async execute(e,t){try{const e=await this.drainer.drain({cursor:Hg(t.cursor),advance:!1!==t.advance});return new Wg.Ev({result:{case:"success",value:new Wg.iS({events:e.events.map((e=>new Wg.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 Wg.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new Wg.Ev({result:{case:"error",value:new Wg.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class Gg{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Pt.nt({result:{case:"error",value:new Pt.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Pt.nt({result:{case:"success",value:new Pt.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var Vg=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)}))}}},Jg=function(e){return this instanceof Jg?(this.v=e,this):new Jg(e)},Kg=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 Jg?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 Zg{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=Vg(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 Kg(this,arguments,(function*(){for(const t of e)yield yield Jg(t)}))}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return function(){return Kg(this,arguments,(function*(){var n,o,i,s;for(const e of t)yield yield Jg(e);try{try{for(var a,l=!0,c=Vg(e);!(n=(a=yield Jg(c.next())).done);l=!0){s=a.value,l=!1;const e=s;yield yield Jg(e)}}catch(e){o={error:e}}finally{try{l||n||!(i=c.return)||(yield Jg(i.call(c)))}finally{if(o)throw o.error}}}finally{r.forks.delete(e)}}))}()}}function Yg(e,t){const r=new ho.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 Xg=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),Qg=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class ev{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),tv(rv(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),tv(new Xg.GL({result:{case:"success",value:new Xg.uX({path:t.path,diagnostics:e.map(nv)})}}),await o))}catch(e){return r("unavailable"),tv(rv(t.path,e instanceof Error?e.message:String(e)),await o)}}}function tv(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function rv(e,t){return new Xg.GL({result:{case:"error",value:new Xg.HW({path:e,error:t})}})}function nv(e){return new Qg.oQ({severity:ov(e.severity),range:new xf.Q6({start:new xf.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new xf.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function ov(e){switch(e){case 1:return Qg.h_.ERROR;case 2:return Qg.h_.WARNING;case 3:return Qg.h_.INFORMATION;case 4:return Qg.h_.HINT;default:return Qg.h_.UNSPECIFIED}}class iv{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 iv(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new iv(e)}static fromString(e){return new iv(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 sv=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 av{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,l.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,n]=e.withTimeoutAndCancel(1e4);try{const r=(0,ko.o1)(t.path,this.workspacePath);try{const e=await(0,uo.stat)(r);if(!e.isFile()&&!e.isDirectory())return new Qg.Ek({result:{case:"fileNotFound",value:new Qg.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new Qg.Ek({result:{case:"fileNotFound",value:new Qg.Mu({path:t.path})}});if("EACCES"===e.code)return new Qg.Ek({result:{case:"permissionDenied",value:new Qg.RP({path:t.path})}});throw e}const n=(0,ko.o1)(r,this.workspacePath),o=new iv(n);await this.diagnosticsProvider.open(e,o);const i=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new Qg.Ek({result:{case:"success",value:new Qg.a1({path:t.path,diagnostics:i,totalDiagnostics:i.length})}})}catch(r){return e.canceled?new Qg.Ek({result:{case:"error",value:new Qg.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new Qg.Ek({result:{case:"error",value:new Qg.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{sv(r)}}convertDiagnostic(e){return new Qg.oQ({severity:this.convertSeverity(e.severity),range:e.range?new xf.Q6({start:new xf.yX({line:e.range.start.line,column:e.range.start.character}),end:new xf.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 Qg.h_.ERROR;case 2:return Qg.h_.WARNING;case 3:return Qg.h_.INFORMATION;case 4:return Qg.h_.HINT;default:return Qg.h_.UNSPECIFIED}}}var lv=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 cv(e){return lv(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 lv(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,hl.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=>lv(this,void 0,void 0,(function*(){const t=i.get(e);if(!0!==t)if(!1!==t)if(function(e){return new uv(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 uv(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 uv{constructor(e,t){this.name=e,this.extname=s.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 dv=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,hv=/^(a|b|i|w|c|o|1|2)\//,pv=e=>{const t=e?.match(dv);return t?.map((e=>e.replace(hv,"").replace(/("|')$/,"")))},fv=/^\\?['"]|\\?['"]$/g,mv=e=>{let t=gv(e,"-+").trim();return t=yv(t),t.replace(fv,"").replace(hv,"")},gv=(e,t)=>{if(e=bv(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=wv(t);return e.replace(new RegExp(`^${r}+`),"")},vv=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,yv=e=>{const t=vv.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},wv=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${bv(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,bv=e=>`${e??""}`,Sv=(0,d.h)("local-git-diff");async function kv(e,t,r={}){const n=await new Promise(((n,o)=>{const i=wl("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 Ev(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]=pv(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=mv(e)}],[/^\+\+\+\s/,e=>{c(),n.to=mv(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 vr.o$({diffs:t.map((e=>function(e){const t=new vr.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new vr.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:vr.Wf.UNSPECIFIED})}const xv=["main","master","develop"];class Cv{async execute(e,t){return async function(e,t,r){const n=function(e){switch(e){case vr.ek.NAME_STATUS:return vr.ek.NAME_STATUS;case vr.ek.NAME_STATUS_AND_NUMSTAT:return vr.ek.NAME_STATUS_AND_NUMSTAT;case vr.ek.FILE_DIFFS:return vr.ek.FILE_DIFFS;case vr.ek.DIFFS_WITH_BEFORE_AND_AFTER:return vr.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return vr.ek.FILE_DIFFS}}(r.outputFormat),o=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await kv(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of xv){const r=`origin/${t}`;try{return await kv(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await kv(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await kv(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 kv(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 a=await kv(t,i,{shouldNotTrimOutput:!0}),l=Ev(a);let c=[];if(r.maxUntrackedFiles>0){c=await async function(e,t){let r=(await kv(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 uo.readFile(s.join(e,t),"utf8"),path:t}}catch{return}})))).filter((e=>void 0!==e))}(t,r.maxUntrackedFiles);for(const e of c){const r=await kv(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});l.diffs.push(...Ev(r).diffs)}}if(n!==vr.ek.FILE_DIFFS)for(const e of l.diffs)e.chunks=[];if(n===vr.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 kv(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 kv(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}else try{i.afterFileContents=await uo.readFile(s.join(t,i.to),"utf8")}catch{try{i.afterFileContents=await kv(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}}else i.afterFileContents=""}catch(t){Sv.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 cv({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 kv(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){Sv.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=wl("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`}(a,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 kv(t,["rev-parse","HEAD"])).trim():void 0,m=!0===r.returnHeadSha?(await kv(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,g=new vr.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 _v=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class Pv{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new _v.M({allowlisted:r})}}const Iv=8388608;var Tv=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Rv=BigInt(0),Av=BigInt(8),Ov=BigInt(16),Mv=BigInt(65535);function jv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Dv(e){const t=e.split(".");if(4!==t.length)return;let r=Rv;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<<Av|BigInt(t)}return{version:4,value:r}}function Nv(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=Dv(n);if(!o)return;t.push(Number(o.value>>Ov&Mv)),t.push(Number(o.value&Mv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function $v(e){var t;return null!==(t=Dv(e))&&void 0!==t?t:function(e){const t=jv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Nv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<Ov|BigInt(t)),Rv)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),i=Nv(n),s=Nv(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<<Ov|BigInt(t)),Rv)}}(e)}function Fv(e,t){const r=jv(e),n=jv(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=$v(t.slice(0,r)),o=$v(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 Lv(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=>Fv(e,t)))}(r.hostname,t)}function Uv(e){return e.trim().toLowerCase()}function Bv(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.map((t=>`${e}:${t}`));case"reads":return[];default:return t}}function zv({autoRunControls:e,allowedMcpServers:t}){var r;const n=!0===(null==e?void 0:e.enabled)&&null!==(r=e.mcpToolAllowlist)&&void 0!==r?r:[],o=function(e){return(null!=e?e:[]).flatMap((e=>{const t=void 0===e.name?"":Uv(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(null!=(n=t)?n:[]).map(Uv).filter((e=>e.length>0));var n;const o=void 0===e?void 0:Uv(e);return"all"===o?{mode:"all"}:"reads"===o?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Bv(t,r)}]}))}(t);return{tools:(i=[...o.flatMap((e=>[...e.flattened])),...n],[...new Set(i)]),policies:o.map((e=>({name:e.name,policy:e.policy})))};var i}const Wv=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Hv(e){return e.trim().split(/\s+/).filter(Boolean)}function qv(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 Hv(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 Wv.has(o)}function Gv(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 Vv(e,t){return e.commandName.localeCompare(t.commandName)}function Jv(e){var t;return null!==(t=e.split(" ")[0])&&void 0!==t?t:e}function Kv(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=Hv(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(Vv);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=Gv(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&&Gv(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(Jv(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(Jv(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(Jv(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const s=n.filter((e=>!i.has(Jv(e))));return{defaultSelectedOptionIds:[...new Set([...s,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Zv="win32"===process.platform;function Yv(e,t){return Zv&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const Xv=(0,s.join)((0,i.homedir)(),".cursor","projects"),Qv=(0,s.join)((0,i.homedir)(),".cursor","worktrees");function ey(e){return Yv(Xv,e)&&e!==Xv}function ty(e){return Yv(Qv,e)&&e!==Qv}function ry(e,t){const r=function(e){if(!Yv(Xv,e))return;if(e===Xv)return;const t=(0,s.relative)(Xv,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function ny(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function oy(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 iy(e,t){const r=(0,ko.o1)(e,t);try{return ny(await(0,uo.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return ny(r,r,oy(t));try{if((await(0,uo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,uo.readlink)(r)}catch{}return ny(r,r,{status:"danglingSymlink",symlinkTarget:e})}return ny(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){const t=e;return"ENOENT"===t.code?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,uo.realpath)(t);return ny((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return ny(e,e,oy(r))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return ny(e,e,{status:"newFile"})}(r):ny(r,r,oy(t))}}}function sy(e){return"resolved"===e.status||"newFile"===e.status}function ay(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 ly=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},cy=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 uy=(0,d.h)("permissions-service"),dy=(0,h.Pu)("local_exec.permissions.mcp_allowlist_check.result",{description:"Result of MCP allowlist checks at user and team levels per tool call.",labelNames:["allowlist_scope","outcome"]});function 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 py(e){return[...new Set(e)]}function fy(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function my(e,t){const r="win32"===process.platform||"darwin"===process.platform,n=r?e.toLowerCase():e,o=r?t.toLowerCase():t;if(n===o)return!0;const i=o.endsWith(s.sep)?o:o+s.sep;return n.startsWith(i)}function gy({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 vy(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yy(e){return"<"!==e.operator&&"<&"!==e.operator}function wy(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function by(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function Sy({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:i,tempPathOptions:s}){if(""!==i.parse(e).root&&!i.isAbsolute(e))return;const a=await o(e,t);if(sy(a.resolution)){for(const e of r){const t=await o(e);if(sy(t.resolution)&&gy({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:i}))return"workspace-file"}return n&&Ry(a.resolvedPath,s)?"tmp-file":void 0}}function ky(e){return py(e.map((e=>e.trim())).filter(Boolean))}function Ey(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 xy(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Cy(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new Rt.r6({type:"word",value:e})));return new Rt.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function _y(e,t={}){return{type:e,...t}}function Py(e,t){if("workspace"===e&&void 0!==t)return t}const Iy={workspace:0,system:1};function Ty(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 Ry(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||!gy({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 Ay(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,fo.isNetworkEnabledByPolicy)(e.networkPolicy),n=(0,fo.isNetworkEnabledByPolicy)(t.networkPolicy);if(r&&!n)return!1;const o=(0,fo.isAllowAllNetworkByPolicy)(e.networkPolicy),i=(0,fo.isAllowAllNetworkByPolicy)(t.networkPolicy);if(o&&n&&!i)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const s=e.readBoundary??"system",a=t.readBoundary??"system";return!(Iy[s]>Iy[a])}class Oy{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&Ay(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||!Ay(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function My(e){return e?.type??"undefined"}class jy{constructor(e,t,r,n,o,a=!1,l){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.rootDirectories=Array.isArray(o)?o:[o??process.cwd()],this.perUserSandboxConfigPath=l?.perUserSandboxConfigPath??(0,s.join)((0,i.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=l?.mcpAllowlistLog}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const e=await this.teamSettingsService.getSandboxingControls(),t=e.readBoundary,r=await this.getPermissions(),n="workspace"===t,o="workspace"===r.readBoundary;if(!n&&!o||"unrestricted"===r.approvalMode)return;const i=n?e.readAllowlistPaths??[]:[];return async(e,t)=>{if(this.isRequestOnTeamReadAllowlist(e,t,i))return!1;if(o&&!n&&(await this.isPathExplicitlyAllowed("Read",t)||e!==t&&await this.isPathExplicitlyAllowed("Read",e)))return!1;for(const e of this.rootDirectories)if(await this.isInsideWorkspaceReadRoot({realAbsolutePath:t,rootPath:e}))return!1;return!0}}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ko.o1)(e),o=await ts(n);if(null===o)return{type:"unsafeResolution",message:hy("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!ey(o)&&!ty(o)&&!t&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:o,requestedAbsolutePath:n});if(e)return e}return!1}async shouldBlockReadForBoundary({realAbsolutePath:e,requestedAbsolutePath:t}){const r=await this.teamSettingsService.getSandboxingControls(),n=r.readBoundary,o=await this.getPermissions(),i="workspace"===n,s="workspace"===o.readBoundary;if(!i&&!s)return!1;if(i&&this.isRequestOnTeamReadAllowlist(t,e,r.readAllowlistPaths??[]))return!1;if(s&&!i&&await this.isPathExplicitlyAllowed("Read",t))return!1;for(const t of this.rootDirectories)if(await this.isInsideWorkspaceReadRoot({realAbsolutePath:e,rootPath:t}))return!1;return"unrestricted"!==o.approvalMode&&{type:"needsApproval",approvalReason:i?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isInsideWorkspaceReadRoot({realAbsolutePath:e,rootPath:t}){const r=await iy(t);return sy(r.resolution)?my(e,r.resolvedPath):my(e,(0,ko.o1)(t))}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{ly(n,(0,l.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const o=await iy(t);if(!sy(o.resolution))return{type:"unsafeResolution",message:ay(o.originalPath,o.resolution)};const c=o.resolvedPath,u=c;if(await this.ignoreService.isRepoBlocked(u))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",c))return{type:"permissionsConfig"};const d=o.originalPath.split(s.sep).pop()?.toLowerCase()??"",h=c.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===d||".cursorignore"===h)return{type:"permissionsConfig"};const p=ey(u),f=ty(u),m=!p&&!f&&await this.ignoreService.isCursorIgnored(u);if(p||f);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",c))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(c))return!1;const 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 iy(e);if(!sy(t.resolution))continue;const r=t.resolvedPath;if(my(c,r)){const e=(0,s.relative)(r,c).split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const v=async()=>{let e=!1,t="";try{t=await Ti(c),e=!1}catch{e=!0}let n="";if(e)n=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,gg.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 iy(e);if(!sy(t.resolution))continue;const r=t.resolvedPath;if(my(c,r)){w=!0,y=r;break}}const b=w?void 0:function(e){if(!ty(e))return;const t=(0,s.relative)(Qv,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(Qv,t[0]):void 0}(c);if(!w&&void 0===b){if(function(e){return Ry(e,{platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,i.homedir)()})}(c))return!1;if(ry(c,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,i.homedir)()}${s.sep}.cursor${s.sep}`;if(c.startsWith(e)){const e=c.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const S=y??b,k=c;let E=(0,s.relative)(S,k).split(s.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,fo.isHardcodedWriteProtected)(c,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{cy(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await ts(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:hy("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const i=(await this.getPermissions()).userConfiguredPolicy,s=r??i;return"workspace_readonly"===i.type&&"workspace_readonly"!==s.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,i=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===i.kind)return i;const s=await this.getPermissions(),a=s.approvalMode,l="unrestricted"===a,c=s.userConfiguredPolicy,u=!s.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(uy.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:My(c),requestedPolicyType:My(n),effectiveRequestedPolicyType:My(n??c),smartAllowlistEnabled:!0===s.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Yt(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,s))return uy.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:My(c),requestedPolicyType:My(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??c);const d=r.parsingResult.executableCommands,h=r.parsingResult.hasRedirects,p=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,m=r.classifierResult,g=r.smartModeApprovalReason,v=r.smartModeApprovalRequestId,y=void 0!==m&&!m.classificationFailed&&m.commands.length>0?m:void 0,w="allowlist"===a&&s.smartAllowlistEnabled?y?.commands:void 0,b=void 0!==w,S=w?w.map(Cy):d,k=void 0!==w?w.map(Ey):S.map((e=>[e.fullText.trim()].filter(Boolean))),E=void 0!==y?y.commands.map(Ey):k;if(n||(n=s.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==c.type&&(n={...n,skipStatsigDefaults:c.skipStatsigDefaults??!0}),"insecure_none"!==c.type&&(0,fo.isNetworkEnabledByPolicy)(c.networkPolicy)&&"insecure_none"!==n.type&&!(0,fo.isAllowAllNetworkByPolicy)(n.networkPolicy)){const e=c.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}}n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,fo.mergeReadBoundary)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,fo.mergeAdditionalReadPaths)(Py(e.readBoundary,e.additionalReadPaths),Py(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:c}),m&&uy.info(e,"Smart allowlist: classifier result received",{classificationFailed:m.classificationFailed,suggestedSandboxMode:m.suggestedSandboxMode,commandCount:m.commands.length,suggestedAllowlistEntryCount:m.commands.filter((e=>e.suggestedAllowlistEntry)).length});let x=!1;const C=[],_=[];let P=[],I=[],T=[];const R=ky(s.smartAllowlistDenylist??[]);if(R.length>0){I=[];const t=E.map((e=>e[0]??""));for(let e=0;e<E.length;e++){const r=E[e];if(r&&0!==r.length&&R.some((e=>xy(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&(uy.info(e,"Command blocklist: commands require approval",{count:I.length}),C.push(`In blocklist: ${I.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=s.allow.filter((e=>this.isShellEntry(e)));uy.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:R.length});const n=k.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),i=[];for(let e=0;e<m.commands.length;e++){if(n[e])continue;const t=m.commands[e];t&&i.push(t)}if(P=ky(i.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(qv(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),ky(o)}(e)))),T=i.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=Kv(P,T),t=e.length>0?e.join(", "):P.join(", ");_.push(`Not in allowlist: ${t}`)}x=o&&0===I.length,x&&uy.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const A="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:c,O=S.map(((e,t)=>new Oy(e,n,A,k[t])));if((0===S.length||f&&!b)&&!l){uy.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:My(n),userConfiguredPolicyType:My(c),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==v});const o={type:Lh.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:g??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:g,smartModeApprovalRequestId:v}},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,O))return{kind:"block",reason:{type:"permissionsConfig"}};const{allRedirectsAreWorkspaceFileSafe:M,redirectsAllowlistSafe:j}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===c.type||"workspace"!==c.readBoundary),D=await this.teamSettingsService.getAutoRunControls(),N={type:"insecure_none"};for(const e of O)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:j,autoRunControls:D,applyTeamAllowlist:u})&&e.approveWithPolicy(N);for(const e of O)D&&this.isInTeamBlocklist(D,e)&&e.deny();const $=await this.teamSettingsService.getDeleteFileProtection();if($)for(const e of O)"rm"===e.command.name&&e.deny();const F=this.buildShellApprovalDecisionFacts({commands:O,autoRunControls:D,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:$,softDenylistedCommands:I});if("workspace_readonly"===c.type&&"workspace_readonly"!==n.type)return uy.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=Yt(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason;let B=L?void 0:this.getShellAutoApprovalPolicy({approvalMode:a,isUnrestricted:l,requestedPolicy:n,facts:F,preserveRequestedPolicyForAllowlistedCommands:b});const z=void 0!==B&&F.allCommandsAllowlisted&&"insecure_none"===B.type&&"allowlistEscalated"in B&&!0===B.allowlistEscalated;if("insecure_none"===B?.type){const{readBoundary:e}=await this.getAdminReadSandboxing();"workspace"===e&&(o?B=void 0:"insecure_none"!==n.type&&(B=n))}const W=void 0!==B&&z;if(B&&(l||void 0===g||W)){b&&F.allCommandsPreapproved&&!F.allCommandsAllowlisted&&uy.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(B);return uy.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:My(n),userConfiguredPolicyType:My(c),autoApprovalPolicyType:My(B),mergedPolicyType:My(t),isSmartAllowlistActive:b,smartModeApprovalBypassedByAllowlist:W,allCommandsRunnable:F.allCommandsRunnable,allCommandsAllowlisted:F.allCommandsAllowlisted,allCommandsPreapproved:F.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==g,commandCount:O.length}),{kind:"allow",policy:t}}let H=(b||(!h||p||M)&&!f)&&("allowlist"===a||"ask-every-time"===a)&&F.canAllowlistInPrompt;const q=[],G=void 0!==g,V=F.notInTeamAllowlist.length>0&&(F.hasSecurityDenies||F.hasSoftDenies||!F.allCommandsRunnable);if(void 0!==g&&q.push(g),L&&(G||q.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),H=!1),C.length>0&&(G||q.push(...C),H=!1),!G)if(b&&_.length>0)q.push(..._);else if(F.unapprovedCommands.length>0){const e=Kv(this.generateAllowlistPatterns(F.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):F.unapprovedCommands.map((e=>e.command.fullText)).join(", ");q.push(`Not in allowlist: ${t}`)}if(F.hasSecurityDenies&&(G||(F.rmDeniedByDeleteProtection.length>0&&q.push("Delete protection is enabled"),F.teamBlocklistedCommands.length>0&&q.push(`In team blocklist: ${F.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),H=!1),V){const t=F.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");uy.info(e,"Shell permissions: commands not in team allowlist",{commandCount:F.notInTeamAllowlist.length}),G||q.push(`Not in team allowlist: ${t}`),H=!1}const J=q.join(" • "),K=[];if(H){const e=void 0!==g?O.filter((e=>"allowlisted"!==e.state)):F.unapprovedCommands;K.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const Z=b&&_.length>0,Y=Z?P:K,X=Z&&T.length>0?T:void 0,Q="insecure_none"!==n.type&&"insecure_none"!==c.type,ee="insecure_none"!==n.type,te=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,C.length>0?"command_blocklist":void 0,b&&_.length>0?"smart_allowlist_miss":void 0,F.unapprovedCommands.length>0?"unapproved_commands":void 0,F.hasSecurityDenies?"security_denies":void 0,V?"team_allowlist_miss":void 0].filter((e=>void 0!==e));uy.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:My(n),userConfiguredPolicyType:My(c),isSandboxAvailable:Q,isSandboxEnabled:ee,canAllowlist:H,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==v,hookForcesPrompt:L,approvalReasonTypes:te,commandCount:O.length,unapprovedCommandCount:F.unapprovedCommands.length,deniedCommandCount:F.deniedCommands.length,notInTeamAllowlistCount:F.notInTeamAllowlist.length,notAllowedCommandCount:Y.length,suggestedAllowlistEntryCount:X?.length??0,allCommandsRunnable:F.allCommandsRunnable,allCommandsAllowlisted:F.allCommandsAllowlisted,allCommandsPreapproved:F.allCommandsPreapproved,hasSecurityDenies:F.hasSecurityDenies,hasSoftDenies:F.hasSoftDenies});const re={type:Lh.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:J,isSandboxAvailable:"allowlist"===a&&Q,isSandboxEnabled:"allowlist"===a&&ee,canAllowlist:H,notAllowedCommands:Y,suggestedAllowlistEntries:X,smartModeApprovalReason:g,smartModeApprovalRequestId:v}},ne=await this.pendingDecisionStore.requestApproval(re);if(ne.approved){const e="unrestricted"===a?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:ne.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,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);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(Cy):u;if(0===d.length)return!1;const h=c?l.commands.map(Ey):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==l?l.commands.map(Ey):h,f={type:"insecure_none"},m=d.map(((e,t)=>new Oy(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=ky(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>xy(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{userSandboxDataFolderName:t}=await this.getPermissions(),r=void 0!==t&&t.length>0?(0,s.join)((0,i.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,n=await this.foldPerUserFilePolicy(e,r),o=n.skipStatsigDefaults?n:await this.applyStatsigDefaults(n),a=await this.loadPerRepoFilePolicy(o.type),l=await this.buildTeamAdminPolicy(o.type),c=(0,fo.isAllowAllNetworkByPolicy)(e.networkPolicy),{policy:u}=await(0,fo.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:o,perRepo:a,teamAdmin:l});return c?{...u,networkPolicy:(0,fo.networkAllowAllPolicy)()}:u}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,fo.loadSandboxPolicyFromFileOrUndefined)(t,(0,i.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,fo.mergeNetworkPolicies)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const o=(0,fo.mergePathsUnion)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),s={...e,networkPolicy:n,additionalReadonlyPaths:o.length>0?o:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,fo.mergePathsUnion)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...s,additionalReadwritePaths:t.length>0?t:void 0}}return s}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,fo.isAllowAllNetworkByPolicy)(e.networkPolicy))return e;const r={default:"deny",allow:py(t.allowlist)};return{...e,networkPolicy:(0,fo.mergeNetworkPolicies)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,fo.loadSandboxPolicyFromFileOrUndefined)((0,s.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?_y(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r:void 0}async buildTeamAdminPolicy(e){const t=await this.buildTeamAdminNetworkPolicy(e),{readBoundary:r,readAllowlistPaths:n}=await this.getAdminReadSandboxing();return void 0===r?t:{...t??_y(e),readBoundary:r,additionalReadPaths:n}}async getAdminReadSandboxing(){const e=await this.teamSettingsService.getSandboxingControls();return{readBoundary:"workspace"===e.readBoundary?"workspace":void 0,readAllowlistPaths:e.readAllowlistPaths??[]}}async buildTeamAdminNetworkPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return _y(e,{networkPolicy:(0,fo.networkDisabledPolicy)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=py(t.allowlist)),t.denylist.length>0&&(r.deny=py(t.denylist)),_y(e,{networkPolicy:r})}async isInShellAllowlist(e){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,o=e.parsingFailed,s=!0===e.allRedirectsAreDevNull,l=!(!n||s||o)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:o=iy,pathModule:s=a,tempPathOptions:l={platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,i.homedir)()}}){if(!e.hasRedirects)return!0;const c=e.redirects;if(0===c.length)return!1;const u=e.executableCommands.length>1,d=fy();for(const e of c){if(by(e))continue;const i=u?fy():d,{operator:a,targetText:c}=e,p=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=wy(c),t=void 0===e?void 0:i.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}for(const e of p)i.fdTargets.set(e,t);continue}if("<&"===a){const e=wy(c),t=void 0===e?void 0:i.fdTargets.get(e);if("dev-null"!==t){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}for(const e of p)i.fdTargets.set(e,t);continue}if("/dev/null"===c){for(const e of p)i.fdTargets.set(e,"dev-null");continue}if(!vy(a)||void 0===c){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}const f=await Sy({targetText:c,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:l});if(!f){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}for(const e of p)i.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),c=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yy))}({parsingResult:e,hasRedirects:n,parsingFailed:o,allRedirectsAreAllowlistSafe:s,allRedirectsAreWorkspaceFileSafe:l});return{allRedirectsAreAllowlistSafe:s,allRedirectsAreWorkspaceFileSafe:l,redirectsAllowlistSafe:c}}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:Lh.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 getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ti({matchForms:t.parsingResult?Yo({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(uy.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Ty(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Ty(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)qv(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)))}isPathOnTeamReadAllowlist(e,t){const r=e=>"win32"===process.platform?e.replaceAll("\\","/"):e,n=r(e);return t.some((e=>this.matchGlob(r(this.expandTilde(e)),n)))}isRequestOnTeamReadAllowlist(e,t,r){return this.isPathOnTeamReadAllowlist(t,r)||e!==t&&this.isPathOnTeamReadAllowlist(e,r)}expandTilde(e){return"~"===e?(0,i.homedir)():e.startsWith("~/")?(0,i.homedir)()+e.slice(1):e}matchGlob(e,t){return Zo(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{ly(n,(0,l.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:o,toolName:i,providerIdentifier:s,args:a}=t,c=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Df(r.annotationsJson)}(t,r),u=e=>{this.mcpAllowlistLog?.(e)};u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${s}"`);const d=await this.getPermissions(),h=await this.teamSettingsService.getMcpToolControls(),p=!0===h?.enabled;if(await this.isMcpExplicitlyDenied(e,s,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${s}"`),{type:"permissionsConfig"};const f=t.smartModeApproval?.reason;if(void 0!==f)return"workspace_readonly"===d.userConfiguredPolicy.type&&"unrestricted"!==d.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${s}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${s}"`),!(p?this.isMcpInTeamAllowlist(h,{providerIdentifier:s,toolName:i,annotations:c}):await this.isMcpExplicitlyAllowed(e,s,i))&&!("unrestricted"===d.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:f,approvalDetails:{type:"mcp",name:o,toolName:i,providerIdentifier:s,args:a,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:f,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(p){const t=this.isMcpInTeamAllowlist(h,{providerIdentifier:s,toolName:i,annotations:c});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${s}"`),!1}else{const t=await this.isMcpExplicitlyAllowed(e,s,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${s}"`),!1}if("workspace_readonly"===d.userConfiguredPolicy.type&&"unrestricted"!==d.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${s}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===d.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${s}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${s}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${s}", approvalMode="${d.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:o,toolName:i,providerIdentifier:s,args:a,canAllowlist:!0}}}catch(e){n.error=e,n.hasError=!0}finally{cy(n)}}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,i=t.annotations??Df(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o))return!1;const s=await this.teamSettingsService.getMcpToolControls();return!0===s?.enabled?!!this.isMcpInTeamAllowlist(s,{providerIdentifier:n,toolName:o,annotations:i}):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}){dy.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&&Fv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&function(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Uv(e);return 0!==r.length&&t.some((e=>Uv(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var Dy=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,d.h)("LocalReadExecutor"),$y=async(e,t,r,n)=>{const o=setTimeout((()=>{Ny.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function Fy(e){return e>=32&&e<=126||9===e||10===e||13===e}const Ly=Buffer.from("\n---\n");const Uy=[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 By(e){const t=(0,s.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 Tv.sV({result:{case:"invalidFile",value:new Tv.cW({path:e,reason:r})}})}function zy(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 Wy(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 Hy(e,t){const r=Wy(e,t);return{text:r.text,truncated:r.truncated}}function qy(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=Wy(n,"\n")),n=Wy(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function Gy(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 Vy extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function Jy(e,t,r,n){const o=void 0!==r.offset||void 0!==r.limit,i=(r.offset??1)<0,s=r.offset??1,a=Math.max(0,s-1),l=void 0===r.limit?void 0:a+r.limit,c=i?Math.abs(s):0,u=[];let d=0,h=!1;const p=[];let f=0,m=!1;const g=[];let v=0,y=!1,w={text:"",truncated:!1},b=0,S=0,k=0,E=!1,x=!1;const C=e=>{let t=e;return!E&&t.length>0&&(E=!0,65279===t.charCodeAt(0)&&(x=!0,t=t.slice(1))),t},_=(e,t)=>{const r=b;if(t&&(e.text.endsWith("\r")?S++:k++),((e,t)=>{if(h&&d>=Iv)return;const r=u.length>0?1:0;let n=Iv-d;if(r>0){if(n<=0)return void(h=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};u.push(o),d+=r+o.line.text.length,(e.truncated||o.line.truncated)&&(h=!0)})(e,t),i){if(c>0){for(g.push({line:e,hasNewline:t}),v+=e.text.length+1;g.length>c;){const e=g.shift();void 0!==e&&(v-=e.line.text.length+1)}for(;g.length>1&&v>Iv;){const e=g.shift();void 0!==e&&(v-=e.line.text.length+1,y=!0)}}}else o&&r>=a&&(void 0===l||r<l)&&((e,t)=>{if(m&&f>=Iv)return;const r=p.length>0?1:0;let n=Iv-f;if(r>0){if(n<=0)return void(m=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};p.push(o),f+=r+o.line.text.length,e.truncated&&(m=!0),o.line.truncated&&(m=!0)})(e,t);b++};for await(const r of async function*(e,t,r){if("strictUtf8"===r.kind){const r=new ii.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n=(0,po.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 Vy;throw e}return}const n=(0,po.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe(si.decodeStream(r.decoderEncoding));for await(const e of n)yield"string"==typeof e?e:String(e)}(e,t,n)){const e=C(r).split("\n");for(let t=0;t<e.length;t++)w=Hy(w,e[t]),t<e.length-1&&(_(w,!0),w={text:"",truncated:!1})}_(w,!1);const P=S+k,I=P>0&&S/P*100>=5;!function(e,t){if(Ei.has(e)&&Ei.delete(e),Ei.set(e,t),Ei.size<=100)return;const r=Ei.keys().next().value;void 0!==r&&Ei.delete(r)}(t,"utf8"===n.cacheEncoding&&x?"utf8bom":n.cacheEncoding);let T={text:"",truncated:h};if(T=qy(T,u,I),!o)return{content:T.text,totalLines:b,truncated:T.truncated,rangeApplied:!1};if(""===T.text)return{content:"",totalLines:b,truncated:!1,rangeApplied:!1};if(i){const e=r.limit??c;let t={text:"",truncated:y};return t=qy(t,g.slice(0,e),I),{content:t.text,totalLines:b,truncated:t.truncated,rangeApplied:!0}}if(a>=b)return{content:T.text,totalLines:b,truncated:T.truncated,rangeApplied:!1};let R={text:"",truncated:m};return R=qy(R,p,I),{content:R.text,totalLines:b,truncated:R.truncated,rangeApplied:!0}}class Ky{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var 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,l.VI)(e.withName("LocalReadExecutor.execute")),!1);const n=t.path,o=(0,ko.o1)(n,this.workspacePath),i=await $y(e,"permissionsService.shouldBlockFileRead",3e3,(()=>async function(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}(this.permissionsService,o)));if(i){const r=await $y(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ss(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lh.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(i,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Tv.sV({result:{case:"rejected",value:new Tv.f4({path:o,reason:r.reason??""})}});if("denied"===r.kind)return new Tv.sV({result:{case:"permissionDenied",value:new Tv.lW({path:o})}})}void 0!==this.mcpStateAccessor&&jm(e,this.mcpStateAccessor,o);try{const r=await $y(e,"stat",3e3,(()=>(0,uo.stat)(o)));if(r.isDirectory())return new Tv.sV({result:{case:"invalidFile",value:new Tv.cW({path:o,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Tv.sV({result:{case:"invalidFile",value:new Tv.cW({path:o,reason:"Path is neither a file nor a directory"})}});const n=function(e){return null!==function(e){const t=tl(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=tl(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 a=await $y(e,"getFormatForFile",3e3,(()=>Ai(o))),l=a.isImageFile,c=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(o),u=Pi(o);if(l){const t=await $y(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,uo.readFile)(o);return jf(e)}));return new Tv.sV({result:{case:"success",value:new Tv.mE({path:o,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c){const t=await $y(e,"readPdfBinary",3e3,(()=>(0,uo.readFile)(o)));return new Tv.sV({result:{case:"success",value:new Tv.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(a.isBinaryFile&&u){const t=await $y(e,"readBinaryFile",3e3,(()=>(0,uo.readFile)(o)));return new Tv.sV({result:{case:"success",value:new Tv.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(a.isBinaryFile)return By(o);{const n=this.useStreamingRead;if(!n||await $y(e,"useStreamingRead",3e3,(()=>n()))){const n=await $y(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=function(e,t,r){const n=function(e,t,r){return Gy(r??Ei.get(e)??t.encoding)}(e,t,r),o=function(e){const t=Gy(e);return"utf8bom"===t?"utf8":t}(n);return"utf8"===o?{kind:"strictUtf8",cacheEncoding:"utf8"}:si.encodingExists(o)?{kind:"iconv",decoderEncoding:o,cacheEncoding:n}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,n.encodingHint);try{return await Jy(e,t,n,o)}catch(r){if(r instanceof Vy)return await Jy(e,t,n,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,o,a,t)));return new Tv.sV({result:{case:"success",value:new Tv.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 $y(e,"readText",3e3,(()=>Ti(o,t.encodingHint))),s=await $y(e,"countLines",3e3,(()=>Oi(i))),l=zy(i,s,t);let c=l.content,u=!1;return c.length>Iv&&(c=c.substring(0,Iv),u=!0),new Tv.sV({result:{case:"success",value:new Tv.mE({path:o,output:{case:"content",value:c},totalLines:s,fileSize:BigInt(r.size),truncated:u,rangeApplied:l.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new Tv.sV({result:{case:"fileNotFound",value:new Tv.Ko({path:o})}}):"EACCES"===t.code||"EPERM"===t.code?new Tv.sV({result:{case:"permissionDenied",value:new Tv.lW({path:o})}}):new Tv.sV({result:{case:"error",value:new Tv.F_({path:o,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Dy(r)}}async readTerminalFile(e,t,r,n,o){const i=await $y(e,"readTerminalFile",3e3,(()=>(0,uo.readFile)(t)));if(o&&(s=i,Uy.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(s,e)))))return By(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*Ly.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(Ly,r-Ly.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+Ly.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&&Fy(t)&&r++,0===t&&Fy(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=Oi(a),c=zy(a,l,n);a=c.content;let u=!1;return a.length>Iv&&(a=a.substring(0,Iv),u=!0),new Tv.sV({result:{case:"success",value:new Tv.mE({path:t,output:{case:"content",value:a},totalLines:l,fileSize:BigInt(r.size),truncated:u,rangeApplied:c.rangeApplied})}})}}var Zy=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),Yy=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 Xy=(0,ii.promisify)(hl.execFile);class Qy{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 uo.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 uo.mkdir(this.stagingDir,{recursive:!0}),await uo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:Zy.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:Zy.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:Zy.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 uo.access(e),!0}catch{return!1}}async movePolishedVideo(e,t){try{return void await uo.rename(e,t)}catch(e){if(!(e instanceof Error&&"code"in e&&"EXDEV"===e.code))throw e}try{await uo.copyFile(e,t,uo.constants.COPYFILE_EXCL)}catch(e){throw e instanceof Error&&"code"in e&&"EEXIST"===e.code||await uo.rm(t,{force:!0}).catch((()=>{})),e}try{await uo.unlink(e)}catch(e){throw await uo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;await this.pathExists(s.join(this.artifactsDir,o));)o=`${r}-${i}${n}`,i++;return s.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=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await Xy("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 Xy("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=s.join(e,"recording"),r=s.join(t,"recording_full.mp4");return await this.polishedRenderer.renderRecordingSession({stagingSessionDir:e,outputVideoPath:r,fps:Qy.PROXY_TARGET_FPS,includeBrandTag:!0}),await uo.access(r,uo.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await Xy("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 ${Qy.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${Qy.PROXY_TARGET_FPS}fps`)}return Qy.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await uo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await mh(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${Qy.DEFAULT_REFRESH_RATE}Hz`),o=Qy.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${Qy.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${Qy.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",Qy.PROXY_PRESET,"-crf",String(Qy.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,hl.spawn)("ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0});Tp(a.pid);const l=new Promise(((e,t)=>{let r="",n=!1;a.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:a,videoStartedPromise:l}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,hl.spawn)("ffmpeg",t,{stdio:["ignore","ignore","pipe"]});Tp(o.pid);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:a,renderProxies:l}=e,c=s.join(t,"recording"),u=s.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:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:l??null};await uo.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,l.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new Zy.Tj({result:{case:"failure",value:new Zy.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===Zy.$u.UNSPECIFIED)return new Zy.Tj({result:{case:"failure",value:new Zy.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case Zy.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){e=!0;try{await this.cleanupRecording(this.activeRecording),await uo.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 uo.mkdir(o,{recursive:!0});const{resolutionString:i,resolution:s}=await mh(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 Nh({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 Zy.Tj({result:{case:"startSuccess",value:new Zy.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 uo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new Zy.Tj({result:{case:"failure",value:new Zy.yH({error:e instanceof Error?e.message:String(e)})}})}}case Zy.$u.SAVE_RECORDING:{if(!this.activeRecording)return new Zy.Tj({result:{case:"failure",value:new Zy.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:a,requestedFilePathRejectedReason:l}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:i}),c=s.join(i,"recording"),u=s.join(c,"recording_render_proxy_1080p.mp4");try{await uo.access(u,uo.constants.R_OK)}catch{return this.activeRecording=null,new Zy.Tj({result:{case:"failure",value:new Zy.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:Qy.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:Qy.PROXY_TARGET_FPS,codec:"h264",profile:Qy.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 uo.copyFile(u,a);else{const e=await this.renderPolished(i);await this.movePolishedVideo(e,a)}return this.activeRecording=null,new Zy.Tj({result:{case:"saveSuccess",value:new Zy.ol({path:a,recordingDurationMs:fr.protoInt64.parse(d.toString()),requestedFilePathRejectedReason:l})}})}catch(t){return await this.cleanupRecording(e),this.invokeStoppedCallbackOnce(),this.activeRecording=null,new Zy.Tj({result:{case:"failure",value:new Zy.yH({error:t instanceof Error?t.message:String(t)})}})}}case Zy.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new Zy.Tj({result:{case:"failure",value:new Zy.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 uo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new Zy.Tj({result:{case:"discardSuccess",value:new Zy.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;return this.activeRecording=null,new Zy.Tj({result:{case:"failure",value:new Zy.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 Zy.Tj({result:{case:"failure",value:new Zy.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{Yy(r)}}}async function ew(e){const t=await(0,uo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await ew(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 tw(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(...tw(t,e,i))}))}return n}async function rw(e){if(!await(0,uo.access)(e,uo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await ew(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>tw(e,"",r===t.length-1))).join("\n")}async function nw(e,t){return rw(s.join(e,"agent-notes",t))}async function ow(e){return rw(s.join(e,"agent-notes","shared"))}Qy.PROXY_TARGET_WIDTH=1920,Qy.PROXY_TARGET_FPS=60,Qy.PROXY_CRF=17,Qy.PROXY_PRESET="veryfast",Qy.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",Qy.DEFAULT_REFRESH_RATE=60;var iw=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},sw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 aw=(0,d.h)("local-exec:request-context");async function lw(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{iw(o,(0,l.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{sw(o)}}async function cw(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 uw(e,t,r={}){const{projectDir:n,notesSessionId:o,metaAgentNotesEnabled:s,getSmartModeClassifierAutoModeEnabled:a,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:c,getSandboxEnabled:u,getSandboxSupported:d,getNetworkAllowlistInfo:h,userTerminalHint:p,artifactsFolder:f,secretRedactionEnabled:m,getComputerUseSupported:g}=r,v=`${i.platform()} ${i.release()}`,y=(0,fo.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!==s?`${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 Gt.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 dw={type:"object",properties:{},additionalProperties:!1};function hw(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>at.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new pr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?fr.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function pw(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 pr.E$({toolName:e.toolName,...Nf(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?fr.Value.fromJson(e.inputSchema):void 0}}})));return!st(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===Qf))||o.push(new pr.E$({toolName:Qf,...r?{}:{description:em,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(dw)}:{inputSchema:fr.Value.fromJson(dw)}}})),new pr.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 pr.U_({enabled:!0,mcpDescriptors:n})}function fw(e){const t=e?.trim();return t||void 0}function mw(e,t){const r=function(e){return fw(e.serverIdentifier)}(e);if(r)return r;const n=fw(e.serverName);return n?t.get(n)??n:void 0}class gw{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(aw.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(aw.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=>mw(e,n))).filter((e=>Boolean(e)));return{servers:[...new Set([...e.map((e=>e.clientKey)),...o,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).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=>mw(e,n)===o)),status:r?.get(o)?.status,errorMessage:r?.get(o)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(aw.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:dt(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function vw(e){return new Tt._W({result:{case:"success",value:new Tt.pv({servers:e.servers.map((e=>new Tt.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new pr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?fr.Value.fromJson(e.inputSchema):void 0}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class yw{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 vw({...r,servers:n})}return vw(r)}}class ww{constructor(e,t,r,n,o,i,s,a,l={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=i,this.gitExecutor=s,this.workspacePaths=a,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:c,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,createFileWatcher:f,getSandboxEnabled:m,getSandboxSupported:g,getNetworkAllowlistInfo:v,userTerminalHint:y,getMcpFileSystemOptions:w,mcpMetaToolEnabled:b,mcpMetaToolSlimDescriptors:S,mcpInputSchemaJson:k,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:C,attributionConfigProvider:_,isAttributionDisabledByAdmin:P,getAgentSkills:I,additionalRules:T,getComputerUseSupported:R}=l;this.projectDir=c,this.isWorkingDirHomeDir=p,this.getSandboxEnabled=m,this.getSandboxSupported=g,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.userTerminalHint=y,this.getMcpFileSystemOptions=w,this.mcpMetaToolEnabled=b??!1,this.mcpMetaToolSlimDescriptors=S??!1,this.mcpInputSchemaJson=k??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=C,this.attributionConfigProvider=_,this.isAttributionDisabledByAdmin=P,this.getAgentSkills=I,this.additionalRules=T??[],this.getComputerUseSupported=R,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=iw(r,(0,l.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 Zi(n.ctx,this.gitExecutor,o):void 0,s={repoPath:o??void 0,remoteUrl:void 0!==i?Yi(i):void 0};this.cachedWorkspaces.set(t,s)}catch(e){r.error=e,r.hasError=!0}finally{sw(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=iw(e,(0,l.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId,this.globalCache=this.computeGlobalCache(r.ctx)}catch(t){e.error=t,e.hasError=!0}finally{sw(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=iw(t,(0,l.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,c,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&&aw.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...i,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{sw(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=iw(t,(0,l.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 Gt.DS({path:t.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:t.remoteUrl,isOriginBacked:Jl(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(lw(e,t,r,n)),o(cw(e,t,r,n))]);return{status:i,branchName:s}}(r.ctx,this.gitExecutor,t.repoPath,3e3);return new Gt.DS({path:t.repoPath,status:s,branchName:a,remoteUrl:t.remoteUrl,isOriginBacked:Jl(t.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:i,gitRepoInfoComplete:o}}catch(e){t.error=e,t.hasError=!0}finally{sw(t)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=iw(r,(0,l.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),o=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=iw(e,(0,l.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{sw(e)}},s=performance.now(),a={},c=(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,b]=await Promise.all([c("globalCache",i()),c("mcpState",this.mcpStateAccessor.getState(n.ctx)),c("env",uw(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.getArtifactsFolder?.(n.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported})),c("git",this.collectWorkspaceCaches(n.ctx)),c("conversationNotes",o&&t.notesSessionId?nw(o,t.notesSessionId):Promise.resolve(void 0)),c("sharedNotes",o?ow(o):Promise.resolve(void 0)),c("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(n.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),c("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),c("agentSkills",this.getAgentSkills?this.getAgentSkills(n.ctx):Promise.resolve([])),c("adminCommandDenylist",this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0))]),S=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(S)),S>1e3&&aw.warn(n.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(S),...a});const k=this.mcpMetaToolEnabled?pw(d,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,E=this.attributionConfigProvider?.get(),x=!y&&(E?.attribution?.attributeCommitsToAgent??!0),C=!y&&(E?.attribution?.attributePRsToAgent??!0),_=new Gt.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}]:[],...hw(d,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:m,sharedNotesListing:g,customSubagents:u.customSubagents,mcpFileSystemOptions:v,mcpMetaToolOptions:k,supportsMcpAuth:!0,commitAttributionMessage:x?"enabled":void 0,prAttributionMessage:C?"enabled":void 0,agentSkills:w,adminCommandDenylist:b?.rules??[]});return null!==u.cloudRule&&void 0!==u.cloudRule&&(_.cloudRule=u.cloudRule),_}catch(e){r.error=e,r.hasError=!0}finally{sw(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=iw(r,(0,l.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 Gt._G({result:{case:"success",value:new Gt.yW({requestContext:e})}})}catch(e){return n.span.recordException(e),new Gt._G({result:{case:"error",value:new Gt.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{sw(r)}}}function bw(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Rt._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var Sw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 kw{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new Rt.W4({result:{case:"success",value:new Rt.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:qo(e.sandboxPolicy)}):new Rt.W4({result:{case:"failure",value:new Rt.xC({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:qo(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,requestId:t.requestId,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=ep(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 Rt.W4({result:{case:"timeout",value:new Rt.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:qo(o)}):e.signal.aborted?new Rt.W4({result:{case:"rejected",value:new Rt.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:qo(o)}):new Rt.W4({result:{case:"spawnError",value:new Rt.mJ({command:t.command,workingDirectory:r,error:i instanceof Error?i.message:"Unknown error"})},sandboxPolicy:qo(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,l.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,l.HF)(n,"LocalShellExecutor.execute");const o=t.command,i=t.requestedSandboxPolicy?Ho(t.requestedSandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(),a=bw(t),c=(0,ko.o1)(s);if(!t.parsingResult)return new Rt.W4({result:{case:"spawnError",value:new Rt.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let u;if(t.skipApproval){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId},i);if("block"===e.kind)return new Rt.W4({result:ls(o,c,e.reason)});u=i}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Zt(t)},i);if("block"===e.kind)return new Rt.W4({result:ls(o,c,e.reason)});u=e.policy}if(Oo()&&(u=Fo(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await rs(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,s,a,u)}catch(e){r.error=e,r.hasError=!0}finally{Sw(r)}}}var Ew=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class xw{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new Rt.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new Ew.e({allowlisted:n})}}class Cw{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new Rt.jK({status:Rt.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}var _w=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},Pw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var 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 Iw=(0,d.h)("local-exec:shell-core"),Tw="win32"===process.platform,Rw=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Aw(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ow(e,t){return e[t]??process.env[t]}function Mw(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}class jw{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{_w(r,(0,l.VI)(e.withName("ShellCoreExecutor.execute")),!1);const n=performance.now(),i=t.workingDirectory||await this.executor.getCwd(),a=(0,ko.o1)(i,this.workspacePath);let c,u=0,d=0,h=!1,p=!1,f=!1;t.fileOutputThresholdBytes&&this.projectDir&&(c={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const m=t.signal,g={CURSOR_AGENT:"1"};t.conversationId&&(g.CURSOR_CONVERSATION_ID=(0,ao.sh)(t.conversationId)),t.requestId&&(g.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(g.AGENT_TRANSCRIPTS=s.join(this.projectDir,ao.O2));const v=this.extraEnvProvider?.(e,t);void 0!==v&&Object.assign(g,v),function(e){const t=[`builtin unset ${Rw.join(" ")} 2>/dev/null || true`];for(const r of Rw){const n=Ow(e,r);void 0!==n&&t.push(`builtin export ${r}=${Aw(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("; ")}(g);const y=function(e,t){const r=Ow(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[]}}(Ow(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=Mw(s.additionalReadonlyPaths,a):s.additionalReadwritePaths=Mw(s.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==s.type?s.additionalReadonlyPaths=Mw(s.additionalReadonlyPaths,e.path):s.additionalReadwritePaths=Mw(s.additionalReadwritePaths,e.path);return{...e,perUser:s}}(t.sandboxPolicy,g),w=(0,fo.getSandboxPolicyType)(y??fo.INSECURE_NONE_SANDBOX_POLICY);y&&(yield{type:"start",sandboxed:"workspace_readonly"===w||"workspace_readwrite"===w}),t.askpassConfig&&!Tw&&(g.SUDO_ASKPASS=t.askpassConfig.helperPath,g.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,g.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let b=0,S="";for await(const r of this.executor.execute(e,t.command,{signal:m,workingDirectory:a,env:g,sandboxPolicy:y,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,bufferOutputEvents:this.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.shellOutputBackpressureOptions?.outputLimiterOptions})){if(b=0,S="",("stdout"===r.type||"stderr"===r.type)&&(S=r.data.toString(),b=r.data.length,c))if(c.size+=b,c.lineCount+=S.split("\n").length-1,c.size>rp);else if(c.file)c.file.write(S);else if(c.buffer+=S,c.size>c.threshold){const e=s.join(this.projectDir,tp);c.path=s.join(e,`${(0,o.randomUUID)()}.txt`),await(0,uo.mkdir)(s.dirname(c.path),{recursive:!0}),c.file=(0,po.createWriteStream)(c.path),c.file.write(c.buffer),c.buffer=""}switch(r.type){case"stdout":h||(u+b>$h?(h=!0,yield{type:"stdout_trimmed"}):(u+=b,yield{type:"stdout",data:S}));break;case"suppressed_output":f||(f=!0,yield{type:"stdout",data:fo.SHELL_OUTPUT_SUPPRESSED_NOTICE});break;case"stderr":p||(d+b>$h?(p=!0,yield{type:"stderr_trimmed"}):(d+=b,yield{type:"stderr",data:S}));break;case"exit":{const e=Math.max(0,Math.round(performance.now()-n));let t;c?.file&&(await new Promise((e=>c.file.end(e))),t=new xf.pV({filePath:c.path,sizeBytes:BigInt(c.size),lineCount:BigInt(c.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{Pw(r)}}async getCwd(){return this.executor.getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Dw{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{_w(r,(0,l.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Iw.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{Pw(r)}}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Nw{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 $w=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 Fw=(0,d.h)("local-exec:shell-stream");class Lw{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===Rt.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:Rt.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:Rt.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 Uw{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 Rt.jK({status:Rt.iA.ACCEPTED,shellResult:r}):new Rt.jK({status:Rt.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,l.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const n=t.command;let o=t.requestedSandboxPolicy?Ho(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(),s=bw(t),a=(0,ko.o1)(i),c=Date.now(),u=new Rt.HO(bo(n).structured),d=ni({command:n,parsingResult:u,blockedCommands:t.adminCommandDenylist});if(void 0!==d)return void(yield new Rt.FI({event:{case:"rejected",value:new Rt.pZ({command:n,workingDirectory:a,reason:d})}}));const h=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:u,toolCallId:t.toolCallId},o);if("block"===h.kind)return"permissionsConfig"===h.reason.type?void(yield new Rt.FI({event:{case:"permissionDenied",value:new Rt.jn({command:n,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:h.reason.isReadonly??!1})}})):void(yield new Rt.FI({event:{case:"rejected",value:new Rt.pZ({command:n,workingDirectory:a,reason:as(h.reason)})}}));if(Fw.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:u.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval)Fw.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:u,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Zt(t)},o);if("block"===r.kind){if(Fw.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 Rt.FI({event:{case:"permissionDenied",value:new Rt.jn({command:n,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const o=as(r.reason);return void(yield new Rt.FI({event:{case:"rejected",value:new Rt.pZ({command:n,workingDirectory:a,reason:o})}}))}o=r.policy,Fw.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:o.type})}if(Oo()&&(o=Fo(n,u)),o&&"insecure_none"!==o.type){const e=await rs(this.ignoreService);o={...o,ignoreMapping:e}}yield new Rt.FI({event:{case:"start",value:new Rt.tD({sandboxPolicy:qo(o)})}});const p=t.timeoutBehavior===Rt._d.BACKGROUND,f=p&&!t.closeStdin&&void 0===t.smartModeApproval,m=new AbortController,g=p?m.signal:e.signal?AbortSignal.any([e.signal,m.signal]):m.signal,v=!0,y=o?{perRepo:o}:void 0,w=this.coreExecutor.execute(e,{command:n,workingDirectory:i,signal:g,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,sandboxPolicy:y,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:f,showElapsedTime:v});let b;p||(b=setTimeout((()=>m.abort()),s));const S=p?new Lw(w[Symbol.asyncIterator](),s):null;let k,E,x,C="",_=!1;const P=t.toolCallId&&S?{requestBackground:()=>{if(S.requestBackground())return x=x??this.backgroundShellManager.generateShellId(),new Rt.W4({result:{case:"success",value:new Rt.QR({shellId:x,pid:E,command:n,workingDirectory:a,msToWait:ep(Date.now()-c),backgroundReason:Rt.Jg.USER_REQUEST,interleavedOutput:C})}})}}:void 0;t.toolCallId&&P&&this.activeForegroundExecutions.set(t.toolCallId,P);const I=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===P&&this.activeForegroundExecutions.delete(t.toolCallId)};let T;S&&e.signal&&e.signal.addEventListener("abort",(()=>{S.backgroundRequested||(m.abort(),S.abort())}),{once:!0});const R=t.hardTimeout;void 0!==R&&R>0&&(T=setTimeout((()=>{void 0!==x?this.backgroundShellManager.abort(x)||m.abort():(_=!0,m.abort(),S?.abort())}),R));const A=S?.iterate()??w;try{for await(const t of A)if("stdout"===t.type)C+=t.data,yield new Rt.FI({event:{case:"stdout",value:new Rt.o0({data:t.data})}});else if("stderr"===t.type)C+=t.data,yield new Rt.FI({event:{case:"stderr",value:new Rt.Db({data:t.data})}});else if("stdin_ready"===t.type)k=t.stdin,E=t.pid;else if("exit"===t.type){let r;t.aborted&&(r=e.signal?.aborted?Rt.Lv.USER_ABORT:S?.timedOut||m.signal.aborted?Rt.Lv.TIMEOUT:Rt.Lv.USER_ABORT),yield new Rt.FI({event:{case:"exit",value:new Rt.vb({code:(t.code??0)>>>0,cwd:await this.coreExecutor.getCwd(),outputLocation:t.outputLocation,aborted:t.aborted,abortReason:r,localExecutionTimeMs:ep(t.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof fo.SandboxUnsupportedError))throw r;const i=o?.type??"unknown";return Fw.warn(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:i,reason:r.reason}),void(yield new Rt.FI({event:{case:"sandboxUnsupported",value:new Rt.rI({command:n,workingDirectory:a,sandboxPolicyType:i,reason:r.reason??r.message,isReadonly:"workspace_readonly"===i})}}))}finally{clearTimeout(b),S?.backgroundRequested||clearTimeout(T),I()}if(S?.backgroundRequested&&!_){const r=x??this.backgroundShellManager.generateShellId();x=r;const o=S.backgroundReasonValue===Rt.Jg.USER_REQUEST?Rt.Jg.USER_REQUEST:Rt.Jg.TIMEOUT,i=o===Rt.Jg.USER_REQUEST?Date.now()-c:s;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:n,workingDirectory:a,toolCallId:t.toolCallId,sandboxPolicy:y,initialOutput:C,stdin:k,pid:E,abortController:m,eventIterator:S.getHandoffIterator(),startTime:c,showElapsedTime:v,description:t.description,outputNotification:t.outputNotification}),yield new Rt.FI({event:{case:"backgrounded",value:new Rt.Y9({shellId:r,command:n,workingDirectory:a,pid:E,msToWait:v?i:void 0,reason:o})}})}else e.signal?.aborted&&void 0!==S?.stopReasonValue?(clearTimeout(T),yield new Rt.FI({event:{case:"exit",value:new Rt.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(),aborted:!0,abortReason:Rt.Lv.USER_ABORT})}})):clearTimeout(T)}catch(e){r.error=e,r.hasError=!0}finally{$w(r)}}}var Bw=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class zw{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new Bw.M({allowlisted:r})}}var Ww=r("node:constants");class Hw extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}var qw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Gw=(0,d.h)("LocalWriteExecutor"),Vw=async(e,t,r,n)=>{const o=setTimeout((()=>{Gw.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};class Jw{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,l.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,o=t.path,i=t.fileText,a=t.fileBytes.length>0?t.fileBytes:void 0,c=(0,ko.o1)(o,this.workspacePath),u=ry(c,["assets","agent-tools","swarm-agents"]);if((0,ko.fl)({targetPath:c,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new At.v3({result:{case:"error",value:new At.QM({path:c,error:ko.PS})}});let d,h=!1;try{(await(0,uo.stat)(c)).size<=Fh?d=await Vw(n,"readText before write",3e3,(()=>Ti(c,t.encodingHint))):h=!0}catch{}const p=(await iy(c)).resolvedPath,f=(".cursorignore"===(c.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await Vw(n,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(n,p,i)));if(f){const e=await Vw(n,"handleBlockReason",3e3,(()=>ss(f,{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:Lh.Write,details:{path:c,reason:e,isNewFile:n,diffString:o,before:d,after:i,blockReason:s},toolCallId:t.toolCallId});return a.approved?null:new At.v3({result:{case:"rejected",value:new At.en({path:c,reason:a.reason||""})}})},onUserRejected:e=>new At.v3({result:{case:"rejected",value:new At.en({path:c,reason:e||""})}}),onPermissionDenied:(e,t)=>new At.v3({result:{case:"permissionDenied",value:new At.U7({path:c,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const m=(0,s.dirname)(p);try{await Vw(n,"mkdir",3e3,(()=>(0,uo.mkdir)(m,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new At.v3({result:{case:"permissionDenied",value:new At.U7({path:c,directory:m,operation:"create_directory",error:"Permission denied"})}}):new At.v3({result:{case:"error",value:new At.QM({path:c,error:e.message})}})}let g,v;if(void 0!==a)g=a,v=0;else{const e=await Vw(n,"getBufferForWrite",3e3,(()=>Ri(p,i,this.workspacePath,t.encodingHint)));g=e.buffer,v=e.lines}try{await Vw(n,"writeFile",3e3,(async()=>{let e;await async function(e,t,r){let n;try{n=await(0,uo.open)(e,function(){const e=po.constants;let t=e.O_WRONLY|e.O_CREAT;return"number"==typeof e.O_NOFOLLOW&&(t|=e.O_NOFOLLOW),"number"==typeof e.O_CLOEXEC&&(t|=e.O_CLOEXEC),t}(),438)}catch(t){if(function(e){const t=e?.code;return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof po.constants.O_NOFOLLOW}(t))throw new Hw(e,`Refusing to write through a symlink at ${e}`);throw t}try{let o;try{o=(0,po.realpathSync)(e)}catch{throw new Hw(e,`Cannot verify canonical path before writing: ${e}`)}if(o!==e)throw new Hw(e,`Refusing write: ${e} now resolves through a symlinked parent to ${o}`);if(!(await n.stat()).isFile())throw new Hw(e,`Refusing to write to non-regular file at ${e}`);await n.truncate(0);const i=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let s=0;for(;s<i.length;){const{bytesWritten:e}=await n.write(i,s,i.length-s,s);if(0===e)break;s+=e}r?.flush&&await n.sync()}finally{await n.close()}}(p,g,{flush:!0});try{e=await(0,uo.open)((0,s.dirname)(p),Ww.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}))}catch(e){if(e instanceof Hw)return new At.v3({result:{case:"permissionDenied",value:new At.U7({path:c,directory:"",operation:"create_file",error:e.message})}});const t=e.code;return"EACCES"===t||"EPERM"===t?new At.v3({result:{case:"permissionDenied",value:new At.U7({path:c,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new At.v3({result:{case:"noSpace",value:new At.bM({path:c})}}):new At.v3({result:{case:"error",value:new At.QM({path:c,error:e.message})}})}if(this.fileChangeTracker&&void 0===a&&!u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(c,d,i,e)}if(this.onWriteForAiTracking&&void 0===a&&!u){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:c,beforeContent:d,afterContent:i,metadata:e})}catch(e){Gw.warn(n,"onWriteForAiTracking failed (write succeeded)",{path:c,error:e instanceof Error?e.message:String(e)})}}const y=g.byteLength;let w;if(t.returnFileContentAfterWrite)try{w=await Vw(n,"readText after write",3e3,(()=>Ti(c,t.encodingHint)))}catch{}return new At.v3({result:{case:"success",value:new At.j6({path:c,linesCreated:v,fileSize:y,...void 0!==w&&{fileContentAfterWrite:w}})}})}catch(e){r.error=e,r.hasError=!0}finally{qw(r)}}}const Kw=(0,d.h)("local-exec:provider");class Zw extends q{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,s.join)(e,".cursor/sandbox.json");try{const r=(0,po.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,fo.parseSandboxPolicyJson)(n);return(0,fo.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.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const o=this.terminalExecutor??(0,fo.createDefaultTerminalExecutor)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let l=new jw(o,t??(0,i.homedir)(),this.projectDir,e.shellOutputBackpressureOptions,e.shellExtraEnvProvider);e.shellCoreWrapper&&(l=e.shellCoreWrapper(l)),this.askpassConfig&&(l=new Nw(l,this.askpassConfig)),this.shellManager&&(l=new Dw(l,this.shellManager));const c=e.overrideShellExecutor??new kw(this.permissionsService,l,this.ignoreService,this.pendingDecisionStore);this.register(Ot,Yg(c)),this.register(vt,Yg(new rg(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=e.overrideWriteExecutor??new Jw(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking});this.register(jt,Yg(u)),this.register(ie,Yg(new Bh(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking))),this.register(ae,Yg(new Gh)),this.register(le,new Cv);const d=this.mcpStateAccessor??new gw(this.mcpLease);this.register(ce,Yg(new qm(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:d,permissionsService:this.permissionsService})));const h=Yg(e.overrideReadExecutor??new Ky(this.permissionsService,a,{mcpStateAccessor:d,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}));this.register(Ct,h),e.registerRedactedReadExecutor&&this.register(_t,h);const p=new Km(this.permissionsService,this.ignoreService,a);this.register(tt,Yg(p)),this.register(Et,Yg(new Lg(this.permissionsService,a))),this.register(yt,Yg(new pg(c))),this.register(wt,Yg(new Cg(this.permissionsService,u,a))),this.register(xt,Yg(new zg(u,a))),this.register(St,Yg(new Mg(this.permissionsService,a))),this.register(bt,Yg(new Tg(this.permissionsService,a))),this.register(kt,Yg(new Ng(this.permissionsService,a))),this.register(se,Yg(new av(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(ne,Yg(new ev(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ht,Yg(new Sm(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded))),this.register(pt,Yg(new km(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ft,Yg(new Em(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(mt,Yg(new yw(d,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const f=Yg(this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(d,t,e));this.register(qt,{execute:async(t,r,n)=>{const o=await f.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 d.getState(t),l=hw(a,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(s.tools=l.tools,s.mcpInstructions=l.mcpInstructions,s.mcpMetaToolOptions=this.mcpMetaToolEnabled?pw(a,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,s.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t)),void 0!==s.env&&(s.env.artifactsFolder=e.getArtifactsFolder?.(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=[],Kw.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new xs(this.permissionsService,l,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(Q,Yg(this.backgroundShellExecutor));const m=new Uw(this.permissionsService,l,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(Mt,function(e,t){const r=new ho.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 Zg(a);r.set(i,l),yield*l.fork()}}}(m)),void 0!==e.agentStoreConflictDrainer&&this.register(Y,new qg(e.agentStoreConflictDrainer)),this.register(Vt,new xw(this.permissionsService)),this.register(gt,new Pv(this.permissionsService)),this.register(ir,new zw(this.permissionsService));const g=new Cw(m);this.register(Jt,Yg(g));const v=!1===e.enableWriteBackgroundShellStdin?new Gg((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new Gg(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(ee,Yg(v)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(oe,Yg(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new Qy({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Ht,Yg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new ww(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,ko.yn)(t,(0,i.homedir)()),createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.rebuildRequestContextOnRulesChange&&(this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function Yw(e){return e.replace(/\\/g,"/")}function Xw(e,t){for(const r of t){const t=Yw(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var Qw;function eb(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return Qw.Plugin;const n=Yw(e.fullPath);return Xw(n,r.builtinDirs)?Qw.Builtin:_d(e.fullPath,t).inAgentStore?Qw.UserStore:Xw(n,r.userDirs)?Qw.UserHome:(Xw(n,r.workspaceDirs),Qw.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(Qw||(Qw={}));var tb=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 rb=(0,ii.debuglog)("merged-agent-skills");class nb{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,l.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(rb("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=>(rb("getDisabledManagedSkillPaths rejected; fail-open: %s",e instanceof Error?e.message:String(e)),[])))]),a=o.flat(),c=this.getPromptSortContext?.(),u=Id(a,c??xd);let d=u;return 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)))),void 0!==c?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ud(e.userHomeDirectory).dirPath],r=pd(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of hd(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:eb(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,c):d}catch(e){t.error=e,t.hasError=!0}finally{tb(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()}),nb.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()}}nb.CHANGE_COALESCE_MS=1500;const ob=(0,d.h)("skill-sync-manifest"),ib=".sync-manifest.json";async function sb(e,t){try{const r=await(0,uo.readFile)((0,s.join)(e,ib),"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:(ob.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||ob.warn(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ab(e,t,r){e.skills[t]={lastSyncedAt:r}}function lb(e,t){delete e.skills[t]}var cb=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 ub=(0,d.h)("builtin-skills-sync");function db(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hb(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function pb(e){const t=qc(e.content),r=db(t.data)?t.data:{};return Gc(`${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={...db(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 fb(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),l=await mb(n);if(a.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,uo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,uo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,uo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,uo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,uo.writeFile)(t,r,"utf-8")}try{await(0,uo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==e.code)throw e}try{await(0,uo.rename)(n,r)}catch(e){throw i&&(await(0,uo.rename)(o,r),i=!1),e}i&&(await(0,uo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,uo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,uo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||ub.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,uo.mkdir)(n,{recursive:!0}),await(0,uo.writeFile)(o,i,"utf-8"),!0}async function mb(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,uo.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 mb(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function gb(e,t){try{return(await(0,uo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||ub.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function vb(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,l.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=ud((0,i.homedir)()).dirPath;await(0,uo.mkdir)(c,{recursive:!0});const[u,d]=await Promise.all([sb(c,o),gb(o,c)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([yb((0,s.join)(r,"SKILL.md")),"canvas"===e?yb((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ub.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ub.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(o,c,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ub.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?a-r.lastSyncedAt:0,i=void 0!==r&&n>2592e5,l=void 0!==t&&Da(t,"local"),h=void 0!==t&&!l,f=void 0!==r||d.includes(e);if(t&&!1!==t.enabled&&l)hb(t),await fb(o,c,{id:e,fileContent:pb(t),resources:t.resources??{}})?m++:g++,ab(u,e,a);else if(!1===t?.enabled||h||i){const n=!1===t?.enabled?"enabled_false":h?"environment_ineligible":"grace_expired";await(0,uo.rm)((0,s.join)(c,e),{recursive:!0,force:!0}),lb(u,e),f&&(v.push(e),ub.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?a-r.lastSyncedAt:null}))}else r||ab(u,e,a)}catch(t){ub.warn(o,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,s.join)(e,".sync-manifest.json.tmp"),n=(0,s.join)(e,ib);await(0,uo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,uo.rename)(r,n)}(c,u)}catch(e){ub.warn(o,"Failed to persist sync manifest",{skillDir:c,error:String(e)})}return{synced:m,upToDate:g,removed:v}}catch(e){r.error=e,r.hasError=!0}finally{cb(r)}var n}async function yb(e){try{return await(0,uo.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const wb=(0,d.h)("managed-skills-sync");function bb(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 Sb{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(...Ya(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=bb(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var kb=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 Eb(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class xb{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._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Is,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],i=new Set(o.map((e=>e.installPath))),s=r.filter((e=>!i.has(e.installPath)));return this.plugins=[...o,...s],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${s.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${e}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(Bu));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Bu(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=Eb(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 Lu({...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,s.resolve)(e),n=await(0,uo.realpath)(r);if(!(await(0,uo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const o=i.homedir();if(n.split(s.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 a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const l=(0,s.basename)(n),c=await this._loadExtensionPluginContent(n,t);a.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,s.resolve)(e);let o;try{o=await(0,uo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Du(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${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,l.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=Eb(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,u=o.loadCursorFirstParty??i.length>0;if(!a&&!u&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const d=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await function(e){return uu(this,arguments,void 0,(function*(e,t={}){var r,n,o,i,a;const l=null!==(r=t.log)&&void 0!==r?r:Is,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!==(a=t.loadCursorFirstParty)&&void 0!==a?a:h.length>0,f=[],m=[];let g;u&&f.push(Fu(e,void 0,{userHomeDir:t.userHomeDir,onError:t.onError,log:l})),p&&h.length>0&&(g=Promise.allSettled(h.map((e=>{var r,n;return Lu(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 uu(this,arguments,void 0,(function*(e={}){var t,r,n;const o=null!==(r=e.log)&&void 0!==r?r:Is,i=performance.now(),a=null!==(n=e.userHomeDir)&&void 0!==n?n:process.env.HOME;if(!a)return o.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const l=(0,s.join)(a,".cursor","plugins","local");let c;try{c=yield(0,uo.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,uo.realpath)(l).catch((()=>(0,s.resolve)(l))),d=[];for(const r of c){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(l,r.name);try{if(r.isSymbolicLink()){let e;try{e=yield(0,uo.realpath)(n)}catch(e){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{ic(u,e)}catch(t){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${l}`);continue}}if(!(yield(0,uo.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,logoUrl:p,version:f,homepage:m,repository:g,variablesSchema:v,skills:y,rules:w,agents:b,commands:S,mcpConfig:k,capabilities:E,hooks:x}=yield Du(n,r.name,void 0,{configuredVariables:s,log:o}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};d.push(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:C,installPath:n},void 0!==a&&{displayName:a}),void 0!==c&&{description:c}),void 0!==h&&{authorName:h}),void 0!==p&&{logoUrl:p}),void 0!==f&&{version:f}),void 0!==m&&{homepage:m}),void 0!==g&&{repository:g}),{variablesSchema:v,skills:y,rules:w,agents:b,commands:S,mcpConfig:null!=k?k:void 0,capabilities:E,hooks:x})),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.allSettled(f),null!=g?g:Promise.resolve([])]);let w=!1;const b=[];for(const e of y)"rejected"!==e.status?(e.value.sourceUnavailable&&(w=!0),b.push(...e.value.plugins),m.push(...e.value.failures)):(w=!0,l.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of v)"rejected"!==e.status?b.push(...e.value):(w=!0,l.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const S=new Set,k=[];for(const e of b){if(!e.installPath){k.push(e);continue}const t=yield(0,uo.realpath)(e.installPath).catch((()=>e.installPath));S.has(t)||(S.add(t),k.push(e))}const E=new Map,x=[];for(const e of k){const t=Uu(e);if(void 0!==t){const r=E.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=x.findIndex((e=>Uu(e)===t&&e.loadError));-1!==r&&x.splice(r,1),E.set(t,!0),x.push(e);continue}E.set(t,n)}x.push(e)}const C=performance.now()-c;return l.log("info",`loadAllPlugins completed in ${C.toFixed(1)}ms (claude=${u}, userLocal=${d}, marketplace=${h.length} sources, total=${x.length} plugins, failures=${m.length}, sourceUnavailable=${w})`),{plugins:x,failures:m,sourceUnavailable:w}}))}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:u&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:d}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return 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:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{kb(e)}}}var Cb=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const _b=3e5;BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function Pb({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||Lv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class Ib{constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new Cb.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new Cb.aYW({}))}}function Tb(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class Rb{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>_b||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,np.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,np.MEY)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const i=Pb({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?Pb({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,np._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 isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=zv({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===Cb.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===Cb.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===Cb._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===Cb.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:Tb(r,t?.sandboxReadAllowlistPaths)}}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>_b)&&(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>_b)&&(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}}const Ab=new Kh,Ob={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 Ki((0,Qe.q6)(),Ab,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?co(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 Mb=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 jb=(0,d.h)("ControlledConversationActionManager");class Db{get signal(){return this.abortController.signal}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.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 lr.QF({action:{case:"cancelAction",value:new lr.TT({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 Mb(this,void 0,void 0,(function*(){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}yield this.clientStream.write(e)}))}enqueueReplayableConversationAction(e){return Mb(this,void 0,void 0,(function*(){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new lr.QF({action:{case:"userMessageAction",value:new lr.Vt({userMessage:e})}})).catch((()=>{}))}run(e,t){return Mb(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){jb.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}}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.runActive=!1}}))}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}let Nb={warn:console.warn.bind(console),error:console.error.bind(console)};const $b=new Cs.AsyncLocalStorage;function Fb(){var e;return null!==(e=$b.getStore())&&void 0!==e?e:Nb}const Lb={warn(...e){Fb().warn(...e)},error(...e){Fb().error(...e)}},Ub="x-blob-encryption-key";function Bb(e,t){const r=Object.assign({},t);return void 0!==r[Ub]||(0,ur.TU)(e)&&(r[Ub]=e),r}const zb=new Map;var Wb=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 Hb(e){var t;if("userMessageAction"===e.action.case)return null===(t=e.action.value.userMessage)||void 0===t?void 0:t.text}function qb(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 Gb(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}var Vb=r("../mcp-core/dist/oauth/rest-mcp-provider-metadata.js"),Jb=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 Kb=new Set(["mcp.slack.com"]);var Zb=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 Yb{constructor(e,t){this.inner=e,this.resolver=t}getDefinitions(e){return Zb(this,arguments,void 0,(function*(e,t=!0){const r=yield this.inner.getDefinitions(e,t);return Promise.all(r.map((e=>Zb(this,void 0,void 0,(function*(){const t=yield function(e,t){return Jb(this,void 0,void 0,(function*(){if(!("url"in e)||!e.url)return e;const r=yield function(e,t,r){return Jb(this,arguments,void 0,(function*(e,t,r,n=fetch){var o;let i;try{i=new URL(e).hostname}catch(e){return t}if(!Kb.has(i)&&void 0===(0,Ip.Di)(e))return t;let s=yield r.resolve(e);if(!s&&void 0!==(0,Ip.Di)(e)){const t=null===(o=yield(0,Vb.Ez)(e,n))||void 0===o?void 0:o.clientId;void 0!==t&&(s={CLIENT_ID:t})}return s?t?Object.assign(Object.assign({},s),t):s:t}))}(e.url,e.auth,t);return r===e.auth?e:Object.assign(Object.assign({},e),{auth:r})}))}(e.serverConfig,this.resolver);return t===e.serverConfig?e:Object.assign(Object.assign({},e),{serverConfig:t})})))))}))}clearCache(){var e,t;null===(t=(e=this.inner).clearCache)||void 0===t||t.call(e)}}var Xb=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 Qb{constructor(e,t){this.storage=e,this.prefix=t}loadTokens(e){return Xb(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.prefix+e)}))}saveTokens(e,t){return Xb(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.prefix+e,t)}))}loadClientInformation(e){return Xb(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.prefix+e)}))}saveClientInformation(e,t){return Xb(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.prefix+e,t)}))}}class eS{constructor(e,t){this.storage=e,this.prefix=t}isServerApproved(e,t,r){return Xb(this,void 0,void 0,(function*(){return this.storage.isServerApproved(this.prefix+e,t,r)}))}}class tS{constructor(e){this.loaders=e}load(e){return Xb(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 tf(i)}))}loadClient(e,t){return Xb(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 rS{constructor(e,t,r,n,o=!1,a,l,c=s.join((0,i.homedir)(),".cursor","mcp.json"),u){const d=Array.isArray(e)?e:[e],h=[];for(let e=0;e<d.length;e++){const t=d[e],r=s.join(t,".cursor","mcp.json"),n=`project-${e}-${s.basename(t)}-`;h.push({path:r,prefix:n})}h.push({path:c,prefix:"user-"});const p=new Map;for(const{path:e,prefix:t}of h)p.has(e)&&"user-"!==t||p.set(e,t);const f=[];for(const[e,i]of p){const s=o?"":i,d=new Qb(t,s),h=new eS(n,s),p=e===c,m=[new fp,...p?[]:[new cp(h)],new wf(r),...l?[new lp(l)]:[]],g=u?new vf(new Yb(new gf(e),u),d,m,{authRedirectUrlGenerator:a}):new bf(e,d,m,a);f.push({prefix:s,loader:g})}this.loader=new tS(f)}static init(e,t,r,n=!1,o,i){const a=new Ef(s.join(r,"mcp-auth.json"));(function(e){return Xb(this,void 0,void 0,(function*(){yield(0,uo.rm)(s.join(e,"mcp-cache.json"),{force:!0})}))})(r).catch((()=>{}));const l=n?{isServerApproved:()=>Promise.resolve(!0)}:new up(s.join(r,"mcp-approvals.json"),t);return new rS(t,a,e,l,!0,void 0,o,void 0,i)}load(e){return Xb(this,arguments,void 0,(function*(e,t=!0){return this.loader.load(e,t)}))}loadClient(e,t){return Xb(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 nS="cursor-plugins/local";function oS(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===nS)return r}var iS=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 sS extends ef{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}dispose(){return iS(this,void 0,void 0,(function*(){this.disposed||(this.disposed=!0,yield this.runtimeManager.closeAllClients())}))}}class aS{constructor(e){this.storagePath=e}isServerDisabled(e){return iS(this,void 0,void 0,(function*(){try{const t=yield(0,uo.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 iS(this,void 0,void 0,(function*(){yield(0,uo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),yield(0,uo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}))}}class lS{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}getDefinitions(){return iS(this,void 0,void 0,(function*(){let e;try{e=yield this.pluginMcpService.getPluginMcpServers()}catch(e){return Lb.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&fS(r))continue;const e=Sf(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}}):Lb.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 cS{constructor(e){this.servers=e}getDefinitions(){return iS(this,void 0,void 0,(function*(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:pS(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}))}}function uS(){return{getDotCursorProtection:()=>iS(this,void 0,void 0,(function*(){return!1})),getShouldBlockMcp:()=>iS(this,void 0,void 0,(function*(){return!1})),getDeleteFileProtection:()=>iS(this,void 0,void 0,(function*(){return!1})),getIsHeadlessDisabled:()=>iS(this,void 0,void 0,(function*(){return!1})),isServerBlocked:()=>iS(this,void 0,void 0,(function*(){return!1})),getTeamRepos:()=>iS(this,void 0,void 0,(function*(){})),getAutoRunControls:()=>iS(this,void 0,void 0,(function*(){return{enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}})),getAdminCommandDenylist:()=>iS(this,void 0,void 0,(function*(){return{rules:[]}})),getMcpToolControls:()=>iS(this,void 0,void 0,(function*(){})),getNetworkAccessControls:()=>iS(this,void 0,void 0,(function*(){return{allowlist:[],denylist:[],available:!0}})),getMcpNetworkControlsConfig:()=>iS(this,void 0,void 0,(function*(){return{enabled:!1}})),getDefaultNetworkAllowlist:()=>iS(this,void 0,void 0,(function*(){return{allowlist:[],available:!0}})),getSandboxingControls:()=>iS(this,void 0,void 0,(function*(){return{sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}})),isAttributionDisabledByAdmin:()=>iS(this,void 0,void 0,(function*(){return!1})),invalidateCache:()=>{}}}function dS(e={}){var t,r,n;const o=null!==(t=e.teamSettingsService)&&void 0!==t?t:uS(),a=null!==(r=e.ignoreApprovals)&&void 0!==r&&r,l=null!==(n=e.importThirdPartyPlugins)&&void 0!==n&&n;return{createLease(t){return iS(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 Qp;const g=new aS((0,s.join)(m,"mcp-disabled.json")),v=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:o,disabledStore:a,includeProjectMcp:l,includeUserMcp:c}=e;if(l&&c)return rS.init(t,r,n,o,a);if(!l&&!c)return;const u=new Ef((0,s.join)(n,"mcp-auth.json")),d=o?{isServerApproved:()=>Promise.resolve(!0)}:new up((0,s.join)(n,"mcp-approvals.json"),r),h=[new fp,new cp(d),new wf(t),new lp(a)],p=[];return l&&p.push({prefix:"",loader:new bf((0,s.join)(r,".cursor","mcp.json"),u,h)}),c&&p.push({prefix:"",loader:new bf((0,s.join)((0,i.homedir)(),".cursor","mcp.json"),u,h)}),hS(p)}({teamSettingsService:o,projectRoot:f,projectDirectory:m,ignoreApprovals:a,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 Ef((0,s.join)(m,"mcp-auth.json")),t=[new fp,new wf(o)];y.push({prefix:"",loader:new vf(new cS(w),e,t)})}const b=oS(t.services.pluginBootstrapOutputs);if(b&&(null===(d=e.includePluginMcp)||void 0===d||d)){const e=new up((0,s.join)(m,"mcp-approvals.json"),f),t=new Ef((0,s.join)(m,"mcp-auth.json")),r=[new fp];a||r.push(new cp(e)),r.push(new wf(o),new lp(g));const n=new Sb(b.pluginsService),i=new vf(new lS(n,l),t,r);y.push({prefix:"",loader:i})}if(v&&y.push({prefix:"",loader:v}),0===y.length)return new Qp;const S=hS(y),k=yield S.load(null!==(h=e.initializationCtx)&&void 0!==h?h:(0,Qe.q6)(),e.cache);return new sS(k)}))}}}function hS(e){return 1===e.length?e[0].loader:new tS(e)}function pS(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 fS(e){return"claude-plugin"===e.pluginSource}var mS=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())}))},gS=function(e){return this instanceof gS?(this.v=e,this):new gS(e)};function vS(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===(null==t?void 0:t.case)}function yS(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class wS{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>wS.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){var o;this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=null==n?void 0:n.skipPathWriteDrain,this.onWakeWrittenPath=null==n?void 0:n.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=null==n?void 0:n.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=null!==(o=null==n?void 0:n.writeBarrierTimeoutMs)&&void 0!==o?o:2e3,this.resolveWriteBarrierTimeoutMs=null==n?void 0:n.resolveWriteBarrierTimeoutMs,this.shouldForceWrittenPathBeforeDrain=null==n?void 0:n.shouldForceWrittenPathBeforeDrain,this.onWriteBarrier=null==n?void 0:n.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch(e){}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===jt.symbol||e===ie.symbol||e===xt.symbol||e===wt.symbol?{kind:"path"}:e===Ot.symbol||e===Mt.symbol||e===Q.symbol||e===yt.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,i=this.skipPathWriteDrain,s=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),l=this.shouldForceWrittenPathBeforeDrain,c=this.onWriteBarrier,u=this.onWakeWrittenPath,d=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=yS(e);void 0!==r&&(o.wakeForWrittenPath(r),null==u||u(r,t))}else o.wakeExposedMounts()}catch(e){}},h=this.cacheCarriersForExecId.bind(this),p=this.carriersByExecId,f=this.inFlightByExecId,m=(e,t)=>mS(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=p.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=f.get(o);if(void 0!==t){const e=yield t;return e.length>0&&r.push(...e),e}}const i=t=>mS(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&&h(o,e.carriers),e.carriers;i.length>0&&r.ack(i);const n=[];return void 0!==o&&h(o,n),n}catch(e){return i.length>0&&r.release(i),[]}}));if(void 0===o)return yield i(r);const s=i(r);f.set(o,s);try{return yield s}finally{f.get(o)===s&&f.delete(o)}}));return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,u)=>{const h=t.execute.call(t,n,o,u);return"object"==typeof(p=h)&&null!==p&&Symbol.asyncIterator in p&&"function"==typeof p[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 gS?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 a=!1,l=!1,c=!1;try{try{for(var p,f=!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)}))}}}(h);!(t=(p=yield gS(g.next())).done);f=!0){s=p.value,f=!1;const t=s;if(e===Mt.symbol&&vS(t)){if(!a){d(o,n);const e=yield gS(m(n,u));a=!0,e.length>0&&(yield yield gS(new Rt.FI({event:{case:"hookContext",value:new Rt.Ng({hookAdditionalContexts:[...e]})}})))}yield yield gS(t)}else yield yield gS(t)}}catch(e){r={error:e}}finally{try{f||t||!(i=g.return)||(yield gS(i.call(g)))}finally{if(r)throw r.error}}c=!0}catch(e){throw l=!0,e}finally{d(o,n),a||l||!c||(yield gS(m(n,u)))}}))}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(h)?(()=>mS(this,void 0,void 0,(function*(){try{const t=yield h;return d(o,n),e===jt.symbol&&!0===(null==i?void 0:i())&&!0===(null==u?void 0:u.enableAgentStoreConflictNotices)||(yield function(e,t,r,n){return mS(this,void 0,void 0,(function*(){const o=e=>{var t;try{null===(t=n.onWriteBarrier)||void 0===t||t.call(n,e)}catch(e){}};if(void 0===e||"path"!==(null==r?void 0:r.kind))return;const i=yS(t);if(void 0===i)return;if(void 0!==n.shouldForce&&!1===n.shouldForce())return void o({durationMs:0,outcome:"skipped"});if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const s=Date.now(),a=e(i).then((e=>e),(()=>"error")),l=yield Promise.race([a,(0,Jr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==l&&o({durationMs:Date.now()-s,outcome:l})}))}(s,o,r,{timeoutMs:a(),shouldForce:l,onWriteBarrier:c}),yield m(n,u)),t}catch(e){throw d(o,n),e}})))():(d(o,n),h);var p}})}}wS.CARRIERS_BY_EXEC_ID_MAX=32,Error,po.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 bS=["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 SS(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,bS)}function kS(e){const t=(0,ao.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,ao.sh)(e.parentConversationId);return`${ao.O2}/${r}/subagents/${t}.${e.ext}`}return`${ao.O2}/${t}/${t}.${e.ext}`}function ES(e){const t=(0,ao.sh)(e.conversationId);return`${ao.O2}/${t}.${e.ext}`}function xS(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(kS({conversationId:e.conversationId,ext:t,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&s(kS({conversationId:e.conversationId,ext:t,kind:"primary"})),o&&s(ES({conversationId:e.conversationId,ext:t}));return i}var CS;(()=>{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"}(CS||(CS={}));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())}))},PS=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},IS=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 TS(e){switch(e){case lr.xy.AGENT:return"agent";case lr.xy.ASK:return"ask";case lr.xy.PLAN:return"plan";case lr.xy.DEBUG:return"debug";case lr.xy.TRIAGE:return"triage";case lr.xy.PROJECT:return"project";case lr.xy.MULTITASK:return"multitask";case lr.xy.CUSTOM:return"custom";case lr.xy.UNSPECIFIED:default:return"agent"}}function RS(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 AS(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 OS=new TextEncoder,MS=new TextDecoder,jS=new class{serialize(e){const t=JSON.stringify(e,RS);return OS.encode(t)}deserialize(e){const t=MS.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,AS):JSON.parse(t)}};function DS(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 NS(e,t,r){return _S(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=jS.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 $S(e,t){switch(e.type){case"text":return t?FS(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 FS(e){return SS(e)}function LS(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function US(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?FS(e):e;return r?LS(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=LS(t?FS(e.text):e.text);return $S(Object.assign(Object.assign({},e),{text:r}),!1)}return $S(e,t)})).filter(Boolean).join("\n")}function BS(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?FS(n):n,i="assistant"===e.role?LS(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?FS(r.text):r.text,i="assistant"===e.role?LS(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 zS(e){return e.endsWith("\n")?e:`${e}\n`}function WS(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 HS(e){if("system"===e.role||DS(e))return;const t=BS(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 qS{constructor(e,t,r,n={}){var o,i,s,a;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,fallbackToFullWriteOnIncrementalFailure:null===(a=n.fallbackToFullWriteOnIncrementalFailure)||void 0===a||a}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=kS({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}writeFromStateFull(e,t,r){return _S(this,arguments,void 0,(function*(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const i=PS(o,(0,l.VI)(e.withName("writeFromState")),!1);try{const e=yield function(e,t,r){return _S(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=PS(n,(0,l.VI)(e.withName("hydrateSummaryArchives")),!1);let i=0;const s=(0,l.OA)(o.ctx),a=[];let c=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=yield Promise.all(r.summaryArchives.map((e=>_S(this,void 0,void 0,(function*(){i++;const r=yield t.getBlob(s,e);if(r)try{const e=lr.An.fromBinary(r);return i+=e.summarizedMessages.length,yield NS(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),c+=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",c),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=PS(n,(0,l.VI)(e.withName("hydratePromptMessages")),!1),y=yield NS(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&&!DS(e)));return a.push(...w),a}catch(e){n.error=e,n.hasError=!0}finally{IS(n)}}))}(i.ctx,this.blobStore,t),{overviewFactory:o}=n,s=WS(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=US(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=BS(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:TS(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=HS(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"),zS(n)))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{IS(o)}}))}writeFromStateIncremental(e,t,r,n){return _S(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=WS(o),c=a.jsonlLines.length>0;if(s===n&&!c&&!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||c))||o.overviewFactory)return(yield this.writeFromStateFull(e,t,r,o))?s:0;const d=PS(i,(0,l.VI)(e.withName("writeFromStateIncremental")),!1);if(s===n&&c)try{return yield u(this.resolveFilePath(r,"jsonl"),zS(a.jsonlLines.join("\n"))),s}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?(yield this.writeFromStateFull(e,t,r,o))?s:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=yield NS(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=HS(e);t&&i.push(t)}if(i.push(...a.jsonlLines),i.length>0){const e=zS(i.join("\n"));yield u(this.resolveFilePath(r,"jsonl"),e)}return s}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?(yield this.writeFromStateFull(e,t,r,o))?s:0:0}}catch(e){i.error=e,i.hasError=!0}finally{IS(i)}}))}}class GS extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class VS extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}function JS(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${KS}`}(t,r);throw new VS(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 KS="To view or modify configured hooks, go to Cursor Settings > Hooks.",ZS="Agent note: Do not suggest workarounds to the blocked tool.";function YS(e){return e.includes(ZS)?e:`${e}\n\n${ZS}`}function XS(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function QS(e,t){return YS(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${KS}`)}function ek(e){return function(e){return e instanceof GS}(e)||function(e){return e instanceof VS}(e)}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())}))};class rk{constructor(e,t,r,n,o,i,s,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=s,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.configReadyPromises=[],this.config=e,i&&this.addConfigReadyPromise(i)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}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 tk(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,Qa.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}))}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){var r,n,o;this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const i=null!==(n=this.activeSessionIdsByConversationId.get(e.conversationId))&&void 0!==n?n:[];this.activeSessionIdsByConversationId.set(e.conversationId,i.filter((t=>t!==e.sessionId)).concat(e.sessionId));const s=null!==(o=null===(r=null==t?void 0:t.userEmail)||void 0===r?void 0:r.trim())&&void 0!==o?o:"";s.length>0&&this.sessionUserEmailById.set(e.sessionId,s)}setSessionUserEmail(e,t){var r;const n=null!==(r=null==t?void 0:t.trim())&&void 0!==r?r:"";0!==n.length&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv=Object.assign(Object.assign({},this.sessionEnv),e):this.sessionEnvById.set(t.sessionId,Object.assign(Object.assign({},this.sessionEnvById.get(t.sessionId)),e))}clearSessionEnvironment(e){var t;if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=(null!==(t=this.activeSessionIdsByConversationId.get(e.conversationId))&&void 0!==t?t:[]).filter((t=>t!==e.sessionId));0===r.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,r)}}resolveUserEmail(e){var t,r;const{conversation_id:n,session_id:o}=e;if(void 0!==o&&this.sessionUserEmailById.has(o))return null!==(r=this.sessionUserEmailById.get(o))&&void 0!==r?r:null;if(void 0!==n){const e=null===(t=this.activeSessionIdsByConversationId.get(n))||void 0===t?void 0:t.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}getTranscriptPathIfExists(e){return tk(this,void 0,void 0,(function*(){try{const t=(0,ao.Rv)((0,i.homedir)(),this.workspacePath),r=xS({conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of r)try{return yield(0,uo.access)(e),e}catch(e){}return null}catch(e){return null}}))}getSubagentTranscriptPathIfExists(e){return tk(this,void 0,void 0,(function*(){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,ao.Rv)((0,i.homedir)(),this.workspacePath),n=xS({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return yield(0,uo.access)(e),e}catch(e){}return null}catch(e){return null}}))}hasHooksForStep(e){var t,r;return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,null===(t=this.options)||void 0===t?void 0:t.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...(null!==(r=this.config.pluginHooks)&&void 0!==r?r:[]).map((e=>e.config))].some((t=>{const r=null==t?void 0:t.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){var r,n;const o=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,this.config.userHooks,null===(r=this.options)||void 0===r?void 0:r.runtimeHooks];for(const r of o){const n=null==r?void 0:r.hooks[e];if(n&&(t?be(n,t):n).some((e=>!0===e.failClosed)))return!0}for(const r of null!==(n=this.config.pluginHooks)&&void 0!==n?n:[]){const n=r.config.hooks[e];if(n&&(t?be(n,t):n).some((e=>Re(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":case"runtime":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){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,i=this.resolveUserEmail({conversation_id:n,session_id:r});return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version},i&&{CURSOR_USER_EMAIL:i}),t&&{CURSOR_TRANSCRIPT_PATH:t}),{CLAUDE_PROJECT_DIR:this.workspacePath}),this.sessionEnv),void 0!==r?this.sessionEnvById.get(r):void 0),o)}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=r.loop_count,o=t.loop_limit;return null!==o&&(void 0===o?n>=5:n>=o)}executeHookForStep(e,t,r){return tk(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c,u,d,h,p,f;this.configReadyPromises.length>0&&(yield Promise.all(this.configReadyPromises));const m=function(e){return je.includes(e)}(e),g=t,v=m?null:g.conversation_id?yield this.getTranscriptPathIfExists(g.conversation_id):null;let y;if(e===ue.subagentStop){const e=t;y=e.subagent_id?yield this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const w=m?void 0:null!==(h=g.session_id)&&void 0!==h?h:g.conversation_id,b=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),void 0!==w&&{session_id:w}),{hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.resolveUserEmail(g)}),!m&&{transcript_path:v}),e===ue.subagentStop&&{agent_transcript_path:null!=y?y:null}),S=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,b),k=[],E=(e,t)=>{var n;if(!e)return;const o=be(e,S),i=null!==(n=null==r?void 0:r.cwd)&&void 0!==n?n:this.getCwdForSource(t);for(const e of o)Te(e)?this.promptHookClient&&k.push({type:"prompt",script:e,source:t}):Re(e)&&k.push({type:"command",script:e,cwd:i,env:null==r?void 0:r.env,source:t})};E(null===(n=this.config.enterpriseHooks)||void 0===n?void 0:n.hooks[e],"enterprise"),E(null===(o=this.config.teamHooks)||void 0===o?void 0:o.hooks[e],"team"),E(null===(i=this.config.projectHooks)||void 0===i?void 0:i.hooks[e],"project"),E(null===(s=this.config.userHooks)||void 0===s?void 0:s.hooks[e],"user"),E(null===(l=null===(a=this.options)||void 0===a?void 0:a.runtimeHooks)||void 0===l?void 0:l.hooks[e],"runtime"),E(null===(c=this.config.claudeProjectLocalHooks)||void 0===c?void 0:c.hooks[e],"claude-project-local"),E(null===(u=this.config.claudeProjectHooks)||void 0===u?void 0:u.hooks[e],"claude-project"),E(null===(d=this.config.claudeUserHooks)||void 0===d?void 0:d.hooks[e],"claude-user");for(const t of null!==(p=this.config.pluginHooks)&&void 0!==p?p:[]){const n=t.config.hooks[e];if(!(null==n?void 0:n.length))continue;const o=null!==(f=null==r?void 0:r.cwd)&&void 0!==f?f:e===ue.stop||e===ue.subagentStop?this.workspacePath:t.installPath,i=Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==t.plugin&&{plugin:t.plugin}),void 0!==t.marketplace&&{marketplace:t.marketplace}),void 0!==t.pluginId&&{pluginId:t.pluginId}),void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId});for(const e of be(n,S))Re(e)&&k.push({type:"command",script:e,cwd:o,env:null==r?void 0:r.env,source:"claude-plugin",attribution:i,pluginInstallPath:t.installPath})}if(0!==k.length)return this.executeAllAndMerge(e,k,b)}))}executeAllAndMerge(e,t,r){return tk(this,void 0,void 0,(function*(){const n=t.map(((t,n)=>tk(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,t.env,r,o,n,i,t.pluginInstallPath)}catch(r){if(!0===t.script.failClosed){const t=XS(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),i=Le(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===ue.sessionStart,i=e===ue.workspaceOpen,s=Ie.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,a,l){return tk(this,void 0,void 0,(function*(){var c,u,d,h,p,f,m,g;if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:i,index:s};const v=Date.now(),y=Buffer.byteLength(JSON.stringify(o),"utf8");let w;try{w=yield this.executeCommandScript(Object.assign({script:t,cwd:r,request:o,env:n},void 0!==l&&{pluginInstallPath:l}))}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out"),l=Date.now()-v,c=o?"timeout":"spawn_error";if(!0===t.failClosed){const r=XS(`Hook "${t.command}" execution failed: ${n}`),u=Le(e,r);if(u)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:o?"timeout":"blocked",latencyMs:l,payloadSizeBytes:y,errorClass:c,failClosed:!0,timedOut:o},a)),{success:!0,data:u,source:i,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:o?"timeout":"failed",latencyMs:l,payloadSizeBytes:y,errorClass:c,failClosed:!0===t.failClosed,timedOut:o},a)),{success:!1,source:i,index:s}}if(2===w.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.`)}(w.stdout,w.stderr,t.command),n=Le(e,r);return n?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,failClosed:!0===t.failClosed,exitCode:w.exitCode},a)),{success:!0,data:n,source:i,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,failClosed:!0===t.failClosed,exitCode:w.exitCode},a)),{success:!1,source:i,index:s})}if(0!==w.exitCode&&null!==w.exitCode){if(!0===t.failClosed){const r=XS(`Hook "${t.command}" failed with exit code ${w.exitCode}${w.stderr?`: ${w.stderr.trim()}`:""}`),n=Le(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"exit_nonzero",failClosed:!0,exitCode:w.exitCode},a)),{success:!0,data:n,source:i,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:w.exitCode},a)),{success:!1,source:i,index:s}}const b=w.stdout.trim();if(!b){if(!0===t.failClosed){const r=XS(`Hook "${t.command}" returned no output.`),n=Le(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"empty_stdout",failClosed:!0,exitCode:null!==(u=w.exitCode)&&void 0!==u?u:void 0},a)),{success:!0,data:n,source:i,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:null!==(d=w.exitCode)&&void 0!==d?d:void 0},a)),{success:!1,source:i,index:s}}const S=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}}(b);if(void 0===S){const r=Fe({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(h=w.exitCode)&&void 0!==h?h:void 0},a)),{success:!0,data:r.blockResponse,source:i,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(p=w.exitCode)&&void 0!==p?p:void 0},a)),{success:!1,source:i,index:s})}const k=Oe(e,S,{enableClaudeNestedHookSpecificOutputCompatibility:null===(c=this.options)||void 0===c?void 0:c.enableClaudeNestedHookSpecificOutputCompatibility});if(k.success){const r=k.data,n="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:n?"blocked":"success",latencyMs:w.duration,payloadSizeBytes:y,failClosed:!0===t.failClosed,exitCode:null!==(f=w.exitCode)&&void 0!==f?f:void 0},a)),{success:!0,data:k.data,source:i,index:s}}const E=Fe({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return E.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(m=w.exitCode)&&void 0!==m?m:void 0},a)),{success:!0,data:E.blockResponse,source:i,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:i,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(g=w.exitCode)&&void 0!==g?g:void 0},a)),{success:!1,source:i,index:s})}))}executePromptHook(e,t,r,n,o,i){return tk(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===ue.beforeSubmitPrompt||e===ue.sessionStart?{continue:!0}:e===ue.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=Le(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=XS(`Prompt hook failed: ${s}`),r=Le(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 tk(this,void 0,void 0,(function*(){var t,r,n,o,a,l;const{script:c,cwd:u,request:d,env:h,pluginInstallPath:p}=e,f=1e3*(null!==(a=c.timeout)&&void 0!==a?a:60),m=Date.now(),g=JSON.stringify(d);let v;const y=new AbortController,w=setTimeout((()=>{y.abort()}),f);try{const e="win32"===process.platform,a=this.getCommandHookPayloadTransportMode(),E=this.shouldUseCommandHookDirectStdinTransport();let x;if(E)x=c.command;else if("windows_temp_file"===a){v=yield(0,uo.mkdtemp)((0,s.join)((0,i.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(v,"payload.json");yield(0,uo.writeFile)(e,g,{encoding:"utf8",flag:"wx"}),x=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,c.command)}else x=e?`@'\n${g.replace(/'/g,"''")}\n'@ | & ${c.command}`:`${c.command} <<'CURSOR_HOOK_EOF'\n${g}\nCURSOR_HOOK_EOF`;const C=d,{conversation_id:_,session_id:P}=C,I=void 0===_?void 0:this.activeSessionIdsByConversationId.get(_),T=void 0===P||P===_&&!this.sessionEnvById.has(P)?void 0===_?void 0:null!==(l=null==I?void 0:I.at(-1))&&void 0!==l?l:_:P,R=this.buildHookEnvironment({transcriptPath:C.transcript_path,sessionId:T,conversationId:_,executionEnv:h}),A={};for(const[e,t]of Object.entries(R))void 0!==t&&(A[e]=t);void 0!==p&&(A.CURSOR_PLUGIN_ROOT=p,A.CLAUDE_PLUGIN_ROOT=p);const O=(0,Qe.q6)();let M="",j="",D=null,N=!1;try{for(var b,S=!0,k=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(O,x,{workingDirectory:u,signal:y.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:A,pipeStdin:E}));!(t=(b=yield k.next()).done);S=!0){o=b.value,S=!1;const e=o;switch(e.type){case"stdin_ready":E&&(yield this.writeCommandHookStdinPayload(e.stdin,g),N=!0);break;case"stdout":M+=e.data.toString("utf8");break;case"stderr":j+=e.data.toString("utf8");break;case"exit":D=e.code}}}catch(e){r={error:e}}finally{try{S||t||!(n=k.return)||(yield n.call(k))}finally{if(r)throw r.error}}if(E&&!N)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(w);const $=Date.now()-m;if(y.signal.aborted)throw new Error(`Hook script timed out after ${f}ms`);return{stdout:M,stderr:j,exitCode:D,duration:$}}catch(e){if(clearTimeout(w),Date.now(),y.signal.aborted)throw new Error(`Hook script timed out after ${f}ms`);throw e}finally{if(v)try{yield(0,uo.rm)(v,{recursive:!0,force:!0})}catch(e){}}}))}}var nk=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 ok(e){switch(null!=e?e:(0,i.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}class ik{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}load(){return nk(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,a=i?s.dirname(s.dirname(i)):void 0,l=(e,t)=>{if(!e||!a)return;if(t)return a;const r=s.relative(s.resolve(a),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:a},c=(e,t,r,n,i,a,l,c)=>nk(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 ${a} 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]=s.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 ${a} 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 Te(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 de&&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=we(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){var t;const r=new Set,n=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks];for(const e of n)if(null==e?void 0:e.hooks)for(const t of Object.keys(e.hooks))r.add(t);for(const n of null!==(t=e.pluginHooks)&&void 0!==t?t:[])for(const e of Object.keys(n.config.hooks))r.add(e);return r}}class sk{constructor(e){this.config=e,this.configuredSteps=ik.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var ak=r("node:perf_hooks");function lk(e,t){void 0!==e&&t.length>0&&e.push(...t)}class ck 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 uk=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function dk({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 ck({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new uk.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ie).map((e=>{if(!function(e){return e===ue.sessionStart||e===ue.beforeSubmitPrompt||e===ue.preToolUse||e===ue.postToolUse||e===ue.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 hk=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())}))},pk=function(e){return this instanceof pk?(this.v=e,this):new pk(e)};const fk=(0,d.h)("generic-hooks");function mk(e,t,r,n){try{return dk({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof ck)return fk.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const gk=e=>Math.round(1e3*e)/1e3;function vk(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)=>hk(this,[n,c,u,...d],void 0,(function*(n,c,u,d=!1){try{const h=yield t.executeHookForStep(ue.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));lk(s,mk(e,r,ue.postToolUseFailure,null==h?void 0:h.additional_context))}catch(t){fk.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}})),fireSuccessAsync:(n,c)=>hk(this,void 0,void 0,(function*(){try{const u=yield t.executeHookForStep(ue.postToolUse,Object.assign(Object.assign(Object.assign({},a),{tool_name:r,tool_input:o,tool_output:c,duration:n,tool_use_id:l}),i));lk(s,mk(e,r,ue.postToolUse,null==u?void 0:u.additional_context))}catch(t){fk.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 yk(e,t,r,n,o,i,s,a){return hk(this,void 0,void 0,(function*(){var l,c;const{baseHookRequest:u,toolUseId:d,extraHookFields:h}=n;try{const a=yield r.executeHookForStep(ue.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=YS(r);try{lk(n.hookContextCollector,dk({hookEventName:ue.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof ck))throw t;fk.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))),lk(n.hookContextCollector,dk({hookEventName:ue.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,ue.preToolUse,i.toolName))&&void 0!==c&&c,u=n instanceof ck;if(a){const e=XS(`${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}}fk.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(ek(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 wk(e){return e.toolCallId}function bk(e,t,r,n){return{execute(o,i,s){return hk(this,void 0,void 0,(function*(){var a,l,c,u,d,h,p,f,m,g;const{hookContext:v,helpers:y}=vk(o,i,t,r,n,s);let w;try{w=yield yk(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=ak.performance.now();try{const r=yield e.execute(o,i,s),a=gk(ak.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(ek(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);fk.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=gk(ak.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*Sk(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}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())}))};class Ek{readFile(e){return kk(this,void 0,void 0,(function*(){try{return yield uo.readFile(e,"utf-8")}catch(e){if("ENOENT"===(null==e?void 0:e.code))return;throw e}}))}exists(e){return kk(this,void 0,void 0,(function*(){try{return yield uo.access(e),!0}catch(e){return!1}}))}pathContainsSymlink(e,t){return kk(this,void 0,void 0,(function*(){return function(e,t){return r=this,n=void 0,i=function*(){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return!0;const i=o.split(s.sep).filter((e=>e.length>0));let a=n;for(const e of i){a=s.join(a,e);try{if((yield(0,uo.lstat)(a)).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 xk{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 Gt.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||i)){const e=n.result.value.requestContext,t=new Gt.bb(Object.assign(Object.assign(Object.assign({},e),o&&{hooksAdditionalContext:o}),i&&{hooksConfig:i}));return new Gt._G({result:{case:"success",value:new Gt.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 Ck(e){return!!e&&e.type!==Lo.vc.INSECURE_NONE&&e.type!==Lo.vc.UNSPECIFIED}const _k="Shell";function Pk(e){return t=this,r=arguments,o=function*({hookExecutor:e,baseHookRequest:t,command:r,cwd:n,sandbox:o}){const i=yield e.executeHookForStep(ue.beforeShellExecution,Object.assign(Object.assign({},t),{command:r,cwd:n,sandbox:o}));if("deny"===(null==i?void 0:i.permission)){const e=QS("Command execution",i.user_message);throw new GS(e)}if("ask"===(null==i?void 0:i.permission))return s=i.user_message,new Rt.In({kind:Rt.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 Ik={toolName:_k,getToolCallId:wk,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 Pt.Lt({result:{case:"rejected",value:new Rt.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=Ck(t.sandboxPolicy);Kt(t,yield Pk({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 Tk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Ik)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Rk={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Pt.nt({result:{case:"error",value:new Pt.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 Ak{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Rk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Ok={toolName:"ComputerUse",getToolCallId:wk,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new dh.ks({result:{case:"error",value:new dh.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 Mk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Ok)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jk={toolName:"Delete",getToolCallId:wk,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new It.Pi({result:{case:"rejected",value:new It.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 Dk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,jk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Nk={toolName:"ReadLints",getToolCallId:wk,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Qg.Ek({result:{case:"rejected",value:new Qg.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 $k{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Nk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Fk={toolName:"Fetch",getToolCallId:wk,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Hh.uN({result:{case:"error",value:new Hh.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 Lk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Fk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Uk={toolName:"Grep",getToolCallId:wk,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 Zh.Ud({result:{case:"error",value:new Zh.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 Bk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Uk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zk={toolName:"List",getToolCallId:wk,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 Gm.fv({result:{case:"rejected",value:new Gm.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 Wk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,zk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var Hk=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 qk=(0,d.h)("hooks-exec:mcp");function Gk(e,t,r,n){try{return dk({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof ck)return qk.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class Vk{constructor(e,t,r,n){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n}execute(e,t,r){return Hk(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(ue.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{lk(h,dk({hookEventName:ue.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof ck))throw t;qk.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 Tt.iz({result:{case:"permissionDenied",value:new Tt.HQ({error:QS("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]=fr.Value.fromJson(n));p=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])))}catch(t){qk.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}lk(h,dk({hookEventName:ue.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,ue.preToolUse,f))&&void 0!==l&&l,o=t instanceof ck;if(r){const r=XS(`${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 Tt.iz({result:{case:"permissionDenied",value:new Tt.HQ({error:QS("MCP tool execution",r),isReadonly:!1})}})}qk.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(ue.beforeMCPExecution,b);if("deny"===(null==S?void 0:S.permission)){const t=QS("MCP tool execution",S.user_message);return yield this.firePostToolUseFailureAsync(e,u,f,p,t,"permission_denied",0,d,!1,h),new Tt.iz({result:{case:"permissionDenied",value:new Tt.HQ({error:t,isReadonly:!1})}})}const k=ak.performance.now();try{const n=yield this.innerExecutor.execute(e,t,r),o=gk(ak.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){qk.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(ue.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 Tt._Z({content:{case:"text",value:new Tt.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 Tt._Z({content:{case:"text",value:new Tt.zN({text:String(e.text)})}})):t.push(new Tt._Z({content:{case:"text",value:new Tt.zN({text:JSON.stringify(e)})}}))}else t.push(new Tt._Z({content:{case:"text",value:new Tt.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Tt.iz({result:{case:"success",value:new Tt.QW({content:t,isError:r})}})}catch(t){return qk.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),n}return n}catch(t){const r=gk(ak.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 Hk(this,void 0,void 0,(function*(){try{const l=yield this.hookExecutor.executeHookForStep(ue.postToolUse,Object.assign(Object.assign({},t),{tool_name:r,tool_input:n,tool_output:o,duration:i,tool_use_id:s}));return lk(a,Gk(e,r,ue.postToolUse,null==l?void 0:l.additional_context)),l}catch(t){return void qk.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 Hk(this,void 0,void 0,(function*(){try{const u=yield this.hookExecutor.executeHookForStep(ue.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}));lk(c,Gk(e,r,ue.postToolUseFailure,null==u?void 0:u.additional_context))}catch(t){qk.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}))}}const Jk={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Tt.kP({result:{case:"error",value:new Tt.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 Kk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Jk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Zk={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 Tt.ZD({result:{case:"error",value:new Tt.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 Yk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Zk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Xk={toolName:"Read",getToolCallId:wk,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Tv.sV({result:{case:"rejected",value:new Tv.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 JS((()=>o.executeHookForStep(ue.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=QS("File read",s.user_message);throw new GS(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 Qk{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,Xk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const eE={toolName:"RecordScreen",getToolCallId:wk,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new Zy.Tj({result:{case:"failure",value:new Zy.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 tE{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,eE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var rE=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 nE(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const oE={toolName:_k,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 Rt.W4({result:{case:"rejected",value:new Rt.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:nE(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:e=>rE(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"";Kt(t,yield Pk({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:Ck(t.requestedSandboxPolicy)}))})),runPostExecutionHooks:e=>rE(void 0,void 0,void 0,(function*(){const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:i}=e,s=nE(r);yield o.executeHookForStep(ue.afterShellExecution,Object.assign(Object.assign({},n),{command:t.command,output:s,duration:i,sandbox:Ck(t.requestedSandboxPolicy)}))}))};class iE{constructor(e,t,r){this.wrappedExecutor=bk(e,t,r,oE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}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{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 lE={toolName:_k,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 Rt.FI({event:{case:"rejected",value:new Rt.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new Rt.FI({event:{case:"hookContext",value:new Rt.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new aE,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=>sE(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",i=Ck(t.requestedSandboxPolicy);Kt(t,yield Pk({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:i}))})),runPostExecutionHooks:e=>sE(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:i}=e,s=Ck(t.requestedSandboxPolicy);yield n.executeHookForStep(ue.afterShellExecution,Object.assign(Object.assign({},r),{command:t.command,output:o.getOutput(),duration:i,sandbox:s}))}))};class cE{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 pk?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}=vk(o,i,t,r,n,s),v=n.runPreExecutionHooks?e=>hk(this,void 0,void 0,(function*(){yield n.runPreExecutionHooks(e)})):void 0,y=yield pk(yk(o,i,t,m,g,n,((e,t)=>n.createRejectedEvent(e,t)),v));if("rejected"===y.type){yield yield pk(y.result);for(const e of Sk(n,m))yield yield pk(e);return yield pk(void 0)}const w=ak.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 pk(x.next())).done);E=!0){u=k.value,E=!1;const e=u;b.onEvent(e),yield yield pk(e)}}catch(e){l={error:e}}finally{try{E||a||!(c=x.return)||(yield pk(c.call(x)))}finally{if(l)throw l.error}}}catch(e){S=!0;const t=gk(ak.performance.now()-w),r=e instanceof Error?e.message:String(e);yield pk(g.fireFailureAsync(t,r,"error"));for(const e of Sk(n,m))yield yield pk(e);throw e}const C=gk(ak.performance.now()-w);if(n.runPostExecutionHooks)try{yield pk(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){fk.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(!S)if(b.isAborted())yield pk(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 pk(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 pk(g.fireFailureAsync(C,e,"error"))}for(const e of Sk(n,m))yield yield pk(e)}))}}}(e,t,r,lE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var uE=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 dE{constructor(e,t,r){const n=new Map;this.wrappedExecutor=bk(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:wk,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 At.v3({result:{case:"error",value:new At.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=>uE(this,void 0,void 0,(function*(){const{args:r,toolUseId:n}=e;let o,i=!1;try{(yield(0,uo.stat)(r.path)).size>262144?i=!0:o=yield Ti(r.path)}catch(e){}t.set(n,{contentBeforeWrite:o,fileTooLarge:i})})),runCleanup:e=>{t.delete(e)},runPostExecutionHooks:r=>uE(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,gg.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(ue.afterFileEdit,d);if(n.returnFileContentAfterWrite&&void 0!==h){const e=o.result.value.path;try{const t=yield Ti(e),r=Oi(t),n=Buffer.byteLength(t,"utf8");return new At.v3({result:{case:"success",value:new At.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 hE{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===Ot.symbol?new iE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Mt.symbol?new cE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===jt.symbol?new dE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ht.symbol?new Vk(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease):e.symbol===Ct.symbol||e.symbol===_t.symbol?new Qk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===tt.symbol?new Wk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ce.symbol?new Bk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ae.symbol?new Lk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ie.symbol?new Dk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===se.symbol?new $k(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===pt.symbol?new Kk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ft.symbol?new Yk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Q.symbol?new Tk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ee.symbol?new Ak(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===oe.symbol?new Mk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ht.symbol?new tE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===qt.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new xk(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===Ot.symbol?yield[t,new iE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Mt.symbol?yield[t,new cE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===jt.symbol?yield[t,new dE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ht.symbol?yield[t,new Vk(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease)]:t.symbol===Ct.symbol||t.symbol===_t.symbol?yield[t,new Qk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===tt.symbol?yield[t,new Wk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ce.symbol?yield[t,new Bk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ae.symbol?yield[t,new Lk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ie.symbol?yield[t,new Dk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===se.symbol?yield[t,new $k(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===pt.symbol?yield[t,new Kk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ft.symbol?yield[t,new Yk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Q.symbol?yield[t,new Tk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ee.symbol?yield[t,new Ak(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===oe.symbol?yield[t,new Mk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ht.symbol?yield[t,new tE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===qt.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[t,new xk(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 pE,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())}))},mE=function(e){return this instanceof mE?(this.v=e,this):new mE(e)};const gE={cursor_version:null!==(pE=process.env.AGENT_CLI_STATIC_VERSION)&&void 0!==pE?pE:"1.0.0",user_email:null};function vE(e=process.cwd()){let t=e;const r={getCwd(){return fE(this,void 0,void 0,(function*(){return t}))},clone:e=>vE(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 mE?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,fo.getPowerShellExecutable)(),args:[...Ge,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),h=(0,hl.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 mE(p.shift()):yield mE(new Promise((e=>{f=e})));if(void 0!==m)throw m}))}};return r}function yE(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function wE(e){return"string"==typeof e&&e.length>0?e:void 0}function bE(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function SE(e){if(Array.isArray(e)&&e.every(bE))return e.map((e=>({id:e.id,value:e.value})))}class kE{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}dispose(){return fE(this,void 0,void 0,(function*(){yield this.sessionHooksRuntime.dispose()}))}}function EE(e={}){return{createHooksRuntime:t=>function(e){return fE(this,arguments,void 0,(function*(e,t={}){const r=yield new ik(new Ek,function(e,t){var r,n,o,a,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===(a=t.includeUserHooks)||void 0===a||a;return{enterpriseConfigPath:null===(l=t.includeEnterpriseHooks)||void 0===l||l?ok():void 0,userConfigPath:d?(0,s.join)((0,i.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:d?(0,s.join)((0,i.homedir)(),".claude","settings.json"):void 0,projectConfigPath:u&&void 0!==c?(0,s.join)(c,".cursor","hooks.json"):void 0,claudeProjectConfigPath:u&&void 0!==c?(0,s.join)(c,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:u&&void 0!==c?(0,s.join)(c,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new sk(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),a=function(e){var t;return Object.freeze(Object.assign(Object.assign({},gE),null!==(t=e.globalContext)&&void 0!==t?t:{}))}(t);return{projectDir:e.projectRoot,workspacePath:o,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){var e;const i=new rk(r,o,a,(null!==(e=t.createTerminalExecutor)&&void 0!==e?e:vE)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(s=t.useCommandHookStdinTransport,!0===s?"stdin":"legacy")});var s;return{hookExecutor:i,hooksConfigLease:n,dispose(){return fE(this,void 0,void 0,(function*(){i.clearSessionEnvironment()}))}}},dispose(){return fE(this,void 0,void 0,(function*(){}))}}}))}(t.workspaceState,e)}}var xE=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");function CE(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 _E=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 PE(e={}){var t,r,n,o,s,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===(s=e.includeManagedSkills)||void 0===s||s,p=null===(a=e.includePluginExtensibility)||void 0===a||a,f=new Kh,m=(0,i.homedir)(),g=ud(m).dirPath;let v,y=!0;return{prepareLocalExtensibility(){return _E(this,void 0,void 0,(function*(){y=h&&(yield function(e){return _E(this,void 0,void 0,(function*(){if(!e)return!1;const t=(0,mr.createClient)(xE.I,e),r=yield async function(e,t){try{const r=await t.getManagedSkills()??[],n=await vb(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return wb.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,Qe.q6)(),{getManagedSkills:()=>_E(this,void 0,void 0,(function*(){var e;return null!==(e=(yield t.getManagedSkills(new Cb.X8g({}))).skills)&&void 0!==e?e:[]}))});return"synced"===r.status}))}(e.dashboardTransport))}))},loadLocalExtensibility(t){return _E(this,void 0,void 0,(function*(){var r;const n=function(e){var t;if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workingDirectory;return void 0!==r?[r]:[]}(t.workspaceState);if(0===n.length)return v=void 0,{cursorRulesService:jE(),getAgentSkills:e=>_E(this,void 0,void 0,(function*(){return[]}))};const o=(0,Qe.q6)(),i=null===(r=e.loadNestedRules)||void 0===r||r,s=u?n.map((e=>new Zd(o,f,e,i,l,void 0))):[],a=function(e,t){const r=IE(t);return{getAllCursorRules(t){return _E(this,void 0,void 0,(function*(){return TE(yield e.getAllCursorRules(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===s.length?jE():1===s.length?s[0]:new Kd(s,(()=>xd)),{allowedRoots:u?n:[],excludedRoots:[]}),h=function(e,t){const r=IE(t);return{getAllCursorRules(t){return _E(this,void 0,void 0,(function*(){return TE(yield e.getAllCursorRules(t),r)}))},getAllAgentSkills(t){return _E(this,void 0,void 0,(function*(){return TE(yield e.getAllAgentSkills(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new Yd(o,u?n:[],m,f,i,void 0,l,Promise.resolve(),"sdk"),{allowedRoots:[...u?n:[],...d?[m]:[],...y?[g]:[]],excludedRoots:y?[]:[g]}),w=u?n.map((e=>new ah(e,l))):[],b=0===w.length?new th:1===w.length?w[0]:new ch(w),S=oS(t.services.pluginBootstrapOutputs),k=S&&p?new Qd(o,(()=>({importThirdPartyPlugins:c})),void 0,S.pluginsService):void 0,E=S&&p?new uh((()=>({importThirdPartyPlugins:c})),S.pluginsService):void 0,x=new Kd([a,h,...k?[k]:[]],(()=>xd)),C=new nb([h,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:u?n:[],userHomeDirectory:m,agentStoreSkillsDirs:[]}))),_=new ch([b,...E?[E]:[]]);return v={localRulesService:a,localSkillsService:h,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:E,mergedCursorRulesService:x,mergedAgentSkillsService:C,mergedSubagentsService:_},{cursorRulesService:x,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:_}}))},disposeLocalExtensibility(){return _E(this,void 0,void 0,(function*(){if(!v)return;const e=v;v=void 0,yield function(e){return _E(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 CE(e)}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}))}(e)}))}}}function IE(e){const t=Promise.all(e.allowedRoots.map(OE)),r=Promise.all(e.excludedRoots.map(OE));return e=>_E(this,void 0,void 0,(function*(){const[n,o,i]=yield Promise.all([ME(e.fullPath),t,r]);return void 0!==n&&!i.some((e=>RE(n,e)))&&o.some((e=>RE(n,e)))}))}function TE(e,t){return _E(this,void 0,void 0,(function*(){const r=yield Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}))}function RE(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function AE(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}function OE(e){return _E(this,void 0,void 0,(function*(){try{return AE(yield(0,uo.realpath)(e))}catch(t){return AE(e)}}))}function ME(e){return _E(this,void 0,void 0,(function*(){try{return AE(yield(0,uo.realpath)(e))}catch(e){return}}))}function jE(){return{getAllCursorRules(){return _E(this,void 0,void 0,(function*(){return[]}))},reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}var DE=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 NE(e={}){var t,r,n,o;const a=null!==(t=e.userHomeDirectory)&&void 0!==t?t:(0,i.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":Lb.warn("[local-plugins-bootstrap]",t,null!=r?r:{});break;case"error":Lb.error("[local-plugins-bootstrap]",t,null!=r?r:{})}},increment(){},distribution(){},captureException(e,t){Lb.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,null!=t?t:{})}},u=$E(e.marketplaceOptions),d=void 0!==e.dashboardTransport,h=null!==(o=e.loadCursorFirstParty)&&void 0!==o?o:u||d;return{loadPluginBootstrapOutputs(t){return DE(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:i}=yield function(e){return DE(this,void 0,void 0,(function*(){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(yield rd(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,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,mr.createClient)(xE.I,e.dashboardTransport),n=Bc((()=>DE(this,void 0,void 0,(function*(){try{return yield r.getEffectiveUserPlugins(new Cb.EwF({}))}catch(e){return{plugins:[]}}}))),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Bc((()=>DE(this,void 0,void 0,(function*(){var e,t;if(void 0===o)return{plugins:[]};try{const n=yield rd(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||Xu(t)})).map((({key:e,entry:t})=>{const r=nd(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=nd(e.key);return new Cb.vwy({name:t.name,marketplaceName:t.marketplaceName})}));l=null!==(t=null===(e=(yield r.resolvePluginsByRef(new Cb.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 ul(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new ul(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:n,userHomeDirectory:a}):void 0,d=$E(u),p=new xb(void 0!==n?[n]:[],a,(()=>({importThirdPartyPlugins:l,loadCursorFirstParty:h})),u,c);let f=[];const m=[...i];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:nS,discoveredEntries:o,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,dispose(){return DE(this,void 0,void 0,(function*(){}))}};for(const e of m)Lb.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)Lb.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 $E(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}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())}))};class LE{getAllCursorRules(e){return FE(this,void 0,void 0,(function*(){return[]}))}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}class UE extends Zw{constructor(e,t){super(e),this.sessionMcpLease=t}dispose(){const e=Object.create(null,{dispose:{get:()=>super.dispose}});return FE(this,void 0,void 0,(function*(){try{yield e.dispose.call(this)}finally{yield CE(this.sessionMcpLease)}}))}}function BE(e){const t=new Kh;return{createResources(r){return FE(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 LE,p=null!==(a=r.workspaceServices.subagentsService)&&void 0!==a?a:new th,f=null!==(l=r.workspaceServices.mcpLease)&&void 0!==l?l:new Qp,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 Wh(v,y):new zh(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 Zw(n):new UE(n,m)}catch(e){throw yield CE(m),e}}))}}}var zE=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 WE=["cursorRulesService","getAgentSkills","subagentsService"],HE=new WeakSet;function qE(e){("object"==typeof e&&null!==e||"function"==typeof e)&&HE.add(e)}function GE(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&HE.has(e)}function VE(e,t){const r=Object.keys(t).filter((e=>!WE.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${WE.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of WE)Object.hasOwn(t,r)&&(e[r]=t[r])}function JE(e,t,r){return zE(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&&(qE(a.cursorRulesService),qE(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&&VE(s,e)}return s}catch(t){try{yield KE(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 KE(e,t){return zE(this,void 0,void 0,(function*(){const r=null==t?void 0:t.preserveSharedContributorsFrom;let n;const o=e=>zE(this,void 0,void 0,(function*(){try{yield CE(e)}catch(e){null!=n||(n=e)}}));if(e.subagentsService===(null==r?void 0:r.subagentsService)||GE(e.subagentsService)||(yield o(e.subagentsService)),e.cursorRulesService===(null==r?void 0:r.cursorRulesService)||GE(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 zE(this,void 0,void 0,(function*(){let t;for(let r=e.length-1;r>=0;r-=1)try{yield CE(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 ZE=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 YE(e){return ZE(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 CE(o)}catch(e){null!=r||(r=e)}}}if(void 0!==r)throw r}))}const XE=["project","user","team","mdm","plugins"],QE=new Set([...XE,"all"]);function ex(e){if(void 0===e||0===e.length)return rx([]);for(const t of e)if(!QE.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({},rx(XE)),{all:!0})}return rx(e)}function tx(e,t){return e[t]}function rx(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 nx=Object.freeze({}),ox=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:nx});var ix=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 sx(){return ix(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:Ob,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({},ox.metadata),e.metadata)),r=Object.assign(Object.assign(Object.assign({},ox),e),{metadata:t});return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:i});let a=yield JE(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 ix(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 ZE(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 YE(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 ZE(this,void 0,void 0,(function*(){var t,r;if(!g){g=!0;try{yield YE(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 ix(this,void 0,void 0,(function*(){l||(yield u((()=>ix(this,void 0,void 0,(function*(){var e,t;if(l)return;const r=a,o=yield JE(n,i,s);l?yield KE(o,{disposeLocalExtensibility:d}):(a=o,yield KE(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 ix(this,void 0,void 0,(function*(){l||(l=!0,yield u((()=>ix(this,void 0,void 0,(function*(){var e;try{yield KE(a,{disposeLocalExtensibility:d})}finally{yield null===(e=n.lifecycle)||void 0===e?void 0:e.dispose()}})))))}))}}}))}var ax=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 lx{requestApproval(e){return ax(this,void 0,void 0,(function*(){return{approved:!0}}))}}class cx{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}getPermissions(){return ax(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 ax(this,void 0,void 0,(function*(){}))}}class ux{open(e,t){return ax(this,void 0,void 0,(function*(){}))}getDiagnostics(e,t){return ax(this,void 0,void 0,(function*(){return[]}))}}class dx{getCodebaseReference(e,t){return ax(this,void 0,void 0,(function*(){}))}}class hx{constructor(e){this.inner=e}getState(e){return ax(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 px{constructor(e){this.subagents=e.map((e=>new Qt.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Qt.b$.DEFAULT,isBackground:!1,source:"sdk"})))}getAllSubagents(){return ax(this,void 0,void 0,(function*(){return this.subagents}))}reload(){return ax(this,void 0,void 0,(function*(){return this.subagents}))}}var fx=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())}))},mx=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),gx=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 vx=co;function yx(e,t){return gx(this,void 0,void 0,(function*(){const r=(0,s.dirname)(e);yield(0,uo.mkdir)(r,{recursive:!0}),yield(0,uo.writeFile)(e,t,"utf-8")}))}class wx{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=vx(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=kS({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new qS(this.projectDir,e.blobStore,yx,Object.assign({writeText:!1,writeJsonl:!0},t?{pathResolver:t}:{})),this.nestedSubagentTranscriptStore=new qS(this.projectDir,e.blobStore,yx,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=kS({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((()=>gx(this,void 0,void 0,(function*(){try{yield e()}catch(e){Lb.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})))),this.writeChain}writeFromState(e,t){return gx(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>gx(this,void 0,void 0,(function*(){yield this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=yield(0,ur.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 gx(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>gx(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=kS({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=kS({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(vx(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var bx=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 Sx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,kx="User aborted/interrupted manually.";class Ex{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 nr}createOrResumeSession(e,t){return bx(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(!Sx.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&or(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 ur.We,r=(0,ur.sh)(e),n=new ur.pH(new ur.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new wx({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 bx(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:Qt.qL.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 bx(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){Lb.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 bx(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 bx(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 Xt.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 bx(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 Xt.Pw(Object.assign(Object.assign({},r),{runInBackground:!1})):new Xt.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 bx(this,void 0,void 0,(function*(){var o,i,s;let a,l=0;const c=new lr.QF({action:{case:"userMessageAction",value:new lr.Vt({userMessage:new lr.RG({text:r.prompt})})}}),u=new lr.Gm({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(u.credentials=r.credentials);const d=new Db,h={sendUpdate:(e,r)=>bx(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)=>bx(this,void 0,void 0,(function*(){return function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return Ln(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return Bn(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return Hn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new mx.tz({result:{case:"rejected",value:new mx.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return zn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)}))},p={handleCheckpoint:(e,t)=>bx(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 G(g,function(e){const t=[[jt,(r=e.errorMessage,{execute(e,t){return Dt(this,void 0,void 0,(function*(){return new At.v3({result:{case:"permissionDenied",value:new At.U7({path:t.path,error:r,isReadonly:!0})}})}))}})],[ie,Bt(e.errorMessage)],[ht,zt(e.errorMessage)]];var r;return e.wrapShell&&t.push([Ot,Ft(e.errorMessage)],[Mt,Lt(e.errorMessage)],[Q,Ut(e.errorMessage)]),e.includeWriteBackgroundShellStdin&&t.push([ee,Wt(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:Bb(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),yield n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:kx}:{status:"success"}),{status:"completed",finalMessage:a,toolCallCount:l}}catch(r){const o=r instanceof Error?r.message:String(r);return Lb.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:kx}:{status:"error",error:o}}}))}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:kx}:{status:"error",error:t}}isAwaitBackgroundMode(e){var t;if(!Boolean(e.resumeAgentId&&!or(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 bx(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 bx(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 bx(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 bx(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 bx(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 xx=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),Cx=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),_x=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),Px=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),Ix=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),Tx=r("./src/agent/analytics.ts");function Rx(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 Ax("tool-call-started",e.message.value);case"partialToolCall":return Ax("partial-tool-call",e.message.value);case"toolCallCompleted":return Ax("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=Rx(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"routedModel":case void 0:return null;default:return e.message,null}}function Ax(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:$x(r)}:{}):null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"delete",args:{path:t.path}},r?{result:Fx(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:Lx(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:Ux(r)}:{}):null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"read",args:{path:t.path}},r?{result:zx(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:Wx(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:Hx(r)}:{}):null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"readLints",args:{paths:t.paths}},r?{result:Gx(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:Vx(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:Kx(r)}:{}):null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"recordScreen",args:{mode:Zx(t.mode)}},r?{result:Yx(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:Jx(r)}:{}):null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"createPlan",args:{plan:t.plan}},r?{result:Xx(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:eC(e.status)})))}},r?{result:Qx(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:Ox(t)},r?{result:Dx(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"adoptToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updatePrCodeTourToolCall":case"getPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"stopAgentToolCall":case"piReadToolCall":case"piBashToolCall":case"piEditToolCall":case"piWriteToolCall":case"piGrepToolCall":case"piFindToolCall":case"piLsToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function Ox(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:Mx(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:jx(e.mode)}:{}),e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{})}function Mx(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function jx(e){switch(e){case Qt.FL.AGENT:return"agent";case Qt.FL.PLAN:return"plan";default:return"unspecified"}}function Dx(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:Nx(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 Nx(e){switch(e){case Qt.qL.AGENT_REQUEST:return"agentRequest";case Qt.qL.USER_REQUEST:return"userRequest";case Qt.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function $x(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 Fx(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 Lx(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 Ux(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]=Bx(n);return{status:"success",value:Object.assign(Object.assign({},Object.keys(r).length>0?{workspaceResults:r}:{}),t.activeEditorResult?{activeEditorResult:Bx(t.activeEditorResult)}:{})}}return{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}}function Bx(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 zx(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 Wx(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 Hx(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:qx(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function qx(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(qx))&&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 Gx(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:tC(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 Vx(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 Jx(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 Kx(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 Zx(e){switch(e){case Zy.$u.START_RECORDING:return"START_RECORDING";case Zy.$u.SAVE_RECORDING:return"SAVE_RECORDING";case Zy.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function Yx(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 Xx(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 Qx(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:eC(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 eC(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function tC(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}const rC={type:"object",properties:{},additionalProperties:!0};function nC(e){return{execute(t,r,n){return o=this,i=void 0,a=function*(){const t=r.toolName||function(e){const t=`${ot}-`;return e.startsWith(t)?e.slice(t.length):e}(r.name),n=e[t];if(void 0===n)return new Tt.iz({result:{case:"error",value:new Tt.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:iC(e)?e:void 0};var t}(e),n=void 0!==r.structuredContent?fr.Struct.fromJson(r.structuredContent):void 0;return new Tt.iz({result:{case:"success",value:new Tt.QW({content:r.content.map(oC),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 Tt.iz({result:{case:"error",value:new Tt.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 oC(e){var t;return"text"===e.type?new Tt._Z({content:{case:"text",value:new Tt.zN({text:e.text})}}):new Tt._Z({content:{case:"image",value:new Tt.do({data:n.Buffer.from(e.data,"base64"),mimeType:null!==(t=e.mimeType)&&void 0!==t?t:""})}})}function iC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var sC=r("./src/agent/errors.ts"),aC=r("./src/agent/executor-common.ts"),lC=r("./src/agent/native/vendored-tree-sitter.ts"),cC=r("./src/agent/platform-package-locator.ts"),uC=r("./src/agent/sdk-config.ts"),dC=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hC=r("./src/agent/utils/logger.ts"),pC=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 fC={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},mC=new Map;var gC=r("./src/agent/tools-option.ts"),vC=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 yC{requestApproval(){return vC(this,void 0,void 0,(function*(){return{approved:!0}}))}}function wC(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof Zw))throw new sC.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ht),i=nC(t),s=new yC;e.resources.base.register(ht,{execute(e,t,r){return vC(this,void 0,void 0,(function*(){if(function(e){return e.providerIdentifier===ot}(t)){const o=yield bm(e,t,Object.assign(Object.assign({},n),{pendingDecisionProvider:s,toolDef:{source:"internal"}}));return void 0!==o?o:i.execute(e,t,r)}return o.execute(e,t,r)}))}})}const bC={warn(){},error(){}},SC={log(){}};class kC{requestApproval(e){return vC(this,void 0,void 0,(function*(){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${EC(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 EC(e){switch(e.type){case Lh.Shell:return"this shell command";case Lh.Mcp:return"this MCP tool call";case Lh.Write:return"this file edit";case Lh.Delete:return"this file deletion";default:return"this operation"}}function xC(e){return void 0!==e&&"insecure_none"!==e.type}function CC(e,t){return vC(this,void 0,void 0,(function*(){var r;const a="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,c=(0,Qe.q6)().with(d._O,SC);ex(a.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}`);Gi=e}((0,uC.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(aC.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0,p=0;if(a.apiKey){const e=performance.now();yield Promise.all([(0,aC.ly)(a.apiKey),(0,aC.mU)(a.apiKey)]),h=performance.now()-e}const f=a.workingDirectory||process.cwd();(0,lC.configureVendoredTreeSitterWorkspaceDir)(f);for(const e of null!==(r=a.dirs)&&void 0!==r?r:[])(0,lC.configureVendoredTreeSitterWorkspaceDir)(e);const m=(0,ao.Rv)((0,i.homedir)(),f);let g;const v="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,cC.hQ)({binaryName:v,excludedWorkspaceDir:f}),g||(g=(0,fo.resolveRipgrepFromPath)()),g&&(0,fo.configureRipgrepPath)(g);let w,b=uS();if(a.apiKey)try{w=(0,aC.KU)(a.apiKey);const e=(0,mr.createClient)(xE.I,w),t=performance.now(),r=yield function(e){let t=mC.get(e);return t||(t=function(e){return pC(this,void 0,void 0,(function*(){try{const t=yield function(e){return pC(this,void 0,void 0,(function*(){const t=yield(0,aC.dC)(e,aC.EV);if(!t)return;const r=aC.EV.endsWith("/")?aC.EV.slice(0,-1):aC.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,aC.tF)(),"x-ghost-mode":(0,aC.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hC.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 fC;const r=new dC.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,aC.tF)()})})}catch(e){hC.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,aC.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 hC.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),fC}}))}(e),mC.set(e,t),t.then((r=>{r===fC&&mC.get(e)===t&&mC.delete(e)}),(()=>{mC.get(e)===t&&mC.delete(e)}))),t}(a.apiKey);p=performance.now()-t;const n={getDefaultNetworkAllowlist:()=>vC(this,void 0,void 0,(function*(){return r.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})}))};b=new Rb(new Ib(e),n,{isMcpAccessNetworkAllowlistEnabled:()=>r.checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:e=>r.checkFeatureGate("mcp_settings_overhaul",e),isAdminCommandDenylistEnforcementKilled:()=>r.checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hC.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const S=performance.now(),k=a.apiKey?yield(0,fo.loadSandboxPolicyFromFileOrUndefined)(`${(0,i.homedir)()}/.cursor/sandbox.json`,(0,i.homedir)()):void 0,E=void 0!==a.apiKey?yield function(e){return vC(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=xC(r)?r:!0===(null==n?void 0:n.enabled)?function(e,t={}){return Object.assign({type:e},t)}("workspace_readwrite",{networkPolicy:(0,fo.networkDisabledPolicy)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,cC.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,fo.configureSandboxPrereqs)({sandboxBinaryPath:r})}(t),!(0,fo.isSandboxSupported)(void 0,{ctx:e.initializationCtx}))throw new sC.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,fo.resolveSandboxPolicyForWorkspace)(t,i);return{defaultSandboxPolicy:s,defaultSandboxPolicySources:i}}))}({cwd:f,perUserSandboxPolicy:k,sandboxOptions:a.sandboxOptions,initializationCtx:c}):void 0,x=performance.now()-S,C=null==E?void 0:E.defaultSandboxPolicy,_=null==E?void 0:E.defaultSandboxPolicySources,P=xC(C),I=performance.now(),T=(()=>{var e;const t=[],r=new Set;for(const n of[f,...null!==(e=a.dirs)&&void 0!==e?e:[]]){const e=(0,s.resolve)(n);r.has(e)||(r.add(e),t.push(n))}return t.length>1?t:void 0})(),R=yield function(e){return ax(this,void 0,void 0,(function*(){var t,r,n,o,i,a,l,c,u;const{workingDirectory:d,projectDir:h}=e,p=function(e,t){const r=[],n=new Set;for(const o of[e,...null!=t?t:[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(d,e.dirs),f=p.length>1?p:void 0,m=ex(e.settingSources),g=null!==(r=e.teamSettingsService)&&void 0!==r?r:uS(),v=null!==(n=e.defaultSandboxPolicy)&&void 0!==n?n:{type:"insecure_none"},y=null!==(o=e.getSandboxSupported)&&void 0!==o?o:()=>(0,fo.isSandboxSupported)(v,{ctx:e.initializationCtx}),w=null!==(i=e.getSandboxEnabled)&&void 0!==i?i:()=>"insecure_none"!==v.type&&y(),b=new Kh,S=new ns(b,g,p),k=new ux,E=new dx,x=null===(t=e.getSmartModeClassifierAutoModeEnabled)||void 0===t?void 0:t.call(e),C=new cx(x?"allowlist":null!==(a=e.approvalMode)&&void 0!==a?a:"unrestricted",v,g,null!==(l=e.respectAdminControls)&&void 0!==l&&l),_=e.pendingDecisionProvider,P={executeIndexedGrep:void 0},I=()=>!0,T=tx(m,"plugins"),R=null!==(c=e.importThirdPartyPlugins)&&void 0!==c&&c,A=null===(u=e.mcpMetaToolEnabled)||void 0===u||u,O=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,M=void 0!==e.customSubagents&&e.customSubagents.length>0,j=O||tx(m,"project")||tx(m,"user")||T,D=tx(m,"project")||tx(m,"user")||tx(m,"mdm"),N=tx(m,"team"),$=N&&void 0!==e.dashboardTransport,F=tx(m,"project")||tx(m,"user")||N||$||T,L=t=>sx(Object.assign(Object.assign({workingDirectory:d},void 0!==f?{workspaceRoots:f}:{}),{adapters:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.includeMcp?{mcp:dS({teamSettingsService:g,initializationCtx:e.initializationCtx,importThirdPartyPlugins:R,ignoreApprovals:!0,includeProjectMcp:tx(m,"project"),includeUserMcp:tx(m,"user"),includePluginMcp:T,inlineMcpServers:e.mcpServers})}:{}),T?{pluginBootstrap:NE({importThirdPartyPlugins:R,dashboardTransport:e.dashboardTransport})}:{}),D?{hooks:EE({includeProjectHooks:tx(m,"project"),includeUserHooks:tx(m,"user"),includeEnterpriseHooks:tx(m,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{}),F?{localExtensibility:PE({includeProjectExtensibility:tx(m,"project"),includeUserExtensibility:tx(m,"user"),includeManagedSkills:$,includeTeamExtensibility:N,includePluginExtensibility:T,teamSettingsService:g,getThirdPartyExtensibilityEnabled:I,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:R})}:{}),{resourceFactory:BE({ignoreService:S,grepProvider:P,workspacePaths:p,diagnosticsProvider:k,repositoryProvider:E,projectDir:null!=h?h:d,shellManager:void 0,defaultSandboxPolicy:v,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:A,createMcpStateAccessor:e=>new hx(new gw(e)),createSessionMcpLease:(t,r)=>dS({teamSettingsService:g,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!=_?_:new lx;return{pendingDecisionStore:r,fileChangeTracker:new Vh(d),permissionsService:new jy(S,r,C,g,d,null!==(t=e.respectAdminControls)&&void 0!==t&&t)}}}),resourceWrappers:D?[{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 kE(new hE(e.resources,n.hookExecutor,(()=>function(e,t){var r,n,o,i;const s=null!==(n=null!==(r=yE(t,wE,"conversationId","conversation_id"))&&void 0!==r?r:e.sessionId)&&void 0!==n?n:"",a=null!==(o=yE(t,wE,"generationId","generation_id"))&&void 0!==o?o:s,l=null!==(i=yE(t,wE,"model"))&&void 0!==i?i:"unknown",c=yE(t,wE,"modelId","model_id"),u=yE(t,SE,"modelParams","model_params");return Object.assign({conversation_id:s,generation_id:a,model:l},Pe({modelId:c,modelParams:u}))}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[]}),M?{workspaceServicesContributors:[{contributeServices:t=>{var r;const n=new px(null!==(r=e.customSubagents)&&void 0!==r?r:[]),o=t.services.subagentsService;return{subagentsService:void 0===o?n:new ch([n,o])}}}]}:{})}));if(!j)return L({includeMcp:!1});try{return yield L({includeMcp:!0})}catch(e){return Lb.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:d,projectDir:h,enablePlugins:T,importThirdPartyPlugins:R}),L({includeMcp:!1})}}))}(Object.assign(Object.assign({workingDirectory:f},void 0!==T?{dirs:T}:{}),{projectDir:m,teamSettingsService:b,initializationCtx:c,dashboardTransport:w,settingSources:a.settingSources,mcpServers:a.mcpServers,customSubagents:a.customSubagents,defaultSandboxPolicy:C,defaultSandboxPolicySources:_,approvalMode:P?"allowlist":void 0,pendingDecisionProvider:P||!0===a.autoReview?new kC:void 0,getNetworkAllowlistInfo:P?()=>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,fo.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,fo.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}}(b,(0,i.homedir)(),f):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===a.autoReview,devForceNextSmartModeClassifierBlockToken:a.devForceNextSmartModeClassifierBlockToken,respectAdminControls:void 0!==a.apiKey,useCommandHookStdinTransport:!0})),A=performance.now()-I;let O,M;return(0,Tx.ou)(a.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:Math.round(p),create_workspace_runtime_ms:Math.round(A),load_sandbox_policy_ms:Math.round(x),total_ms:Math.round(performance.now()-u)}),{run:(e,t,r)=>vC(this,void 0,void 0,(function*(){return function(e,t){return $b.run(e,t)}(bC,(()=>vC(this,void 0,void 0,(function*(){var i,s,c,u;const h=(0,l.VI)((0,Qe.q6)().withName("sdk.run").with(d._O,SC)),[p,m]=h.ctx.withCancel(),g=null!==(i=t.sessionId)&&void 0!==i?i:(0,o.randomUUID)(),v=t.mcpServersOverride,y=void 0===(w=t.customTools)?[]:Object.entries(w).map((([e,t])=>{var r,n;return Object.assign(Object.assign({clientKey:ot,providerIdentifier:ot,toolName:e,name:`${ot}-${e}`,description:null!==(r=t.description)&&void 0!==r?r:"",inputSchema:null!==(n=t.inputSchema)&&void 0!==n?n:rC},void 0===t.outputSchema?{}:{outputSchema:t.outputSchema}),{source:"internal"})}));var w;let b;b=yield R.createSessionRuntime({sessionId:g,mcpServersOverride:v,extraMcpTools:y});const S=new Map;try{const i=b.resources.wrapped;wC(b,t.customTools);const l=null!==(s=t.blobStore)&&void 0!==s?s:new ur.ve;let d=null!==(c=t.initialState)&&void 0!==c?c:new lr.Y9({});const h=void 0!==t.model?new _x.G4({modelId:t.model.id,parameters:(null!==(u=t.model.params)&&void 0!==u?u:[]).map((e=>new _x.SR({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,aC.v8)(r);return new Px.d(Object.assign(Object.assign({uuid:t},i?{mimeType:i}:{}),{dataOrBlobId:{case:"data",value:r}}))})):[],k=w.length>0?new Px.xv({selectedImages:w}):void 0,E=function(e){switch(e){case"agent":return lr.xy.AGENT;case"plan":return lr.xy.PLAN;default:return}}(t.mode),x=new lr.QF({action:{case:"userMessageAction",value:new lr.Vt({userMessage:new lr.RG(Object.assign({text:e.text,selectedContext:k},void 0!==E?{mode:E}:{}))})}}),C={sendUpdate:(e,t)=>vC(this,void 0,void 0,(function*(){const e=Rx(t,g);null!==e&&(yield r.sendUpdate(e))})),query:(e,t)=>vC(this,void 0,void 0,(function*(){return function(e){var t;switch(e.query.case){case"webSearchRequestQuery":return Fn(e.id);case"webFetchRequestQuery":return Un(e.id);case"switchModeRequestQuery":return Wn(e.id);case"askQuestionInteractionQuery":return zn(e.id,new mx.tz({result:{case:"rejected",value:new mx.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return qn(e.id,new On.bK({result:{case:"success",value:new On.Jo},planUri:""}));case"setupVmEnvironmentArgs":return Gn(e.id,new Ix.r$({result:{case:"success",value:new Ix.JH}}));case"replaceEnvArgs":return Vn(e.id,new Cx.dV({result:{case:"failure",value:new Cx.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return Jn(e.id,new Xn.HL({result:{case:"error",value:new Xn.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Kn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Zn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Yn(e.id,null===(t=e.query.value.args)||void 0===t?void 0:t.description);case void 0:throw new sC.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new sC.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)}))};if(O!==t.apiKey||!M){yield Promise.all([(0,aC.ly)(t.apiKey),(0,aC.mU)(t.apiKey)]);const e=(0,aC.KU)(t.apiKey),r=so((0,mr.createClient)(xx.N,e),{injectTraceHeaders:!0});M=new Rn(r),O=t.apiKey}const _=(0,aC.Vh)(M,(()=>{const e=(0,aC.KU)(t.apiKey),r=so((0,mr.createClient)(xx.N,e),{injectTraceHeaders:!0}),n=new Rn(r);return M=n,O=t.apiKey,n})),P=new Ex({agentClient:_,getResources:e=>vC(this,[e],void 0,(function*({agentId:e}){let r=S.get(e);return r||(r=yield R.createSessionRuntime({sessionId:e,mcpServersOverride:v,extraMcpTools:y}),wC(r,t.customTools),r.resources.base.register(rr,I),S.set(e,r)),r.resources.wrapped})),mcpTools:y,workspacePath:f,parentConversationId:g,onSessionReleased:e=>{const t=S.get(e);t&&(t.dispose(),S.delete(e))}}),I=tr(P);b.resources.base.register(rr,I);const T=R.services.hooksRuntime,A=T?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(ue.sessionStart)||t.hooksConfigLease.hasHookForStep(ue.sessionEnd)||t.hooksConfigLease.hasHookForStep(ue.stop)||t.hooksConfigLease.hasHookForStep(ue.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{onSessionStart(e){return fx(this,void 0,void 0,(function*(){if(o=e,n.hasHooksForStep(ue.sessionStart))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Pe(e)),{is_background_agent:!1}),r=yield n.executeHookForStep(ue.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){Lb.warn("[hooks-adapter] sessionStart hook failed:",e)}}))},onSessionEnd(e,t){return fx(this,void 0,void 0,(function*(){var r,i,s;if(n.hasHooksForStep(ue.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?Pe(o):{}),{reason:e,duration_ms:t,is_background_agent:!1,final_status:e});yield n.executeHookForStep(ue.sessionEnd,a)}catch(e){Lb.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()}))},onBeforeSubmitPrompt(e){return fx(this,void 0,void 0,(function*(){var t;if(n.hasHooksForStep(ue.beforeSubmitPrompt))try{const r=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Pe(e)),{prompt:null!==(t=e.promptText)&&void 0!==t?t:"",attachments:[]});yield n.executeHookForStep(ue.beforeSubmitPrompt,r)}catch(e){Lb.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}}))},onTurnCompleted(e){return fx(this,void 0,void 0,(function*(){if(!n.hasHooksForStep(ue.stop))return;const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Pe(e)),{status:"completed",loop_count:e.loopCount}),r=yield n.executeHookForStep(ue.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 fx(this,void 0,void 0,(function*(){if(n.hasHooksForStep(ue.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Pe(e)),{status:"error",loop_count:e.loopCount});yield n.executeHookForStep(ue.stop,t)}catch(e){Lb.warn("[hooks-adapter] onTurnError stop hook failed:",e)}}))},onTurnAborted(e){return fx(this,void 0,void 0,(function*(){if(n.hasHooksForStep(ue.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},Pe(e)),{status:"aborted",loop_count:e.loopCount});yield n.executeHookForStep(ue.stop,t)}catch(e){Lb.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}}))},dispose(){return fx(this,void 0,void 0,(function*(){yield r.dispose()}))}}}({workspaceRuntime:T,sessionState:b.state,metadata:b.metadata}):void 0,j=new wx({workspacePath:f,conversationId:g,blobStore:l}),D=Object.assign(Object.assign({},void 0!==t.allowedTools?{[gC.$$]:t.allowedTools.join(",")}:{}),void 0!==t.disallowedTools&&t.disallowedTools.length>0?{[gC.VJ]:t.disallowedTools.join(",")}:{}),N=function(e,t,r){var n;const{hooks:o}=r,[i,s]=e.withCancel(),a=new Db;let l=r.initialState;const c={handleCheckpoint(e,t){return Wb(this,void 0,void 0,(function*(){var e;l=t,yield null===(e=r.onCheckpoint)||void 0===e?void 0:e.call(r,t)}))},getLatestCheckpoint:()=>l};let u="completed";const d=Date.now(),h=Bb(function(e,t){if((0,ur.TU)(t))return t;const r=zb.get(e);if(void 0!==r)return r;const n=(0,ur.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return zb.set(e,n),n}(r.conversationId,r.blobEncryptionKey),null===(n=r.runOptions)||void 0===n?void 0:n.headers),p=(()=>Wb(this,void 0,void 0,(function*(){var e,n,s,d,p,f,m,g,v;const y=qb(r,0,Hb(t));try{const t=yield null===(e=null==o?void 0:o.onSessionStart)||void 0===e?void 0:e.call(o,y);if(null==t?void 0:t.blocked)throw u="error",new Error(null!==(m=t.blockedReason)&&void 0!==m?m:"Session blocked by sessionStart hook")}catch(e){if("completed"!==u)throw e;Lb.warn("[agent-session-runner] sessionStart hook failed:",e)}let w=t,b=0;for(;w;){const e=qb(r,b,Hb(w));try{yield null===(n=null==o?void 0:o.onBeforeSubmitPrompt)||void 0===n?void 0:n.call(o,e)}catch(e){Lb.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}try{yield r.agentClient.run(i,l,w,void 0,r.interactionListener,r.resources,r.blobStore,a,c,null!==(g=r.mcpTools)&&void 0!==g?g:[],Object.assign(Object.assign({conversationId:r.conversationId},r.runOptions),{headers:h,subagentModelOverrides:null!==(v=null===(s=r.runOptions)||void 0===s?void 0:s.subagentModelOverrides)&&void 0!==v?v:[]}))}catch(t){throw u=Gb(t)?"aborted":"error",null==(S="aborted"===u?null===(d=null==o?void 0:o.onTurnAborted)||void 0===d?void 0:d.call(o,e):null===(p=null==o?void 0:o.onTurnError)||void 0===p?void 0:p.call(o,e))||S.catch((e=>{Lb.warn("[agent-session-runner] fire-and-forget hook failed:",e)})),t}let t;try{t=yield null===(f=null==o?void 0:o.onTurnCompleted)||void 0===f?void 0:f.call(o,e)}catch(e){throw u="error",e}const m="string"==typeof t?t.trim():"";0!==m.length?(b+=1,a.resetStream(),k=m,w=new lr.QF({action:{case:"userMessageAction",value:new lr.Vt({userMessage:new lr.RG({text:k})})}})):w=void 0}var S,k})))().finally((()=>Wb(this,void 0,void 0,(function*(){var e,t;const r=Date.now()-d;try{yield null===(e=null==o?void 0:o.onSessionEnd)||void 0===e?void 0:e.call(o,u,r)}catch(e){Lb.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{yield null===(t=null==o?void 0:o.dispose)||void 0===t?void 0:t.call(o)}catch(e){Lb.warn("[agent-session-runner] hooks dispose failed:",e)}}))));return{done:p,abort(){s()}}}(p,x,{agentClient:_,interactionListener:C,resources:i,blobStore:l,initialState:d,conversationId:g,mcpTools:y,blobEncryptionKey:t.blobEncryptionKey,runOptions:Object.assign({generationUUID:t.requestId,requestedModel:h,enableAgentRetries:!1!==a.enableAgentRetries},Object.keys(D).length>0?{headers:D}:{}),hooks:A,onCheckpoint(e){return vC(this,void 0,void 0,(function*(){var r;d=e,j.writeFromState(p,e),yield null===(r=t.onCheckpoint)||void 0===r?void 0:r.call(t,e)}))}}),$=N.done.finally((()=>vC(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){hC.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(){N.abort(),m()},done:$}}catch(e){for(const e of S.values())try{yield e.dispose()}catch(e){}throw S.clear(),yield b.dispose(),e}}))))})),reload(){return vC(this,void 0,void 0,(function*(){yield R.reload()}))},dispose(){return vC(this,void 0,void 0,(function*(){yield R.dispose()}))}}}))}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),i=o({packageName:"tree-sitter",nativeRequire:require});e.exports=i.available?i.module:n(i.reason)},"../constants/dist/mcp.js"(e,t,r){"use strict";r.d(t,{Di:()=>i,G$:()=>u,Qy:()=>o,RJ:()=>f,sr:()=>s,tl:()=>h,uS:()=>c,vI:()=>a});const n={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"consent"}},o="x-cursor-auth";function i(e){if(void 0===e)return;let t;try{t=new URL(e)}catch(e){return}return"https:"===t.protocol&&"api.cursor.com"===t.hostname.toLowerCase()&&""===t.port?s(e):void 0}function s(e){if(void 0===e)return;let t;try{t=new URL(e)}catch(e){return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return null==r?void 0:r[1]}function a(e){if("object"!=typeof e||null===e)return{};const t=e,r="string"==typeof t.cursor_client_id&&t.cursor_client_id.length>0?t.cursor_client_id:void 0;let n;if("object"==typeof t.cursor_authorization_params&&null!==t.cursor_authorization_params){const e=Object.entries(t.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(n=Object.fromEntries(e))}return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==r?{clientId:r}:{}),!0===t.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{}),void 0!==n?{authorizationParams:n}:{}),!0===t.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{}),!0===t.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{})}const l=new Map([["gmailmcp.googleapis.com",Object.assign(Object.assign({},n),{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({},n),{scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]})],["calendarmcp.googleapis.com",Object.assign(Object.assign({},n),{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({},n),{scopes:["https://www.googleapis.com/auth/documents"]})],["sheetsmcp.googleapis.com",Object.assign(Object.assign({},n),{scopes:["https://www.googleapis.com/auth/spreadsheets"]})],["slidesmcp.googleapis.com",Object.assign(Object.assign({},n),{scopes:["https://www.googleapis.com/auth/presentations"]})]]);function c(e,t){var r;const n=null===(r=function(e){if(void 0===e)return;let t;try{t=new URL(e).hostname}catch(e){return}return function(e){return l.get(e.toLowerCase())}(t)}(t))||void 0===r?void 0:r.authorizationParams;if(void 0!==n)for(const[t,r]of Object.entries(n))e.searchParams.set(t,r)}new Set([...l].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e)));const u="https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg",d=["cursor"],h="http://localhost:8787/callback";function p(e){return`${e}://anysphere.cursor-mcp/oauth/callback`}function f(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([...d])).map(p))t.add(e);return t.add("https://www.cursor.com/agents/mcp/oauth/callback"),t.add(h),e&&r&&t.add(e),Array.from(t)}},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){"use strict";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){"use strict";r.d(t,{B1j:()=>J,c8u:()=>$e,uOd:()=>Fe,E_S:()=>Le,Ico:()=>Me,O3I:()=>re,tBH:()=>Q,MEY:()=>L,Fmf:()=>Ne,jIB:()=>Te,VDJ:()=>pe,X5z:()=>de,$HQ:()=>W,YaX:()=>G,PKk:()=>He,_NE:()=>z,Ezk:()=>Ue.Ez,eaG:()=>ce,q2e:()=>Y,mtU:()=>ze,utF:()=>We});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=N(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)}const u=new Map,d=new Map;function h(e,t){return function(e,t){switch(t.kind){case"matchAll":return!0;case"invalidCidr":return!1;case"cidr":{const r=function(e){if(d.has(e))return d.get(e);d.size>=I&&d.clear();const t=c(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value}}(N(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=N(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=c(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const i=BigInt(o-n);return{kind:"cidr",version:r.version,shift:i,shiftedNetwork:r.value>>i}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),v=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",w=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=N(e);return t.length>0&&t.length<=253&&g.test(t)}function E(e){const t=N(e);return w.test(t)||function(e){const t=N(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch(e){return!1}}(t)}function x(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function C(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 x(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return x(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function _(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||E(t))}(t.hostname)}catch(e){return!1}}(e);const t=N(e);return"*"===t||!!v.test(t)||(t.includes("/")?function(e){const t=N(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||E(t))}function P(e){if(T.has(e))return T.get(e);T.size>=I&&T.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=`${N(t.slice(0,r))}/${t.slice(r+1).trim()}`;return _(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=C(e);if(!_(t))return;return t}{const t=C(e);if(!_(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||!_(i)||i!==o&&"*"===i?void 0:i}(e);return T.set(e,t),t}const I=2048,T=new Map,R=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function O(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=j(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("*")&&N(i)===N(s)&&(A(a=o.pathname,l=n.pathname)||A(O(a),O(l)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var i,s,a,l}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function j(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=$(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!N(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(N(r.hostname)!==N(o))return}return r}}function D(e,t){if(A(e,t))return!0;let r;return R.has(t)?r=R.get(t):(R.size>=I&&R.clear(),r=$(t),R.set(t,r)),!!r&&h(r.hostname,e)}function N(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function $(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch(e){return}}function F(e){return(null!=(t=e.mcpNetworkAllowlist)?t:[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}));var t}function L(e,t){var r,n;if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!j(e))return{allowed:!1,message:null!==(r=t.blockMessage)&&void 0!==r?r:p};const o=F(t);return o.length>0&&o.some((t=>function(e,t){const r=j(t);if(!r)return!1;if(!e.includes("://"))return h(N(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch(e){return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:null!==(n=t.blockMessage)&&void 0!==n?n:p}}function U(e){const t=null==e?void 0:e.trim();return t&&t.length>0?t:void 0}function B(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 z({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=U(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),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(null==r?void 0:r.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const i=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===i||i.includes("@"))return;const s=P(i.replace(/:\d+$/,""));if(void 0!==s)return s;try{return P(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=U(e.command),n=U(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&A(r,t.command),i=void 0===n||void 0!==t.url&&D(n,t.url);return o&&i}(e,t)))}(s,t),c=B(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||B(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!==U(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!==U(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 W(e){if(!0===(null==e?void 0:e.enabled)&&"no_sandbox"!==e.mcpNetworkMode)return e}function H(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function q(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function G(e,t,r){var n;if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(function(e){var t;return!0===(null===(t=e.url)||void 0===t?void 0:t.startsWith("mcp-provider://"))}(e))return!0;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:D;return t.some((t=>{const r=H(t.command),n=q(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&A(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:D;return(null!=t?t:[]).some((t=>{const r=H(t.command),n=q(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&A(r,e.command),s=void 0===n||void 0!==e.url&&o(n,e.url);return i&&s}))}(e,t.deniedMcpServers,r)}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=P(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=P(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=F(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)}}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=86d9e9a547a0846ef9cda8ba5f96290ca3716a5e30e_d57f5b7d543a43715faa38571acaced1/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]);const Fe=8192;function Le(e,t){void 0!==t&&t.length>0&&e.searchParams.set("scope",t.join(" "))}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);var Ue=r("../mcp-core/dist/oauth/rest-mcp-provider-metadata.js");Error;var Be=r("../constants/dist/mcp.js");function ze(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===Be.Qy));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch(e){o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==Be.Qy))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function We(e,t,r){return(n,o)=>{return i=this,s=void 0,l=function*(){let i;try{i=new URL("string"==typeof n?n:n.toString()).origin}catch(e){return r(n,o)}if(i!==t)return r(n,o);const s=yield e();if(void 0===s||0===s.length)return r(n,o);const a=new Headers(null==o?void 0:o.headers);return a.set(Be.Qy,s),r(n,Object.assign(Object.assign({},o),{headers:a,redirect:"manual"}))},new((a=void 0)||(a=Promise))((function(e,t){function r(e){try{o(l.next(e))}catch(e){t(e)}}function n(e){try{o(l.throw(e))}catch(e){t(e)}}function o(t){var o;t.done?e(t.value):(o=t.value,o instanceof a?o:new a((function(e){e(o)}))).then(r,n)}o((l=l.apply(i,s||[])).next())}));var i,s,a,l}}function He(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)}},"../mcp-core/dist/oauth/rest-mcp-provider-metadata.js"(e,t,r){"use strict";r.d(t,{Ez:()=>i});var n=r("../constants/dist/mcp.js");const o=new Map;function i(e){return t=this,r=arguments,s=function*(e,t=fetch){if(void 0===(0,n.sr)(e))return;const r=new URL(e),i=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,s=o.get(i);if(void 0!==s&&s.expiresAtMs>Date.now())return s.metadata;let a;try{const e=yield t(i);if(!e.ok)return;a=(0,n.vI)(yield e.json())}catch(e){return}return o.set(i,{metadata:a,expiresAtMs:Date.now()+3e5}),a},new((i=void 0)||(i=Promise))((function(e,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}l((s=s.apply(t,r||[])).next())}));var t,r,i,s}},"../shell-exec/dist/index.js"(e,t,r){"use strict";r.r(t),r.d(t,{BashState:()=>Ct,INSECURE_NONE_SANDBOX_POLICY:()=>mr,KnownShellExecutor:()=>Ue,NaiveTerminalExecutor:()=>Ot,OutputSuppressionController:()=>nr,PowerShellState:()=>Rt,SHELL_OUTPUT_SUPPRESSED_NOTICE:()=>rr,SandboxUnsupportedError:()=>Me,ZshState:()=>Ft,configureRipgrepPath:()=>v,configureSandboxPrereqs:()=>De,createDefaultTerminalExecutor:()=>fr,createIgnoreMapping:()=>cr,createNaiveTerminalExecutor:()=>Mt,getLastSandboxFailureReason:()=>Oe,getPowerShellExecutable:()=>Tt,getRipgrepBinaryPath:()=>S,getSandboxPolicyType:()=>tt,getShellExecutablePath:()=>ur,getSuggestedShell:()=>pr,isAllowAllNetworkByPolicy:()=>re,isHardcodedWriteProtected:()=>X,isNetworkEnabledByPolicy:()=>te,isRipgrepConfigured:()=>k,isSandboxSupported:()=>Fe,loadSandboxPolicyFromFileOrUndefined:()=>ar,mergeAdditionalReadPaths:()=>lt,mergeNetworkPolicies:()=>ut,mergePathsIntersection:()=>nt,mergePathsUnion:()=>ot,mergeReadBoundary:()=>at,networkAllowAllPolicy:()=>oe,networkDisabledPolicy:()=>ne,parseSandboxPolicyJson:()=>sr,primeSandboxSupport:()=>Le,resolvePolicyPaths:()=>lr,resolveRipgrepFromPath:()=>g,resolveSandboxPolicyForWorkspace:()=>pt,spawnInSandbox:()=>Ne,spawnWithSignal:()=>ze,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 F=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/usr/local/bin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/local/lib"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"},{platform:"darwin",scope:"global",path:"/dev/tty"}],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:".cursor/sandbox-policies"}];function U(e){const t=L.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function B(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 z=[];let W=null,H=null;let q=null;const G=new Map;const V="win32"===process.platform||"darwin"===process.platform;function J(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 K(e){return e.endsWith(n.sep)?e:e+n.sep}function Z(e,t){const r=J(t);if(V){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(K(n))}return e===r||e.startsWith(K(r))}function Y(e,t){const r=J(e);return V?(0,n.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,n.relative)(r,t).replace(/\\/g,"/")}async function X(e,t){if(Z(e,t)){const r=Y(t,e);if((null===W&&(W=$({ignoreCase:!0}),W.add(L.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),W).ignores(r))return!0}const{isWorktree:r,gitDirParent:o}=await async function(e){const t=G.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 G.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 G.set(e,i),i}(t);if(Z(e,o)){const t=Y(o,e);if((null===H&&(H=$({ignoreCase:!0}),H.add(L.filter((e=>"git"===e.type)).map((e=>e.pattern)))),H).ignores(t))return!0}if(r&&Z(e,t)&&".git"===Y(t,e))return!0;for(const t of function(){if(null!==q)return q;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 q=t,t}())if(Z(e,t))return!0;return!1}const Q=new WeakMap;function ee(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}function te(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function re(e){return void 0!==e&&"allow"===e.default}function ne(){return{version:1,default:"deny"}}function oe(){return{version:1,default:"allow"}}let ie=0;function se(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?n.resolve(e):n.resolve(n.join(h.homedir(),".cursor","sandbox-policies"))}();o.mkdirSync(e,{recursive:!0,mode:448});try{o.chmodSync(e,448)}catch{}const t=Date.now();return t-ie>=9e5&&(ie=t,function(e){let t;try{t=o.readdirSync(e)}catch{return}const r=Date.now();for(const i of t){if(!i.startsWith("sandbox-policy-"))continue;const t=n.join(e,i);try{const e=o.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&o.unlinkSync(t)}catch{}}}(e)),e}function ae(e){const t=se(),r=P.randomBytes(8).toString("hex"),i=n.join(t,`sandbox-policy-${r}`);return o.writeFileSync(i,e,{encoding:"utf-8",mode:384}),i}const le="darwin"===process.platform,ce="linux"===process.platform,ue=(0,R.h)("shell-exec:sandbox");function de(e){const t=se();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let he,pe=!0;function fe(){return he}function me(e){"linux"===process.platform&&Object.assign(e,b(e))}let ge=null,ve=null,ye=null,we=null,be=!1,Se=null;function ke(e){return{...e,additionalReadonlyPaths:de(e.additionalReadonlyPaths)}}function Ee(e,t,r){let i;e.ignoreMapping&&(i=function(e){return Te(e)}(e.ignoreMapping));const s=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=!ce||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 Te(l)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),a=(l=e.readBoundary,r?.workspaceReadEnabled??function(){const e=pe;return"function"==typeof e?e():e}()?l??"system":"system");var l;const c=function(e=process.platform){const t=[],r=new Set,i={};try{i.ripgrep=S()}catch{}for(const s of function(e=process.platform,t=h.homedir(),r={}){const i=[];for(const s of F){if(s.platform!==e)continue;if("global"===s.scope){i.push(s.path);continue}const a="home"===s.scope?(0,n.join)(t,s.path):r[s.path];if(a)try{("home"===s.scope?(0,o.lstatSync)(a).isFile():(0,o.statSync)(a).isFile())&&i.push(a)}catch{}}return i}(e,h.homedir(),i))r.has(s)||(r.add(s),t.push(s));return t}(),u="workspace"===a?function(e){const t=[],r=new Set;for(const o of e){let e=o.trim();if(!e)continue;"~"===e?e=h.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=n.join(h.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const i=n.basename(e);if((i.includes("*")||i.includes("?"))&&(e=n.dirname(e)),!e||"."===e)continue;const s=n.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],d=[...c],p=new Set(c);for(const e of u)p.has(e)||(p.add(e),d.push(e));const f={cwd:t,readBoundary:a,hardcodedReadPaths:d,additionalReadonlyPaths:s,networkAccess:te(e.networkPolicy),ignoreMapping:i};return"workspace_readonly"===e.type?{type:e.type,...f}:{type:e.type,...f,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function xe(e){if(null!==ge)return!!ge;try{const t=fe();return ue.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(ge=o.existsSync(t),ge?ue.info(e,`[checkBinaryAvailable] Binary path exists: ${ge}`):(ve=new Error(`Sandbox binary not found at ${t}`),ue.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!ge):(ve=new Error("Sandbox binary path was not configured"),ge=!1,ue.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return ve=t,ge=!1,ue.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function Ce(e){if(null!==we)return we;const t=e??(0,A.q6)();if(ue.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!xe(t)){const e=ve?.message||"Binary check failed";return ye=e,ue.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),we=!1,we}if("win32"===process.platform)return ye="Windows sandbox helper only provides network proxy, not filesystem isolation",ue.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),we=!1,we;if("darwin"===process.platform)return ye=null,ue.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),we=!0,we;const{binaryPath:r,args:n,env:o}=Pe(t,process.cwd());try{const e=Date.now();(0,E.execFileSync)(r,n,{stdio:["ignore","ignore","pipe"],timeout:_e,env:o,shell:!1});const i=Date.now()-e;return ye=null,ue.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),we=!0,we}catch(e){const r=e;return Ie(t,{message:r.message,status:r.status,stderrText:r.stderr?.toString?.()||""})}}const _e=15e3;function Pe(e,t){const r={sandbox:Ee(ke({type:"workspace_readwrite"}),t)},n=String(fe());ue.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),ue.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return me(o),{binaryPath:n,args:["--policy",ae(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}function Ie(e,t){const{message:r,status:n,stderrText:o}=t;return ue.error(e,`[sandboxPreflight] Preflight failed: ${r}`),ue.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&ue.error(e,`[sandboxPreflight] Stderr: ${o}`),ye=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"}`,we=!1,!1}function Te(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Re(t):t;o[e]=r;const n=Ae(e);n!==e&&(o[n]=r)}return o}function Re(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ae(e){try{return(0,o.realpathSync)(e)}catch{return e}}function Oe(){return ye}class Me extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const je="darwin"===process.platform;function De(e){!function(e){S();const{sandboxBinaryPath:t,workspaceReadEnabled:r}=e;he||(he=t),void 0!==r&&(pe=r)}(e)}function Ne(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(Ce())return function(e,t=[],r={},n){const o=(0,A.q6)();if(r.env=x(r.env),!xe(o))throw new Error(`Sandbox binary not available: ${ve?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,E.spawn)(e,t,r);if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const o=String(r.cwd??process.cwd()),i=n.sandboxWorkspaceRoot??o;let s=e,a=t;r.shell&&("win32"===process.platform?(s="string"==typeof r.shell?r.shell:"cmd.exe",a=["/c",`${e} ${t.join(" ")}`]):(s="string"==typeof r.shell?r.shell:"/bin/sh",a=["-c",`${e} ${t.join(" ")}`]));const l=Ee(ke(n),i),c=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!te(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),u={sandbox:l};void 0!==c&&(u.networkPolicy=c),!1===n.networkPolicyStrict&&(u.networkPolicyStrict=!1);const d=["--policy",ae(JSON.stringify(u)),"--",s,...a],h={..."linux"===process.platform?_(process.env):process.env,..."linux"===process.platform&&r.env?_(r.env):r.env,CURSOR_SANDBOX:"native"};me(h);const p={cwd:r.cwd||o,env:h,stdio:r.stdio||["pipe","pipe","pipe"]};try{const e=new Date,t=(0,E.spawn)(String(fe()),d,p);return le&&t.pid&&function(e,t){Q.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${e}`)}}(e,t,r,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}(e,t,r,n);const o=Oe();throw new Me(`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 $e(e){return je?async function(e){const t=Q.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:ee(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:ee(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 Fe(e,t){if(je)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return Ce(t?.ctx)}async function Le(e){if(je)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return async function(e){return be&&null!==we?we:(null!==Se||(Se=async function(e){const t=e.ctx??(0,A.q6)();if(!ce||!xe(t)){const e=Ce(t);return be=!0,e}null!==we&&ue.info(t,`[primeSandboxHelperSupport] Re-probing from ${e.workspaceCwd}; the cached verdict (${we}) was measured from a different directory`);const r=e.timeoutMs??_e,{binaryPath:n,args:o,env:i}=Pe(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 ye=`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"}`,ue.error(t,`[primeSandboxHelperSupport] Preflight timed out after ${r}ms, treating sandbox as unsupported`),we=!1,be=!0,!1;if("failed"===a.kind){const e=Ie(t,{message:a.message,status:a.status,stderrText:a.stderrText});return be=!0,e}return ye=null,ue.info(t,`[primeSandboxHelperSupport] Preflight rooted at ${e.workspaceCwd} succeeded in ${l}ms, sandbox supported!`),we=!0,be=!0,!0}(e).finally((()=>{Se=null}))),Se)}(e)}var Ue;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Ue||(Ue={}));const Be={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function ze(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=Ne(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 We(e){e?.on("error",(()=>{}))}function He(e,t){e&&(We(e),e.write(t),e.end())}function qe(e,t){e&&(We(e),e.on("data",(e=>{t(e.toString())})))}function Ge(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function Ve(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}const Je="__CURSOR_BASH_STATE_START__",Ke="__CURSOR_BASH_STATE_END__",Ze=50,Ye=262144;class Xe{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Ze,this.maxBufferedBytes=t?.maxBufferedBytes??Ye}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 Qe(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 Xe(e.writable,e.outputLimiterOptions);let r;const n=Promise.all([et(e.stdout,"stdout",t),et(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 et(e,t,r){if(e)for await(const n of e)await r.push(t,n)}function tt(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function rt(...e){return e.some((e=>!0===e))}function nt(...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=ct(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Set(t[0].map(ct));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(ct));r=new Set([...r].filter((e=>n.has(e))))}return[...r]}function ot(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ct(e));return[...t]}const it=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]<t[e]?r:e))}}}({defaultValue:"system",rank:{workspace:0,system:1}}),st=(...e)=>nt(...e);function at(...e){return it.merge(...e)}function lt(...e){return st(...e)}function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function ut(...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 dt(...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 ht(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function pt(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"===tt(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:dt(i?.writeProtectionMapping,B(e))}}}}if(i)return ft(t,{workspaceDir:e,gitDirParent:r})}return ft(t,{workspaceDir:e})}function ft(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 vt(e,t);switch(r){case"workspace_readwrite":return vt(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=mt(e,t),o={policy:gt({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:rt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:ht(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:rt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:ht(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 mt(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!==z.length)return{version:1,deny:[...z]}}(),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:U(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=rt(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=rt(o?.networkPolicyStrict,i?.networkPolicyStrict,s?.networkPolicyStrict,l.networkPolicyStrict);l.networkPolicyStrict&&p("networkPolicyStrict",3);const g=ht(o?.readBoundary,i?.readBoundary,s?.readBoundary)??"system",v=ht(o?.additionalReadPaths,i?.additionalReadPaths,s?.additionalReadPaths),y="workspace"===g?v??[]:void 0,w=ot(o?.additionalReadonlyPaths,i?.additionalReadonlyPaths,s?.additionalReadonlyPaths,l.additionalReadonlyPaths),b=w.length>0?w:void 0;let S=ut(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=ht(o?.debugOutputDir,i?.debugOutputDir,s?.debugOutputDir),_=rt(o?.captureDenies,i?.captureDenies,s?.captureDenies),P=ht(o?.enableSharedBuildCache,i?.enableSharedBuildCache,s?.enableSharedBuildCache),I=dt(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:dt(o?.writeProtectionMapping,i?.writeProtectionMapping,s?.writeProtectionMapping,l.writeProtectionMapping,T),fieldSources:c}}function gt(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function vt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,i=t?.debug,s=mt(e,t),a=ot(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),l={policy:gt({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 yt="win32"===process.platform;function wt(e){return!yt&&!!e?.SUDO_ASKPASS}function bt(e){return wt(e)?"alias sudo='sudo -A'; ":""}function St(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 kt=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 Et(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 xt(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 Ct{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 Ct(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,...Be,...r?.env};let u='builtin eval "$1"';s||(u+=" < /dev/null");const m=bt(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=xt(y),t=xt(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=Et(this.userTerminalHint);if(!S)throw new Error("Can't find Bash");const k=r?.sandboxWorkspaceRoot??l,E=(await pt(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=ze(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=Qe({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=`${Je}\n`,t=`${Ke}\n`;if(C.startsWith(e)&&C.endsWith(t)){let t=C.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=Ge(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(x.captureDenies)try{const e=await $e(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||(He(j,this.state),qe(D,(e=>{C+=e}))),yield*a}catch(e){o.error=e,o.hasError=!0}finally{kt(o)}}}var _t=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Pt{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 Pt((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{_t(n)}}}var It=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 Tt(){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 Rt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Rt(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,...Be,...r?.env},u=wt(c)?St(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 -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n 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=Tt(),S="win32"===process.platform,k=r?.sandboxWorkspaceRoot??a,E=(await pt(k,r?.sandboxPolicy)).policy,x=ze(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=Qe({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}=Ge(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{It(o)}}}var At=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 Ot{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new Ot(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,...Be,...r?.env},l=wt(a)?St(t):t,c=r?.workingDirectory??this.cwd,u=r?.sandboxWorkspaceRoot??c,d=(await pt(u,r?.sandboxPolicy)).policy,h="insecure_none"!==d.type?{...d,sandboxWorkspaceRoot:u}:d,m=ze(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=Qe({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 $e(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{At(n)}}}function Mt(e){const t="win32"===process.platform,r=e?.shell??(t?Tt():void 0),n=process.cwd();return new Ot(n,{...e,shell:r})}const jt="__CURSOR_ZSH_STATE_START__",Dt="__CURSOR_ZSH_STATE_END__";var Nt=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 $t(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class Ft{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Ft(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,...Be,...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; ${bt(l)}${c}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],d=r?.sandboxWorkspaceRoot??a,h=(await pt(d,r?.sandboxPolicy)).policy,m="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:d}:h,g=ze($t(),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=Qe({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=`${jt}\n`,t=`${Dt}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=Ge(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(m.captureDenies)try{const e=await $e(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];He(E,this.state),qe(x,(e=>{v+=e})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Nt(n)}}}const Lt="__CURSOR_ZSH_STATE_LIGHT_VALID__",Ut='#!/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_REQUEST_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 Bt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 zt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class Wt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Wt(e??this.cwd,this.state)}async*execute(e,t,r){const 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,...Be,...r?.env};let c='builtin eval "$1"';i||(c+=" < /dev/null");const u=bt(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; ${Ut} 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 pt(h,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,v=ze(zt(),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=Qe({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=`${Lt}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=Ge(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await $e(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];He(x,this.state),qe(C,(e=>{y+=e})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Bt(n)}}}var Ht,qt,Gt=r("node:perf_hooks");!function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}(Ht||(Ht={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(qt||(qt={}));const Vt={eventLoopDelayP95Ms:0,eventLoopUtilization:0};let Jt,Kt=0;class Zt{eventLoopMonitor;sampleTimer;lastEventLoopUtilization=Gt.performance.eventLoopUtilization();latestSnapshot=Vt;constructor(){this.eventLoopMonitor=(0,Gt.monitorEventLoopDelay)({resolution:qt.EventLoopResolutionMs}),this.lastEventLoopUtilization=Gt.performance.eventLoopUtilization(),this.eventLoopMonitor.enable(),this.sample(),this.sampleTimer=setInterval((()=>{this.sample()}),qt.SampleIntervalMs),this.sampleTimer.unref?.()}dispose(){void 0!==this.sampleTimer&&(clearInterval(this.sampleTimer),this.sampleTimer=void 0,this.eventLoopMonitor.disable(),this.latestSnapshot=Vt,this.lastEventLoopUtilization=Gt.performance.eventLoopUtilization())}isUnderPressure(){return this.latestSnapshot.eventLoopDelayP95Ms>=Ht.EventLoopDelayP95Ms||this.latestSnapshot.eventLoopUtilization>=Ht.EventLoopUtilization}formatSuppressionSection(){const e=this.latestSnapshot,t=[`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms (threshold ${Ht.EventLoopDelayP95Ms}ms)`,`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% (threshold ${(100*Ht.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>=Ht.EventLoopDelayP95Ms&&t.push(`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms >= ${Ht.EventLoopDelayP95Ms}ms`),e.eventLoopUtilization>=Ht.EventLoopUtilization&&t.push(`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% >= ${(100*Ht.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-qt.EventLoopResolutionMs)}computeEventLoopUtilization(){const e=Gt.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 Yt=6e4,Xt=65536,Qt=2097152,er=262144,tr=1e3,rr="\n[This shell is producing too much output to stream. The command will still run.]\n";class nr{bucketChars;bucketStarts;totalChars=0;outputSuppressed=!1;noticeSent=!1;windowMs;minimumThresholdCharsPerSecond;thresholdCharsPerSecondWithoutPressure;minChars;eventLoopPressureTracker;disposed=!1;constructor(e){this.windowMs=e?.windowMs??Yt,this.minimumThresholdCharsPerSecond=e?.minimumThresholdCharsPerSecond??Xt,this.thresholdCharsPerSecondWithoutPressure=e?.thresholdCharsPerSecondWithoutPressure??Qt,this.minChars=e?.minChars??er;const t=Math.ceil(this.windowMs/tr)+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(){Kt++,void 0===Jt&&(Jt=new Zt);const e=Jt;let t=!1;return{isUnderPressure:()=>e.isUnderPressure(),formatSuppressionSection:()=>e.formatSuppressionSection(),dispose:()=>{t||(t=!0,Kt--,0===Kt&&void 0!==Jt&&(Jt.dispose(),Jt=void 0))}}}()),this.eventLoopPressureTracker}recordChars(e,t){if(this.prune(t),e<=0)return;const r=Math.floor(t/tr)*tr,n=Math.floor(r/tr)%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(tr,Math.min(this.windowMs,e-r+tr));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 or=r("../utils/dist/path-utils.js");function ir(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 sr(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:ir(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 ar(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)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=t.networkPolicy;if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}(n);if(o)return{success:!1,error:`Invalid sandbox policy: ${o}`};let i=sr(n);return t&&(i=lr(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 lr(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,or.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,or.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,or.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}function cr(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 ur(e){switch(e){case Ue.Zsh:case Ue.ZshLight:return u("zsh",[]).cmd;case Ue.Bash:return u("bash",[]).cmd;case Ue.PowerShell:return Tt();default:return process.env.SHELL||"/bin/sh"}}function dr(e){try{return u(e,[]).cmd!==e}catch(e){return!1}}function hr(){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 pr(e){if(e===Ue.ZshLight)return Ue.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?hr():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")?Ue.Zsh:t.includes("bash")&&i?Ue.Bash:t.includes("pwsh")||t.includes("powershell")?Ue.PowerShell:n?Ue.Bash:r&&(dr("pwsh")||dr("powershell"))?Ue.PowerShell:dr("zsh")?Ue.Zsh:dr("bash")&&i?Ue.Bash:dr("pwsh")||dr("powershell")?Ue.PowerShell:Ue.Naive}function fr(e){let t=e;if(!e?.userTerminalHint){const r=hr();r&&(t={...e,userTerminalHint:r})}switch(pr(t?.userTerminalHint??"")){case Ue.Zsh:return new Pt((()=>async function(e){const t={...process.env,...Be,...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_REQUEST_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=ze($t(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),o.on("error",(e=>{console.warn(`[shell-exec] zsh state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=Ve(i,r),a=`${jt}\n`,l=`${Dt}\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}=Ge(c);return new Ft(u,d)}(t)));case Ue.Bash:return new Pt((()=>async function(e){const t={...process.env,...Be,...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_REQUEST_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=Et(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const i=ze(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()})),i.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{i.on("close",(()=>{e(void 0)}))}));const a=Ve(s,r),l=`${Je}\n`,c=`${Ke}\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}=Ge(u),p="win32"===process.platform,f="win32"===process.platform?process.cwd():d;return new Ct(f,h,e?.userTerminalHint,p)}(t)));case Ue.PowerShell:return new Pt((()=>async function(){return new Rt(process.cwd(),"")}()));case Ue.ZshLight:return new Pt((()=>async function(e){const t={...process.env,...Be,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`${Ut} builtin printf '${r}\\n'; dump_zsh_state_light`],o=ze(zt(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),o.on("error",(e=>{console.warn(`[shell-exec] zsh-light state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=Ve(i,r),a=`${Lt}\n`,l=s.startsWith(a)?s.slice(a.length):`${process.cwd()}\n`,{cwd:c,rest:u}=Ge(l);return new Wt(c,u)}(t)));default:return Mt(t)}}process.platform;const mr={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){"use strict";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,$,F,L,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)),L.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",F).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,L=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")},F=function(){const e=new ue(te(this,a,"f"));ee(this,g,0,"f"),ee(this,_,e,"f"),ee(this,L,(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:F=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"),F=!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,L,"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")&&(F||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,L,"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,L,"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){"use strict";r.d(t,{DN:()=>c,PS:()=>p,ZU:()=>u,fl:()=>f,o1:()=>l,oL:()=>h,yn:()=>a});var n=r("node:fs/promises"),o=r("node:os"),i=r("node:path"),s=r("node:url");function a(e,t){return void 0!==e&&("win32"===process.platform?(0,i.normalize)(e).toLowerCase()===(0,i.normalize)(t).toLowerCase():e===t)}function l(e,t){const r=function(e){return e.replace(/^~(?=$|\/|\\)/,(0,o.homedir)())}(function(e){if(!e.startsWith("file://"))return e;try{return(0,s.fileURLToPath)(e)}catch(t){return e}}(e));return t&&!(0,i.isAbsolute)(r)?(0,i.resolve)(t,r):(0,i.resolve)(r)}function c(e,t){return r=this,o=void 0,a=function*(){const r=l(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{l(a.next(e))}catch(e){t(e)}}function i(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(n,i)}l((a=a.apply(r,o||[])).next())}));var r,o,s,a}function u({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 d(e,t){for(const r of t)if(u({basePath:r,targetPath:e}))return!0;return!1}function h(e){return e.replace(/\\/g,"/")}const p="You cannot search other worktrees for this repository, stay within your workspace paths.";function f(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 h(e).includes(".cursor/worktrees")}(e))))return!1;if(d(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=h(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=>d(e,s))))||!(void 0===n||!o.some((e=>d(e,[n]))))}},"../utils/dist/writable-iterable.js"(e,t,r){"use strict";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}))})}}}};
|