@cursor/sdk 1.0.27-beta.0 → 1.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/616.js +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/sqlite.js +1 -1
- package/dist/esm/357.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/sqlite.js +1 -1
- package/package.json +6 -6
- package/dist/cjs/417.js +0 -1
package/dist/cjs/616.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports.id=616,exports.ids=[616],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>SC});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)}))}}},L=function(e){return this instanceof L?(this.v=e,this):new L(e)};const F=(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,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){F.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 L?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,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 L(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 L(t))}}catch(e){o={error:e}}finally{try{u||n||!(i=d.return)||(yield L(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}}}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 Le({step:e,command:t,failClosed:r,kind:n}){const o=$e(e);if(!r&&!o)return{shouldNotifyUser:!1};const i=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:Fe(e,i),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:i,shouldNotifyUser:o&&!r}}function Fe(e,t){return $e(e)?{permission:"deny",user_message:t}:e===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/agent_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.W0W({permission:null==r?void 0:r.permission,userMessage:null==r?void 0:r.user_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"subagentStop":{const e=M.request.value,t=Object.assign(Object.assign({conversation_id:null!==(a=e.conversationId)&&void 0!==a?a:"",generation_id:null!==(l=e.generationId)&&void 0!==l?l:"",model:null!==(c=e.model)&&void 0!==c?c:""},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.AHw({followupMessage:null==r?void 0:r.followup_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"beforeSubmitPrompt":{const e=M.request.value,t=yield this.hookExecutor.executeHookForStep(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.u1V({continue:null==t?void 0:t.continue,userMessage:null==t?void 0:t.user_message,additionalContext:null==t?void 0:t.additional_context})}})})}case"afterAgentResponse":{const e=M.request.value;return yield this.hookExecutor.executeHookForStep(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.FW9}})})}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.HaO}})})}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.rTS({followupMessage:null==t?void 0:t.followup_message})}})})}case"preToolUse":{const e=M.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(x=e.conversationId)&&void 0!==x?x:"",generation_id:null!==(C=e.generationId)&&void 0!==C?C:"",model:null!==(_=e.model)&&void 0!==_?_:""},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.D2O({permission:null==n?void 0:n.permission,userMessage:null==n?void 0:n.user_message,agentMessage:null==n?void 0:n.agent_message,updatedInput:(null==n?void 0:n.updated_input)?JSON.stringify(n.updated_input):void 0,additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUse":{const e=M.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(P=e.conversationId)&&void 0!==P?P:"",generation_id:null!==(I=e.generationId)&&void 0!==I?I:"",model:null!==(T=e.model)&&void 0!==T?T:""},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.uB8({additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUseFailure":{const e=M.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(R=e.conversationId)&&void 0!==R?R:"",generation_id:null!==(A=e.generationId)&&void 0!==A?A:"",model:null!==(O=e.model)&&void 0!==O?O:""},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.U15({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 Lt(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 Ft(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");class Qt 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 er(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 Qt&&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 tr=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 rr{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 nr(e){return"string"==typeof e&&e.trim().length>0}const or=W((e=>new B(e,V("webFetchAllowlistPrecheckArgs"),J("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new T(e,Z("webFetchAllowlistPrecheckArgs"),K("webFetchAllowlistPrecheckResult")))})),ir=e=>String(e).replace(/[\r\n]/g,""),sr="x-inference-authentication-jwt",ar={textDelta:e=>new Ze.Uq({message:{case:"textDelta",value:new Ze.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new Ze.Uq({message:{case:"toolCallStarted",value:new Ze.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new Ze.Uq({message:{case:"toolCallCompleted",value:new Ze.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r)=>new Ze.Uq({message:{case:"toolCallDelta",value:new Ze.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t)=>new Ze.Uq({message:{case:"thinkingDelta",value:new Ze.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:e=>new Ze.Uq({message:{case:"thinkingCompleted",value:new Ze.tr3({thinkingDurationMs:e})}}),userMessageAppended:e=>new Ze.Uq({message:{case:"userMessageAppended",value:new Ze.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new Ze.Uq({message:{case:"partialToolCall",value:new Ze.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new Ze.Uq({message:{case:"tokenDelta",value:new Ze.Fyz({tokens:e})}}),summary:e=>new Ze.Uq({message:{case:"summary",value:new Ze.ECk({summary:e})}}),summaryStarted:()=>new Ze.Uq({message:{case:"summaryStarted",value:new Ze.lWT}}),heartbeat:()=>new Ze.Uq({message:{case:"heartbeat",value:new Ze.ih1}}),summaryCompleted:e=>new Ze.Uq({message:{case:"summaryCompleted",value:new Ze.ZM9({hookMessage:e})}}),shellOutputDelta:e=>new Ze.Uq({message:{case:"shellOutputDelta",value:new Ze.Nn_({event:e})}}),turnEnded(e){var t;return new Ze.Uq({message:{case:"turnEnded",value:new Ze.lJj(e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(null!==(t=e.reasoningTokens)&&void 0!==t?t:0)}:{})}})},stepStarted:e=>new Ze.Uq({message:{case:"stepStarted",value:new Ze.dwJ({stepId:BigInt(e)})}}),stepCompleted:(e,t)=>new Ze.Uq({message:{case:"stepCompleted",value:new Ze.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),promptSuggestion:e=>new Ze.Uq({message:{case:"promptSuggestion",value:new Ze.yfd({suggestion:e})}}),activeBranchChange:(e,t)=>new Ze.Uq({message:{case:"activeBranchChange",value:new Ze.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new Ze.Uq({message:{case:"feedbackRequest",value:new Ze.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};var lr=r("../agent-kv/dist/index.js");function cr(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 ur=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),dr=r("../proto/dist/generated/agent/v1/mcp_pb.js"),hr=r("@bufbuild/protobuf"),pr=r("@connectrpc/connect"),fr=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_ef7275568c8b1f1f499006dc986c70d2/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),mr=r("../proto/dist/generated/aiserver/v1/utils_pb.js");class gr 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 vr extends gr{get kind(){return"RetriableError"}}class yr extends gr{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class wr extends gr{get kind(){return"NonRetriableError"}}class br extends gr{get kind(){return"CancelledError"}}const Sr=new Set([mr.yM.NOT_LOGGED_IN,mr.yM.AGENT_REQUIRES_LOGIN,mr.yM.AUTH_TOKEN_NOT_FOUND,mr.yM.AUTH_TOKEN_EXPIRED,mr.yM.INVALID_AUTH_ID,mr.yM.UNAUTHORIZED,mr.yM.GITHUB_NO_USER_CREDENTIALS,mr.yM.GITHUB_USER_NO_ACCESS]),kr=new Set([mr.yM.FREE_USER_USAGE_LIMIT,mr.yM.FREE_USER_RATE_LIMIT_EXCEEDED,mr.yM.PRO_USER_ONLY,mr.yM.PRO_USER_USAGE_LIMIT,mr.yM.PRO_USER_RATE_LIMIT_EXCEEDED,mr.yM.RATE_LIMITED,mr.yM.RATE_LIMITED_CHANGEABLE,mr.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Er=new Set([mr.yM.USAGE_PRICING_REQUIRED,mr.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),xr=new Set([mr.yM.BAD_API_KEY,mr.yM.BAD_USER_API_KEY,mr.yM.OUTDATED_CLIENT]),Cr=new Set([mr.yM.USER_ABORTED_REQUEST,mr.yM.DEBOUNCED]),_r=new Set([mr.yM.CUSTOM_MESSAGE]),Pr=["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"],Ir=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH"]),Tr=new RegExp(`\\b(${[...Ir].join("|")})\\b`),Rr=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"];function Ar(e,t={}){const{requestId:r}=t;if(e instanceof gr)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(mr.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,mr.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===pr.Code.Canceled||e.code===pr.Code.Aborted)return Mr(e)?new vr(e.message,h):new br(e.message,h);if(void 0!==(null==u?void 0:u.error)){const t=u.error;if(Cr.has(t))return new br(Or(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 yr(Or(e,u),r,h);if(Sr.has(t))return new yr(Or(e,u),"login",h);if(kr.has(t))return new yr(Or(e,u),"upgrade",h);if(Er.has(t))return new yr(Or(e,u),"payment",h);if(xr.has(t))return new yr(Or(e,u),"config",h);if(_r.has(t)&&!0!==(null===(a=u.details)||void 0===a?void 0:a.isRetryable))return new wr(Or(e,u),h);if(!1===(null===(l=u.details)||void 0===l?void 0:l.isRetryable))return new wr(Or(e,u),h)}return e.code===pr.Code.Unauthenticated?new yr(e.message,"login",h):new vr(e.message,h)}(e,r);const n=(0,lr.y_)(e);if(void 0!==n)return new wr(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 br(e.message,{cause:e,requestId:r});if(Mr(e))return new vr(e.message,{cause:e,requestId:r})}const o=e instanceof Error?e.message:String(e);return new vr(o,{cause:e instanceof Error?e:void 0,requestId:r})}function Or(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 Mr(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(Pr.some((t=>e.includes(t)))||Tr.test(e))return!0;const n=r.code;if("string"==typeof n&&(Pr.some((e=>n.includes(e)))||Ir.has(n)))return!0;r=r.cause}return!1}function jr(e){return!0===e.isTransport||(e.cause instanceof Error?Mr(e.cause):Pr.some((t=>e.message.includes(t)))||Tr.test(e.message))}var Dr=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())}))},Nr=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){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}),Lr=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 Fr extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ur{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}run(e){return Dr(this,void 0,void 0,(function*(){var t,r,n,o;const i={stack:[],error:void 0,hasError:!1};try{Nr(i,(0,l.VI)(e.withName("ClientExecController.run")),!1);const u=[];try{try{for(var s,a=!0,c=Lr(this.serverStream);!(t=(s=yield c.next()).done);a=!0){o=s.value,a=!1;const t=o;if((0,hr.isMessage)(t,ur.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const r=(()=>Dr(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;Nr(a,p?new l.r2(h,p):void 0,!1);const f=this.controlledExecManager.handle(h,t);try{for(var c,u=!0,d=Lr(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{$r(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 pr.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Fr(e.message);if(e instanceof pr.ConnectError&&e.code===pr.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 Fr(e.message)}else{if(e instanceof f.W2)throw new Fr(e.message);if(e instanceof pr.ConnectError&&e.code===pr.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Fr(e.message)}}throw e}}catch(e){i.error=e,i.hasError=!0}finally{$r(i)}}))}}var Br=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())}))},zr=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 Wr=(0,d.h)("ClientInteractionController"),Hr=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class qr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}run(e){return Br(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=>{Wr.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{zr(i)}}))}handleInteractionUpdate(e,t){return Br(this,void 0,void 0,(function*(){yield this.interactionListener.sendUpdate(e,t)}))}handleInteractionQuery(e,t){var r;const n=void 0!==t.query.case&&Hr.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=>{Wr.error(e,"Error handling interaction query",t)})).finally(i)}}var Gr=r("../utils/dist/promise-extras.js");function Vr(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,lr.Bk)(i),(0,lr.Bk)(s),(0,lr.Bk)(a),(0,lr.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 Jr=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 Kr=15728640,Zr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Yr=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Xr=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});class Qr{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,lr.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,lr.nj)(t),r);return this.transientBytes=o,!0}has(e){return this.transientBlobs.has((0,lr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}getBlob(e,t){return Jr(this,void 0,void 0,(function*(){const r=(0,lr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?yield this.parent.getBlob(e,t):n}))}persistForRemoteRead(e,t){return Jr(this,void 0,void 0,(function*(){const r=(0,lr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(yield(0,Gr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}))}setBlob(e,t,r){return Jr(this,void 0,void 0,(function*(){yield this.parent.setBlob(e,t,r)}))}setBlobLocallyOnly(e,t,r){return Jr(this,void 0,void 0,(function*(){yield this.parent.setBlobLocallyOnly(e,t,r)}))}flush(e){return Jr(this,void 0,void 0,(function*(){yield this.parent.flush(e)}))}}function en(e){const t=void 0===(null==(r=e.tokenDetails)?void 0:r.promptContextUsageTree)?r:new Ze.VNy(Object.assign(Object.assign({},r),{promptContextUsageTree:void 0}));var r;const n=t!==e.tokenDetails;let o=!1,i=e.subagentStates;for(const[t,r]of Object.entries(e.subagentStates)){const n=r.conversationState;if(void 0===n)continue;const s=en(n);s!==n&&(o||(i=Object.assign({},e.subagentStates),o=!0),i[t]=new Ze.aK_(Object.assign(Object.assign({},r),{conversationState:s})))}return n||o?new Ze.Y9z(Object.assign(Object.assign({},e),{tokenDetails:t,subagentStates:i})):e}const tn=(0,d.h)("@anysphere/agent-client:stall-detector"),rn=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type"]}),nn=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type"]}),on=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall"}),sn=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored"});class an{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 ln{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(),sn.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(mn),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"});tn.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(mn);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(tn.warn(this.ctx,d,o),rn.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,on.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});tn.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"),nn.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 cn=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 un=(0,d.h)("@anysphere/agent-client:turn-runner");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())}))},hn=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},pn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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}),fn=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 mn=(0,Qe.cF)(Symbol("agentStreamMetadata"),void 0),gn=(0,d.h)("@anysphere/agent-client:abort"),vn=(0,d.h)("@anysphere/agent-client:retry"),yn=(0,d.h)("@anysphere/agent-client:request-context-blob");function wn(e){return dn(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 Jr(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 Jr(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),Kr),m=yield Vr({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,Zr.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,Zr.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 Zr.increment(e,1,{mode:o,outcome:h?"hydrated":"inline"}),Yr.histogram(e,g,{mode:o}),Xr.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:Kr,maxInlineDynamicBytes:null!==(c=o.requestContextDynamicInlineMaxBytes)&&void 0!==c?c:1048576,notesSessionId:o.conversationId})}catch(r){t.requestContextParts=void 0,yn.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 bn=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 Sn(e,t,r){return dn(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c;try{for(n=!0,o=fn(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,ar.shellOutputDelta({case:"stdout",value:new Rt.o0({data:t.event.value.data})}));break;case"stderr":yield r.sendUpdate(e,ar.shellOutputDelta({case:"stderr",value:new Rt.Db({data:t.event.value.data})}));break;case"exit":yield r.sendUpdate(e,ar.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 kn=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0;function En(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function xn(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}function Cn(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 _n(e){return e instanceof Error?e.name:void 0}function Pn(e){const t={errorName:_n(e)};let r=e;for(let e=0;e<10&&void 0!==r;e++){if(En(r)){const e=xn(r),n=Cn(e),o=_n(e);return Object.assign(Object.assign({},t),{underlyingConnectError:{code:r.code,codeName:pr.Code[r.code],cause:void 0!==n||void 0!==o?{code:n,name:o}:void 0}})}r=xn(r)}return t}class In{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 dn(this,void 0,void 0,(function*(){var h,p;const f={stack:[],error:void 0,hasError:!1};try{const m=new Qr(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){vn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const S=hn(f,(0,l.VI)(e.withName("networkPhase")),!1);e=S.ctx,yield function(e){return cn(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 cn(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 br("Cancelled during backoff"));const n=setTimeout((()=>{null==t||t.removeEventListener("abort",o),e()}),i+s);function o(){clearTimeout(n),r(new br("Cancelled during backoff"))}null==t||t.addEventListener("abort",o,{once:!0})}))}))}(e,t,S.isRunningInTest,S.fixedRetryDelayMs);let P,I,T=e.state,R=e.action,A=0,O=k,M=0,j=0,D=!1;const N=()=>{var e;D&&(null===(e=S.onConnectionStateChange)||void 0===e||e.call(S,{state:"connected"}),D=!1)},$={handleCheckpoint:(e,t,r)=>cn(this,void 0,void 0,(function*(){var n;yield b.handleCheckpoint(e,t,r),P=t,I=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible",N()})),getLatestCheckpoint:()=>b.getLatestCheckpoint()};for(;;){if(w.canceled)throw x.toCancelledError(void 0,O);if(P=void 0,I=void 0,null===(t=E.beginAttempt)||void 0===t||t.call(E,{attempt:A,originalRequestId:C}),A>0?(O=crypto.randomUUID(),yield null===(r=S.onRetryStarting)||void 0===r?void 0:r.call(S,A,{actionCase:R.action.case,conversationState:T,isResume:"resumeAction"===R.action.case,attemptRequestId:O}),e.logging&&un.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&&un.info(w,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:A,reason:"resume_action"}))):(e.logging&&un.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&&un.info(w,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:A,reason:"resume_action"}))),w.canceled)throw x.toCancelledError(void 0,O);try{return yield E.runAttempt({state:T,action:R,checkpointHandler:$,attempt:A,attemptRequestId:O,notifyConnected:N}),N(),void(e.logging&&un.info(w,`[${e.logging.tag}] Request successful`,{attempt:A,actionCase:R.action.case,requestId:O,originalRequestId:C}))}catch(t){if(!0===(null===(i=x.shortCircuit)||void 0===i?void 0:i.call(x,t)))throw x.toCancelledError(t,O);const r=!0===(null===(s=S.endlessRetries)||void 0===s?void 0:s.call(S)),n=E.classify(t,{attempt:A,attemptRequestId:O,originalRequestId:C,serverErrorRetries:M,transportErrorRetries:j,endlessRetries:r});if(e.logging){const o="retry"===n.action?`RETRY (countAsServerError=${n.countAsServerError}, countAsTransportError=${n.countAsTransportError})`:`THROW ${n.error.kind}`;un.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&&un.warn(w,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(t),requestId:O,originalRequestId:C})}}throw e.logging&&un.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&&un.warn(w,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:t instanceof Error?t.name:typeof t,errorMessage:t instanceof Error?t.message:String(t)}));null===(d=S.onConnectionStateChange)||void 0===d||d.call(S,{state:"reconnecting",attempt:o,trigger:null!==(y=null===(h=E.reconnectTrigger)||void 0===h?void 0:h.call(E,t,n,{originalRequestId:C,failedAttemptRequestId:O,nextAttempt:o}))&&void 0!==y?y:{originatingRequestId:C,attemptRequestId:O}}),D=!0,n.countAsServerError&&M++,n.countAsTransportError&&j++,A=o,void 0!==P&&(T=P,R=new Ze.QFf({action:{case:"resumeAction",value:new Ze.qKo}}),null===(p=E.onResumeFromCheckpoint)||void 0===p||p.call(E)),yield _(A,w.signal)}}}))}({ctx:e,state:t,action:r,checkpointHandler: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},Pn(e))},cancellation:{toCancelledError:()=>new br("Request cancelled")},hooks:{beginAttempt:()=>{v.value=!1,y.sources=[],y.abortReasonName=void 0,y.abortReasonMessage=void 0,b=++w},runAttempt:t=>dn(this,[t],void 0,(function*({state:t,action:r,checkpointHandler:s,attempt:l,attemptRequestId:c,notifyConnected:h}){const p=function(e,t,r){return{sendUpdate:(n,o)=>dn(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)&&vn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})})),query:(n,o)=>dn(this,void 0,void 0,(function*(){if(t!==r())throw new br("Stale query from previous attempt");return e.query(n,o)})),enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(o,b,(()=>w));yield this.runInternal(e,t,r,n,p,i,m,a,s,u,d,c,g,v,y,h,l)})),classify:(e,t)=>{var r,n;return function(e,t,r,n,o,i,s,a,l,c){const u=i||s,d=c?2:10,h=e instanceof gr?e:Ar(e,{requestId:o});return t?u?!s&&n>=d?{action:"throw",error:new vr("Connection stalled repeatedly",{cause:h.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:new vr("Connection stalled",{cause:h.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0}})}:h instanceof br&&!l&&function(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(En(t)&&(t.code===pr.Code.Canceled||t.code===pr.Code.Aborted))return!0;t=xn(t)}return!1}(h)?u?!s&&n>=d?{action:"throw",error:new vr("Connection failed repeatedly",{cause:h.cause,requestId:o,displayInfo:{title:"Connection failed",detail:`The connection failed ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:h}:a&&(h instanceof yr||h instanceof wr)&&function(e){var t;const r=null===(t=e.displayInfo)||void 0===t?void 0:t.inferenceRequestErrorType;return void 0!==r&&!Rr.some((e=>e===r))}(h)?!s&&r>=3?{action:"throw",error:h}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:h instanceof br||h instanceof yr||h instanceof wr?{action:"throw",error:h}:h instanceof vr&&jr(h)?u?!s&&n>=d?{action:"throw",error:new vr("Connection failed repeatedly",{cause:h.cause,requestId:o,displayInfo:{title:"Connection failed",detail:`The connection failed ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:h}:u?!s&&r>=3?{action:"throw",error:h}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:{action:"throw",error:h}}(e,v.value,t.serverErrorRetries,t.transportErrorRetries,t.attemptRequestId,null!==(r=d.enableAgentRetries)&&void 0!==r&&r,t.endlessRetries,null!==(n=d.retryAllInferenceErrors)&&void 0!==n&&n,y.sources.length>0,d.isRunningInTest)},buildNonRetriedErrorInfo:e=>{var t;return Object.assign(Object.assign({},e),{enableAgentRetries:null!==(t=d.enableAgentRetries)&&void 0!==t&&t,stallAborted:v.value,abortSources:[...y.sources],abortReasonName:y.abortReasonName,abortReasonMessage:y.abortReasonMessage})},reconnectTrigger:(e,t,r)=>{var n,o,i;const s=Pn(e),a=e instanceof gr?e:Ar(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{pn(f)}}))}runInternal(e,t,r,n,o,i,s,a,c,d,h,m,g,v,y,w,b){return dn(this,arguments,void 0,(function*(e,t,r,n,o,i,s,a,c,d,h,m,g,v,y,w,b,S="agent.request.attempt"){var k,E,x,C,_,P,I;const T={stack:[],error:void 0,hasError:!1};try{const R=e,O=hn(T,(0,l.VI)(e.withName(S)),!1);O.span.setAttribute("agent.attempt",b),O.span.setAttribute("agent.request_id",m),O.span.setAttribute("agent.original_request_id",g),e=O.ctx,e=(0,l.Mf)(e,"agent.request_id",m),e=(e=(0,l.Mf)(e,"agent.original_request_id",g)).with(mn,{requestId:m,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const M=new Set(y.sources);let j=void 0!==y.abortReasonName||void 0!==y.abortReasonMessage;const D=(t,r)=>{if(M.has(t))return;M.add(t),y.sources=[...M];const n=(e=>{const t="string"==typeof(null==e?void 0:e.abortReasonName)?e.abortReasonName:void 0,r="string"==typeof(null==e?void 0:e.abortReasonMessage)?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);j||void 0===n||(j=!0,y.abortReasonName=n.abortReasonName,y.abortReasonMessage=n.abortReasonMessage),gn.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;D("ctx_signal_abort",cr(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;D("ctx_signal_abort",cr(t))}),{once:!0});const[N,$]=e.withCancel();if(null===(k=a.signal)||void 0===k?void 0:k.aborted){const e=null===(x=a.signal)||void 0===x?void 0:x.reason;D("conversation_action_abort",cr(e)),$()}else null===(E=a.signal)||void 0===E||E.addEventListener("abort",(()=>{var e;const t=null===(e=a.signal)||void 0===e?void 0:e.reason;D("conversation_action_abort",cr(t)),$()}),{once:!0});if(e.canceled||N.canceled){const t={ctxCanceled:e.canceled,softCancel:N.canceled};throw D("pre_run_cancel",t),new br("User aborted request")}const L=(0,l.VI)(e.withName("createControlledExecManager")),F=A.fromResources(i);L[Symbol.dispose]();const[U,B]=e.withCancel(),z=new an,{failThresholdMs:W,advisoryThresholdMs:H}=(e=>{var t;const r=null!==(t=kn(null==e?void 0:e.failTimeoutMs))&&void 0!==t?t:3e4,n=kn(null==e?void 0:e.advisoryTimeoutMs);return{failThresholdMs:r,advisoryThresholdMs:void 0!==n&&n>0&&(r<=0||n<r)?n:void 0}})(h.stallDetectorConfig),q=hn(T,new ln(U,{thresholdMs:W,advisoryThresholdMs:H,onStall:()=>{v.value=!0,D("stall_detector",{thresholdMs:W,advisoryThresholdMs:H}),B()},onStallCallback:h.onStall,handlerTracker:z}),!1);let G,V;const J=(0,fr.Jt)(),K=new f.F8(J,(e=>(q.reset("outbound_write",bn(e)),e))),Z=hn(T,(0,l.VI)(e.withName("writeInitialRequest")),!1);let Y;const X=d.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?hr.Value.fromJson(e.inputSchema):void 0}))),Q=null!==(_=h.requestContextBlobTransportMode)&&void 0!==_?_:"legacy",ee=0===b&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Q&&ee?"dual":Q;yield wn({ctx:e,action:r,resources:i,blobStore:s,options:h,source:"run_request",transportMode:te});const re=new Ze.Mpn({conversationState:en(t),action:r,modelDetails:n,requestedModel:h.requestedModel,mcpTools:new dr.Or({mcpTools:X}),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!==(P=h.subagentModelOverrides)&&void 0!==P?P:[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsPromptContextUsageRpc:h.clientSupportsPromptContextUsageRpc,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,runId:g});if(Y=K.write(new ur.KS({message:{case:"runRequest",value:re}})),N.canceled){const t={ctxCanceled:e.canceled,softCancel:N.canceled};throw D("post_write_cancel",t),Z[Symbol.dispose](),new br("User aborted request")}const ne=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":ir(e.parentRequestId)}:{}),void 0!==e.rootParentRequestId?{"x-root-parent-request-id":ir(e.rootParentRequestId)}:{}),void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":ir(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("$")?{}:{[sr]:n}}()),null!==(I=h.headers)&&void 0!==I?I:{});G=(0,l.VI)(e.withName("handshakeEstablishment")),G.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=this.client.run(G.ctx,J,{signal:U.signal,headers:ne,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===V&&(V=performance.now())}}),ie=performance.now(),se=e=>{var t,r;G&&(G.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==V&&G.span.setAttribute("handshake.preNetworkMs",V-ie),G[Symbol.dispose](),G=void 0),w();const n=performance.now();null===(t=h.onFirstMessage)||void 0===t||t.call(h,n-ie),void 0!==V&&(null===(r=h.onFirstMessageNetwork)||void 0===r||r.call(h,n-V))},ae=h.onFirstNonHeartbeatResponse?()=>{h.onFirstNonHeartbeatResponse(performance.now()-ie,b)}:void 0,le=h.onTtftBreakdown?e=>{h.onTtftBreakdown(e,b)}:void 0,{interactionStream:ce,execStream:ue,checkpointStream:de,kvStream:he,done:pe}=function(e,t,r,n,o,i,s,a){const l=(0,fr.Jt)(),c=(0,fr.Jt)(),u=(0,fr.Jt)(),d=(0,fr.Jt)();let h=!1,p=!1;return{interactionStream:l,execStream:c,checkpointStream:u,kvStream:d,done:function(){return dn(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=fn(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){vn.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){vn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",bn(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 gr?e:Ar(e);return t instanceof vr&&jr(t)}(y)&&(vn.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}`;vn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===y?(vn.warn(e,t),w=new vr(t,{isTransport:!0})):y instanceof Error&&"[aborted] aborted"===y.message?(vn.warn(e,`${t}; retrying caught [aborted] aborted error`),w=new vr(t,{cause:y,isTransport:!0})):vn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:y instanceof Error?`${y.name}: ${y.message}`:String(y)})}l.close(),c.close(),u.close(),d.close()}if(void 0!==w)throw w}))}()}}(e,oe,q,se,N.signal,e.signal,ae,le);let fe;const me={handleCheckpoint:(e,t,r)=>dn(this,void 0,void 0,(function*(){var n;yield c.handleCheckpoint(e,t,r),fe=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"})),getLatestCheckpoint:()=>c.getLatestCheckpoint()};Z[Symbol.dispose]();const ge=5e3;let ve;const ye=()=>{ve=setTimeout((()=>{K.write(new ur.KS({message:{case:"clientHeartbeat",value:new ur.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),ye()}),ge)},we=()=>{void 0!==ve&&(clearTimeout(ve),ve=void 0)};ye();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,s=new Rt.a({command:(null===(C=n.shellCommand)||void 0===C?void 0:C.command)||"",parsingResult:new Rt.HO,skipApproval:!0}),a=i.get(Mt).execute(e,s,{execId:n.execId}),l=new qr(ce,o,new f.F8(K,(e=>new ur.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:e=>dn(this,void 0,void 0,(function*(){yield Promise.all([z.track("handleShellStream",Sn(e,a,o)),z.track("interactionController",l.run(e))])}))}}else{const e=new qr(ce,o,new f.F8(K,(e=>new ur.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:t=>dn(this,void 0,void 0,(function*(){yield z.track("interactionController",e.run(t))}))}}void 0!==Y&&(yield Promise.race([Y,pe.catch((()=>{}))]));const l=new f.F8(K,(e=>{if((0,hr.isMessage)(e,p.yT))return new ur.KS({message:{case:"execClientMessage",value:e}});if((0,hr.isMessage)(e,p.$Y))return new ur.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,hr.isMessage)(e)?e.getType().typeName:typeof e})`)})),c=new Ur(ue,l,F),b=new lr.hC(he,new f.F8(K,(e=>new ur.KS({message:{case:"kvClientMessage",value:e}}))),s,{beforeGetBlob:(e,t)=>dn(this,void 0,void 0,(function*(){return s.persistForRemoteRead(e,t)}))}),S=new u(de,me,e);let k,E;const x={promise:new Promise(((e,t)=>{k=e,E=t})),resolve:k,reject:E};N.canceled?(x.resolve(),ce.close()):N.signal.addEventListener("abort",(()=>{x.resolve(),ce.close()}),{once:!0}),c.run(N).then(x.resolve).catch(x.reject);const _=Promise.allSettled([z.track("streamSplitter",pe.finally((()=>{we(),a.close(),l.close()}))),z.track("execHandler",x.promise),t.run(e),z.track("checkpointController",S.run()),z.track("kvHandler",b.run(e)),z.track("conversationActionManager",a.run(e,{write:t=>dn(this,void 0,void 0,(function*(){yield wn({ctx:e,action:t,resources:i,blobStore:s,options:h,source:"queued_action"}),yield K.write(new ur.KS({message:{case:"conversationAction",value:t}}))}))}))]);let P,I;const T={promise:new Promise(((e,t)=>{P=e,I=t})),resolve:P,reject:I};_.then(T.resolve).catch(T.reject),e.canceled?T.reject(new br("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new br("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?B():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:pe,lingerMs:h.softCancelLingerMs}).then((t=>{vn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:m}),B()}))};N.canceled?(A(),T.reject(new br("User aborted request"))):N.signal.addEventListener("abort",(()=>{A(),T.reject(new br("User aborted request"))}),{once:!0});const O=yield T.promise,M=O[0],j=O[1],D=O[3],$=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===D.status)throw new wr("Checkpoint persistence failed",{cause:D.reason instanceof Error?D.reason:void 0,requestId:m,displayInfo:{title:"Checkpoint persistence failed",detail:$(D),isRetryable:!1}});const L="ineligible_terminal_turn"===fe;if(L){const t=Object.assign(Object.assign({},"rejected"===M.status?{streamSplitter:$(M)}:{}),"rejected"===j.status?{execHandler:$(j)}:{});Object.keys(t).length>0&&vn.warn(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!L)throw M.reason;if("rejected"===j.status&&!L)throw j.reason;N.canceled||(yield this.processUnprocessedMessages(R,a,me,n,o,i,s,d,h,m,g,v,y,q,w))}finally{we(),G&&(G[Symbol.dispose](),G=void 0)}}catch(e){T.error=e,T.hasError=!0}finally{pn(T)}}))}processUnprocessedMessages(e,t,r,n,o,i,s,a,l,c,u,d,h,p,f){return dn(this,void 0,void 0,(function*(){if(!t.hasUnprocessedMessages())return;const m=t.getUnprocessedUserMessages(),g=r.getLatestCheckpoint();if(!g||0===m.length)return;const v=m[0];t.markMessageAsProcessed(v),t.resetStream(),p[Symbol.dispose]();const y=r.getLatestCheckpoint();try{yield this.runInternal(e,g,new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:v})}}),n,o,i,s,t,r,a,l,c,u,d,h,f,0,"agent.request.queuedMessage")}catch(e){throw y===r.getLatestCheckpoint()&&t.requeueMessage(v),e}}))}}var Tn=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Rn=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),An=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),On=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Mn=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),jn=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Dn=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");Error;const Nn=e=>new Ze.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Dn.lI({result:{case:"approved",value:new Dn.XJ}})}}),$n=(e,t)=>new Ze.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Dn.lI({result:{case:"rejected",value:new Dn.yc({reason:null!=t?t:""})}})}}),Ln=e=>new Ze.Y5({id:e,result:{case:"webFetchRequestResponse",value:new jn.fS({result:{case:"approved",value:new jn.Hs}})}}),Fn=(e,t)=>new Ze.Y5({id:e,result:{case:"webFetchRequestResponse",value:new jn.fS({result:{case:"rejected",value:new jn.m$({reason:null!=t?t:""})}})}}),Un=(e,t)=>new Ze.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new Ze.zT({result:t})}}),Bn=e=>new Ze.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Mn.w$({result:{case:"approved",value:new Mn.q5}})}}),zn=(e,t)=>new Ze.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Mn.w$({result:{case:"rejected",value:new Mn.rA({reason:null!=t?t:""})}})}}),Wn=(e,t)=>new Ze.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Rn.gz({result:t})}}),Hn=(e,t)=>new Ze.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),qn=(e,t)=>new Ze.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),Gn=(e,t)=>new Ze.Y5({id:e,result:{case:"prManagementResult",value:t}}),Vn=(e,t)=>new Ze.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new On.h({result:{case:"rejected",value:new On.OI({reason:null!=t?t:"Authentication was rejected"})}})}}),Jn=(e,t)=>new Ze.Y5({id:e,result:{case:"connectScmRequestResponse",value:new Tn.qG({result:{case:"rejected",value:new Tn.lB({reason:null!=t?t:"Connecting GitHub was skipped"})}})}}),Kn=(e,t)=>new Ze.Y5({id:e,result:{case:"generateImageRequestResponse",value:new An.vW({result:{case:"approved",value:new An.l3({description:null!=t?t:""})}})}});var Zn=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js");Error;var Yn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),Xn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),Qn=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 eo=(0,pr.createContextKey)(void 0,{description:"anysphere.callerContext"});function to(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function ro(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:Yn.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):null==t||t.setStatus({code:Yn.s.OK}),null==t||t.end(),null==r||r())};return{next(){return Qn(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 Qn(this,void 0,void 0,(function*(){return i(),n.return?n.return(e):{done:!0,value:void 0}}))},throw(e){return Qn(this,void 0,void 0,(function*(){if(i(e),n.throw)return n.throw(e);throw e}))}}}}}function no(...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 oo(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:Xn.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=no(o,e))}const s=no(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,pr.createContextValues)()).set(eo,d),y=Object.assign(Object.assign({},c),{headers:s,signal:m,contextValues:v}),w=i.call(e,a,y);return to(w)?ro(w,h,p):null!==(f=w)&&"object"==typeof f&&"then"in f&&"function"==typeof f.then?w.then((e=>to(e)?ro(e,h,p):(null==h||h.setStatus({code:Yn.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:Yn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e})):(null==h||h.setStatus({code:Yn.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:Yn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e}var f}}})}var io=r("node:child_process"),so=r("node:fs"),ao=r("node:util");(0,ao.promisify)(io.execFile),Error;var lo=r("../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/index.js");const co=process.env.HTTPS_PROXY||process.env.https_proxy||void 0;let uo;try{uo=void 0!==co&&co.length>0?new lo.kT(co):void 0}catch(uE){uo=void 0}Error,r("@connectrpc/connect-node"),new Ze.Gmx({modelId:"gpt-5",displayModelId:"gpt-5",displayName:"GPT-5",displayNameShort:"GPT-5",aliases:["gpt-5"]});var ho=r("node:fs/promises"),po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),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="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",xo="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Co=/\$\(|`|<\(|>\(/,_o=/[;&|]/;let Po,Io,To,Ro;function Ao(){if(void 0===Po){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Po=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Po}function Oo(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 Mo(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function jo(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 Do(){if(void 0===Ro){const e=(process.env[Eo]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Eo} (expected "allow" or "deny"); using "deny".`);const r=Mo("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[xo]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Mo(xo)),Ro={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Mo("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:jo("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ro}function No(e,t,r={}){const n=[Oo(e),Oo(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 $o(e,t){const r=function(){const e=Do();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===Io&&(Io=No("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Io);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Co.test(e))return r;const i=(void 0===To&&(To=No("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),To);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||i?.test(t)||_o.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Do();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 Fo(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 Uo(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 Bo(e){switch(e){case"system":return Lo.Sz.SYSTEM;case"workspace":return Lo.Sz.WORKSPACE;default:return Lo.Sz.UNSPECIFIED}}function zo(e){const t=function(e){switch(e){case Lo.Sz.SYSTEM:return"system";case Lo.Sz.WORKSPACE:case Lo.Sz.CUSTOM: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 Wo(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:Uo(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,...zo(e)};case Lo.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Uo(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...zo(e)};default:return{type:"insecure_none"}}}function Ho(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:Fo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Bo(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:Fo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Bo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Lo.Mw({type:Lo.vc.INSECURE_NONE})}function qo(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||""===e||""===e||""===e||"\ufeff"===e}function Go(e){let t="",r=!1;for(const n of e)qo(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function Vo(e){return e.length>0&&[...e].every((e=>"*"===e))}function Jo(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 Ko(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 Zo({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const Yo={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function Xo(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=Yo[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 Go(t)}function Qo({rule:e,command:t}){const r=Go(e).trim();return 0!==r.length&&(null!==function(e){const t=Go(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Vo(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=Jo(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Vo(e)&&(0===t.length||Vo(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Go(t).trim(),Xo(t).trim()].some((e=>function(e,t){const r=Jo(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(Ko(e,i)&&Ko(n,s))return!0}return e.includes("*")?Ko(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ei({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=>Qo({rule:e,command:t}))))return e}function ti(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 ri({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=ei({matchForms:Zo({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:ti(n)}async function ni(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(ti(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function oi(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return ti(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 ii(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:oi(r)})}}var si=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 ai=(0,d.h)("local-exec:background-shell");function li(e,t,r){return new Pt.Lt({result:ii(e,t,r)})}class ci{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 ui(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 di(e){e().catch((()=>{}))}const hi=65536;class pi{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=So.L3.compile(e.config.pattern,So.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>hi){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=hi)this.observe(e.slice(t,t+hi));return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrences<this.limit&&n.find();){const e=n.group()??"";n.end()>t&&this.queueMatch(e)}this.carryover=r.slice(-1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer())}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,i=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;var s;this.args.registry.enqueue({conversationId:this.args.conversationId,id:i,source:"shell",payload:{taskId:i,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(s=t,s.length<=500?s:`${s.slice(0,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}})}}class fi{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 pi({shellId:t,outputPath:i,config:o,conversationId:r??re,toolCallId:n,registry:this.backgroundWorkRegistry})}catch(r){return void(void 0!==e&&ai.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 mi{async spawn(e,t){const r=new AbortController,n=new ci(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof fo.SandboxUnsupportedError)throw e}return di((()=>ui(n,o))),n}async adopt(e){const t=new ci(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,di((()=>ui(t,e.eventIterator))),t}}function gi(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function vi(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: ${gi(e.cwd)}\n`,n+=`command: ${gi(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${gi(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}class yi{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,ho.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=vi({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=vi({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:m,startedAt:p,runningForMs:r});await(0,ho.writeFile)(b,n,"utf8"),c=setInterval((()=>{k()}),5e3)},C=async()=>{a||(a=await so.promises.open(b,"r+")),l||(l=await so.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=gi(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,ho.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=vi({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:a})+(e.initialOutput??"");await(0,ho.writeFile)(r,l,"utf8");const c=await so.promises.open(r,"r+");let u;try{u=await so.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=vi({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 wi{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 bi{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class Si{constructor(e,t,r,n,o,i,s){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=i&&void 0!==s?new bi(i,s):i,l=o??function(e){const t=new mi;return new yi(t,e)}(n),c=new fi(l,n,a);this.backgroundShellManager=new wi(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?Wo(t.sandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(),s=(0,ko.o1)(i),a=new Rt.HO(bo(n).structured),c=ri({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(ai.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 ai.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),li(n,s,r.reason);ai.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 ai.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),li(n,s,r.reason);u=r.policy,ai.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(Ao()&&(u=$o(n,a),"insecure_none"!==u.type)){const e=await this.ignoreService.getCursorIgnoreMapping();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,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 ai.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{si(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var ki=r("node:async_hooks"),Ei=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),xi=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js"),Ci=r("zod");const _i={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Pi=Ci.z.object({command:Ci.z.string().optional(),args:Ci.z.array(Ci.z.string()).optional(),env:Ci.z.record(Ci.z.string(),Ci.z.string()).optional(),url:Ci.z.string().optional(),headers:Ci.z.record(Ci.z.string(),Ci.z.string()).optional(),cwd:Ci.z.string().optional(),envFile:Ci.z.string().optional(),auth:Ci.z.object({CLIENT_ID:Ci.z.string(),CLIENT_SECRET:Ci.z.string().optional(),scopes:Ci.z.array(Ci.z.string()).optional()}).optional(),enabledTools:Ci.z.array(Ci.z.string()).optional()}),Ii=Ci.z.object({mcpServers:Ci.z.record(Ci.z.string(),Pi).optional()}),Ti=Ci.z.enum(["canvas"]),Ri=Ci.z.array(Ti).transform((e=>[...new Set(e)].sort()));class Ai extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function Oi(e){const t=e.trim();if(!t)throw new Ai("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Ai("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Ai("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Ai("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 Ai("Missing plugin name before @",e);if(!i)throw new Ai("Missing source after @",e);if(!r.test(o))throw new Ai("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Ai("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 Ai("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 Ai("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 Ai("Missing Git URL after 'url:'",e);try{new URL(t)}catch(t){throw new Ai("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 Ai("Missing marketplace name",e);if(!r.test(a))throw new Ai("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:l,raw:e}}function Mi(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 ji(e){return e.sourceInfo.name}function Di(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Ni(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function $i(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const Li=/\$\{([A-Z][A-Z0-9_]*)(?::-([^}]*))?\}/g,Fi=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Ui=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSWORD","SECRET","TOKEN"]);function Bi(e){return e.split("_").some((e=>Ui.has(e)))}const zi=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Wi(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return zi.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Hi(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Hi(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Hi(r,t)}else for(const[,r,n]of e.matchAll(Li))Fi.has(r)||t.has(r)||t.set(r,n)}function qi(e){if(void 0===(null==e?void 0:e.mcpServers))return;const t=new Map;if(Hi(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:Wi(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.`},Bi(e)?{writeOnly:!0}:{})}return{type:"object",properties:r}}var Gi=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const Vi=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Ji=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Ki(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 Zi(e){let t;try{t=new URL(e).pathname.split("/")}catch(r){t=e.split("/")}for(const e of t){const t=Ji.exec(e);if(null!==t)return t[1]}}function Yi(e){var t;return void 0===e?{kind:"absent"}:Vi.has(e)?{kind:"supported",id:e,version:null!==(t=Zi(e))&&void 0!==t?t:e}:{kind:"unsupported",id:e}}const Xi=10485760,Qi=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,es=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],ts=[".cursor-plugin",".claude-plugin"],rs=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ns=Ci.z.object({source:Ci.z.literal("github"),repo:Ci.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Ci.z.string().optional(),sha:Ci.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),os=Ci.z.object({source:Ci.z.literal("url"),url:Ci.z.string().url().endsWith(".git","URL must end with .git"),ref:Ci.z.string().optional(),sha:Ci.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),is=Ci.z.object({source:Ci.z.literal("git-subdir"),url:Ci.z.string().url().endsWith(".git","URL must end with .git"),path:Ci.z.string().min(1),ref:Ci.z.string().optional(),sha:Ci.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ss=Ci.z.union([Ci.z.string(),ns,os,is]),as=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,ls=Ci.z.object({cursor:Ci.z.string().regex(as,"Must be a semver version (X.Y.Z)").optional(),sand:Ci.z.string().regex(as,"Must be a semver version (X.Y.Z)").optional()}),cs=Ci.z.object({name:Ci.z.string().min(1,"Author name is required"),email:Ci.z.string().email().optional()}),us=Ci.z.enum(["string","number","integer","boolean","object","array","null"]),ds=Ci.z.union([us,Ci.z.array(us).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Ci.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function hs(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Ci.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:Ci.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:Ci.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:Ci.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:Ci.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:Ci.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:Ci.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const ps=Ci.z.lazy((()=>Ci.z.object({type:ds.optional(),title:Ci.z.string().optional(),description:Ci.z.string().optional(),format:Ci.z.string().optional(),writeOnly:Ci.z.boolean().optional(),default:Ci.z.unknown().optional(),enum:Ci.z.array(Ci.z.any()).nonempty().optional(),const:Ci.z.unknown().optional(),properties:Ci.z.record(Ci.z.string(),ps).optional(),required:Ci.z.array(Ci.z.string()).optional(),additionalProperties:Ci.z.union([Ci.z.boolean(),ps]).optional(),items:Ci.z.union([ps,Ci.z.array(ps)]).optional(),minLength:Ci.z.number().int().nonnegative().optional(),maxLength:Ci.z.number().int().nonnegative().optional(),minimum:Ci.z.number().optional(),maximum:Ci.z.number().optional(),exclusiveMinimum:Ci.z.number().optional(),exclusiveMaximum:Ci.z.number().optional(),multipleOf:Ci.z.number().positive().optional(),minItems:Ci.z.number().int().nonnegative().optional(),maxItems:Ci.z.number().int().nonnegative().optional(),uniqueItems:Ci.z.boolean().optional(),minProperties:Ci.z.number().int().nonnegative().optional(),maxProperties:Ci.z.number().int().nonnegative().optional()}).strict().superRefine(hs)));function fs(e){const t=ps.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:Ci.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 ms=Ci.z.unknown().superRefine(((e,t)=>{const r=fs(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),gs=(Ci.z.object({name:Ci.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Qi.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ci.z.string().optional(),source:ss,description:Ci.z.string().optional(),version:Ci.z.string().optional(),author:cs.optional(),publisher:Ci.z.string().min(1).optional(),homepage:Ci.z.string().url().optional(),repository:Ci.z.string().url().optional(),license:Ci.z.string().optional(),keywords:Ci.z.array(Ci.z.string()).optional(),capabilities:Ri.optional(),logo:Ci.z.string().optional(),category:Ci.z.string().optional(),tags:Ci.z.array(Ci.z.string()).optional(),minClientVersions:ls.optional(),strict:Ci.z.boolean().default(!0),commands:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),agents:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),skills:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),rules:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),hooks:Ci.z.union([Ci.z.string(),Ci.z.record(Ci.z.unknown())]).optional(),variables:ms.optional(),mcpServers:Ci.z.union([Ci.z.string(),Ci.z.record(Ci.z.unknown()),Ci.z.array(Ci.z.union([Ci.z.string(),Ci.z.record(Ci.z.unknown())]))]).optional()}),Ci.z.object({description:Ci.z.string().optional(),version:Ci.z.string().optional(),pluginRoot:Ci.z.string().optional()}),Ci.z.object({name:Ci.z.string().min(1).regex(Qi,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ci.z.string().optional(),description:Ci.z.string().optional(),version:Ci.z.string().optional(),author:cs.optional(),publisher:Ci.z.string().min(1).optional(),homepage:Ci.z.string().url().optional(),repository:Ci.z.string().url().optional(),license:Ci.z.string().optional(),logo:Ci.z.string().optional(),keywords:Ci.z.array(Ci.z.string()).optional(),capabilities:Ri.optional(),minClientVersions:ls.optional(),commands:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),agents:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),skills:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),rules:Ci.z.union([Ci.z.string(),Ci.z.array(Ci.z.string())]).optional(),hooks:Ci.z.union([Ci.z.string(),Ci.z.record(Ci.z.unknown())]).optional(),variables:ms.optional(),mcpServers:Ci.z.union([Ci.z.string(),Ci.z.record(Ci.z.unknown()),Ci.z.array(Ci.z.union([Ci.z.string(),Ci.z.record(Ci.z.unknown())]))]).optional()}));function vs(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ys(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function ws(e,t){if(vs(e)&&"string"==typeof e.name){const t=ys(e.name);if(t.length>0)return t}return function(e){var t;const r=void 0!==e.repoName?ys(e.repoName):"";return r.length>0?r:`cursor-marketplace-${null!==(t=e.fallbackId)&&void 0!==t?t:(0,o.randomUUID)()}`}(t)}function bs(e){if(vs(e)&&vs(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 Ss(e){return"string"==typeof e?e:void 0}function ks(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Es(e){return"string"==typeof e?e:ks(e)}function xs(e){if(!vs(e)||!vs(e.metadata))return;const t={description:Ss(e.metadata.description),version:Ss(e.metadata.version),pluginRoot:Ss(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Cs(e){if(!vs(e))return;const t=Ss(e.name);if(void 0===t||0===t.length)return;const r=Ss(e.email);return Object.assign({name:t},void 0!==r?{email:r}:{})}function _s(e){if("string"==typeof e||vs(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||vs(e)));return t.length>0?t:void 0}}function Ps(e){if("string"==typeof e||vs(e))return e}function Is(e){if(void 0===e)return;const t=fs(e);return t.success?t.data:void 0}function Ts(e,t={}){if(e.length>Xi)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(!vs(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(!vs(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:vs(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Ss(n.ref),sha:Ss(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Ss(n.ref),sha:Ss(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:Ss(n.ref),sha:Ss(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Ss(n.ref),sha:Ss(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Ss(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?ys(e.name):"")||function(e){var t;if("string"==typeof e){const t=ys((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const r=ys(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=ys((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=ys((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=Ri.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,l=function(e){const t=ls.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:Ss(e.displayName),source:r,description:Ss(e.description),version:Ss(e.version),author:Cs(e.author),publisher:Ss(e.publisher),homepage:Ss(e.homepage),repository:Ss(e.repository),license:Ss(e.license),keywords:ks(e.keywords),logo:Ss(e.logo),category:Ss(e.category),tags:ks(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Es(e.commands),agents:Es(e.agents),skills:Es(e.skills),rules:Es(e.rules),hooks:Ps(e.hooks),variables:Is(e.variables),mcpServers:_s(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:ws(r,t),owner:bs(r),description:Ss(r.description),plugins:n,metadata:xs(r),skippedPluginEntries:o}}}function Rs(e){if(e.length>Xi)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=Yi(Ki(t));if("unsupported"===r.kind)return{success:!1,error:`Unsupported plugin manifest $schema version: ${r.id}`,unsupportedSchema:!0};const n=gs.safeParse(t);return n.success?{success:!0,data:n.data}:{success:!1,error:`Invalid plugin manifest: ${n.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function As(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 Os(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function Ms(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 Gi.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var js=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ds=/\$\{([^:}]+)(?::-([^}]*))?\}/g;function Ns(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 $s(e,r)}function $s(e,t){if("string"==typeof e)return e.replace(Ds,((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=>$s(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=$s(o,t);return r}return e}function Ls(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}var Fs=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 Us=[".mcp.json","mcp.json"],Bs=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function zs(e,t){if(!function(e){return Bs.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 Ws(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Hs(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Us.map((e=>void 0!==t?`${t}/${e}`:e))}function qs(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=Ls(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ls(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?Ls(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ls(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 Ns(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 Gs(e,t,r){try{const n=(0,js.qg)(e),o=Ki(n);if(void 0!==o){if("unsupported"===Yi(o).kind)return null;if(function(e,t){if(void 0===e||void 0===t)return!1;const r=Zi(e),n=Zi(t);return void 0!==r&&void 0!==n&&r!==n}(null==r?void 0:r.pluginSchemaId,o))return null}const i=Ii.safeParse(n),s=!0===(null==r?void 0:r.skipExpansion);if(i.success&&i.data.mcpServers&&Object.keys(i.data.mcpServers).length>0)return s?i.data:qs(i.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!zs(e,t)&&Ws(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Ii.safeParse({mcpServers:a});if(e.success)return s?e.data:qs(e.data,t,r)}return null}catch(e){return null}}function Vs(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}function Js(e,t,r){return Fs(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:Us,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=Gs(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 Fs(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=>Fs(this,void 0,void 0,(function*(){const n=e.replace(/^\.\//,"");if(!Os(n))return;const o=yield t(n);if(null===o)return;const l=Gs(o,s,r.parserOptions);(null==l?void 0:l.mcpServers)&&Object.keys(l.mcpServers).length>0&&Vs(a,l.mcpServers,i(n))})),c=e=>{var t;const n=Gs(JSON.stringify(e),s,r.parserOptions);(null==n?void 0:n.mcpServers)&&Object.keys(n.mcpServers).length>0&&Vs(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 Ks(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 Zs=r("node:stream"),Ys=r("node:stream/promises"),Xs=r("node:zlib");function Qs(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 ea(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var ta=r("../../node_modules/.pnpm/tar@7.5.7/node_modules/tar/dist/esm/index.js"),ra=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 na=".cache-complete";function oa(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function ia(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function sa(e){return ea(e)}function aa(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,oa(t.marketplaceSlug),ia(t.pluginId),void 0!==t.version?sa(t.version):void 0)}class la{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 aa(this.cacheRoot,e)}isCached(e){return ra(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{const e=(0,s.join)(t,na);return(yield(0,ho.stat)(e)).isFile()}catch(e){return!1}}))}extractToCache(e){return ra(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,ho.mkdir)(t,{recursive:!0});const r=Zs.Readable.from(e.tarball);return yield(0,Ys.pipeline)(r,(0,Xs.createGunzip)(),(0,ta.o6)({cwd:t,strip:1})),yield this.markCacheComplete(e),t}))}listCachedVersions(e){return ra(this,void 0,void 0,(function*(){const t=oa(e.marketplaceSlug),r=ia(e.pluginId),n=(0,s.join)(this.cacheRoot,t,r);try{return(yield(0,ho.readdir)(n,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(e){return[]}}))}removeVersion(e){return ra(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{yield(0,ho.rm)(t,{recursive:!0,force:!0})}catch(e){}}))}removeAllVersions(e){return ra(this,void 0,void 0,(function*(){const t=aa(this.cacheRoot,e);yield(0,ho.rm)(t,{recursive:!0,force:!0})}))}pruneOldVersions(e){return ra(this,void 0,void 0,(function*(){const t=yield this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>sa(e))));for(const n of t)r.has(n)||(yield this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n}))}))}markCacheComplete(e){return ra(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,ho.writeFile)((0,s.join)(t,na),"")}))}}function ca(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}}const ua=[["safe.bareRepository","explicit"],["core.fsmonitor","false"],["core.hooksPath",i.devNull],["core.attributesFile",i.devNull]];var da=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 ha=(0,ao.promisify)(io.execFile);function pa(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 fa(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 ua)t===o&&(r[`GIT_CONFIG_VALUE_${e}`]=i,n.add(o))}let o=t;for(const[e,t]of ua)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:pa(e),optionsEnv:t})}function ma(e,t,r){return n=this,o=void 0,s=function*(){const n=null!=r?r:{},{env:o,encoding:i="utf8"}=n,s=da(n,["env","encoding"]),a=yield ha(e,t,Object.assign(Object.assign({},s),{encoding:i,env:fa(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 ga(e,t,r){const n=null!=r?r:{},{env:o}=n,i=da(n,["env"]);return(0,io.spawn)(e,t,Object.assign(Object.assign({},i),{env:fa(t,o)}))}function va(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function ya(e){return"function"==typeof e?e():e}function wa(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 ma("git",[...va(),...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 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 Sa=/^[0-9a-f]{7,40}$/i,ka=/^[0-9a-f]{40}$/i;function Ea(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 xa(e,t,r){return ba(this,void 0,void 0,(function*(){const n=t.trim();if(ka.test(n))return{fullSha:n.toLowerCase()};if(Sa.test(n)){try{const t=yield function(e,t,r){return ba(this,void 0,void 0,(function*(){var n;const{stdout:o}=yield wa(["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=Ea(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 wa(["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=Ea(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 wa(["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=Ea(o);if(!i)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:i.toLowerCase()}}))}var Ca=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 _a=rs.map((e=>e.split("/")[0]));let Pa;function Ia(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 Ta(e){const t=[];for(const r of e){const e=Ia(r);if(null===e)return"all";t.push(e)}return t}function Ra(e,t){return Ca(this,void 0,void 0,(function*(){const r="all"===e?"all":Ta(e),n=t&&"all"!==r&&(yield function(){return process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(null!=Pa||(Pa=(()=>Ca(this,void 0,void 0,(function*(){try{const{stdout:e}=yield wa(["--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}})))()),Pa)}());return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([..._a,...o])]):[]};var o}))}function Aa(e){return e.toLowerCase().includes("filtering not recognized by server")}function Oa(e,t,r){return Ca(this,void 0,void 0,(function*(){yield wa(["sparse-checkout","set","--cone","--",...t],Object.assign(Object.assign({},r),{cwd:e}))}))}function Ma(e){return Ca(this,void 0,void 0,(function*(){try{yield(0,ho.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch(e){return!1}try{const{stdout:t}=yield wa(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch(e){return!1}}))}function ja(e,t,r){return Ca(this,void 0,void 0,(function*(){if("all"!==t&&0===t.length)return;if(!(yield Ma(e)))return;const n=Object.assign(Object.assign({},r),{cwd:e,sshBatchMode:!0});if("all"===t)return void(yield wa(["sparse-checkout","disable"],n));const o=Ta(t);"all"!==o?yield wa(["sparse-checkout","add","--",...o],n):yield wa(["sparse-checkout","disable"],n)}))}const Da=/\.git$/i,Na=new Set(["account","dashboard"]);function $a(e){return e.replace(Da,"")}function La(e){let t;try{t=decodeURIComponent(e)}catch(e){return}return t.length>0&&!t.includes("/")?t:void 0}function Fa(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Ua(e){return e.toLowerCase().split(".").includes("gitlab")}function Ba(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function za(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}function Wa(e){return void 0!==function(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||!za(n.hostname))return;const o=function(e){const t=e.replace(/\/+$/,"").replace(/\.git$/i,"");return t&&"/"!==t?t.startsWith("/")?t:`/${t}`:""}(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?{hostname:n.hostname,owner:a,name:l}:void 0}(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}function Ha(e){const t=e.toLowerCase();return Ua(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function qa(e){return Fa(e)?"github":Ua(e)?"gitlab":Ba(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Ga(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);za(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=$a(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(o);return void 0===i?null:{provider:qa(n),owner:i.owner,repo:i.repo,host:n}}function Va(e){const t=Ja(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean);return r.length>=3&&"scm"===r[0].toLowerCase()}function Ja(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch(e){return null}}function Ka(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Ga(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Ua(r.host)){const e=Ja(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=$a(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=Ja(e.trim());if(null!==t&&Ba(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=La(t),o=La(r);if(void 0===n||void 0===o||Na.has(n.toLowerCase()))return;const i=$a(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=Ja(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=$a(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!za(e.host)&&null===Ha(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=Ya(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Va(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=Ha(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function Za(e){const t=Ka(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 Ya(e){return Fa(e)?"github.com":e}new Map;function Xa(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 Qa(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function el(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 tl=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 rl=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 nl(e){const t=ea(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":rl.has(t.toLowerCase())?`_${t}`:t}const ol=18e5,il=6e5,sl=["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"],al=["enotempty: directory not empty, rename","/_staging/"],ll=["upload-pack: not our ref","server does not allow request for unadvertised object"];function cl(e){const t=String(e).toLowerCase().replaceAll("\\","/");return sl.some((e=>t.includes(e)))?"user_git_access":al.every((e=>t.includes(e)))?"local_cache_race":ll.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function ul(e){return"object"==typeof e&&null!==e&&(!0===e.killed||ul(e.cause))}function dl(e){return ul(e)?"killed_by_budget":cl(e)}function hl(e){const t=Ka(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=Ga(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:Ya(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const pl=new Map;class fl{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?ol:void 0}localTimeoutMs(){return this.sparsePluginClones?il:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}cloneResolvedRef(e,t,r,n){return tl(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({},ya(null===(o=this.options)||void 0===o?void 0:o.extraGitConfig)),{"safe.directory":e})},{sparse:l,sparseDirs:c}=yield Ra(null!==(s=null==n?void 0:n.materialize)&&void 0!==s?s:"all",this.sparsePluginClones);yield wa(["init"],Object.assign(Object.assign({},a),{timeoutMs:this.localTimeoutMs()})),l&&(yield Oa(e,c,{sshBatchMode:null==n?void 0:n.sshBatchMode,extraGitConfig:ya(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.localTimeoutMs()}));const{stderr:u}=yield wa(["fetch","--depth","1",...l?["--filter=blob:none"]:[],t,r],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()}));return yield wa(["checkout","FETCH_HEAD"],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()})),{strategy:l?"sparse":"full",filterIgnoredByServer:l&&Aa(null!=u?u:"")}}))}createStagingDir(){return tl(this,void 0,void 0,(function*(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,o.randomUUID)());return yield(0,ho.mkdir)(e,{recursive:!0}),e}))}moveToCanonicalDir(e,t){return tl(this,void 0,void 0,(function*(){return yield(0,ho.mkdir)((0,s.dirname)(t),{recursive:!0}),yield(0,ho.rm)(t,{recursive:!0,force:!0}),yield(0,ho.rename)(e,t),t}))}cleanStaleStagingDirs(){return tl(this,void 0,void 0,(function*(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=yield(0,ho.readdir)(e,{withFileTypes:!0}),r=Date.now();yield Promise.all(t.filter((e=>e.isDirectory())).map((t=>tl(this,void 0,void 0,(function*(){try{const n=(0,s.join)(e,t.name),o=yield(0,ho.stat)(n);r-o.mtimeMs>fl.STALE_STAGING_THRESHOLD_MS&&(yield(0,ho.rm)(n,{recursive:!0,force:!0}))}catch(e){}})))))}catch(e){}}))}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,nl(e),nl(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=hl(e);return(0,s.join)(this.cacheRoot,nl(r),...n.map(nl),nl(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=hl(e);return(0,s.join)(this.cacheRoot,nl(t),...r.map(nl))}pruneSiblingCloneDirs(e,t,r){return tl(this,void 0,void 0,(function*(){const n=this.getCanonicalRepoRootDir(e),o=nl(t);try{const e=yield(0,ho.readdir)(n,{withFileTypes:!0});yield Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,ho.rm)((0,s.join)(n,e.name),{recursive:!0,force:!0}))))}catch(e){}if(void 0!==r)try{yield(0,ho.rm)(r,{recursive:!0,force:!0})}catch(e){}}))}ensureCloned(e,t,r){return tl(this,arguments,void 0,(function*(e,t,r,n=_i,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,Gr.wj)(i,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}))}ensureMaterialized(e,t){return tl(this,arguments,void 0,(function*(e,t,r=_i){const n=this.serializedOnRepo((0,s.dirname)(e),(()=>tl(this,void 0,void 0,(function*(){var n;const o=performance.now();try{yield ja(e,t,{extraGitConfig:ya(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:dl(n)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:dl(n)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o,{outcome:"error"}),n}}))));return this.sparsePluginClones?n:(0,Gr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}))}serializedOnRepo(e,t){return tl(this,void 0,void 0,(function*(){const r=`${this.cacheRoot}:${e}`,n=pl.get(r),o=(null!=n?n:Promise.resolve()).catch((()=>{})).then(t);pl.set(r,o);try{return yield o}finally{pl.get(r)===o&&pl.delete(r)}}))}ensureClonedImpl(e,t,r,n,o){return tl(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:Za(t);if(null!==d)try{u=(yield xa(d,c,{sshBatchMode:!0,extraGitConfig:ya(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&ul(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:cl(e)}),d=null,u=(yield xa(t,c,{extraGitConfig:ya(null===(s=this.options)||void 0===s?void 0:s.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else u=(yield xa(t,c,{extraGitConfig:ya(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 Ma(h);return e&&(yield ja(h,o,{extraGitConfig:ya(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 tl(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,ho.utimes)(u,e,e).catch((()=>{}))}),fl.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&&ul(e))throw e;s.log("error","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:i,error:String(e),errorCategory:dl(e)}),yield(0,ho.rm)(u,{recursive:!0,force:!0}),yield(0,ho.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=dl(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,ho.rm)(u,{recursive:!0,force:!0})}catch(e){}}}))}isCloneComplete(e){return tl(this,void 0,void 0,(function*(){try{if(!(yield(0,ho.stat)(e)).isDirectory())return!1;const t=yield(0,ho.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(yield(0,ho.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch(e){return!1}}catch(e){return!1}}))}getPluginDir(e,t){return el(e,t)}copyPluginToDir(e,t){return tl(this,void 0,void 0,(function*(){yield(0,ho.mkdir)(t,{recursive:!0}),yield(0,ho.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}))}readManifest(e){return tl(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 tl(this,arguments,void 0,(function*(e,t={}){for(const r of rs){const n=(0,s.join)(e,r);let o;try{o=yield(0,ho.readFile)(n,"utf-8")}catch(e){continue}const i=Ts(o,t);if(i.success)return i.data}return null}))}(e,t);return this.manifestCache.set(n,o),o}))}resolvePluginPath(e,t){return tl(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=As(o.source,null===(r=n.metadata)||void 0===r?void 0:r.pluginRoot);return i&&Os(i)?i:null}))}discoverPlugins(e){return tl(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=As(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":Os(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):[]}))}}fl.STALE_STAGING_THRESHOLD_MS=3e5,fl.STAGING_HEARTBEAT_INTERVAL_MS=6e4;var ml=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 gl=(0,ao.debuglog)("cursor-plugins");function vl(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 yl(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 wl(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)&&!Rl(e,t.gitUrl)?e:n:e}function bl(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 Sl(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=yl(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 kl="backend-git://";function El(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${kl}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function xl(e){if(!e.startsWith(kl))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 Cl="backend-release://";function _l(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${Cl}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Pl(e){if(!e.startsWith(Cl))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 Il=/^[0-9a-f]{7,40}$/i;function Tl(e){let t;try{t=hl(e)}catch(e){return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Rl(e,t){if(e.trim()===t.trim())return!0;const r=Tl(e),n=Tl(t);return null!==r&&r===n}const Al=104857600;function Ol(e,t,r,n,a,l){return ml(this,void 0,void 0,(function*(){const c=yield function(e){return ml(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>Al)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||!Ml(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||!Ml(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>Al)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,ho.mkdir)(n,{recursive:!0});const d=yield(0,ho.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,ho.writeFile)(h,c),yield(0,ho.mkdir)(p,{recursive:!0});let e=0,t=0;yield ta.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,ho.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,ho.readdir)(e)).some((e=>ts.includes(e)))&&(a=e)}const l=yield(0,ho.readdir)(a);yield Promise.all(l.map((e=>(0,ho.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{yield(0,ho.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}))}function Ml(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class jl{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:_i,this.extraGitConfig=h.extraGitConfig,this.githubToken=h.githubToken,this.sparsePluginClones=null!==(l=h.sparsePluginClones)&&void 0!==l&&l,this.marketplaceCache=h.marketplaceCacheRoot?new fl(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 ml(this,void 0,void 0,(function*(){var e,t,r,n,i,s,a,l,c,u,d,h,p,f,m;const g=yield this.getEffectiveUserPlugins(),v=null!==(t=g.plugins)&&void 0!==t?t:[],y=null!==(r=g.marketplaces)&&void 0!==r?r:[],w=[],b=[],S=new Map,k=(e,t)=>ml(this,void 0,void 0,(function*(){const r=`${e}\0${t}`;let n=S.get(r);if(!n){const o=ya(this.extraGitConfig),i=this.sparsePluginClones?3e4:void 0,s=e.startsWith("git@")||e.startsWith("ssh://")?null:Za(e),a=(e,r)=>ml(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 xa(e,t,n):yield xa(e,t)).fullSha}));if(null!==s)try{n=yield a(s,!0)}catch(t){if(this.sparsePluginClones&&ul(t))throw t;n=yield a(e,!1)}else n=yield a(e,!1);S.set(r,n)}return n})),E=e=>ml(this,void 0,void 0,(function*(){const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){const e=`${t}\0${n}`,i=!S.has(e);let s;i&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{s={sha:yield k(t,n),gitUrl:t}}catch(e){i&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==s){if(i)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch(e){}return s}}return{sha:yield k(r,n),gitUrl:r}}));for(const t of v){if(!t.isEnabled||!(null===(e=t.plugin)||void 0===e?void 0:e.name))continue;const r=t.plugin,g=yl(r,y);if(!this.isMarketplaceAllowed(g)){this.pluginLogger.log("info",`Skipping plugin ${r.name} because marketplace ${null!==(n=null==g?void 0:g.name)&&void 0!==n?n:"<none>"} is not allowed`,{pluginId:r.name,marketplaceName:null==g?void 0:g.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const v=vl({name:r.name,pluginId:void 0!==r.id?String(r.id):null!==(i=r.name)&&void 0!==i?i:""}),S=v;if(!r.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${v} without gitUrl (enableInlinePlugins=false)`,{pluginId:S});continue}const e=t.inlineContentJson;if(!e){this.pluginLogger.log("info",`Skipping DB-inline plugin ${v}: no inline content provided`,{pluginId:S});continue}const n=(0,o.createHash)("sha256").update(`${null!==(s=r.id)&&void 0!==s?s:"0"}:${null!==(a=r.updatedAt)&&void 0!==a?a:"0"}`).digest("hex").slice(0,40),i=(null==g?void 0:g.name)?{id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-inline`,name:g.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${S}`,{pluginId:S,marketplaceId:null!==(l=null==i?void 0:i.id)&&void 0!==l?l:"unknown",version:n}),w.push({pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:v,version:n,downloadUrl:`inline://${null!==(c=r.id)&&void 0!==c?c:S}`,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:i,inlineContentJson:e});continue}const k=r.gitUrl,x=wl(k,g),C=Sl(t,y),_=ca(r,C),P=null!==(u=null==g?void 0:g.gitRef)&&void 0!==u?u:C;let I,T,R=x;try{if(void 0!==_)I=`release/${_.releaseTag}`;else{const e=yield E({preferredGitUrl:x,sourceGitUrl:k,gitRef:C,pluginId:S});I=e.sha,R=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${v}@${C}, skipping plugin`,{pluginId:S,ref:C,error:String(e)});const t=e instanceof Error?e.message:String(e);b.push({pluginName:v,pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,marketplaceName:null==g?void 0:g.name,errorMessage:t,errorType:/timed?\s*out/i.test(t)?"timeout":"clone"});continue}T=void 0!==_?_l({repo:_.releaseRepo,asset:_.releaseAsset,tag:_.releaseTag}):El(R,C,null!==(d=r.gitPath)&&void 0!==d?d:void 0);const A=bl(g);let O=A,M=P;if((null==g?void 0:g.gitUrl)&&A){const e=Rl(k,g.gitUrl),t=e?R:A,r=e?k:g.gitUrl,n=e?C:P;try{const e=yield E({preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:S});M=e.sha,O=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${v} from ${t}@${n}, falling back to raw ref`,{pluginId:S,cacheRepoUrl:t,cacheRef:n,error:String(e)}),O=r}}const j=(null==g?void 0:g.name)?Object.assign({id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-${encodeURIComponent(null!==(h=g.gitUrl)&&void 0!==h?h:"project")}`,name:g.name},O&&{gitUrl:O,gitRef:M}):void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${S} from ${M} at ${r.gitPath}`,{pluginId:S,marketplaceId:null!==(p=null==j?void 0:j.id)&&void 0!==p?p:"unknown",gitPath:null!==(f=r.gitPath)&&void 0!==f?f:void 0,gitRef:M}),w.push({pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:v,version:I,downloadUrl:T,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:j,gitPath:null!==(m=r.gitPath)&&void 0!==m?m:void 0,isOriginBacked:void 0===_&&R!==k||void 0})}return{plugins:w,listFailures:b}}))}isDirectInstallSameFetch(e){const t=e.marketplace;if(!(null==t?void 0:t.gitUrl)||!t.gitRef)return!1;const r=xl(e.downloadUrl);return!(!r||!Rl(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}installPlugin(e,t){return ml(this,void 0,void 0,(function*(){if(e.inlineContentJson)yield function(e){return t=this,r=void 0,o=function*(){var t,r;const{targetDir:n,inlineContentJson:o,pluginName:i}=e,a=JSON.parse(o);yield(0,ho.mkdir)(n,{recursive:!0});const l={};if(a.rules&&a.rules.length>0){const e=(0,s.join)(n,"rules");yield(0,ho.mkdir)(e,{recursive:!0});const t=[];for(const r of a.rules){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${ea(r.name)}.md`,o=[];o.push(`description: ${Qa(r.name)}`),r.globs&&r.globs.length>0&&o.push(`globs: ${Qa(r.globs.join(", "))}`),o.push(`alwaysApply: ${!0===r.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;yield(0,ho.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,ho.mkdir)(e,{recursive:!0});const t=[];for(const r of a.commands){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${ea(r.name)}.md`,o=r.description?`---\ndescription: ${Qa(r.description)}\n---\n\n`:"";yield(0,ho.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,ho.mkdir)(e,{recursive:!0});const o={};for(const e of a.hooks){const n=e.hookStep;n&&!1!==e.isActive&&Xa(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,ho.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,ho.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,ho.mkdir)(u,{recursive:!0}),yield(0,ho.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{if(null===Pl(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)&&ul(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 ml(this,arguments,void 0,(function*(e,t,r=_i,n,o){var a;const l=null!==(a=null==o?void 0:o.sparsePluginClones)&&void 0!==a&&a,c=l?ol:void 0,u=Pl(e.downloadUrl);if(u){if(e.gitPath){const r=yield(0,ho.mkdtemp)((0,s.join)((0,i.tmpdir)(),"release-plugin-"));try{yield Ol(u.repo,u.asset,u.tag,r,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);const n=el(r,e.gitPath);yield(0,ho.mkdir)(t,{recursive:!0}),yield(0,ho.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,ho.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else yield Ol(u.repo,u.asset,u.tag,t,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);return}const d=xl(e.downloadUrl);if(!d)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const h=yield(0,ho.mkdtemp)((0,s.join)((0,i.tmpdir)(),"backend-plugin-"));try{let o;if(yield function(e,t,r){return ml(this,arguments,void 0,(function*(e,t,r,n=_i,o,i="all",s=!1){const a=performance.now(),l=Il.test(t),c="HEAD"===t.toUpperCase(),u=Object.assign(Object.assign({},o),{"safe.directory":r}),d=s?ol:void 0,h=s?il:void 0,{sparse:p,sparseDirs:f}=yield Ra(i,s),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,v=e=>ml(this,void 0,void 0,(function*(){p&&(yield Oa(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0}))})),y=(e,n)=>ml(this,void 0,void 0,(function*(){let o="";return c?(({stderr:o}=yield wa(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield v(d)):l?(yield wa(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield wa(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield v(h),({stderr:o}=yield wa(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield wa(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=yield wa(["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:Za(e);let b="";if(null!==w)try{b=yield y(w,!0)}catch(t){if(s&&ul(t))throw t;yield(0,ho.rm)(r,{recursive:!0,force:!0}),yield(0,ho.mkdir)(r,{recursive:!0}),b=yield y(e,g)}else b=yield y(e,g);p&&Aa(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);gl("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?Ta([d.gitPath]):[],l),d.gitPath)o=el(h,d.gitPath);else{const t=yield function(e,t){return ml(this,void 0,void 0,(function*(){var r;for(const n of rs){const o=(0,s.join)(e,n);let i;try{i=yield(0,ho.readFile)(o,"utf-8")}catch(e){continue}const a=Ts(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=As(c.source,null===(r=l.metadata)||void 0===r?void 0:r.pluginRoot);return u&&Os(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 ja(h,Ta([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=el(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 ja(h,"all",{extraGitConfig:n,timeoutMs:c}),o=h}}yield(0,ho.mkdir)(t,{recursive:!0}),yield(0,ho.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,ho.rm)(h,{recursive:!0,force:!0}).catch((()=>{}))}}))}(e,t,this.pluginLogger,ya(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 ml(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=Ta(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 ml(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?Ta([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,Ta([c]),this.pluginLogger));const u=s.getPluginDir(l,c);return yield s.copyPluginToDir(u,t),!0}))}discoverMarketplacePlugins(e,t,r){return ml(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 Dl(e,t,r,n,o){return new jl(e,t,r,n,o)}var Nl=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const $l=()=>({});function Ll(e,t){return Nl(e,Object.assign(Object.assign({},t),{engines:Object.assign(Object.assign({},null==t?void 0:t.engines),{js:$l,javascript:$l})}))}function Fl(e,t,r){return Nl.stringify({content:e,data:{}},t,r)}function Ul(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Bl(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?Ul(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)&&(Ul(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 zl=r("../../node_modules/.pnpm/js-yaml@4.1.0/node_modules/js-yaml/dist/js-yaml.mjs"),Wl=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 Hl=[".md",".mdc",".markdown"],ql=[...Hl,".txt"],Gl=/^---\s*\n([\s\S]*?)\n---/,Vl="";function Jl(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function Kl(e){var t,r;const n=e.match(Gl);if(!n)return{};try{const e=zl.Ay.load(n[1],{schema:zl.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const o=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,i=Zl(null!==(t=e.environments)&&void 0!==t?t:null==o?void 0:o.environments);return{disabledEnvironments:Zl(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 Zl(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 Yl(e){return Jl((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function Xl(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 Ql{constructor(e){this.fetcher=e}discoverComponents(){return Wl(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=Us.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,Hl,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,Hl,i):l.has("agents")?this.discoverMarkdownComponents(`${o}agents`,Hl,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,ql,i):l.has("commands")?this.discoverMarkdownComponents(`${o}commands`,ql,i):Promise.resolve([]),void 0!==(null==s?void 0:s.rules)?this.discoverFromManifestPaths(o,s.rules,!1,Hl,i):l.has("rules")?this.discoverMarkdownComponents(`${o}rules`,Hl,i):Promise.resolve([]),this.discoverMcpServers(o,null==s?void 0:s.mcpServers,c)]);return{skills:Xl(d?[d,...h]:h),agents:Xl(p),hooks:f,commands:Xl(m),rules:Xl(g),mcpServers:v.servers,mcpVariables:v.variables}}))}discoverHooksFromJson(e){return Wl(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:Jl(r),path:e,description:t?Vl:`Hook: ${r}`})))}catch(e){return[]}}))}discoverHooksFromManifest(e,t){return Wl(this,arguments,void 0,(function*(e,t,r=!1){var n;if("string"==typeof t){if(!Os(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:Jl(e),path:"manifest",description:r?Vl:`Hook: ${e}`})))}))}discoverFromManifestPaths(e,t){return Wl(this,arguments,void 0,(function*(e,t,r=!1,n=Hl,o=!1){var i,s;if("string"==typeof t){if(!Os(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(!Os(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=Yl(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t),n=o?Vl:void 0;if(!o){const{content:t}=yield this.fetcher.fetchFile(e),o=Kl(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:Jl(r),path:e};void 0!==n&&(t.description=n),a.push(t)}continue}if(r){const t={name:Jl(r),path:e};void 0!==n&&(t.description=n),a.push(t)}}else{if(!(yield this.fetcher.fileExists(t)))continue;let e=Yl(t),r=o?Vl:void 0;if(!o){const{content:n}=yield this.fetcher.fetchFile(t),o=Kl(n);e=null!==(s=o.name)&&void 0!==s?s:e,r=o.description}if(e){const n={name:Jl(e),path:t};void 0!==r&&(n.description=r),a.push(n)}}}catch(e){}return a}))}discoverMarkdownComponents(e){return Wl(this,arguments,void 0,(function*(e,t=Hl,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=>Wl(this,void 0,void 0,(function*(){try{let t=Yl(e.name),n=r?Vl:void 0;if(!r){const{content:r}=yield this.fetcher.fetchFile(e.path),o=Kl(r);t=o.name?Jl(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 Wl(this,arguments,void 0,(function*(e,t=!1){try{const r=`${e}SKILL.md`,n=(0,s.basename)(e.replace(/[\\/]+$/,""));let o=Jl(t?n||Yl(r):n),i=t?Vl:void 0;if(!t){const{content:e}=yield this.fetcher.fetchFile(r),t=Kl(e);if(o=t.name?Jl(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 Wl(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=>Wl(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=Jl(e.name);return t?{name:t,path:r,description:Vl}:null}const{content:n}=yield this.fetcher.fetchFile(r),o=Kl(n),i=o.name?Jl(o.name):Jl(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 Wl(this,void 0,void 0,(function*(){const n=new Map,o=t=>Wl(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=>Wl(this,void 0,void 0,(function*(){return Js(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:Jl(e),path:null!==(r=null===(t=s.mcpServerSourcePaths)||void 0===t?void 0:t[e])&&void 0!==r?r:"manifest"}})),variables:qi(null!=a?a:s)}}))}}var ec=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 tc(e){var t;const r=null!==(t=null!=e?e:process.env.HOME)&&void 0!==t?t:"";return(0,s.join)(r,".claude")}function rc(e){return ec(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,ho.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,ho.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 nc=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 oc(e){return nc(this,void 0,void 0,(function*(){try{return(yield(0,ho.lstat)(e)).isSymbolicLink()}catch(e){return!1}}))}function ic(e){return nc(this,void 0,void 0,(function*(){if(yield oc(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,ho.readFile)(e,"utf-8")}))}function sc(e){return nc(this,void 0,void 0,(function*(){if((yield(0,ho.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}))}function ac(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 lc(e){return nc(this,void 0,void 0,(function*(){var t;for(const r of es){const n=(0,s.join)(e,r);let o;try{if(yield oc(n))continue;if(!(yield(0,ho.stat)(n)).isFile())continue;yield sc(n),o=yield ic(n)}catch(e){continue}const i=Rs(o);if(!i.success){if(i.unsupportedSchema)throw new Error(i.error);continue}const a=i.data,l=a.commands,c=a.agents,u=a.skills,d=a.rules,h=a.hooks,p=a.mcpServers,f=void 0!==l||void 0!==c||void 0!==u||void 0!==d||void 0!==h||void 0!==p,m="string"==typeof a.displayName?a.displayName:void 0,g="string"==typeof a.description?a.description:void 0,v=null===(t=a.author)||void 0===t?void 0:t.name,y=a.variables,w=a.capabilities,b=void 0!==m||void 0!==g||void 0!==v||void 0!==y||void 0!==w;if(f||b)return Object.assign(Object.assign({manifestFilePath:n},f&&{manifestOptions:{commands:l,agents:c,skills:u,rules:d,hooks:h,mcpServers:p}}),b&&{metadata:{displayName:m,description:g,authorName:v,variables:y,capabilities:w}})}}))}function cc(e,t){return nc(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,ho.realpath)(i).catch((()=>i));function l(e){const t=(0,s.resolve)(e);try{return el(o,t)}catch(t){throw new Error(`Path escapes plugin directory: ${e}`)}}function c(e){return nc(this,void 0,void 0,(function*(){const t=l(e),r=yield a,n=yield(0,ho.realpath)(t);try{return el(r,n)}catch(t){throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}))}return{listDirectory(t,r){return nc(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,ho.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,ho.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 nc(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 sc(i);const a=yield(0,ho.readFile)(i,"utf-8");return n.set(t,a),{content:a}}))},fileExists(t){return nc(this,void 0,void 0,(function*(){try{const r=l((0,s.join)(e,t)),n=yield c(r);return(yield(0,ho.stat)(n)).isFile()}catch(e){return!1}}))}}}(e),n=new Ql(r),o=yield n.discoverComponents({manifest:t}),[i,a,l,c]=yield Promise.all([uc(r,o.skills,e),hc(r,o.agents,e),pc(r,o.commands,e),dc(r,o.rules,e)]);return{skills:i,agents:a,commands:l,rules:c}}))}function uc(e,t,r){return nc(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=mc({content:Ls(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function dc(e,t,r){return nc(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=mc({content:Ls(t,r),relativePath:o.path});i&&n.push(Object.assign(Object.assign({},i),{name:o.name}))}catch(e){}return n}))}function hc(e,t,r){return nc(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=gc({content:Ls(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function pc(e,t,r){return nc(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=vc({content:Ls(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function fc(e){if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function mc({content:e,relativePath:t}){var r,n,o,i,s;try{const a=Ll(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=Zl(null!==(i=a.data.environments)&&void 0!==i?i:null===(r=a.data.metadata)||void 0===r?void 0:r.environments),m=Zl(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:fc(a.data.globs),alwaysApply:!0===a.data.alwaysApply,content:e,environments:f,disabledEnvironments:m}}catch(e){return null}}function gc({content:e,relativePath:t}){var r,n;try{const o=Ll(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 vc({content:e,relativePath:t}){try{const r=Ll(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 yc(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}function wc(e,t,r){return nc(this,void 0,void 0,(function*(){const n=null!=r?r:yc(t);return function(e){return Fs(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 es){const r=yield e(t);if(null===r)continue;let a;try{a=JSON.parse(r)}catch(e){continue}s=Ki(a);const l=Rs(r);if(l.success){void 0!==l.data.mcpServers&&(o=l.data.mcpServers,i=n(t));break}}return Js(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=>nc(this,void 0,void 0,(function*(){if(!Os(t))return null;const r=(0,s.join)(e,t);try{return(yield oc(r))?null:(yield(0,ho.stat)(r)).isFile()?(yield sc(r),yield ic(r)):null}catch(e){return null}}))}(e),{fallbackFileNames:Hs(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}))}function bc(e,t){return nc(this,void 0,void 0,(function*(){var r;const n=yield wc(e);if(n)return n;for(const n of rs){const o=(0,s.join)(e,n);try{if(!(yield(0,ho.stat)(o)).isFile())continue;const n=yield(0,ho.readFile)(o,"utf-8"),i=JSON.parse(n).plugins;if(!Array.isArray(i))continue;const a=t.name,l=i.find((e=>e.name===a));if(!(null===(r=null==l?void 0:l.mcpServers)||void 0===r?void 0:r.length))continue;for(const t of l.mcpServers){const r=t.replace(/^\.\//,"");if(!Os(r))continue;const n=(0,s.join)(e,r);try{yield sc(n);const t=Gs(yield ic(n),e);if((null==t?void 0:t.mcpServers)&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,n])));return Object.assign(Object.assign({},t),{mcpServerSourcePaths:e})}}catch(e){}}return null}catch(e){}}return null}))}function Sc(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:Ls(e.command,t)}):"prompt"in e&&"string"==typeof e.prompt?Object.assign(Object.assign({},e),{prompt:Ls(e.prompt,t)}):e)));return Object.assign(Object.assign({},e),{hooks:r})}function kc(e,t,r,n){return nc(this,void 0,void 0,(function*(){if("object"==typeof r){const o=Ec(r,t);return o&&"config"in o?Object.assign({config:Sc(o.config,e)},void 0!==n&&{sourcePath:n}):o}let o,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Os(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 oc(o))return;if(!(yield(0,ho.stat)(o)).isFile())return}catch(e){return}try{yield sc(o),i=yield(0,ho.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=Ec(a,t);return l&&"config"in l?{config:Sc(l.config,e),sourcePath:o}:l}))}function Ec(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 xc(e,t,r,n){return nc(this,void 0,void 0,(function*(){var o,i,s,a,l,c,u,d;const h=yield lc(e),p=null!==(u=yc(r))&&void 0!==u?u:(null==n?void 0:n.configuredVariables)?{configuredVariables:n.configuredVariables}:void 0,[f,m,g]=yield Promise.all([cc(e,null==h?void 0:h.manifestOptions),wc(e,r,p),kc(e,t,null===(o=null==h?void 0:h.manifestOptions)||void 0===o?void 0:o.hooks,null==h?void 0:h.manifestFilePath)]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},f),void 0!==(null===(i=null==h?void 0:h.metadata)||void 0===i?void 0:i.displayName)&&{displayName:h.metadata.displayName}),void 0!==(null===(s=null==h?void 0:h.metadata)||void 0===s?void 0:s.description)&&{description:h.metadata.description}),void 0!==(null===(a=null==h?void 0:h.metadata)||void 0===a?void 0:a.authorName)&&{authorName:h.metadata.authorName}),{variablesSchema:null===(l=null==h?void 0:h.metadata)||void 0===l?void 0:l.variables,mcpConfig:m,capabilities:null!==(d=null===(c=null==h?void 0:h.metadata)||void 0===c?void 0:c.capabilities)&&void 0!==d?d:[],hooks:g})}))}function Cc(e,t){return nc(this,void 0,void 0,(function*(){var r,n,o,i,s,a;const l=yield lc(e),[c,u,d]=yield Promise.all([cc(e,null==l?void 0:l.manifestOptions),bc(e,t),kc(e,t.raw,null===(r=null==l?void 0:l.manifestOptions)||void 0===r?void 0:r.hooks,null==l?void 0:l.manifestFilePath)]),h={source:"claude-plugin",sourceInfo:t};return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:h,installPath:e},void 0!==(null===(n=null==l?void 0:l.metadata)||void 0===n?void 0:n.displayName)&&{displayName:l.metadata.displayName}),void 0!==(null===(o=null==l?void 0:l.metadata)||void 0===o?void 0:o.description)&&{description:l.metadata.description}),void 0!==(null===(i=null==l?void 0:l.metadata)||void 0===i?void 0:i.authorName)&&{authorName:l.metadata.authorName}),c),{mcpConfig:null!=u?u:void 0,capabilities:null!==(a=null===(s=null==l?void 0:l.metadata)||void 0===s?void 0:s.capabilities)&&void 0!==a?a:[],hooks:d})}))}function _c(e,t,r){return nc(this,void 0,void 0,(function*(){const n=`${r.name}@${r.version}`,{displayName:o,description:i,authorName:s,variablesSchema:a,skills:l,rules:c,agents:u,commands:d,mcpConfig:h,capabilities:p,hooks:f}=yield xc(e,n,r),m={source:t,sourceInfo:r};return Object.assign(Object.assign(Object.assign(Object.assign({identifier:m,installPath:e},void 0!==o&&{displayName:o}),void 0!==i&&{description:i}),void 0!==s&&{authorName:s}),{variablesSchema:a,skills:l,rules:c,agents:u,commands:d,mcpConfig:null!=h?h:void 0,capabilities:p,hooks:f})}))}function Pc(e,t){return nc(this,arguments,void 0,(function*(e,t,r={}){var n,o;const i=null!==(n=r.log)&&void 0!==n?n:_i,a=performance.now(),l=yield function(e){return ec(this,void 0,void 0,(function*(){const t=tc(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yield(0,ho.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 ec(this,void 0,void 0,(function*(){const t=tc(e),r=(0,s.join)(t,"settings.json");try{const e=yield(0,ho.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 Bl(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=Bl(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,Gr.PH)(u,(e=>nc(this,void 0,void 0,(function*(){return{workspacePath:e,settings:yield rc(e)}}))),{max:8})),h=[],p=r.onError;for(const{pluginId:e,installPath:t}of d)try{const r=performance.now(),n=Oi(e),o=yield Cc(t,n);h.push(o),i.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(p)try{p(Oi(e),r)}catch(t){p({name:null!==(o=e.split("@")[0])&&void 0!==o?o:e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return i.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-a).toFixed(1)}ms (${d.length} resolved, ${h.length} loaded)`),h}))}Error;function Ic(e){return nc(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:_i,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 la(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,ho.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,ho.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 _c(a,h,p);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:ac(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 Tc(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 Rc(e){var t;return null!==(t=Tc(e))&&void 0!==t?t:`path:${e.installPath}`}function Ac(e,t={}){return Object.assign(Object.assign({},e),{model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools})}(0,s.join)((0,i.homedir)(),".claude","plugins","marketplaces");var Oc=r("node:url");function Mc(e,t){const r=[];for(const o of e){const e=Mi(o.identifier),i=`plugin:${e}`,a=ji(o.identifier),l=Di(o.identifier),c=Ni(o.identifier),u=$i(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}const jc=Ci.z.object({path:Ci.z.string(),name:Ci.z.string().optional(),description:Ci.z.string().optional(),globs:Ci.z.array(Ci.z.string()).optional(),alwaysApply:Ci.z.boolean().optional(),content:Ci.z.string(),environments:Ci.z.array(Ci.z.string()).optional(),disabledEnvironments:Ci.z.array(Ci.z.string()).optional()}),Dc=jc.extend({name:Ci.z.string()}),Nc=Ci.z.object({path:Ci.z.string(),name:Ci.z.string(),description:Ci.z.string().optional(),tools:Ci.z.array(Ci.z.string()).optional(),model:Ci.z.string().optional(),prompt:Ci.z.string(),permissionMode:Ci.z.enum(["default","readonly"]).optional()}),$c=Ci.z.object({path:Ci.z.string(),name:Ci.z.string(),description:Ci.z.string().optional(),argumentHint:Ci.z.string().optional(),content:Ci.z.string()}),Lc=Ci.z.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),Fc=Ci.z.object({config:Lc,sourcePath:Ci.z.string().optional()}),Uc=Ci.z.custom((e=>"object"==typeof e&&null!==e));Ci.z.object({schemaVersion:Ci.z.number().int(),displayName:Ci.z.string().optional(),description:Ci.z.string().optional(),authorName:Ci.z.string().optional(),skills:Ci.z.array(jc),rules:Ci.z.array(Dc),agents:Ci.z.array(Nc),commands:Ci.z.array($c),mcpConfig:Ii.extend({mcpServerSourcePaths:Ci.z.record(Ci.z.string(),Ci.z.string()).optional()}).optional(),hooks:Fc.optional(),hooksError:Ci.z.string().optional(),capabilities:Ci.z.array(Ci.z.string()),variablesSchema:Uc.optional()}),Error;var Bc=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 zc(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 Wc extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function Hc(e){return Bc(this,void 0,void 0,(function*(){try{return yield(0,ho.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 qc(e){return Bc(this,void 0,void 0,(function*(){const t=yield Hc(e);return void 0===t?[]:function(e){const t=function(e){const t=[],r=(0,js.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,js._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Wc(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const n=r;return void 0===n.plugins||"object"==typeof n.plugins&&null!==n.plugins&&!Array.isArray(n.plugins)?n:{}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||zc(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}))}function Gc(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var Vc=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),Jc=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),Kc=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zc=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");const Yc="utf8",Xc="utf8bom",Qc="latin1",eu={"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 tu(e){const t=e.toLowerCase();return"latin-1"===t?Qc:"utf-8"===t?Yc:"utf-8-bom"===t||"utf-8 bom"===t?Xc:t}var ru,nu=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())}))},ou=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)}))}}},iu=function(e){return this instanceof iu?(this.v=e,this):new iu(e)},su=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:iu(e[n](t)),done:!1}:o?o(t):t}:o}};!function(e){e.CRLF="CRLF",e.LF="LF"}(ru||(ru={}));const au=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],lu=new Set(au),cu=new ao.TextDecoder("utf-8",{fatal:!0}),uu=new ao.TextDecoder("latin1"),du=Buffer.from([239,187,191]),hu=new Map,pu=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...au]),fu=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i;function mu(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function gu(e){const t=mu(e);return lu.has(t)}function vu(e){const t=mu(e);return{encoding:"binary",lineEnding:ru.LF,isBinaryFile:!0,isImageFile:fu.test(t),isVideoFile:lu.has(t)}}function yu(e,t){return nu(this,void 0,void 0,(function*(){const r=yield(0,ho.readFile)(e),n=ku(r);if(n.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const o=hu.get(e);let i;i=t||o||n.encoding;const{text:s,encoding:a}=function(e,t){const r=tu(t);if(r===Yc||r===Xc||"ascii"===r){const t=Iu(e);return r===Xc&&t.encoding===Yc?{text:t.text,encoding:Xc}:t}if(r===Qc)return{text:uu.decode(e),encoding:Qc};try{const t=function(e){return eu[e]||e}(r);if(Kc.encodingExists(t))return{text:Kc.decode(e,t),encoding:r}}catch(e){}return Iu(e)}(r,i),l=function(e){return e.startsWith("\ufeff")?e.slice(1):e}(s);return Pu(e,a===Yc&&Tu(r)?Xc:a),n.lineEnding===ru.CRLF?l.replaceAll("\r\n","\n"):l}))}function wu(e,t,r,n){return nu(this,void 0,void 0,(function*(){let o;try{o=r?yield function(e,t){return nu(this,void 0,void 0,(function*(){try{return yield bu(e)}catch(e){}const r=mu(e);if(pu.has(r))return vu(e);try{return yield function(e){return nu(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=ou(Cu(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 bu(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:_u()}))}(t)}catch(e){return _u()}}))}(e,r):yield bu(e)}catch(t){const r=mu(e);o=pu.has(r)?vu(e):_u()}const i=hu.get(e);if(!o.isBinaryFile){let t;t=tu(n||i||o.encoding);const r=t===Xc||t===Yc&&!n&&(yield function(e){return nu(this,void 0,void 0,(function*(){try{return Tu(yield xu(e))}catch(e){return!1}}))}(e));o=Object.assign(Object.assign({},o),{encoding:r?Xc:t}),Pu(e,o.encoding)}const s=Su(t);if(o.lineEnding===ru.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===Xc?Buffer.concat([du,Kc.encode(t,Yc,{defaultEncoding:Yc})]):Kc.encode(t,o.encoding,{defaultEncoding:Yc}),format:o}}))}function bu(e){return nu(this,void 0,void 0,(function*(){const t=ku(yield xu(e));return t.isBinaryFile?Object.assign(Object.assign({},t),{isVideoFile:gu(e)}):Object.assign(Object.assign({},t),{isVideoFile:!1})}))}function Su(e){if(""===e)return 1;let t=1;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}function ku(e){if(0===e.length)return _u();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:Eu(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:Eu(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:ru.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:Eu(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zc.detect(e);let s=i.confidence>.7?i.encoding:"utf-8";return"ascii"===s&&(s="utf-8"),{encoding:null!=s?s:"utf-8",lineEnding:Eu(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Eu(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?ru.LF:t/(t+r)*100>=5?ru.CRLF:ru.LF}function xu(e){return nu(this,void 0,void 0,(function*(){const t=yield(0,ho.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 Cu(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 iu?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 iu((0,ho.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 iu(yield*su(ou(Cu(r))))):n.isFile()&&(yield yield iu(r))}}catch(e){return yield iu(void 0)}}))}function _u(){return{encoding:Yc,lineEnding:"win32"===process.platform?ru.CRLF:ru.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Pu(e,t){if(hu.has(e)&&hu.delete(e),hu.set(e,t),hu.size<=100)return;const r=hu.keys().next().value;void 0!==r&&hu.delete(r)}function Iu(e){try{return{text:cu.decode(e),encoding:Yc}}catch(t){return{text:uu.decode(e),encoding:Qc}}}function Tu(e){return e.length>=du.length&&e[0]===du[0]&&e[1]===du[1]&&e[2]===du[2]}class Ru{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.ttlMs="function"==typeof e?e:Ru.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 Au=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Ou(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{Au(r)}}(),didTimeout:g}}let Mu;function ju({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 Du{constructor(e=()=>function(e=process.env){if(void 0!==Mu)return Mu;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 Ru({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(ju(e))}walk(e,t){const r=ju(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=Ou(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 Nu(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}async function $u(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Lu(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 Fu(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 Uu=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];var Bu=r("../utils/dist/lru-cache.js"),zu=r("../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js");const Wu=[".gitignore",".cursorignore"];async function Hu(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ko.DN)(e);return null===t?null:t}class qu{constructor(e,t,r){this.ignoreServicePromise=Vu.init((0,Qe.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e){return this.ignoreServicePromise.then((t=>t.isCursorIgnored(e)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}}const Gu=Math.min(8,Math.max(1,Math.floor(i.availableParallelism()/2)));class Vu{constructor(e,t,r,n,o){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.gitIgnoreCache=new Bu.q({max:2e3}),this.cursorIgnoreCache=new Bu.q({max:2e3}),this.gitRootCache=new Bu.q({max:1e3}),this.gitRemoteUrlCache=new Bu.q({max:200}),this.hasGitDirCache=new Bu.q({max:1e3}),this.gitParsedIgnoreCache=new Map,this.cursorParsedIgnoreCache=new Map}static getRipwalkCache(){return Vu.ripwalkCache??=new Du,Vu.ripwalkCache}getIgnoreInstance(e,t,r){let n=r.get(e);return n||(n=Ei().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,Gr.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,Gr.PH)(o,(r=>Nu(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([Vu.initializeIgnoreMapping(a,".gitignore",i),Vu.initializeIgnoreMapping(o,".cursorignore",s)]),new Vu(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 Vu.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,ho.access)(n,ho.constants.F_OK);const t=await yu(n),o=Vu.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=Vu.deduplicateRootDirectories(e),o=await Vu.promiseQueue.enqueueList(n,(e=>Vu.findFilesWithRipgrep(e,t))),i=Array.from(o.values()).flat();await Promise.all(i.map((async e=>{try{const t=await yu(e),n=Vu.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 Vu.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:Wu.map((e=>`**/${e}`)),excludeGlobs:Uu,source:"ignore_scan"},i=Vu.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 yu(e),o=Vu.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)=>Ei().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 Vu.promiseQueue.enqueueList(o,(e=>Vu.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,ho.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,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 yu(e),n=Vu.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await yu(e),n=Vu.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,ho.access)((0,s.join)(e,".git"),ho.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 $u((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=Fu(e).toLowerCase(),n=Fu(t).toLowerCase();return this.matchRepoUrlGlob(r,n)}return Fu(e).toLowerCase()===Fu(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return zu(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,ho.access)((0,s.join)(o,".git"),ho.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,ho.access)((0,s.join)(i,".git"),ho.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=Vu.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 $u(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}Vu.promiseQueue=new Gr.TJ({max:Gu});var Ju=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 Ku=[{pattern:/[/\\]\.cursor[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.agents[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.codex[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.cursor[/\\]skills-cursor[/\\]/i,requiresThirdParty:!1}],Zu=/[/\\]\.cursor[/\\]rules[/\\]/i,Yu=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Xu=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Qu(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Xu.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Zu.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Ku)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Yu)if(e.test(r)){if(n&&!t)continue;return"agents"}}class ed{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return ed.ripwalkCache??=new Du,ed.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 Nu(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:Uu,followSymlinks:!0,source:"nested_extensibility"},c={rules:[],skills:[],markdown:[],agents:[]},u=ed.getRipwalkCache();try{const e=u.walk(r.ctx,a);try{for await(const t of e.lines){const e=Qu(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{Ju(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const td=new Set(["node_modules",".git",".svn",".hg","__pycache__",".cache","dist","build",".next",".nuxt"]);async function rd({rootDir:e,includeFile:t,maxDepth:r=10,skipDirectories:n=td,containmentRootDir:o}){const i=[],a=[{dir:e,depth:0}],l=new Set,c=void 0!==o?await(0,ho.realpath)(o):null,u=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;a.length>0;){const e=a.pop();if(void 0===e)continue;const{dir:o,depth:c}=e;if(c>r)continue;try{const e=await(0,ho.realpath)(o);if(!u(e))continue;if(l.has(e))continue;l.add(e)}catch{continue}const d=await(0,ho.readdir)(o,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(o,e.name);let l=e.isDirectory(),u=e.isFile();if(e.isSymbolicLink())try{const e=await(0,ho.stat)(r);l=e.isDirectory(),u=e.isFile()}catch{continue}if(l){if(n.has(e.name))continue;a.push({dir:r,depth:c+1})}else u&&t(e.name)&&i.push(r)}}return i.sort(((e,t)=>e.localeCompare(t))),i}const nd=new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]);function od(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean),r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&nd.has(o)}function id(e){return{dirPath:(0,s.join)(e,".cursor","skills-cursor"),scope:"builtin",source:"builtin"}}function sd(e,t){const r=[];return t&&r.push({dirPath:(0,s.join)(e,".claude","skills"),scope:"project",source:"workspace"},{dirPath:(0,s.join)(e,".codex","skills"),scope:"project",source:"workspace"}),r.push({dirPath:(0,s.join)(e,".agents","skills"),scope:"project",source:"workspace"},{dirPath:(0,s.join)(e,".cursor","skills"),scope:"project",source:"workspace"}),r}function ad(e,t){const r=[];return t&&r.push({dirPath:(0,s.join)(e,".claude","skills"),scope:"user",source:"user"},{dirPath:(0,s.join)(e,".codex","skills"),scope:"user",source:"user"}),r.push({dirPath:(0,s.join)(e,".agents","skills"),scope:"user",source:"user"},{dirPath:(0,s.join)(e,".cursor","skills"),scope:"user",source:"user"}),r}var ld=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},cd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 ud=(0,d.h)("local-exec:cursor-rules");function dd(e){return fd(e.data?.environments??e.data?.metadata?.environments)??[]}function hd(e){return fd(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function pd(e){return fd(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function fd(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 md(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 gd(e){return e.slice(0,1536)}async function vd(e){const t=await yu(e);return{skillFilePath:e,content:t,parsed:Ll(t)}}function yd(e){return!0===e.data?.alwaysApply}function wd({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---`:Fl("",null!==(n=e.data)&&void 0!==n?n:{}).trim()}(e)}(r);if(yd(r))return new Jc.DX({fullPath:e,content:t,frontmatter:n,type:new Jc.f5({type:{case:"global",value:new Jc.i9}}),environments:dd(r),disabledEnvironments:hd(r),scopedTo:pd(r)});const o="string"==typeof r.data?.description?gd(r.data.description):void 0;return o?new Jc.DX({fullPath:e,content:t,frontmatter:n,type:new Jc.f5({type:{case:"agentFetched",value:new Jc.Xo({description:o})}}),environments:dd(r),disabledEnvironments:hd(r),scopedTo:pd(r)}):new Jc.DX({fullPath:e,parseError:"Description is required",frontmatter:n,scopedTo:pd(r),type:new Jc.f5({type:{case:"agentFetched",value:new Jc.Xo}})})}function bd({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?gd(r.data.description):"",o=fc(r.data?.paths??r.data?.globs);return new Vc.N({fullPath:e,content:t,description:n,globs:o??[],parseError:n?void 0:"Description is required",environments:dd(r),disabledEnvironments:hd(r),scopedTo:pd(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function Sd({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jc.DX({fullPath:e,parseError:t,type:new Jc.f5({type:{case:"agentFetched",value:new Jc.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new Vc.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`}))}function kd(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),i=r.indexOf("/.codex/"),s=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+8)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+9)}`:e}function Ed(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function xd(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=Ed(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=Ed(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 Cd{constructor(e){this.cursorRulesServices=e,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=ld(t,(0,l.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,ao.debuglog)("Failed to load cursor rules from service:",e),[]))))),o=(await Promise.all(n)).flat(),i=new Set,s=[];for(const e of o){const t=kd(e.fullPath);i.has(t)||(i.add(t),s.push(e))}return s}catch(e){t.error=e,t.hasError=!0}finally{cd(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()}),Cd.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()}}Cd.CHANGE_COALESCE_MS=1e3;class _d{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 ed(r,t,(0,i.homedir)(),o),this.ignoreService=c??new qu(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{ud.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,ao.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=ld(t,(0,l.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return _d.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{cd(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,ao.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return _d.ripwalkCache??=new Du,_d.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=ld(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,ao.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{cd(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=ld(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 Nu(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=xd(await yu(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{cd(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=ld(r,(0,l.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Nu(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{cd(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{ld(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,ho.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await yu(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{cd(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return ld(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{cd(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jc.i9};else{const r=fc(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jc.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jc.Xo({description:gd(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jc._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 Jc.DX({fullPath:e.path,content:e.body,type:new Jc.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=ld(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{cd(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{ld(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,ho.stat)(e)).isFile()){const t=await yu(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{cd(n)}}async isCursorIgnored(e){try{const t=await Hu((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=ld(r,(0,l.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=xd(await yu(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{cd(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=ld(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{cd(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=ld(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=_d.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{cd(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{ld(r,(0,l.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,ho.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{cd(r)}}}class Pd{constructor(e,t,r,n,o,i,s=()=>!0,a=Promise.resolve(),l="ide",c){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.surface=l,this.fileWatcher=i,this.getThirdPartyExtensibilityEnabled=s,void 0!==c&&c.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${c.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new ed(e,n,r,s))):[],this.foldersToWatch=this.computeFoldersToWatch();const u=performance.now(),d=this.loadAll(e,c).then((t=>{try{ud.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,ao.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=d.then((e=>e.rules)),this._agentSkills=d.then((e=>e.agentSkills)),this.setupWatchers(this.foldersToWatch)}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of sd(r,e))t.add(n.dirPath)}for(const r of ad(this.userHomeDirectory,e))t.add(r.dirPath);return t.add(id(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=ld(t,(0,l.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{cd(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){return await this._rules}reload(e){const t=this.computeFoldersToWatch(),r=new Set(this.foldersToWatch),n=new Set(t),o=this.foldersToWatch.filter((e=>!n.has(e)));this.removeWatchers(o);const i=t.filter((e=>!r.has(e)));this.setupWatchers(i),this.foldersToWatch=t;const s=this.loadAll(e).catch((e=>((0,ao.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=s.then((e=>e.rules)),this._agentSkills=s.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{ld(r,(0,l.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1);const n=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md"),o=vd(n);o.catch((()=>{}));const i=async(e,t)=>{const r=(await e).filter((e=>e.fullPath!==n));if(od(n))return r;try{await(0,ho.stat)(n);const e=await o;if(md(e.parsed,this.surface))return r;const i=t(e);return void 0===i?r:[...r,i]}catch{return r}};this._rules=i(this._rules,(e=>wd(e))).catch((e=>((0,ao.debuglog)("Failed to load Agent Skills at path:",e),[]))),this._agentSkills=i(this._agentSkills,(e=>yd(e.parsed)?void 0:bd(e))).catch((e=>((0,ao.debuglog)("Failed to load Agent Skills (proto) at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{cd(r)}}async getAllAgentSkills(e){return await this._agentSkills}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=ld(r,(0,l.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],i=[],s=new Set,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{(0,ao.debuglog)("cursor-rules-service")("Failed to discover nested agent skills: %O",e)}))))),c=await Promise.all(this.foldersToWatch.map((async e=>{const t=(await async function(e){return await rd({rootDir:e,includeFile:e=>"SKILL.md"===e})}(e)).filter((e=>!od(e)));return Promise.all(t.map((async e=>{try{return await vd(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})))})));for(const e of c)for(const t of e)if(s.add(t.skillFilePath),"error"in t)Sd({rules:o,agentSkills:i,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(md(t.parsed,this.surface))continue;o.push(wd(t)),yd(t.parsed)||i.push(bd(t))}const u=(await a).flatMap((e=>e?.skills??[])).filter((e=>!od(e))),d=[],h=new Set;for(const e of u)s.has(e)||h.has(e)||(h.add(e),d.push(e));const p=await Promise.all(d.map((async e=>{try{return await vd(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})));for(const e of p)if(s.add(e.skillFilePath),"error"in e)Sd({rules:o,agentSkills:i,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(md(e.parsed,this.surface))continue;o.push(wd(e)),yd(e.parsed)||i.push(bd(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{cd(r)}}}function Id(e){let t;switch(e.type){case"global":t=new Jc.f5({type:{case:"global",value:new Jc.i9}});break;case"fileGlobbed":t=new Jc.f5({type:{case:"fileGlobbed",value:new Jc.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jc.f5({type:{case:"agentFetched",value:new Jc.Xo({description:gd(e.description??"")})}});break;case"manuallyAttached":t=new Jc.f5({type:{case:"manuallyAttached",value:new Jc._u}});break;default:e.type,t=new Jc.f5({type:{case:"manuallyAttached",value:new Jc._u}})}return new Jc.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 Td{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{ud.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,ao.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,ao.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=ld(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 Mc(e,(e=>e.skills))}(e),a=function(e){return Mc(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(Id(e));for(const t of e){const e=`plugin:${Mi(t.identifier)}`,r=ji(t.identifier),n=Di(t.identifier),o=Ni(t.identifier),a=$i(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===Ll(l.content).data?.["disable-model-invocation"]}catch{}i.push(new Vc.N({fullPath:(0,s.join)(t.installPath,l.path),content:l.content,description:gd(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{cd(r)}}}var Rd=r("../proto/dist/generated/agent/v1/subagents_pb.js");const Ad=(0,ao.debuglog)("local-subagents");class Od{async getAllSubagents(){return[]}async reload(){return[]}}function Md(e){return"true"===(e??"").trim().toLowerCase()}function jd(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=Md(o["force-default-model"]),c="true"===(o.readonly??"").trim().toLowerCase()?Rd.b$.READONLY:Rd.b$.DEFAULT,u=Md(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 Dd(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Nd(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function $d(e,t){return await rd({rootDir:e,includeFile:Dd,containmentRootDir:t})}class Ld{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=>(Ad("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(Ad("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 $d(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,ho.stat)(r)).isFile())continue}catch(e){Ad("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=jd(await yu(r));if(!o)continue;t.push(new Rd.zz({fullPath:r,name:o.name||Nd(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){Ad("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Fd=new Set(["claude-code-tutor"]);class Ud{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(Ad("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Fd.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 Bd{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&&(Ad("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=ji(o.identifier),i=Di(o.identifier),a=Ni(o.identifier),l=$i(o.identifier);for(const c of o.agents){const u=Ac(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?Rd.b$.READONLY:Rd.b$.DEFAULT;t.push(new Rd.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 zd=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");function Wd(e,t,r){return new Promise(((n,o)=>{const i={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0};(0,io.execFile)(e,t.map(String),{...i,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}zd.w3.UNSPECIFIED,zd.w3.LEFT,zd.w3.MIDDLE,zd.w3.RIGHT,zd.w3.BACK,zd.w3.FORWARD,zd.Dh.UNSPECIFIED,zd.Dh.UP,zd.Dh.DOWN,zd.Dh.LEFT,zd.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,d.h)("computer-use");const Hd=(0,ao.promisify)(io.execFile);function qd(e,t){const r=e/t;return{display:{width:e,height:t},api:{width:1280,height:Math.round(1280/r)}}}async function Gd(e){const{stdout:t}=await Hd("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:qd(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}var Vd,Jd,Kd,Zd,Yd;!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"}(Vd||(Vd={})),hr.proto3.util.setEnumType(Vd,"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"}(Jd||(Jd={})),hr.proto3.util.setEnumType(Jd,"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"}(Kd||(Kd={})),hr.proto3.util.setEnumType(Kd,"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"}(Zd||(Zd={})),hr.proto3.util.setEnumType(Zd,"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"}(Yd||(Yd={})),hr.proto3.util.setEnumType(Yd,"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 Xd extends hr.Message{constructor(e){super(),this.executionTimestampMs=hr.protoInt64.zero,this.commandDurationMs=hr.protoInt64.zero,this.cursorTypeAfter=Vd.UNSPECIFIED,hr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Xd).fromBinary(e,t)}static fromJson(e,t){return(new Xd).fromJson(e,t)}static fromJsonString(e,t){return(new Xd).fromJsonString(e,t)}static equals(e,t){return hr.proto3.util.equals(Xd,e,t)}}Xd.runtime=hr.proto3,Xd.typeName="agent.v1.InputEvent",Xd.fields=hr.proto3.util.newFieldList((()=>[{no:1,name:"execution_timestamp_ms",kind:"scalar",T:3},{no:2,name:"action",kind:"message",T:zd.ho},{no:3,name:"command_duration_ms",kind:"scalar",T:3},{no:4,name:"position_before",kind:"message",T:zd.xp},{no:5,name:"position_after",kind:"message",T:zd.xp},{no:6,name:"cursor_type_after",kind:"enum",T:hr.proto3.getEnumType(Vd)}]));class Qd extends hr.Message{constructor(e){super(),this.videoTimestampMs=hr.protoInt64.zero,this.x=0,this.y=0,this.cursorType=Vd.UNSPECIFIED,this.velocity=0,hr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Qd).fromBinary(e,t)}static fromJson(e,t){return(new Qd).fromJson(e,t)}static fromJsonString(e,t){return(new Qd).fromJsonString(e,t)}static equals(e,t){return hr.proto3.util.equals(Qd,e,t)}}Qd.runtime=hr.proto3,Qd.typeName="agent.v1.CursorPathKeyframe",Qd.fields=hr.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:hr.proto3.getEnumType(Vd)},{no:5,name:"velocity",kind:"scalar",T:2}]));class eh extends hr.Message{constructor(e){super(),this.style=Jd.UNSPECIFIED,this.keyframes=[],hr.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 hr.proto3.util.equals(eh,e,t)}}eh.runtime=hr.proto3,eh.typeName="agent.v1.CursorPath",eh.fields=hr.proto3.util.newFieldList((()=>[{no:1,name:"style",kind:"enum",T:hr.proto3.getEnumType(Jd)},{no:2,name:"keyframes",kind:"message",T:Qd,repeated:!0}]));class th extends hr.Message{constructor(e){super(),this.startMs=hr.protoInt64.zero,this.endMs=hr.protoInt64.zero,this.centerX=0,this.centerY=0,this.suggestedZoom=0,this.actionType="",this.actionIndex=0,this.importanceScore=0,this.context="",hr.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 hr.proto3.util.equals(th,e,t)}}th.runtime=hr.proto3,th.typeName="agent.v1.ZoomCandidate",th.fields=hr.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 rh extends hr.Message{constructor(e){super(),this.startMs=hr.protoInt64.zero,this.endMs=hr.protoInt64.zero,this.durationMs=hr.protoInt64.zero,this.classification=Kd.UNSPECIFIED,this.suggestedSpeed=0,this.precedingActionType="",this.followingActionType="",hr.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 hr.proto3.util.equals(rh,e,t)}}rh.runtime=hr.proto3,rh.typeName="agent.v1.IdlePeriod",rh.fields=hr.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:hr.proto3.getEnumType(Kd)},{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 nh extends hr.Message{constructor(e){super(),this.videoTimestampMs=hr.protoInt64.zero,this.x=0,this.y=0,this.clickType=Zd.UNSPECIFIED,this.actionIndex=0,this.hasModifiers=!1,hr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new nh).fromBinary(e,t)}static fromJson(e,t){return(new nh).fromJson(e,t)}static fromJsonString(e,t){return(new nh).fromJsonString(e,t)}static equals(e,t){return hr.proto3.util.equals(nh,e,t)}}nh.runtime=hr.proto3,nh.typeName="agent.v1.ClickEffectKeyframe",nh.fields=hr.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:hr.proto3.getEnumType(Zd)},{no:5,name:"action_index",kind:"scalar",T:5},{no:6,name:"has_modifiers",kind:"scalar",T:8}]));class oh extends hr.Message{constructor(e){super(),this.videoTimestampMs=hr.protoInt64.zero,this.displayText="",this.eventType=Yd.UNSPECIFIED,this.displayDurationMs=hr.protoInt64.zero,this.actionIndex=0,hr.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 hr.proto3.util.equals(oh,e,t)}}oh.runtime=hr.proto3,oh.typeName="agent.v1.KeystrokeEvent",oh.fields=hr.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:hr.proto3.getEnumType(Yd)},{no:4,name:"display_duration_ms",kind:"scalar",T:3},{no:5,name:"action_index",kind:"scalar",T:5}]));class ih extends hr.Message{constructor(e){super(),this.videoPath="",this.videoDurationMs=hr.protoInt64.zero,this.videoWidth=0,this.videoHeight=0,this.actionCount=0,this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.cursorPaths=[],hr.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 hr.proto3.util.equals(ih,e,t)}}ih.runtime=hr.proto3,ih.typeName="agent.v1.DecisionInput",ih.fields=hr.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:th,repeated:!0},{no:11,name:"idle_periods",kind:"message",T:rh,repeated:!0},{no:12,name:"click_effects",kind:"message",T:nh,repeated:!0},{no:13,name:"keystroke_events",kind:"message",T:oh,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:eh,repeated:!0}]));class sh extends hr.Message{constructor(e){super(),this.candidateIndex=0,hr.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 hr.proto3.util.equals(sh,e,t)}}sh.runtime=hr.proto3,sh.typeName="agent.v1.ZoomSelection",sh.fields=hr.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 ah extends hr.Message{constructor(e){super(),this.candidateIndex=0,hr.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 hr.proto3.util.equals(ah,e,t)}}ah.runtime=hr.proto3,ah.typeName="agent.v1.SpeedupSelection",ah.fields=hr.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"speed_override",kind:"scalar",T:2,opt:!0}]));class lh extends hr.Message{constructor(e){super(),this.cursorStyle=Jd.UNSPECIFIED,this.selectedZooms=[],this.selectedSpeedups=[],this.showClickEffects=!1,this.selectedClickEffects=[],this.showKeystrokes=!1,this.cuts=[],hr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new lh).fromBinary(e,t)}static fromJson(e,t){return(new lh).fromJson(e,t)}static fromJsonString(e,t){return(new lh).fromJsonString(e,t)}static equals(e,t){return hr.proto3.util.equals(lh,e,t)}}lh.runtime=hr.proto3,lh.typeName="agent.v1.DecisionOutput",lh.fields=hr.proto3.util.newFieldList((()=>[{no:1,name:"cursor_style",kind:"enum",T:hr.proto3.getEnumType(Jd)},{no:2,name:"selected_zooms",kind:"message",T:sh,repeated:!0},{no:3,name:"selected_speedups",kind:"message",T:ah,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:ch,repeated:!0}]));class ch extends hr.Message{constructor(e){super(),this.startMs=hr.protoInt64.zero,this.endMs=hr.protoInt64.zero,this.reason="",hr.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 hr.proto3.util.equals(ch,e,t)}}ch.runtime=hr.proto3,ch.typeName="agent.v1.VideoCut",ch.fields=hr.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 uh extends hr.Message{constructor(e){super(),this.rawVideoPath="",this.durationMs=hr.protoInt64.zero,this.displayWidth=0,this.displayHeight=0,this.apiWidth=0,this.apiHeight=0,this.recordingStartEpochMs=hr.protoInt64.zero,this.inputEvents=[],this.cursorPaths=[],this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.polishedVideoPath="",hr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new uh).fromBinary(e,t)}static fromJson(e,t){return(new uh).fromJson(e,t)}static fromJsonString(e,t){return(new uh).fromJsonString(e,t)}static equals(e,t){return hr.proto3.util.equals(uh,e,t)}}uh.runtime=hr.proto3,uh.typeName="agent.v1.RecordingDataPackage",uh.fields=hr.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:Xd,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:eh,repeated:!0},{no:30,name:"zoom_candidates",kind:"message",T:th,repeated:!0},{no:31,name:"idle_periods",kind:"message",T:rh,repeated:!0},{no:32,name:"click_effects",kind:"message",T:nh,repeated:!0},{no:33,name:"keystroke_events",kind:"message",T:oh,repeated:!0},{no:40,name:"decision_input",kind:"message",T:ih},{no:41,name:"decision_output",kind:"message",T:lh},{no:50,name:"polished_video_path",kind:"scalar",T:9}]));class dh{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 hh={left_ptr:Vd.ARROW,arrow:Vd.ARROW,default:Vd.ARROW,top_left_arrow:Vd.ARROW,hand:Vd.POINTER,hand1:Vd.POINTER,hand2:Vd.POINTER,pointer:Vd.POINTER,pointing_hand:Vd.POINTER,xterm:Vd.TEXT,ibeam:Vd.TEXT,text:Vd.TEXT,watch:Vd.WAIT,wait:Vd.WAIT,progress:Vd.WAIT,left_ptr_watch:Vd.WAIT,crosshair:Vd.CROSSHAIR,cross:Vd.CROSSHAIR,tcross:Vd.CROSSHAIR,move:Vd.MOVE,fleur:Vd.MOVE,size_all:Vd.MOVE,sb_v_double_arrow:Vd.RESIZE_NS,v_double_arrow:Vd.RESIZE_NS,ns_resize:Vd.RESIZE_NS,row_resize:Vd.RESIZE_NS,top_side:Vd.RESIZE_NS,bottom_side:Vd.RESIZE_NS,sb_h_double_arrow:Vd.RESIZE_EW,h_double_arrow:Vd.RESIZE_EW,ew_resize:Vd.RESIZE_EW,col_resize:Vd.RESIZE_EW,left_side:Vd.RESIZE_EW,right_side:Vd.RESIZE_EW,top_left_corner:Vd.RESIZE_NWSE,bottom_right_corner:Vd.RESIZE_NWSE,nwse_resize:Vd.RESIZE_NWSE,size_fdiag:Vd.RESIZE_NWSE,top_right_corner:Vd.RESIZE_NESW,bottom_left_corner:Vd.RESIZE_NESW,nesw_resize:Vd.RESIZE_NESW,size_bdiag:Vd.RESIZE_NESW,not_allowed:Vd.NOT_ALLOWED,no_drop:Vd.NOT_ALLOWED,forbidden:Vd.NOT_ALLOWED,circle:Vd.NOT_ALLOWED,grab:Vd.GRAB,openhand:Vd.GRAB,grabbing:Vd.GRABBING,closedhand:Vd.GRABBING};class ph{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 dh(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=Vd.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 Wd("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 Wd("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return hh[t]??Vd.ARROW}try{const e=await Wd("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(hh))if(e.toLowerCase().includes(t))return r}catch{}return Vd.ARROW}catch{return Vd.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 fh=1048576,mh=52428800;var gh;!function(e){e.Write="write",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(gh||(gh={}));var vh=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 yh{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 ni(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:gh.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,ho.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<=mh)try{u=await yu(o)}catch{}const d=u??"";try{await(0,ho.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{vh(r)}}}class wh{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 dr.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 bh extends wh{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Sh=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),kh=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 Eh{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 Sh.uN({result:{case:"success",value:new Sh.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Sh.uN({result:{case:"error",value:new Sh.fk({url:n,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{kh(r)}}}class xh{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,ho.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 nu(this,void 0,void 0,(function*(){const{buffer:o}=yield wu(e,t,r,n);yield(0,ho.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 Ch=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 _h{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 ma("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{Ch(o)}}}var Ph=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const Ih=-(2**31),Th=2**31-1;function Rh(e){return Number.isNaN(e)?0:e<Ih?Ih:e>Th?Th:e}function Ah(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Rh(Math.trunc(e))}const Oh="agent-tools",Mh=52428800;var jh=r("../mcp-core/dist/index.js"),Dh=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())}))},Nh=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 $h extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Lh extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class Fh{constructor(e){this.disabledService=e}load(e,t,r,n,o){return Dh(this,void 0,void 0,(function*(){if(yield this.disabledService.isServerDisabled(t))throw new $h(t);return yield o(e,r)}))}}class Uh{constructor(e){this.approvalService=e}load(e,t,r,n,o){return Dh(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 Lh(t);return yield o(e,r)}catch(e){i.error=e,i.hasError=!0}finally{Nh(i)}}))}}class Bh{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}isServerApproved(e,t,r){return Dh(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 Dh(this,void 0,void 0,(function*(){try{const e=yield(0,ho.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 Dh(this,void 0,void 0,(function*(){return this.approvalsPromise}))}addApproval(e){return Dh(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise;t.includes(e)||(t.push(e),yield this.saveApprovals(t))}))}addApprovals(e){return Dh(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 Dh(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 Dh(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 Dh(this,void 0,void 0,(function*(){yield(0,ho.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),yield(0,ho.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}))}saveApprovals(e){return Dh(this,void 0,void 0,(function*(){yield this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}))}}var zh=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())}))},Wh=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},Hh=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 qh{load(e,t,r,n,o){return zh(this,void 0,void 0,(function*(){const n=o(e,r);return new Vh(e,t,n,r)}))}}function Gh(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Vh{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=>zh(this,void 0,void 0,(function*(){return null===t?[]:yield t.getTools(e)})))),this.resourcesPromise=this.clientPromise.then((t=>zh(this,void 0,void 0,(function*(){return null===t?[]:(yield t.listResources(e)).resources})))),this.promptsPromise=this.clientPromise.then((t=>zh(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 zh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Wh(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=Gh(this.toolsPromise);return void 0!==o?o:yield this.toolsPromise}catch(e){r.error=e,r.hasError=!0}finally{Hh(r)}}))}callTool(e,t,r,n,o){return zh(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const s=Wh(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{Hh(i)}}))}getInstructions(e){return zh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Wh(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{Hh(t)}}))}getClient(e){return zh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Wh(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{Hh(r)}}))}listResources(e){return zh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Wh(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=Gh(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:yield this.resourcesPromise}}catch(e){r.error=e,r.hasError=!0}finally{Hh(r)}}))}readResource(e,t){return zh(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=Wh(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{Hh(r)}}))}listPrompts(e){return zh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Wh(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=Gh(this.promptsPromise);return void 0!==o?o:yield this.promptsPromise}catch(e){r.error=e,r.hasError=!0}finally{Hh(r)}}))}getPrompt(e,t,r){return zh(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=Wh(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{Hh(n)}}))}getState(e){return zh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Wh(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{Hh(t)}}))}close(){return zh(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 Jh(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 Kh=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Zh(e,t){if("string"==typeof e)return function(e,t){return e.replace(Kh,((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=>Zh(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Zh(o,t);return r}return e}const Yh=Ci.z.object({type:Ci.z.literal("stdio").optional(),command:Ci.z.string(),args:Ci.z.array(Ci.z.string()).optional(),env:Ci.z.record(Ci.z.string(),Ci.z.string()).optional(),cwd:Ci.z.string().optional()}),Xh=Ci.z.object({CLIENT_ID:Ci.z.string(),CLIENT_SECRET:Ci.z.string().optional(),scopes:Ci.z.array(Ci.z.string()).optional()}),Qh=Ci.z.object({caBundle:Ci.z.string().trim().min(1).max(131072)}).strict(),ep=Ci.z.object({type:Ci.z.enum(["http","sse"]).optional(),url:Ci.z.string(),headers:Ci.z.record(Ci.z.string(),Ci.z.string()).optional(),auth:Xh.optional(),tls:Qh.optional()}),tp=Ci.z.union([Yh,ep]),rp=Ci.z.object({mcpServers:Ci.z.record(Ci.z.string(),tp)});function np(e){return t=this,r=arguments,o=function*(e,t=e=>process.env[e]){try{const r=yield(0,ho.readFile)(e,"utf8"),n=Zh((0,js.qg)(r),t);return rp.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 op=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");const ip={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"consent"}},sp=new Map([["gmailmcp.googleapis.com",Object.assign(Object.assign({},ip),{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({},ip),{scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]})],["calendarmcp.googleapis.com",Object.assign(Object.assign({},ip),{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({},ip),{scopes:["https://www.googleapis.com/auth/documents"]})],["sheetsmcp.googleapis.com",Object.assign(Object.assign({},ip),{scopes:["https://www.googleapis.com/auth/spreadsheets"]})],["slidesmcp.googleapis.com",Object.assign(Object.assign({},ip),{scopes:["https://www.googleapis.com/auth/presentations"]})]]);new Set([...sp].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e)));const ap=["cursor"],lp="http://localhost:8787/callback";function cp(e){return`${e}://anysphere.cursor-mcp/oauth/callback`}function up(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([...ap])).map(cp))t.add(e);return t.add("https://www.cursor.com/agents/mcp/oauth/callback"),t.add(lp),e&&r&&t.add(e),Array.from(t)}function dp(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,so.writeFileSync)(`/proc/${e}/oom_score_adj`,"0")}catch(e){}}var hp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),pp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),fp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),vp=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const yp="mcpStdioStderrTail";function wp(e){if(!(e instanceof Error))return;const t=e[yp];return"string"==typeof t?t:void 0}var bp=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())}))},Sp=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},kp=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 Ep=["authorization_code","refresh_token"],xp=["code"];class Cp{constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,o.randomUUID)(),this._oauthState=function(e,t,r){const n=Object.assign({id:e,owner:t},r?{attemptId:r}:{});return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}saveClientInformation(e){return bp(this,void 0,void 0,(function*(){this._clientInformation=e,yield this._saveClientInformation(e)}))}tokens(){return this._tokens}saveTokens(e){return bp(this,void 0,void 0,(function*(){this._tokens=e,yield this._saveTokens(e)}))}prepareForRefresh(){return bp(this,void 0,void 0,(function*(){var e;yield null===(e=this._prepareForRefresh)||void 0===e?void 0:e.call(this)}))}releaseRefreshLeaseOnError(e){return bp(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 bp(this,void 0,void 0,(function*(){var t;switch(e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0;break;default:return e}yield null===(t=this._invalidateCredentials)||void 0===t?void 0:t.call(this,e)}))}redirectToAuthorization(e){(0,jh.E_S)(e,this._scopes),void 0!==this._serverUrl&&function(e,t){var r;let n;try{n=new URL(t).hostname}catch(e){return}const o=null===(r=function(e){return sp.get(e.toLowerCase())}(n))||void 0===r?void 0:r.authorizationParams;if(void 0!==o)for(const[t,r]of Object.entries(o))e.searchParams.set(t,r)}(e,this._serverUrl),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}saveCodeVerifier(e){return bp(this,void 0,void 0,(function*(){this._codeVerifier=e}))}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}function _p(e){return bp(this,void 0,void 0,(function*(){var t;const{serverName:r,config:n,tokenStorage:o,authRedirectUrl:i}=e,s=function(e,t){if(e)return Object.assign(Object.assign({client_id:e.CLIENT_ID},e.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{}),{redirect_uris:up(t),grant_types:[...Ep],response_types:[...xp],token_endpoint_auth_method:"none"})}(n.auth,i),a=function({storedClientInformation:e,staticClientInformation:t}){var r,n,o,i;return t?e&&e.client_id===t.client_id?Object.assign(Object.assign(Object.assign({},t),e),{client_secret:null!==(r=t.client_secret)&&void 0!==r?r:e.client_secret,redirect_uris:t.redirect_uris,grant_types:null!==(n=e.grant_types)&&void 0!==n?n:t.grant_types,response_types:null!==(o=e.response_types)&&void 0!==o?o:t.response_types,token_endpoint_auth_method:null!==(i=e.token_endpoint_auth_method)&&void 0!==i?i:t.token_endpoint_auth_method}):t:e}({storedClientInformation:yield o.loadClientInformation(),staticClientInformation:s});return new Cp({identifier:r,redirectUrl:i,serverUrl:n.url,clientMetadata:{redirect_uris:up(i),token_endpoint_auth_method:"none",grant_types:[...Ep],response_types:[...xp],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:null===(t=n.auth)||void 0===t?void 0:t.scopes,tokens:yield o.loadTokens(),clientInformation:a,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>{var e,t;return null!==(t=null===(e=o.prepareForRefresh)||void 0===e?void 0:e.call(o))&&void 0!==t?t:Promise.resolve()},releaseRefreshLeaseOnError:e=>{var t,r;return null!==(r=null===(t=o.releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(o,e))&&void 0!==r?r:Promise.resolve()},invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e)})}))}const Pp=new Set;let Ip=!1;function Tp(){for(const e of Pp)try{process.kill(e,"SIGKILL")}catch(e){}}class Rp{constructor(e,t,r){this._callToolLock=Promise.resolve(),this._stateEnteredAtMs=Date.now(),this.serverName=e,this.client=t,this.tools=new jh.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,jh.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 pp.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}setupElicitationHandler(){this.client.setRequestHandler(vp.$9,(e=>bp(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 bp(this,void 0,void 0,(function*(){const l=new URL(t.url);o=null!=o?o:lp;const c=yield r.loadTokens(),u=yield _p({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o}),d=null!=i?i:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=e=>void 0===d||void 0===s?d:(0,jh.jIB)({fetch:d,logger:s.logger,metadata:Object.assign(Object.assign({},s.metadata),{transportType:e})}),p=Rp.createClient(),f=r=>{var n,o,i;const s=null!==(i=null===(o=null===(n=u.lastRedirectUrl)||void 0===n?void 0:n.toString)||void 0===o?void 0:o.call(n))&&void 0!==i?i:"",c=new Rp(e,p,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:s,callback:t=>bp(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,hp.j2)(u,Object.assign({serverUrl:l.toString(),authorizationCode:t},void 0!==d?{fetchFn:d}:{})),a&&(0,jh.VDJ)({logger:a,event:"mcp_oauth_callback_completion",metadata:Object.assign(Object.assign({identifier:e},(0,jh.q2e)(l.toString())),(0,jh.tBH)(u.tokens(),{expiresInIsFresh:!0}))}),c.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}))},authProvider:u,sessionId:r,config:t});return c},m=()=>bp(this,void 0,void 0,(function*(){const r=new fp.A(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=n?n:{})},fetch:h("sse")});try{return yield p.connect(r),new Rp(e,p,{initialState:{kind:"ready"},authProvider:u,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof hp.D_)return a&&(0,jh.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,jh.q2e)(l.toString())),(0,jh.X5z)(t))}),f();throw t}}));if("sse"===t.type)return m();const g=new gp.j(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=n?n:{})},fetch:h("streamableHttp")});try{return yield p.connect(g),new Rp(e,p,{initialState:{kind:"ready"},authProvider:u,sessionId:g.sessionId,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof hp.D_)return a&&(0,jh.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,jh.q2e)(l.toString())),(0,jh.X5z)(t))}),f(g.sessionId);if((0,jh.PKk)(t))return m();throw t}}))}static fromCachedSession(e,t,r,n,o){return bp(this,arguments,void 0,(function*(e,t,r,n,o,i=lp,s,a,l){const c=new URL(t.url),u=yield _p({serverName:e,config:t,tokenStorage:n,authRedirectUrl:i}),d=null!=s?s:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=new gp.j(c,{authProvider:u,sessionId:r.sessionId,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:void 0!==d&&void 0!==a?(0,jh.jIB)({fetch:d,logger:a.logger,metadata:Object.assign(Object.assign({},a.metadata),{transportType:"streamableHttp"})}):d}),p=Rp.createClient();return yield p.connect(h),new Rp(e,p,{initialState:{kind:"ready"},authProvider:u,sessionId:h.sessionId,config:t,oauthLifecycleLogger:l})}))}get sessionId(){return this._sessionId}static fromCommand(e,t,r,n,o){return bp(this,void 0,void 0,(function*(){var i,s,a;const c={stack:[],error:void 0,hasError:!1};try{Sp(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,io.spawn)(e,t,r);return(e,r,n)=>{const o=t(e,r,n);return dp(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=jh.uOd-t.length;r<=0||(t+=e.toString().slice(0,r))})),e.once("end",(()=>{r=!0}))),{read:()=>(0,jh.eaG)(t.replace(/\s+/g," ").trim(),{maxLength:jh.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=Rp.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,yp,{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,Pp.add(u),Ip||(Ip=!0,process.on("exit",Tp))),new Rp(t,f,{initialState:{kind:"ready"},config:r,stdioChildPid:w})}catch(e){c.error=e,c.hasError=!0}finally{kp(c)}var u}))}close(){return bp(this,void 0,void 0,(function*(){var e;void 0!==this._stdioChildPid&&(e=this._stdioChildPid,Pp.delete(e)),yield this.client.close()}))}getTools(e){return bp(this,void 0,void 0,(function*(){var t,r,n;const o={stack:[],error:void 0,hasError:!1};try{if(Sp(o,(0,l.VI)(e.withName("McpSdkClient.getTools")),!1),"requires_authentication"===this.stateValue.kind)return[];try{return yield this.tools.get((()=>bp(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 hp.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=>bp(this,void 0,void 0,(function*(){}))},this._logStateTransition(o,this.stateValue,"runtime_unauthorized",Object.assign({},(0,jh.X5z)(e))),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){o.error=e,o.hasError=!0}finally{kp(o)}}))}callTool(e,t,r,n,o){return bp(this,void 0,void 0,(function*(){var i,s,a;const c={stack:[],error:void 0,hasError:!1};try{Sp(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:void 0!==e.error}}catch(e){if(e instanceof hp.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=>bp(this,void 0,void 0,(function*(){}))},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",Object.assign({},(0,jh.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{kp(c)}}))}getInstructions(e){return bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(Sp(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{kp(t)}}))}listResources(e){return bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(Sp(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{kp(t)}}))}readResource(e,t){return bp(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{return Sp(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{kp(r)}}))}listPrompts(e){return bp(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{if(Sp(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{kp(r)}}))}getPrompt(e,t,r){return bp(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{return Sp(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{kp(n)}}))}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}getState(e){return bp(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 Ap extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}class Op 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 Mp{constructor(e){this.tools=e}execute(e,t,r,n){return bp(this,void 0,void 0,(function*(){const o=this.tools[e];if(!o)throw new Ap(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 jp{getClients(e){return bp(this,void 0,void 0,(function*(){return{}}))}getClient(e,t){return bp(this,void 0,void 0,(function*(){}))}getInstructions(e){return bp(this,void 0,void 0,(function*(){return[]}))}getToolSet(e){return bp(this,void 0,void 0,(function*(){return new Mp({})}))}getTools(e){return bp(this,void 0,void 0,(function*(){return[]}))}getToolsForServers(e,t){return bp(this,void 0,void 0,(function*(){return[]}))}}class Dp{constructor(e){this.manager=e}getClients(e){return bp(this,void 0,void 0,(function*(){return this.manager.getClients()}))}getClient(e,t){return bp(this,void 0,void 0,(function*(){return this.manager.getClient(t)}))}getInstructions(e){return bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Sp(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{kp(t)}}))}getToolSet(e){return bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Sp(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{kp(t)}}))}getTools(e){return bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Sp(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{kp(t)}}))}getToolsForServers(e,t){return bp(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 bp(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 Np{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 bp(this,void 0,void 0,(function*(){const e=Object.values(this.clients);yield Promise.all(e.map((e=>bp(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 bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Sp(t,(0,l.VI)(e.withName("McpManager.getToolSet")),!1),n=yield(0,Gr.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)=>bp(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 Mp(i)}catch(e){t.error=e,t.hasError=!0}finally{kp(t)}}))}getInstructions(e){return bp(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Sp(t,(0,l.VI)(e.withName("McpManager.getInstructions")),!1),n=yield(0,Gr.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new dr.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{kp(t)}}))}}Error;var $p=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 Lp(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 Fp{constructor(e){this.options=e,(0,jh.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,jh.q2e)(this.options.serverUrl)}:{})}loadTokens(){return $p(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadTokens();return(0,jh.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,jh.tBH)(e))}),e}))}saveTokens(e){return $p(this,void 0,void 0,(function*(){yield this.options.inner.saveTokens(e),(0,jh.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,jh.tBH)(e,{expiresInIsFresh:!0}))})}))}prepareForRefresh(){return $p(this,void 0,void 0,(function*(){var e,t;(0,jh.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 $p(this,void 0,void 0,(function*(){var t,r;(0,jh.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:Object.assign(Object.assign({},this.baseMetadata),(0,jh.X5z)(e))}),yield null===(r=(t=this.options.inner).releaseRefreshLeaseOnError)||void 0===r?void 0:r.call(t,e)}))}loadClientInformation(){return $p(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadClientInformation();return(0,jh.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,jh.O3I)(e))}),e}))}saveClientInformation(e){return $p(this,void 0,void 0,(function*(){yield this.options.inner.saveClientInformation(e),(0,jh.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,jh.O3I)(e))})}))}invalidateCredentials(e){return $p(this,void 0,void 0,(function*(){void 0!==this.options.inner.invalidateCredentials&&((0,jh.VDJ)({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:Object.assign(Object.assign({},this.baseMetadata),{scope:e})}),yield this.options.inner.invalidateCredentials(e))}))}}class Up{constructor(e,t){this.storage=e,this.identifier=t}loadTokens(){return $p(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.identifier)}))}saveTokens(e){return $p(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.identifier,e)}))}loadClientInformation(){return $p(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.identifier)}))}saveClientInformation(e){return $p(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.identifier,e)}))}}class Bp{constructor(e){this.inner=e}loadTokens(){return $p(this,void 0,void 0,(function*(){}))}loadClientInformation(){return $p(this,void 0,void 0,(function*(){}))}saveTokens(e){return $p(this,void 0,void 0,(function*(){return this.inner.saveTokens(e)}))}saveClientInformation(e){return $p(this,void 0,void 0,(function*(){return this.inner.saveClientInformation(e)}))}invalidateCredentials(e){return $p(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 zp=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())}))},Wp=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},Hp=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 qp=(0,d.h)("DefinitionMcpLoader");function Gp(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 Vp(e){return"function"==typeof e.getMcpNetworkControlsConfig}function Jp(e){var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0}function Kp(e){if(void 0!==e)return(0,o.createHash)("sha256").update((0,jh.Fmf)(e)).digest("hex")}class Zp{constructor(e){this.configPath=e,this.configPromise=np(e)}clearCache(){this.configPromise=np(this.configPath)}getDefinitions(e){return zp(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 Yp{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}load(e){return zp(this,arguments,void 0,(function*(e,t=!0){var r,n,o;const i={stack:[],error:void 0,hasError:!1};try{Wp(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,Gr.PH)([...s],(r=>zp(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){qp.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:wp(r)})}(e,r,t)}}))),{max:null!==(o=this.options.maxConcurrency)&&void 0!==o?o:Math.max(s.length,1)}),new Np(a,this.options.elicitationFactory)}catch(e){i.error=e,i.hasError=!0}finally{Hp(i)}}))}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}evictClientsOnSandboxPolicyChange(e,t){return zp(this,void 0,void 0,(function*(){const r=this.middlewares.find(Vp);if(!r)return;let n;try{n=JSON.stringify(yield Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((e=>zp(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,jh.Fmf)(o)]}))))))}catch(e){return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(qp.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),yield this.closeAllCachedClients())}))}closeAllCachedClients(){return zp(this,void 0,void 0,(function*(){const e=[...this.clientCache.values()];this.clientCache.clear(),yield(0,Gr.PH)(e,(e=>zp(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 zp(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{Wp(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{Hp(n)}}))}loadDefinitionClient(e,t,n){return zp(this,void 0,void 0,(function*(){var o,i;const s=null!==(o=t.authStorageKey)&&void 0!==o?o:t.identifier,a=new Up(this.tokenStorage,s),c=Lp(e,qp),u=new Fp({inner:a,logger:c,identifier:s,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),d=n?new Bp(u):u;return function(e,t,n,o){return zp(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=Wp(a,(0,l.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let h=(e,n)=>zp(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const a=Wp(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(Vp);return yield function(e,t,n,o){return zp(this,void 0,void 0,(function*(){var i,s,a;const l=n.cwd?Gp({filePath:n.cwd}):void 0;let c,u;if(n.args&&n.args.length>0)c=Gp({filePath:n.command,baseDir:l}),u=n.args.map((e=>Gp({filePath:e,baseDir:l})));else{const e=(0,op.A)(n.command);c=Gp({filePath:e[0],baseDir:l}),u=e.slice(1).map((e=>Gp({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,jh.$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);qp.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=${Jp(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${Jp(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${Jp(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist)}, sandboxPolicyHash=${null!==(a=Kp(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:Jp(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist),mcpNetworkDenylistCount:Jp(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist),localAgentNetworkAllowlistCount:Jp(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist),sandboxPolicyHash:Kp(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:p}));try{return yield Rp.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 jh.c8u(t,e);throw e}}return!0===(null==h?void 0:h.enabled)&&"no_sandbox"===h.mcpNetworkMode&&qp.info(e,`Starting local MCP server "${t}" without MCP sandboxing`),Rp.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 zp(this,void 0,void 0,(function*(){const i=Lp(e,qp),s=function(e,t){return{logger:{debug:(t,r)=>qp.debug(e,t,r),info:(t,r)=>qp.info(e,t,r),warn:(t,r)=>qp.warn(e,t,r),error:(t,r,n)=>qp.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t);return Rp.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{Hp(i)}}));for(const e of c){const r=h;h=(n,o)=>zp(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{Hp(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){qp.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 $h||e instanceof Lh||e instanceof Xp}(r)}}class Xp 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 Qp{constructor(e){this.blockingService=e}getMcpNetworkControlsConfig(e){return zp(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 zp(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 Xp(t,null!==(l=u.reason)&&void 0!==l?l:"teamPolicy",u.message);return o(e,r)}))}}class ef extends Yp{constructor(e,t,r=[],n,o){super(new Zp(e),t,r,{authRedirectUrlGenerator:n,elicitationFactory:o}),this.configPath=e,this.elicitationFactory=o}static init(e,t,r=[]){return new ef(t,e,r)}}function tf(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 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())}))};class nf{constructor(e){this.mcpAuthPath=e;const t=nf.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,nf.mcpAuthPromises.set(e,t),t.catch((()=>{nf.mcpAuthPromises.get(e)===t&&nf.mcpAuthPromises.delete(e)}))}nf.saveLocks.has(e)||nf.saveLocks.set(e,Promise.resolve())}loadMcpAuth(){return rf(this,void 0,void 0,(function*(){try{const e=yield(0,ho.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 rf(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 rf(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>rf(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 rf(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 rf(this,void 0,void 0,(function*(){var t;const r=null!==(t=nf.saveLocks.get(this.mcpAuthPath))&&void 0!==t?t:Promise.resolve();let n;nf.saveLocks.set(this.mcpAuthPath,new Promise((e=>{n=e})));try{return yield r,yield e()}finally{n()}}))}saveClientInformation(e,t){return rf(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>rf(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 rf(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>rf(this,void 0,void 0,(function*(){const t=yield this.mcpAuthPromise;e in t&&(delete t[e],yield this.saveMcpAuth(t))}))))}))}saveMcpAuth(e){return rf(this,void 0,void 0,(function*(){yield(0,ho.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),yield(0,ho.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}))}}nf.mcpAuthPromises=new Map,nf.saveLocks=new Map;var of=r("../proto/dist/generated/agent/v1/utils_pb.js");let sf;function af(){if(void 0===sf){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 sf===e&&(sf=void 0),t}));sf=e}return sf}const lf=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},cf=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),uf=e=>lf().encode(e);var df=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 hf=1048576,pf=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),ff=(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}},mf=e=>df(void 0,void 0,void 0,(function*(){if(cf(e))return(e=>df(void 0,void 0,void 0,(function*(){const t=(e=>{if(!cf(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}})(e);if(void 0!==t&&!ff(t.width,t.height,1280).needsResize&&e.length<=hf)return{data:pf(e),mimeType:"image/webp"};const r=yield(n=e,lf().decode(n));var n;const o=(yield af()).fromBitmap({data:Buffer.from(r.data),width:r.width,height:r.height});let{width:i,height:s,needsResize:a}=ff(o.bitmap.width,o.bitmap.height,1280);a&&o.resize({w:i,h:s});let l=yield uf({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});for(;l.length>hf&&i>1&&s>1;)i=Math.max(1,Math.round(.8*i)),s=Math.max(1,Math.round(.8*s)),o.resize({w:i,h:s}),l=yield uf({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});return{data:pf(l),mimeType:"image/webp"}})))(e);const t=yield af(),r=yield t.read(e),n=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(r),{width:o,height:i,needsResize:s}=ff(r.width,r.height);if(!s&&e.length<=hf)return{data:pf(e),mimeType:n};let a=o,l=i;s&&r.resize({w:a,h:l});let c=yield r.getBuffer(n);for(;c.length>hf&&a>1&&l>1;)a=Math.max(1,Math.round(.8*a)),l=Math.max(1,Math.round(.8*l)),r.resize({w:a,h:l}),c=yield r.getBuffer(n);return{data:pf(c),mimeType:n}}));function gf(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 vf=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},yf=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 wf=(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"]}),bf=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),Sf=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),kf=(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"]}),Ef=(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"]}),xf=(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"]}),Cf=(0,d.h)("McpFileSystemWriter"),_f="mcpFsStructuredLogOptIn";function Pf(e,t){return t?.includeStructuredLogs?{...e??{},[_f]:!0}:e}const If={debug(e,t,r,n){Cf.debug(e,t,Pf(r,n))},info(e,t,r,n){Cf.info(e,t,Pf(r,n))},warn(e,t,r,n){Cf.warn(e,t,Pf(r,n))},error(e,t,r,n,o){Cf.error(e,t,r,Pf(n,o))}},Tf="mcps",Rf="tools",Af="~staging",Of="~prev",Mf="mcp_auth",jf="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.",Df="# >>> CURSOR MANAGED BLOCK >>>",Nf="# <<< CURSOR MANAGED BLOCK <<<",$f=["# 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 Lf(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function Ff(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function Uf(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function Bf(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 zf(e){if(Array.isArray(e))return e.map((e=>zf(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,zf(t)]));return Object.fromEntries(t)}return e}function Wf(e){return JSON.stringify(zf(e))}function Hf(e){const t=e.map((e=>({value:e,key:Wf(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function qf(e){const t=Hf(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=Hf(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=Hf(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return Wf({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 Gf{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=>{If.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),If.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=`${Df}\n${$f}\n${Nf}\n`;let n;await(0,ho.mkdir)(e,{recursive:!0});try{n=await(0,ho.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==e?.code)throw e}if(void 0===n)return void await(0,ho.writeFile)(t,r);const o=n.indexOf(Df),i=n.indexOf(Nf,o+30);if(-1===o||-1===i)await(0,ho.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,ho.writeFile)(t,e)}})((0,s.join)((0,i.homedir)(),".cursor")).catch((e=>{If.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,Tf);try{const e=await(0,ho.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(Af))).map((e=>(0,ho.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==e?.code&&If.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){If.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 Uf(this.mcpAuthCopyOverrides?.authToolDescription)??jf}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&st(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return Uf(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=Uf(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:Mf},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&st(e)?this.getNeedsAuthStatusMessage(e):Uf(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){If.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${n}`);const o=await this.mcpLease.getTools(e).catch((e=>(If.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 If.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 Lf(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||If.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?Lf(r.getTools(e),[]).then((e=>(0===e.length&&If.info(o,`Direct client getTools() returned 0 tools for "${t}" (state=${i.kind})`),e))):Promise.resolve([]),s?Lf(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?Lf(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?Lf(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:Bf(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=Qf(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,Tf,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=Qf(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,Tf,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){If.info(e,`Skipping direct client tool fallback for "${t}": settings report 0 enabled tools`);continue}If.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===Mf))||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:Mf,name:Mf,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)?If.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):If.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===Mf))){const t=e.tools.find((e=>e.toolName===Mf));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??[])];If.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=>(If.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 If.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=>{If.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):If.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)),If.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=Qf(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{vf(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=>(If.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(If.warn(n,`getClients() threw, defaulting to {}: ${e}`),{}))),this.getEnabledToolsByServer(e)]),a=Object.keys(i);If.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){If.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{yf(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,Rf,`${Ff(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{vf(n,(0,l.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,Tf);await(0,ho.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,qf(e))}catch(t){If.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&If.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,ho.stat)((0,s.join)(i,e.sanitizedId))}catch{If.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Qf(e);r.has(n)?(If.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(If.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),u.add(n))}if(void 0===this.cachedServerData)try{const e=await(0,ho.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(Af)&&!e.endsWith(Of))));for(const r of e)if(r.endsWith(Af))await(0,ho.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else if(r.endsWith(Of)){const e=r.slice(0,-5);if(t.has(e))await(0,ho.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,ho.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,ho.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else u.add(e)}catch(e){If.error(o,"Error clearing mcps directory",e)}const d=Array.from(u);if(c.length>0||u.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));If.info(o,`Incremental write: ${c.length} changed, ${u.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t<c.length;t++){const r=h[t];if("rejected"===r.status){const n=c[t],o=this.cachedFingerprints.get(n.serverIdentifier);void 0!==o?a.set(n.serverIdentifier,o):a.delete(n.serverIdentifier),If.error(e,"Error writing server directory",r.reason,{serverIdentifier:n.serverIdentifier,sanitizedId:n.sanitizedId},{includeStructuredLogs:!0})}}const p=await Promise.allSettled(d.map((e=>(0,ho.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r<p.length;r++){const n=p[r];if("rejected"===n.status){const o=d[r];If.error(e,"Error removing server directory",n.reason,{sanitizedId:o,removalIndex:r,removalAttemptCount:p.length,removedServerCount:d.length,removedServerSanitizedIds:d,changedServerCount:c.length,unchangedServerCount:t.length-c.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=a}catch(e){n.error=e,n.hasError=!0}finally{yf(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{vf(n,(0,l.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=`${t.sanitizedId}${Af}`,i=`${t.sanitizedId}${Of}`,a=(0,s.join)(r,o),c=(0,s.join)(r,i),u=(0,s.join)(r,t.sanitizedId);await(0,ho.rm)(a,{recursive:!0,force:!0});try{await(0,ho.rename)(c,u)}catch{await(0,ho.rm)(c,{recursive:!0,force:!0})}await this.writeServerDirectory(e,t,{basePath:r,dirName:o});try{try{await(0,ho.rename)(u,c)}catch{}await(0,ho.rename)(a,u)}catch(r){If.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0});try{await(0,ho.rename)(c,u)}catch{}throw await(0,ho.rm)(a,{recursive:!0,force:!0}),r}await(0,ho.rm)(c,{recursive:!0,force:!0}).catch((()=>{}))}catch(e){n.error=e,n.hasError=!0}finally{yf(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{vf(n,(0,l.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,ho.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,Rf);await(0,ho.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=Ff(r.toolName),n=(0,s.join)(e,`${t}.json`),o=lt(r);await(0,ho.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,ho.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=Ff(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,ho.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,ho.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=Ff(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,ho.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,ho.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,ho.writeFile)(e,r)}const i=(0,s.join)(o,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,ho.writeFile)(i,JSON.stringify(a,null,2))}catch(e){n.error=e,n.hasError=!0}finally{yf(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;vf(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&&If.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=Ff(t.toolName),n=(0,s.join)(e.folderPath,Rf,`${r}.json`);return new dr.E$({toolName:t.toolName,definitionPath:n,...gf(t.annotations)})}));return new dr.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 dr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{yf(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&&If.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){If.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&If.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){If.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{vf(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,Tf),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=Qf(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=Ff(e.name);return new dr.E$({toolName:e.name,definitionPath:(0,s.join)(r,Rf,`${t}.json`),...gf(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===Mf))){const e=Ff(Mf);n.push(new dr.E$({toolName:Mf,definitionPath:(0,s.join)(r,Rf,`${e}.json`)}))}return new dr.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 If.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new dr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{yf(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<Gf.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{If.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,Tf),i=new Set,a=new Map;for(const e of t){const t=Qf(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let l=[];try{l=await(0,ho.readdir)(o),l=l.filter((e=>!e.endsWith(Af)&&!e.endsWith(Of)))}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++,wf.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),If.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++,wf.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,Rf);let h=0;try{h=(await(0,ho.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==l&&(u=!1,p++,wf.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),If.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}))}bf.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),Sf.gauge(e,i.size,this.getMetricTags({mcp_source:r})),kf.gauge(e,c.size,this.getMetricTags({mcp_source:r})),Ef.gauge(e,d,this.getMetricTags({mcp_source:r})),xf.gauge(e,p,this.getMetricTags({mcp_source:r})),If.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||If.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())}}Gf.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var Vf=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},Jf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Kf=(0,d.h)("local-exec:mcp");function Zf(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function Yf(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function Xf(e){return new Tt._Z({content:{case:"text",value:new Tt.zN({text:e})}})}function Qf(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 em(e,t,r){const n=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t);if(n)return await ni(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:gh.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 tm{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=Vf(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.providerIdentifier===t.providerIdentifier&&e.toolName===t.toolName)),d=await em(n,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u});if(void 0!==d)return d;const h=await this.toolSet.getToolSet(n);let p;try{p=await h.execute(t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(r instanceof Ap&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new Op(t.providerIdentifier,c)),r instanceof Op){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(r instanceof Ap)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(Xf(t.text))}else if("resource"===t){const t=e;t.resource?.text&&f.push(Xf(t.resource.text))}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),n=await mf(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=Jh(e);f.push(Xf(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,Oh),n=s.join(r,`${(0,o.randomUUID)()}.txt`);await(0,ho.mkdir)(s.dirname(n),{recursive:!0});const i=e.slice(0,Mh),a=i.split("\n").length,l=Buffer.byteLength(i,"utf8");return await(0,ho.writeFile)(n,i,"utf8"),new of.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)?hr.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{Jf(r)}}}class rm{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Vf(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{Jf(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 nm{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=Vf(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:gh.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:hr.Value.fromJson(t.server),uri:hr.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:hr.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,ho.realpath)(r),o=s.resolve(r,t.replace(/^\/+/,""));if(!Zf(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.dirname(o);for(;;)try{if(!Zf(n,await(0,ho.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==Yf(e))throw e;const t=s.dirname(i);if(t===i)throw e;i=t}if(await(0,ho.mkdir)(s.dirname(o),{recursive:!0}),!Zf(n,await(0,ho.realpath)(s.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,ho.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==Yf(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,ho.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,ho.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 Kf.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{Jf(r)}}}async function om(e,t){const r=Qf(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,ho.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,ho.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 im=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),sm="/mcps/",am=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),lm=(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"]}),cm=(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"]}),um=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),dm=new Map;function hm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function pm({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 im.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=s.servers.find((e=>Qf(e.serverIdentifier)===n));if(void 0===a)return;let l;try{l=await o(r,a.serverIdentifier)}catch(t){return void im.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"};am.increment(e,1,{...c,outcome:l}),lm.histogram(e,s.length,c),cm.histogram(e,a.length,c),um.histogram(e,s.length+a.length,c),"mismatch"===l&&im.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 fm(e,t,r,n=om){if(void 0===r||(void 0===(o=r)||!hm(o).includes(sm)))return;var o;const i=function(e){const t=hm(e),r=t.indexOf(sm);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=dm.get(s);void 0!==c&&clearTimeout(c);const u=e,d=setTimeout((()=>{dm.delete(s),(async()=>{if(l){const e=await t.getState(u);for(const r of e.servers){const o=Qf(r.serverIdentifier);await pm({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await pm({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{im.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);dm.set(s,d)}var mm=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},gm=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 vm(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}function ym(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 wm=(0,d.h)("local-exec/grep");function bm(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function Sm(e){try{return(0,so.existsSync)(e)}catch{return"check_failed"}}function km(e,t,r,n){return{...xm(e),...n,cwd:t,cwdExists:Sm(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function Em(e){return new Error(`Path does not exist: ${e}`)}function xm(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,so.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,so.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,so.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,so.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,so.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,so.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,so.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,so.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,so.existsSync)(n),t.asarUnpackedDirExists){const e=(0,s.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,so.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class Cm{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor}computeRelativeTarget(e,t){const r=(0,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=[];for(const n of e){const e=await Hu((0,ko.o1)(n.file,t));null===e||await this.isPostRipgrepBlocked(e)||r.push(n)}return r}async isPostRipgrepBlocked(e){const[t,r]=await Promise.all([this.ignoreService.isCursorIgnored(e),this.ignoreService.isRepoBlocked(e)]);return t||r}async runFilesMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=mm(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?vm(n):[],i=o.length,s=o.slice(0,t),a=o.length>t;return{files:s,totalFiles:Rh(i),clientTruncated:a,ripgrepTruncated:i>=r}}(c.stdout,Cm.CLIENT_LIMIT_LINES,Cm.HARD_MAX_OUTPUT_LINES),f=[];for(const e of u){const r=await Hu((0,ko.o1)(e,t));null===r||await this.isPostRipgrepBlocked(r)||f.push(e)}const m=u.length-f.length,g=new Ph.T7({files:f,totalFiles:Rh(d-m),clientTruncated:h,ripgrepTruncated:p});return new Ph.vD({result:{case:"files",value:g}})}catch(e){i.error=e,i.hasError=!0}finally{gm(i)}}async runCountMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=mm(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?vm(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:Rh(s),totalMatches:Rh(a),clientTruncated:c,ripgrepTruncated:s>=r}}(c.stdout,Cm.CLIENT_LIMIT_LINES,Cm.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 Ph.xA({counts:m.map((e=>new Ph.sS({file:e.file,count:Rh(e.count)}))),totalFiles:Rh(d-v),totalMatches:Rh(h-y),clientTruncated:p,ripgrepTruncated:f});return new Ph.vD({result:{case:"count",value:w}})}catch(e){i.error=e,i.hasError=!0}finally{gm(i)}}async runContentMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=mm(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{mm(o,(0,l.VI)(n.withName("parseContentOutput")),!1);const i=""===e.trim()?[]:vm(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:Rh(i.length),totalMatchedLines:Rh(c),totalFiles:Rh(d),clientTruncated:u>=t,ripgrepTruncated:i.length>=r}}catch(e){o.error=e,o.hasError=!0}finally{gm(o)}}(c.stdout,Cm.CLIENT_LIMIT_LINES,Cm.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 Ph.Zp({matches:g.map((e=>new Ph.uI({file:e.file,matches:e.matches.map((e=>new Ph.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Rh(d-y),totalMatchedLines:Rh(h-w),clientTruncated:p,ripgrepTruncated:f});return new Ph.vD({result:{case:"content",value:b}})}catch(e){i.error=e,i.hasError=!0}finally{gm(i)}}async executeIndexedGrepWithTimeout(e,t,r,n){if(void 0===this.grepProvider.executeIndexedGrep)return;const[o,i]=e.withTimeoutAndCancel(Cm.INDEXED_GREP_CONTEXT_TIMEOUT_MS),s={phase:"provider"},a=performance.now();try{return await(0,Gr.wj)(this.grepProvider.executeIndexedGrep(o,t,r,s),Cm.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${Cm.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Gr.MU)return void wm.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??Cm.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(),bm(r)){const n=r,o=(0,fo.getRipgrepBinaryPath)();if(wm.error(e,"rg_diagnostics.spawn_throw",void 0,km(o,t,n,i)),!1===Sm(t))return u(Em(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 ${Cm.MAIN_TIMEOUT_MS/1e3}s`)),f.kill()}catch{}}),Cm.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(),bm(r)){const n=(0,fo.getRipgrepBinaryPath)(),o=r;if(wm.error(e,"rg_diagnostics.spawn_enoent",void 0,km(n,t,o,i)),!1===Sm(t))return void u(Em(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=mm(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=Wo(t.sandboxPolicy);try{const r=this.grepProvider.getWorktreeGuardInfo?.(a);if((0,ko.fl)({targetPath:t.path,workspacePaths:a,mainWorktreePath:r?.mainWorktreePath}))return new Ph.Ud({result:{case:"error",value:new Ph.ts({error:ko.PS})}});if(t.path){const r=await Hu((0,ko.o1)(t.path,this.singleWorkspacePath));if(null===r)return new Ph.Ud({result:{case:"error",value:new Ph.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 Ph.Ud({result:{case:"error",value:new Ph.ts({error:`Path '${t.path}' is filtered out by .cursorignore`})}});void 0!==this.mcpStateAccessor&&fm(e,this.mcpStateAccessor,r)}let n={};const l=await this.executeIndexedGrepWithTimeout(i.ctx,a,t,u);if(void 0!==l)n=l;else for(const e of a){if(!1===Sm(e))return new Ph.Ud({result:{case:"error",value:new Ph.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=>ym(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 Ph.vD({result:{case:"content",value:new Ph.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 Ph.vD({result:{case:"files",value:new Ph.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 Ph.vD({result:{case:"count",value:new Ph.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 Ph._0({pattern:t.pattern,path:t.path,outputMode:c,workspaceResults:h});return new Ph.Ud({result:{case:"success",value:p}})}catch(e){if(t.path){const e=(0,ko.o1)(t.path,this.singleWorkspacePath);try{await(0,ho.stat)(e)}catch(t){return new Ph.Ud({result:{case:"error",value:new Ph.ts({error:`Path does not exist: ${e}`})}})}}return new Ph.Ud({result:{case:"error",value:new Ph.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{gm(n)}var o}}Cm.MAIN_TIMEOUT_MS=25e3,Cm.INDEXED_GREP_TIMEOUT_MS=25e3,Cm.INDEXED_GREP_CONTEXT_TIMEOUT_MS=Cm.INDEXED_GREP_TIMEOUT_MS+100,Cm.HARD_MAX_OUTPUT_LINES=1e4,Cm.CLIENT_LIMIT_LINES=2e3;var _m=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),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},Im=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Tm{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{Pm(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,ho.stat)(n)}catch(e){return"ENOENT"===e.code?function(e){const t=Qs(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new _m.fv({result:{case:"error",value:new _m.uj({path:n,error:"No active terminals."})}}):new _m.fv({result:{case:"error",value:new _m.uj({path:n,error:`Path does not exist: ${n}`})}}):new _m.fv({result:{case:"error",value:new _m.uj({path:n,error:e.message})}})}if(!r.isDirectory())return new _m.fv({result:{case:"error",value:new _m.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Wo(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 _m.fv({result:{case:"timeout",value:new _m.ze({directoryTreeRoot:a})}}):new _m.fv({result:{case:"success",value:new _m.PC({directoryTreeRoot:a})}})}catch(e){return new _m.fv({result:{case:"error",value:new _m.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Im(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return Pm(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{Im(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{Pm(i,(0,l.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new _m.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}=Ou(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 Hu(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{Im(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 _m.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]=Rh(e.fullSubtreeExtensionCounts[o]+1),e.numFiles??=0,e.numFiles=Rh(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 _m.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 Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Am=1e4,Om={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class Mm{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<Am){const r=Math.min(e.length,Am-t);this.fullOutput+=e.slice(0,r)}this.totalChars>Am&&(this.fullOutput="")}getOutput(){return this.totalChars<=Am?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=Am))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-Am}}}function jm(e,t){const r=fh-e.length;return r<=0?e:e+t.slice(0,r)}function Dm(e,t){return null!==e?e:null===t?-1:-i.constants.signals[t]}class Nm{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:Ho(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const i=performance.now(),s=r,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 Mm;let a,c,u="",d="",h=!1,p=!1,f="",m=()=>{};const g=(0,fo.withConfiguredRipgrepEnv)({...process.env,...Om,CURSOR_AGENT:"1"}),v={shell:!0,cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform},y="insecure_none"===l.type?(0,io.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:Ah(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=jm(u,t),s.append(t)})),y.stderr?.on("data",(e=>{const t=e.toString();d=jm(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:Dm(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?Wo(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:oi(c.reason)})}});a=c.policy,Ao()&&(a=$o(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{Rm(r)}}}var $m=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),Lm=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const Fm=51200;function Um(e){return Buffer.byteLength(e,"utf8")}function Bm(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function zm(e){return new Lm.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 Wm(e,t){const r=t?.maxLines??2e3,n=t?.maxBytes??Fm,o=e.split("\n"),i=o.length;if(Um(o[0]??"")>n)return{content:"",truncation:zm({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=Um(t)+i;if(l+c>n){a="bytes";break}s.push(t),l+=c}return{content:s.join("\n"),truncation:zm({truncated:void 0!==a,truncatedBy:a,totalLines:i,outputLines:s.length,outputBytes:l,maxLines:r,maxBytes:n})}}function Hm(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var qm=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 Gm(e){const{content:t,truncation:r}=function(e){const t=Fm,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=Um(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=Um(o[0]),a=!0}break}o.unshift(n),s+=c}return{content:o.join("\n"),truncation:zm({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,ho.mkdtemp)((0,s.join)((0,i.tmpdir)(),"pi-bash-")),o=(0,s.join)(n,"output.log");await(0,ho.writeFile)(o,e,"utf8");const a=r.totalLines-r.outputLines+1,l=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${Bm(r.outputBytes)} of line ${l} (${Bm(Fm)} limit). Full output: ${o}]`:`[Showing lines ${a}-${l} of ${r.totalLines}. Full output: ${o}]`}`,fullOutputPath:o,truncation:r}}class Vm{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 Gm(`${i.result.value.stdout}${i.result.value.stderr}`);return new $m.AH({result:{case:"success",value:new $m.cV(e)}})}case"failure":{const e=await Gm(`${i.result.value.stdout}${i.result.value.stderr}`);return new $m.AH({result:{case:"success",value:new $m.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{qm(n)}}error(e){return new $m.AH({result:{case:"error",value:new $m.bD({error:e})}})}}var Jm=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function Km(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;case"adminCommandDenylist":return ti(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 Zm=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function Ym(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function Xm(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 Qm(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 eg(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 tg=new Map;async function rg(e,t){const r=await async function(e){try{return await(0,ho.realpath)(e)}catch{return e}}(e),n=tg.get(r)??Promise.resolve();let o;const i=new Promise((e=>{o=e})),s=n.then((()=>i));tg.set(r,s),await n;try{return await t()}finally{o(),tg.get(r)===s&&tg.delete(r)}}function ng(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,Oc.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 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 ig{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=ng(t.path,this.workspacePath);return rg(i,(async()=>{const e=await this.permissionsService.shouldBlockRead(i);if(e)return this.error(`Read blocked: ${Km(e)}`);try{if((await(0,ho.stat)(i)).isDirectory())return this.error(`Path is a directory: ${i}`);const e=(await(0,ho.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=Ym(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=Ym(o.oldText),i=Qm(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:Ym(o.newText)})}if(!n)return{matches:r,matchedContent:e};const o=Xm(e),i=[];for(const e of t){const t=Xm(Ym(e.oldText)),r=Qm(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:Xm(Ym(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,Zm.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:h,patch:h,firstChangedLine:eg(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 Jm.u7({result:{case:"success",value:new Jm.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 Jm.u7({result:{case:"rejected",value:new Jm.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{og(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 Jm.u7({result:{case:"error",value:new Jm.Nd({error:e})}})}}var sg=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),ag=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 lg(e){return e.split(s.sep).join("/")}class cg{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=ng(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Find blocked: ${Km(o)}`);try{if(!(await(0,ho.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,ho.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:lg((0,s.relative)(n,e))}))).filter((({relative:e})=>(0,xi.xF)(e,o,{dot:!0})));if(0===i.length)return this.success("No files found matching pattern");const a=Wm(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(`${Bm(Fm)} 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{ag(r)}}success(e,t){return new sg.bT({result:{case:"success",value:new sg.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new sg.bT({result:{case:"error",value:new sg.Uy({error:e})}})}}var ug=r("node:readline"),dg=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),hg=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 pg{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=ng(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Search blocked: ${Km(o)}`);try{const e=(await(0,ho.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,io.spawn)((0,fo.getRipgrepBinaryPath)(),r,{stdio:["ignore","pipe","pipe"]}),i=[];let s="",a=!1;const l=Math.max(1,t.limit??100),c=(0,ug.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=Wm(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(`${Bm(Fm)} 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{hg(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=Hm(a.lineText);i=i||t.wasTruncated,o.push(`${e}:${a.lineNumber}: ${t.text}`);continue}const l=(await(0,ho.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=Hm(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 dg.mr({result:{case:"success",value:new dg.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new dg.mr({result:{case:"error",value:new dg.hP({error:e})}})}}var fg=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),mg=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 gg{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=ng(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`List blocked: ${Km(o)}`);try{if(!(await(0,ho.stat)(n)).isDirectory())return this.error(`Not a directory: ${n}`);const e=Math.max(1,t.limit??500),r=(await(0,ho.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,ho.stat)(e);o.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===o.length)return this.success("(empty directory)");const a=Wm(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(`${Bm(Fm)} 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{mg(r)}}success(e,t){return new fg.pX({result:{case:"success",value:new fg.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new fg.pX({result:{case:"error",value:new fg.iG({error:e})}})}}var vg=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),yg=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 wg{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=ng(e,t);if((0,so.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,so.existsSync)(e))return e;return r}(t.path,this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Read blocked: ${Km(o)}`);try{if((await(0,ho.stat)(n)).isDirectory())return this.error(`Path is a directory: ${n}`);const e=(await(0,ho.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}=Wm(o),a=r+1;let l=i;if(s.firstLineExceedsLimit)l=`[Line ${a} is ${Bm(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${Bm(Fm)} 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 vg.Q({result:{case:"success",value:new vg.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{yg(r)}}error(e){return new vg.Q({result:{case:"error",value:new vg.tB({error:e})}})}}var bg=r("../proto/dist/generated/agent/v1/pi_write_exec_pb.js"),Sg=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 kg{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=ng(t.path,this.workspacePath);return rg(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 bg.hO({result:{case:"success",value:new bg.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new bg.hO({result:{case:"rejected",value:new bg.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new bg.hO({result:{case:"error",value:new bg.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new bg.hO({result:{case:"error",value:new bg.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){n.error=e,n.hasError=!0}finally{Sg(n)}}}var Eg=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function xg(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class Cg{constructor(e){this.drainer=e}async execute(e,t){try{const e=await this.drainer.drain({cursor:xg(t.cursor),advance:!1!==t.advance});return new Eg.Ev({result:{case:"success",value:new Eg.iS({events:e.events.map((e=>new Eg.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 Eg.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new Eg.Ev({result:{case:"error",value:new Eg.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class _g{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 Pg=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)}))}}},Ig=function(e){return this instanceof Ig?(this.v=e,this):new Ig(e)},Tg=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 Ig?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 Rg{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=Pg(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 Tg(this,arguments,(function*(){for(const t of e)yield yield Ig(t)}))}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return function(){return Tg(this,arguments,(function*(){var n,o,i,s;for(const e of t)yield yield Ig(e);try{try{for(var a,l=!0,c=Pg(e);!(n=(a=yield Ig(c.next())).done);l=!0){s=a.value,l=!1;const e=s;yield yield Ig(e)}}catch(e){o={error:e}}finally{try{l||n||!(i=c.return)||(yield Ig(i.call(c)))}finally{if(o)throw o.error}}}finally{r.forks.delete(e)}}))}()}}function Ag(e,t){const r=new po.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 Og=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),Mg=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class jg{constructor(e){this.getCanvasDiagnostics=e}async execute(e,t){try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?Dg(t.path,"diagnostics unavailable"):new Og.GL({result:{case:"success",value:new Og.uX({path:t.path,diagnostics:e.map(Ng)})}})}catch(e){return Dg(t.path,e instanceof Error?e.message:String(e))}}}function Dg(e,t){return new Og.GL({result:{case:"error",value:new Og.HW({path:e,error:t})}})}function Ng(e){return new Mg.oQ({severity:$g(e.severity),range:new of.Q6({start:new of.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new of.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function $g(e){switch(e){case 1:return Mg.h_.ERROR;case 2:return Mg.h_.WARNING;case 3:return Mg.h_.INFORMATION;case 4:return Mg.h_.HINT;default:return Mg.h_.UNSPECIFIED}}class Lg{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 Lg(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new Lg(e)}static fromString(e){return new Lg(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 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 Ug{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,ho.stat)(r);if(!e.isFile()&&!e.isDirectory())return new Mg.Ek({result:{case:"fileNotFound",value:new Mg.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new Mg.Ek({result:{case:"fileNotFound",value:new Mg.Mu({path:t.path})}});if("EACCES"===e.code)return new Mg.Ek({result:{case:"permissionDenied",value:new Mg.RP({path:t.path})}});throw e}const n=(0,ko.o1)(r,this.workspacePath),o=new Lg(n);await this.diagnosticsProvider.open(e,o);const i=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new Mg.Ek({result:{case:"success",value:new Mg.a1({path:t.path,diagnostics:i,totalDiagnostics:i.length})}})}catch(r){return e.canceled?new Mg.Ek({result:{case:"error",value:new Mg.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new Mg.Ek({result:{case:"error",value:new Mg.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{Fg(r)}}convertDiagnostic(e){return new Mg.oQ({severity:this.convertSeverity(e.severity),range:e.range?new of.Q6({start:new of.yX({line:e.range.start.line,column:e.range.start.character}),end:new of.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 Mg.h_.ERROR;case 2:return Mg.h_.WARNING;case 3:return Mg.h_.INFORMATION;case 4:return Mg.h_.HINT;default:return Mg.h_.UNSPECIFIED}}}var Bg=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 zg(e){return Bg(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 Bg(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,io.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=>Bg(this,void 0,void 0,(function*(){const t=i.get(e);if(!0!==t)if(!1!==t)if(function(e){return new Wg(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 Wg(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 Wg{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 Hg=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,qg=/^(a|b|i|w|c|o|1|2)\//,Gg=e=>{const t=e?.match(Hg);return t?.map((e=>e.replace(qg,"").replace(/("|')$/,"")))},Vg=/^\\?['"]|\\?['"]$/g,Jg=e=>{let t=Kg(e,"-+").trim();return t=Yg(t),t.replace(Vg,"").replace(qg,"")},Kg=(e,t)=>{if(e=Qg(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=Xg(t);return e.replace(new RegExp(`^${r}+`),"")},Zg=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,Yg=e=>{const t=Zg.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},Xg=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${Qg(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,Qg=e=>`${e??""}`,ev=(0,d.h)("local-git-diff");async function tv(e,t,r={}){const n=await new Promise(((n,o)=>{const i=ga("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 rv(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]=Gg(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=Jg(e)}],[/^\+\+\+\s/,e=>{c(),n.to=Jg(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 mr.o$({diffs:t.map((e=>function(e){const t=new mr.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new mr.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:mr.Wf.UNSPECIFIED})}const nv=["main","master","develop"];class ov{async execute(e,t){return async function(e,t,r){const n=function(e){switch(e){case mr.ek.NAME_STATUS:return mr.ek.NAME_STATUS;case mr.ek.NAME_STATUS_AND_NUMSTAT:return mr.ek.NAME_STATUS_AND_NUMSTAT;case mr.ek.FILE_DIFFS:return mr.ek.FILE_DIFFS;case mr.ek.DIFFS_WITH_BEFORE_AND_AFTER:return mr.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return mr.ek.FILE_DIFFS}}(r.outputFormat),o=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await tv(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of nv){const r=`origin/${t}`;try{return await tv(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await tv(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await tv(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 tv(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 tv(t,i,{shouldNotTrimOutput:!0}),l=rv(a);let c=[];if(r.maxUntrackedFiles>0){c=await async function(e,t){let r=(await tv(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 ho.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 tv(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});l.diffs.push(...rv(r).diffs)}}if(n!==mr.ek.FILE_DIFFS)for(const e of l.diffs)e.chunks=[];if(n===mr.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 tv(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 tv(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}else try{i.afterFileContents=await ho.readFile(s.join(t,i.to),"utf8")}catch{try{i.afterFileContents=await tv(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}}else i.afterFileContents=""}catch(t){ev.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 zg({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 tv(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){ev.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=ga("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 tv(t,["rev-parse","HEAD"])).trim():void 0,m=!0===r.returnHeadSha?(await tv(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,g=new mr.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 iv=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class sv{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName});return new iv.M({allowlisted:r})}}const av=8388608;var lv=r("../proto/dist/generated/agent/v1/read_exec_pb.js"),cv=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 uv=(0,d.h)("LocalReadExecutor"),dv=async(e,t,r,n)=>{const o=setTimeout((()=>{uv.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function hv(e){return e>=32&&e<=126||9===e||10===e||13===e}const pv=Buffer.from("\n---\n");const fv=[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 mv(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 lv.sV({result:{case:"invalidFile",value:new lv.cW({path:e,reason:r})}})}function gv(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 vv(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 yv(e,t){const r=vv(e,t);return{text:r.text,truncated:r.truncated}}function wv(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=vv(n,"\n")),n=vv(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function bv(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 Sv extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function kv(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>=av)return;const r=u.length>0?1:0;let n=av-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>av;){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>=av)return;const r=p.length>0?1:0;let n=av-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 ao.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n=(0,so.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 Sv;throw e}return}const n=(0,so.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe(Kc.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=yv(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(hu.has(e)&&hu.delete(e),hu.set(e,t),hu.size<=100)return;const r=hu.keys().next().value;void 0!==r&&hu.delete(r)}(t,"utf8"===n.cacheEncoding&&x?"utf8bom":n.cacheEncoding);let T={text:"",truncated:h};if(T=wv(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=wv(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=wv(R,p,I),{content:R.text,totalLines:b,truncated:R.truncated,rangeApplied:!0}}class Ev{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalReadExecutor.execute")),!1);const n=t.path,o=(0,ko.o1)(n,this.workspacePath);if(await dv(e,"permissionsService.shouldBlockRead",3e3,(()=>this.permissionsService.shouldBlockRead(o))))return new lv.sV({result:{case:"permissionDenied",value:new lv.lW({path:o})}});void 0!==this.mcpStateAccessor&&fm(e,this.mcpStateAccessor,o);try{const r=await dv(e,"stat",3e3,(()=>(0,ho.stat)(o)));if(r.isDirectory())return new lv.sV({result:{case:"invalidFile",value:new lv.cW({path:o,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new lv.sV({result:{case:"invalidFile",value:new lv.cW({path:o,reason:"Path is neither a file nor a directory"})}});const n=function(e){return null!==function(e){const t=Qs(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=Qs(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 dv(e,"getFormatForFile",3e3,(()=>bu(o))),l=a.isImageFile,c=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(o),u=gu(o);if(l){const t=await dv(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,ho.readFile)(o);return mf(e)}));return new lv.sV({result:{case:"success",value:new lv.mE({path:o,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c){const t=await dv(e,"readPdfBinary",3e3,(()=>(0,ho.readFile)(o)));return new lv.sV({result:{case:"success",value:new lv.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(a.isBinaryFile&&u){const t=await dv(e,"readBinaryFile",3e3,(()=>(0,ho.readFile)(o)));return new lv.sV({result:{case:"success",value:new lv.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(a.isBinaryFile)return mv(o);{const n=this.useStreamingRead;if(n&&await dv(e,"useStreamingRead",3e3,(()=>n()))){const n=await dv(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=function(e,t,r){const n=function(e,t,r){return bv(r??hu.get(e)??t.encoding)}(e,t,r),o=function(e){const t=bv(e);return"utf8bom"===t?"utf8":t}(n);return"utf8"===o?{kind:"strictUtf8",cacheEncoding:"utf8"}:Kc.encodingExists(o)?{kind:"iconv",decoderEncoding:o,cacheEncoding:n}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,n.encodingHint);try{return await kv(e,t,n,o)}catch(r){if(r instanceof Sv)return await kv(e,t,n,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,o,a,t)));return new lv.sV({result:{case:"success",value:new lv.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 dv(e,"readText",3e3,(()=>yu(o,t.encodingHint))),s=await dv(e,"countLines",3e3,(()=>Su(i))),l=gv(i,s,t);let c=l.content,u=!1;return c.length>av&&(c=c.substring(0,av),u=!0),new lv.sV({result:{case:"success",value:new lv.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 lv.sV({result:{case:"fileNotFound",value:new lv.Ko({path:o})}}):"EACCES"===t.code||"EPERM"===t.code?new lv.sV({result:{case:"permissionDenied",value:new lv.lW({path:o})}}):new lv.sV({result:{case:"error",value:new lv.F_({path:o,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{cv(r)}}async readTerminalFile(e,t,r,n,o){const i=await dv(e,"readTerminalFile",3e3,(()=>(0,ho.readFile)(t)));if(o&&(s=i,fv.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(s,e)))))return mv(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*pv.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(pv,r-pv.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+pv.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&&hv(t)&&r++,0===t&&hv(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=Su(a),c=gv(a,l,n);a=c.content;let u=!1;return a.length>av&&(a=a.substring(0,av),u=!0),new lv.sV({result:{case:"success",value:new lv.mE({path:t,output:{case:"content",value:a},totalLines:l,fileSize:BigInt(r.size),truncated:u,rangeApplied:c.rangeApplied})}})}}var xv=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),Cv=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 _v=(0,ao.promisify)(io.execFile);class Pv{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 ho.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 ho.mkdir(this.stagingDir,{recursive:!0}),await ho.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:xv.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:xv.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:xv.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 ho.access(e),!0}catch{return!1}}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 _v("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 _v("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:Pv.PROXY_TARGET_FPS,includeBrandTag:!0}),await ho.access(r,ho.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await _v("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 ${Pv.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${Pv.PROXY_TARGET_FPS}fps`)}return Pv.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await ho.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await Gd(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${Pv.DEFAULT_REFRESH_RATE}Hz`),o=Pv.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${Pv.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${Pv.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",Pv.PROXY_PRESET,"-crf",String(Pv.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,io.spawn)("ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0});dp(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,io.spawn)("ffmpeg",t,{stdio:["ignore","ignore","pipe"]});dp(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 ho.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 xv.Tj({result:{case:"failure",value:new xv.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===xv.$u.UNSPECIFIED)return new xv.Tj({result:{case:"failure",value:new xv.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case xv.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){e=!0;try{await this.cleanupRecording(this.activeRecording),await ho.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 ho.mkdir(o,{recursive:!0});const{resolutionString:i,resolution:s}=await Gd(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 ph({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 xv.Tj({result:{case:"startSuccess",value:new xv.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 ho.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new xv.Tj({result:{case:"failure",value:new xv.yH({error:e instanceof Error?e.message:String(e)})}})}}case xv.$u.SAVE_RECORDING:{if(!this.activeRecording)return new xv.Tj({result:{case:"failure",value:new xv.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 ho.access(u,ho.constants.R_OK)}catch{return this.activeRecording=null,new xv.Tj({result:{case:"failure",value:new xv.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:Pv.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:Pv.PROXY_TARGET_FPS,codec:"h264",profile:Pv.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 ho.copyFile(u,a);else{const e=await this.renderPolished(i);await ho.rename(e,a)}return this.activeRecording=null,new xv.Tj({result:{case:"saveSuccess",value:new xv.ol({path:a,recordingDurationMs:hr.protoInt64.parse(d.toString()),requestedFilePathRejectedReason:l})}})}catch(t){return await this.cleanupRecording(e),this.invokeStoppedCallbackOnce(),this.activeRecording=null,new xv.Tj({result:{case:"failure",value:new xv.yH({error:t instanceof Error?t.message:String(t)})}})}}case xv.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new xv.Tj({result:{case:"failure",value:new xv.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 ho.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new xv.Tj({result:{case:"discardSuccess",value:new xv.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;return this.activeRecording=null,new xv.Tj({result:{case:"failure",value:new xv.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 xv.Tj({result:{case:"failure",value:new xv.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{Cv(r)}}}async function Iv(e){const t=await(0,ho.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 Iv(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 Tv(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(...Tv(t,e,i))}))}return n}async function Rv(e){if(!await(0,ho.access)(e,ho.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await Iv(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>Tv(e,"",r===t.length-1))).join("\n")}async function Av(e,t){return Rv(s.join(e,"agent-notes",t))}async function Ov(e){return Rv(s.join(e,"agent-notes","shared"))}Pv.PROXY_TARGET_WIDTH=1920,Pv.PROXY_TARGET_FPS=60,Pv.PROXY_CRF=17,Pv.PROXY_PRESET="veryfast",Pv.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",Pv.DEFAULT_REFRESH_RATE=60;var Mv=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},jv=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dv=(0,d.h)("local-exec:request-context");async function Nv(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{Mv(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{jv(o)}}async function $v(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 Lv(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 Fv={type:"object",properties:{},additionalProperties:!1};function Uv(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>at.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new dr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?hr.Value.fromJson(e.inputSchema):void 0}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function Bv(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 dr.E$({toolName:e.toolName,...gf(e.annotations),...r?{}:{description:e.description,inputSchema:void 0!==e.inputSchema?hr.Value.fromJson(e.inputSchema):void 0}})));return!st(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===Mf))||o.push(new dr.E$({toolName:Mf,...r?{}:{description:jf,inputSchema:hr.Value.fromJson(Fv)}})),new dr.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 dr.U_({enabled:!0,mcpDescriptors:n})}function zv(e){const t=e?.trim();return t||void 0}function Wv(e,t){const r=function(e){return zv(e.serverIdentifier)}(e);if(r)return r;const n=zv(e.serverName);return n?t.get(n)??n:void 0}class Hv{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(Dv.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(Dv.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=>Wv(e,n))).filter((e=>Boolean(e)));return{servers:[...new Set([...e.map((e=>e.clientKey)),...o,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e)).map((([e])=>e))])].map((o=>{const i=e.filter((e=>e.clientKey===o));return{serverName:i[0]?.providerIdentifier??o,serverIdentifier:o,plugin:i[0]?.plugin,marketplace:i[0]?.marketplace,tools:i,instructions:t.filter((e=>Wv(e,n)===o)),status:r?.get(o)}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(Dv.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>[t,dt(await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"}))))])));return new Map(n)}(e,this.mcpLease))}}function qv(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 dr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?hr.Value.fromJson(e.inputSchema):void 0}))),instructions:e.instructions,status:e.status})))})}})}class Gv{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 qv({...r,servers:n})}return qv(r)}}class Vv{constructor(e,t,r,n,o,i,s,a,l,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.lsExecutor=i,this.mcpStateAccessor=s,this.gitExecutor=a,this.workspacePaths=l,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:u,getSmartModeClassifierAutoModeEnabled:d,getAdminCommandDenylist:h,devForceNextSmartModeClassifierBlockToken:p,isWorkingDirHomeDir:f,createFileWatcher:m,getSandboxEnabled:g,getSandboxSupported:v,getNetworkAllowlistInfo:y,userTerminalHint:w,getMcpFileSystemOptions:b,mcpMetaToolEnabled:S,mcpMetaToolSlimDescriptors:k,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:C,attributionConfigProvider:_,isAttributionDisabledByAdmin:P,getAgentSkills:I,additionalRules:T,getComputerUseSupported:R}=c;this.projectDir=u,this.isWorkingDirHomeDir=f,this.getSandboxEnabled=g,this.getSandboxSupported=v,this.getNetworkAllowlistInfo=y,this.getSmartModeClassifierAutoModeEnabled=d,this.getAdminCommandDenylist=h,this.devForceNextSmartModeClassifierBlockToken=p,this.userTerminalHint=w,this.getMcpFileSystemOptions=b,this.mcpMetaToolEnabled=S??!1,this.mcpMetaToolSlimDescriptors=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!==m&&(this.fileWatcher=m(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,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=Mv(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 $u(n.ctx,this.gitExecutor,o):void 0,s={repoPath:o??void 0,remoteUrl:void 0!==i?Lu(i):void 0};this.cachedWorkspaces.set(t,s)}catch(e){r.error=e,r.hasError=!0}finally{jv(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=Mv(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{jv(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Mv(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&&Dv.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{jv(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=Mv(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:Wa(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(Nv(e,t,r,n)),o($v(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:Wa(t.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:i,gitRepoInfoComplete:o}}catch(e){t.error=e,t.hasError=!0}finally{jv(t)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Mv(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=Mv(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{jv(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",Lv(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?Av(o,t.notesSessionId):Promise.resolve(void 0)),c("sharedNotes",o?Ov(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&&Dv.warn(n.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(S),...a});const k=this.mcpMetaToolEnabled?Bv(d,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors}):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}]:[],...Uv(d,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors}),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{jv(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Mv(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{jv(r)}}}function Jv(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Rt._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var Kv=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 Zv{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:Ho(e.sandboxPolicy)}):new Rt.W4({result:{case:"failure",value:new Rt.xC({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Ho(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const i=Date.now(),s=new AbortController,a=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal,l=setTimeout((()=>{s.abort()}),n);try{let n,s,c="",u="",d=null,h=!1;const p=o?{perRepo:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:p,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?c+=o.data:"stderr"===o.type?u+=o.data:"exit"===o.type&&(d=null!=o.code?0|o.code:null,n=o.outputLocation,h=o.aborted,s=Ah(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:Ho(o)}):e.signal.aborted?new Rt.W4({result:{case:"rejected",value:new Rt.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Ho(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:Ho(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?Wo(t.requestedSandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(),a=Jv(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:ii(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:ii(o,c,e.reason)});u=e.policy}if(Ao()&&(u=$o(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await this.ignoreService.getCursorIgnoreMapping();u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,s,a,u)}catch(e){r.error=e,r.hasError=!0}finally{Kv(r)}}}var Yv=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class Xv{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 Yv.e({allowlisted:n})}}class Qv{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 ey=r("../utils/dist/workspace-paths.js"),ty=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},ry=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ny=(0,d.h)("local-exec:shell-core"),oy="win32"===process.platform,iy=["CURSOR_CONVERSATION_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function sy(e){return`'${e.replace(/'/g,"'\\''")}'`}function ay(e,t){return e[t]??process.env[t]}function ly(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}class cy{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{ty(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,ey.sh)(t.conversationId)),this.projectDir&&(g.AGENT_TRANSCRIPTS=s.join(this.projectDir,ey.O2));const v=this.extraEnvProvider?.(e,t);void 0!==v&&Object.assign(g,v),function(e){const t=[`builtin unset ${iy.join(" ")} 2>/dev/null || true`];for(const r of iy){const n=ay(e,r);void 0!==n&&t.push(`builtin export ${r}=${sy(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=ay(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[]}}(ay(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=ly(s.additionalReadonlyPaths,a):s.additionalReadwritePaths=ly(s.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==s.type?s.additionalReadonlyPaths=ly(s.additionalReadonlyPaths,e.path):s.additionalReadwritePaths=ly(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&&!oy&&(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>Mh);else if(c.file)c.file.write(S);else if(c.buffer+=S,c.size>c.threshold){const e=s.join(this.projectDir,Oh);c.path=s.join(e,`${(0,o.randomUUID)()}.txt`),await(0,ho.mkdir)(s.dirname(c.path),{recursive:!0}),c.file=(0,so.createWriteStream)(c.path),c.file.write(c.buffer),c.buffer=""}switch(r.type){case"stdout":h||(u+b>fh?(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>fh?(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 of.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{ry(r)}}async getCwd(){return this.executor.getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class uy{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{ty(r,(0,l.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),ny.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{ry(r)}}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class dy{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 hy=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 py=(0,d.h)("local-exec:shell-stream");class fy{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 my{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?Wo(t.requestedSandboxPolicy):void 0;if(o&&"insecure_none"!==o.type){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}const i=t.workingDirectory||await this.coreExecutor.getCwd(),s=Jv(t),a=(0,ko.o1)(i),c=Date.now(),u=new Rt.HO(bo(n).structured),d=ri({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:oi(h.reason)})}}));if(py.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)py.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(py.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=oi(r.reason);return void(yield new Rt.FI({event:{case:"rejected",value:new Rt.pZ({command:n,workingDirectory:a,reason:o})}}))}o=r.policy,py.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:o.type})}if(Ao()&&(o=$o(n,u),"insecure_none"!==o.type)){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}yield new Rt.FI({event:{case:"start",value:new Rt.tD({sandboxPolicy:Ho(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,sandboxPolicy:y,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:f,showElapsedTime:v});let b;p||(b=setTimeout((()=>m.abort()),s));const S=p?new fy(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:Ah(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:Ah(t.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof fo.SandboxUnsupportedError))throw r;const i=o?.type??"unknown";return py.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{hy(r)}}}var gy=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class vy{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new gy.M({allowlisted:r})}}var yy=r("node:constants");function wy(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function by(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 Sy(e,t){const r=(0,ko.o1)(e,t);try{return wy(await(0,ho.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return wy(r,r,by(t));try{if((await(0,ho.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,ho.readlink)(r)}catch{}return wy(r,r,{status:"danglingSymlink",symlinkTarget:e})}return wy(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,ho.realpath)(t);return wy((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return wy(e,e,by(r))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return wy(e,e,{status:"newFile"})}(r):wy(r,r,by(t))}}}function ky(e){return"resolved"===e.status||"newFile"===e.status}function Ey(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}\`.`}}class xy extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}const Cy="win32"===process.platform;function _y(e,t){return Cy&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const Py=(0,s.join)((0,i.homedir)(),".cursor","projects"),Iy=(0,s.join)((0,i.homedir)(),".cursor","worktrees");function Ty(e){return _y(Py,e)&&e!==Py}function Ry(e){return _y(Iy,e)&&e!==Iy}function Ay(e,t){const r=function(e){if(!_y(Py,e))return;if(e===Py)return;const t=(0,s.relative)(Py,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}var Oy=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 My=(0,d.h)("LocalWriteExecutor"),jy=async(e,t,r,n)=>{const o=setTimeout((()=>{My.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};class Dy{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=Ay(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,ho.stat)(c)).size<=mh?d=await jy(n,"readText before write",3e3,(()=>yu(c,t.encodingHint))):h=!0}catch{}const p=(await Sy(c)).resolvedPath,f=(".cursorignore"===(c.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await jy(n,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(n,p,i)));if(f){const e=await jy(n,"handleBlockReason",3e3,(()=>ni(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:gh.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 jy(n,"mkdir",3e3,(()=>(0,ho.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 jy(n,"getBufferForWrite",3e3,(()=>wu(p,i,this.workspacePath,t.encodingHint)));g=e.buffer,v=e.lines}try{await jy(n,"writeFile",3e3,(async()=>{let e;await async function(e,t,r){let n;try{n=await(0,ho.open)(e,function(){const e=so.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 so.constants.O_NOFOLLOW}(t))throw new xy(e,`Refusing to write through a symlink at ${e}`);throw t}try{let o;try{o=(0,so.realpathSync)(e)}catch{throw new xy(e,`Cannot verify canonical path before writing: ${e}`)}if(o!==e)throw new xy(e,`Refusing write: ${e} now resolves through a symlinked parent to ${o}`);if(!(await n.stat()).isFile())throw new xy(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,ho.open)((0,s.dirname)(p),yy.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}))}catch(e){if(e instanceof xy)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){My.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 jy(n,"readText after write",3e3,(()=>yu(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{Oy(r)}}}const Ny=(0,d.h)("local-exec:provider");class $y 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,so.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.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;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 cy(o,t??(0,i.homedir)(),this.projectDir,e.shellOutputBackpressureOptions,e.shellExtraEnvProvider);e.shellCoreWrapper&&(l=e.shellCoreWrapper(l)),this.askpassConfig&&(l=new dy(l,this.askpassConfig)),this.shellManager&&(l=new uy(l,this.shellManager));const c=e.overrideShellExecutor??new Zv(this.permissionsService,l,this.ignoreService,this.pendingDecisionStore);this.register(Ot,Ag(c)),this.register(vt,Ag(new Nm(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=e.overrideWriteExecutor??new Dy(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking});this.register(jt,Ag(u)),this.register(ie,Ag(new yh(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking))),this.register(ae,Ag(new Eh)),this.register(le,new ov);const d=this.mcpStateAccessor??new Hv(this.mcpLease);this.register(ce,Ag(new Cm(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:d})));const h=Ag(e.overrideReadExecutor??new Ev(this.permissionsService,a,{mcpStateAccessor:d,useStreamingRead:e.useStreamingRead}));this.register(Ct,h),e.registerRedactedReadExecutor&&this.register(_t,h);const p=new Tm(this.permissionsService,this.ignoreService,a);this.register(tt,Ag(p)),this.register(Et,Ag(new wg(this.permissionsService,a))),this.register(yt,Ag(new Vm(c))),this.register(wt,Ag(new ig(this.permissionsService,u,a))),this.register(xt,Ag(new kg(u,a))),this.register(St,Ag(new pg(this.permissionsService,a))),this.register(bt,Ag(new cg(this.permissionsService,a))),this.register(kt,Ag(new gg(this.permissionsService,a))),this.register(se,Ag(new Ug(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(ne,Ag(new jg(e.getCanvasDiagnostics))),this.register(ht,Ag(new tm(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded))),this.register(pt,Ag(new rm(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ft,Ag(new nm(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(mt,Ag(new Gv(d,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const f=Ag(this.sharedRequestContextExecutor??new Vv(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,p,d,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,ko.yn)(t,(0,i.homedir)()),createFileWatcher:this.createFileWatcher,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:e.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:e.getArtifactsFolder,secretRedactionEnabled:e.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor}));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=Uv(a,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors});if(s.tools=l.tools,s.mcpInstructions=l.mcpInstructions,s.mcpMetaToolOptions=this.mcpMetaToolEnabled?Bv(a,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors}):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=[],Ny.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new Si(this.permissionsService,l,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(Q,Ag(this.backgroundShellExecutor));const m=new my(this.permissionsService,l,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(Mt,function(e,t){const r=new po.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 Rg(a);r.set(i,l),yield*l.fork()}}}(m)),void 0!==e.agentStoreConflictDrainer&&this.register(Y,new Cg(e.agentStoreConflictDrainer)),this.register(Vt,new Xv(this.permissionsService)),this.register(gt,new sv(this.permissionsService)),this.register(or,new vy(this.permissionsService));const g=new Qv(m);this.register(Jt,Ag(g));const v=!1===e.enableWriteBackgroundShellStdin?new _g((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new _g(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(ee,Ag(v)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(oe,Ag(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new Pv({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Ht,Ag(this.recordScreenExecutor))}}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function Ly(e){return e.replace(/\\/g,"/")}function Fy(e,t){for(const r of t){const t=Ly(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var Uy;function By(e,t){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return Uy.Plugin;const r=Ly(e.fullPath);return Fy(r,t.builtinDirs)?Uy.Builtin:Fy(r,t.userDirs)?Uy.UserHome:(Fy(r,t.workspaceDirs),Uy.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserHome=1]="UserHome",e[e.Workspace=2]="Workspace",e[e.Plugin=3]="Plugin"}(Uy||(Uy={}));var zy=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Wy=(0,ao.debuglog)("merged-agent-skills");class Hy{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=>(Wy("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=>(Wy("getDisabledManagedSkillPaths rejected; fail-open: %s",e instanceof Error?e.message:String(e)),[])))]),a=o.flat(),c=new Set,u=[];for(const e of a){const t=kd(e.fullPath);c.has(t)||(c.add(t),u.push(e))}let d=u;i.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,i))));const h=this.getPromptSortContext;return void 0!==h?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[id(e.userHomeDirectory).dirPath],r=ad(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 sd(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,t)=>({skill:e,index:t,tier:By(e,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,h()):d}catch(e){t.error=e,t.hasError=!0}finally{zy(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()}),Hy.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()}}Hy.CHANGE_COALESCE_MS=1500;const qy=(0,d.h)("skill-sync-manifest"),Gy=".sync-manifest.json";async function Vy(e,t){try{const r=await(0,ho.readFile)((0,s.join)(e,Gy),"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:(qy.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||qy.warn(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function Jy(e,t,r){e.skills[t]={lastSyncedAt:r}}function Ky(e,t){delete e.skills[t]}var Zy=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Yy=(0,d.h)("builtin-skills-sync");function Xy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Qy(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 ew(e){const t=Ll(e.content),r=Xy(t.data)?t.data:{};return Fl(`${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={...Xy(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 tw(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 rw(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,ho.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,ho.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,ho.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,ho.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,ho.writeFile)(t,r,"utf-8")}try{await(0,ho.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==e.code)throw e}try{await(0,ho.rename)(n,r)}catch(e){throw i&&(await(0,ho.rename)(o,r),i=!1),e}i&&(await(0,ho.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,ho.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,ho.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||Yy.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,ho.mkdir)(n,{recursive:!0}),await(0,ho.writeFile)(o,i,"utf-8"),!0}async function rw(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,ho.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 rw(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function nw(e,t){try{return(await(0,ho.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||Yy.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function ow(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=(0,s.join)((0,i.homedir)(),".cursor","skills-cursor");await(0,ho.mkdir)(c,{recursive:!0});const[u,d]=await Promise.all([Vy(c,o),nw(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([iw((0,s.join)(r,"SKILL.md")),"canvas"===e?iw((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}})));Yy.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){Yy.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):Yy.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&&Ms(t,"local"),h=void 0!==t&&!l,f=void 0!==r||d.includes(e);if(t&&!1!==t.enabled&&l)Qy(t),await tw(o,c,{id:e,fileContent:ew(t),resources:t.resources??{}})?m++:g++,Jy(u,e,a);else if(!1===t?.enabled||h||i){const n=!1===t?.enabled?"enabled_false":h?"environment_ineligible":"grace_expired";await(0,ho.rm)((0,s.join)(c,e),{recursive:!0,force:!0}),Ky(u,e),f&&(v.push(e),Yy.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||Jy(u,e,a)}catch(t){Yy.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,Gy);await(0,ho.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,ho.rename)(r,n)}(c,u)}catch(e){Yy.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{Zy(r)}var n}async function iw(e){try{return await(0,ho.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const sw=(0,d.h)("managed-skills-sync");function aw(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 lw{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(...Ks(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=aw(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var cw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 uw(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class dw{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.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??_i,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{let t=[];try{t=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const r=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],n=[...e.plugins,...r],o=new Set(n.map((e=>e.installPath))),i=t.filter((e=>!o.has(e.installPath)));return this.plugins=[...n,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${r.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0;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(Rc));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Rc(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=uw(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 Ic({...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,ho.realpath)(r);if(!(await(0,ho.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,ho.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 xc(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${e}`);const o=this._extensionPlugins.get(n),i=o?.get(r);i&&t.push(i)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,Qe.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,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=uw(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 nc(this,arguments,void 0,(function*(e,t={}){var r,n,o,i,a;const l=null!==(r=t.log)&&void 0!==r?r:_i,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(Pc(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 Ic(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 nc(this,arguments,void 0,(function*(e={}){var t,r,n;const o=null!==(r=e.log)&&void 0!==r?r:_i,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,ho.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,ho.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,ho.realpath)(n)}catch(e){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{el(u,e)}catch(t){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${l}`);continue}}if(!(yield(0,ho.stat)(n)).isDirectory()){r.isSymbolicLink()&&o.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const i=performance.now(),s=yield null===(t=e.localPluginVariablesLookup)||void 0===t?void 0:t.call(e,r.name),{displayName:a,description:c,authorName:h,variablesSchema:p,skills:f,rules:m,agents:g,commands:v,mcpConfig:y,capabilities:w,hooks:b}=yield xc(n,r.name,void 0,{configuredVariables:s}),S={source:"user-local",sourceInfo:{name:r.name,localPath:n}};d.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:S,installPath:n},void 0!==a&&{displayName:a}),void 0!==c&&{description:c}),void 0!==h&&{authorName:h}),{variablesSchema:p,skills:f,rules:m,agents:g,commands:v,mcpConfig:null!=y?y:void 0,capabilities:w,hooks:b})),o.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-i).toFixed(1)}ms`)}catch(e){o.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return o.log("info",`loadUserLocalPlugins completed in ${(performance.now()-i).toFixed(1)}ms (${d.length} plugins loaded)`),d}))}({userHomeDir:t.userHomeDir,log:l,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[v,y]=yield Promise.all([Promise.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,ho.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=Tc(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=>Tc(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{cw(e)}}}const hw=BigInt(0),pw=BigInt(8),fw=BigInt(16),mw=BigInt(65535);function gw(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function vw(e){const t=e.split(".");if(4!==t.length)return;let r=hw;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<<pw|BigInt(t)}return{version:4,value:r}}function yw(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=vw(n);if(!o)return;t.push(Number(o.value>>fw&mw)),t.push(Number(o.value&mw))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function ww(e){var t;return null!==(t=vw(e))&&void 0!==t?t:function(e){const t=gw(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=yw(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<fw|BigInt(t)),hw)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),i=yw(n),s=yw(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<<fw|BigInt(t)),hw)}}(e)}function bw(e,t){const r=gw(e),n=gw(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=ww(t.slice(0,r)),o=ww(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 Sw(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=>bw(e,t)))}(r.hostname,t)}const kw=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Ew(e){return e.trim().split(/\s+/).filter(Boolean)}function xw(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 Ew(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 kw.has(o)}function Cw(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 _w(e,t){return e.commandName.localeCompare(t.commandName)}function Pw(e){var t;return null!==(t=e.split(" ")[0])&&void 0!==t?t:e}function Iw(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=Ew(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(_w);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=Cw(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&&Cw(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(Pw(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(Pw(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(Pw(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const s=n.filter((e=>!i.has(Pw(e))));return{defaultSelectedOptionIds:[...new Set([...s,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}var Tw=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},Rw=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)("permissions-service"),Ow=(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 Mw(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 jw(e){return[...new Set(e)]}function Dw(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Nw(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 $w({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 Lw(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Fw(e){return"<"!==e.operator&&"<&"!==e.operator}function Uw(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Bw(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function zw({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(ky(a.resolution)){for(const e of r){const t=await o(e);if(ky(t.resolution)&&$w({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:i}))return"workspace-file"}return n&&Yw(a.resolvedPath,s)?"tmp-file":void 0}}function Ww(e){return jw(e.map((e=>e.trim())).filter(Boolean))}function Hw(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 qw(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Gw(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 Vw(e,t={}){return{type:e,...t}}function Jw(e,t){if("workspace"===e&&void 0!==t)return t}const Kw={workspace:0,system:1};function Zw(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 Yw(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||!$w({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 Xw(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!(Kw[s]>Kw[a])}class Qw{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&Xw(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||!Xw(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function eb(e){return e?.type??"undefined"}class tb{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,{cursorIgnoreChecked:t=!1}={}){const r=(0,ko.o1)(e),n=await Hu(r);return null===n?{type:"unsafeResolution",message:Mw("Read","path",r)}:await this.ignoreService.isRepoBlocked(n)?{type:"adminBlock",source:"Team repo blocklist"}:await this.isPathExplicitlyDenied("Read",r)?{type:"permissionsConfig"}:!Ty(n)&&!Ry(n)&&(!t&&await this.ignoreService.isCursorIgnored(n)?{type:"cursorIgnore"}:(await this.isPathExplicitlyAllowed("Read",r),!1))}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Tw(n,(0,l.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const o=await Sy(t);if(!ky(o.resolution))return{type:"unsafeResolution",message:Ey(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=Ty(u),f=Ry(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 Sy(e);if(!ky(t.resolution))continue;const r=t.resolvedPath;if(Nw(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 yu(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,Zm.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 Sy(e);if(!ky(t.resolution))continue;const r=t.resolvedPath;if(Nw(c,r)){w=!0,y=r;break}}const b=w?void 0:function(e){if(!Ry(e))return;const t=(0,s.relative)(Iy,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(Iy,t[0]):void 0}(c);if(!w&&void 0===b){if(function(e){return Yw(e,{platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,i.homedir)()})}(c))return!1;if(Ay(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{Rw(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 Hu(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Mw("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(Aw.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:eb(c),requestedPolicyType:eb(n),effectiveRequestedPolicyType:eb(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 Aw.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:eb(c),requestedPolicyType:eb(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(Gw):d,k=void 0!==w?w.map(Hw):S.map((e=>[e.fullText.trim()].filter(Boolean))),E=void 0!==y?y.commands.map(Hw):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)(Jw(e.readBoundary,e.additionalReadPaths),Jw(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:c}),m&&Aw.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=Ww(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=>qw(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&(Aw.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)));Aw.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=Ww(i.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(xw(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),Ww(o)}(e)))),T=i.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=Iw(P,T),t=e.length>0?e.join(", "):P.join(", ");_.push(`Not in allowlist: ${t}`)}x=o&&0===I.length,x&&Aw.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 Qw(e,n,A,k[t])));if((0===S.length||f&&!b)&&!l){Aw.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:eb(n),userConfiguredPolicyType:eb(c),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==v});const o={type:gh.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 L=this.buildShellApprovalDecisionFacts({commands:O,autoRunControls:D,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:$,softDenylistedCommands:I});if("workspace_readonly"===c.type&&"workspace_readonly"!==n.type)return Aw.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const F=Yt(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason;let B=F?void 0:this.getShellAutoApprovalPolicy({approvalMode:a,isUnrestricted:l,requestedPolicy:n,facts:L,preserveRequestedPolicyForAllowlistedCommands:b});const z=void 0!==B&&L.allCommandsAllowlisted&&"insecure_none"===B.type&&"allowlistEscalated"in B&&!0===B.allowlistEscalated;"insecure_none"===B?.type&&"workspace"===await this.resolveAdminReadBoundary()&&(o?B=void 0:"insecure_none"!==n.type&&(B=n));const W=void 0!==B&&z;if(B&&(void 0===g||W)){b&&L.allCommandsPreapproved&&!L.allCommandsAllowlisted&&Aw.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(B);return Aw.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:eb(n),userConfiguredPolicyType:eb(c),autoApprovalPolicyType:eb(B),mergedPolicyType:eb(t),isSmartAllowlistActive:b,smartModeApprovalBypassedByAllowlist:W,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.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)&&L.canAllowlistInPrompt;const q=[],G=void 0!==g,V=L.notInTeamAllowlist.length>0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==g&&q.push(g),F&&(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(L.unapprovedCommands.length>0){const e=Iw(this.generateAllowlistPatterns(L.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");q.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(G||(L.rmDeniedByDeleteProtection.length>0&&q.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&q.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),H=!1),V){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");Aw.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.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)):L.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,F?"hook_forces_prompt":void 0,C.length>0?"command_blocklist":void 0,b&&_.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,V?"team_allowlist_miss":void 0].filter((e=>void 0!==e));Aw.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:eb(n),userConfiguredPolicyType:eb(c),isSandboxAvailable:Q,isSandboxEnabled:ee,canAllowlist:H,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==v,hookForcesPrompt:F,approvalReasonTypes:te,commandCount:O.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:Y.length,suggestedAllowlistEntryCount:X?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const re={type:gh.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(Gw):u;if(0===d.length)return!1;const h=c?l.commands.map(Hw):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==l?l.commands.map(Hw):h,f={type:"insecure_none"},m=d.map(((e,t)=>new Qw(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=Ww(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>qw(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const v=await this.teamSettingsService.getAutoRunControls();if(void 0!==v&&m.some((e=>this.isInTeamBlocklist(v,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:s,autoRunControls:v,applyTeamAllowlist:i}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=await this.foldPerUserFilePolicy(e),r=t.skipStatsigDefaults?t:await this.applyStatsigDefaults(t),n=await this.loadPerRepoFilePolicy(r.type),o=await this.buildTeamAdminPolicy(r.type),i=(0,fo.isAllowAllNetworkByPolicy)(e.networkPolicy),{policy:s}=await(0,fo.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:r,perRepo:n,teamAdmin:o});return i?{...s,networkPolicy:(0,fo.networkAllowAllPolicy)()}:s}async foldPerUserFilePolicy(e){const t=await(0,fo.loadSandboxPolicyFromFileOrUndefined)(this.perUserSandboxConfigPath,(0,i.homedir)());if(!t||"insecure_none"===t.type)return e;let r=(0,fo.mergeNetworkPolicies)(t.networkPolicy,e.networkPolicy);r&&void 0!==e.networkPolicy?.default&&(r={...r,default:e.networkPolicy.default});const n=(0,fo.mergePathsUnion)(t.additionalReadonlyPaths,e.additionalReadonlyPaths),o={...e,networkPolicy:r,additionalReadonlyPaths:n.length>0?n:void 0};if("workspace_readwrite"===e.type&&"workspace_readwrite"===t.type){const r=(0,fo.mergePathsUnion)(t.additionalReadwritePaths,e.additionalReadwritePaths);return{...o,additionalReadwritePaths:r.length>0?r:void 0}}return o}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,fo.isAllowAllNetworkByPolicy)(e.networkPolicy))return e;const r={default:"deny",allow:jw(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?Vw(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict}):r:void 0}async buildTeamAdminPolicy(e){const t=await this.buildTeamAdminNetworkPolicy(e),r=await this.resolveAdminReadBoundary();return void 0===r?t:{...t??Vw(e),readBoundary:r}}async resolveAdminReadBoundary(){const{readBoundary:e}=await this.teamSettingsService.getSandboxingControls();return"workspace"===e?"workspace":void 0}async buildTeamAdminNetworkPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return Vw(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=jw(t.allowlist)),t.denylist.length>0&&(r.deny=jw(t.denylist)),Vw(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=Sy,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=Dw();for(const e of c){if(Bw(e))continue;const i=u?Dw():d,{operator:a,targetText:c}=e,p=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=Uw(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=Uw(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(!Lw(a)||void 0===c){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}const f=await zw({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(Fw))}({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:gh.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=ei({matchForms:t.parsingResult?Zo({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(Aw.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!==Zw(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Zw(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)xw(n.name)||(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}matchesPathEntry(e,t,r){const n=new RegExp(`^\\s*${e}\\s*\\((.*)\\)\\s*$`),o=t.match(n);if(!o)return!1;const i=(o[1]??"").trim(),s=this.expandTilde(i);return this.matchGlob(s,r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}expandTilde(e){return"~"===e?(0,i.homedir)():e.startsWith("~/")?(0,i.homedir)()+e.slice(1):e}matchGlob(e,t){return Ko(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t){const r={stack:[],error:void 0,hasError:!1};try{Tw(r,(0,l.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:n,toolName:o,providerIdentifier:i,args:s}=t,a=e=>{this.mcpAllowlistLog?.(e)};a(`[permissions-service] shouldBlockMcp: toolName="${o}", providerIdentifier="${i}"`);const c=await this.getPermissions(),u=await this.teamSettingsService.getMcpToolControls(),d=!0===u?.enabled;if(await this.isMcpExplicitlyDenied(e,i,o))return a(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig"};const h=t.smartModeApproval?.reason;if(void 0!==h)return"workspace_readonly"===c.userConfiguredPolicy.type&&"unrestricted"!==c.approvalMode?(a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0}):(a(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${o}", providerIdentifier="${i}"`),!(d?this.isMcpInTeamAllowlist(u,{providerIdentifier:i,toolName:o}):await this.isMcpExplicitlyAllowed(e,i,o))&&{type:"needsApproval",approvalReason:h,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:i,args:s,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:h,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(d){const t=this.isMcpInTeamAllowlist(u,{providerIdentifier:i,toolName:o});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${o}", providerIdentifier="${i}"`),!1}else{const t=await this.isMcpExplicitlyAllowed(e,i,o);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${o}", providerIdentifier="${i}"`),!1}if("workspace_readonly"===c.userConfiguredPolicy.type&&"unrestricted"!==c.approvalMode)return a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===c.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return a(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${o}", providerIdentifier="${i}"`),!1;a(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${o}", providerIdentifier="${i}"`)}return a(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${o}", providerIdentifier="${i}", approvalMode="${c.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${o}`,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:i,args:s,canAllowlist:!0}}}catch(e){r.error=e,r.hasError=!0}finally{Rw(r)}}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t;if(await this.isMcpExplicitlyDenied(r,n,o))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o}):await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const i=e.slice(0,o).trim().toLowerCase(),s=e.slice(o+1).trim().toLowerCase(),a=t.lastIndexOf("::mcpScope:"),l=(-1===a?t:t.slice(0,a)).toLowerCase().trim(),c=r.toLowerCase().trim(),u="*"===i||this.matchGlob(i,l),d="*"===s||this.matchGlob(s,c),h=u&&d,p=`[permissions-service] ${n}: serverPattern="${i}", toolPattern="${s}", normalizedProviderIdentifier="${l}", normalizedToolName="${c}", serverMatches=${u}, toolMatches=${d}, result=${h}`;return this.mcpAllowlistLog?.(p),h}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){Ow.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&&bw(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r}){return e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r})))}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var rb=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const nb=3e5;BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function ob({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||Sw(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 rb.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new rb.aYW({}))}}class sb{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>nb||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,jh.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,jh.MEY)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const i=ob({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?ob({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,jh._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=(0,jh.FC3)({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers,isMcpSettingsOverhaulEnabled:!0});return 0!==r.length?{enabled:!0,mcpToolAllowlist:r,allowUserOverride:t?.allowUserOverrideMcpServers??!1}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls;return{sandboxingDisabled:t?.sandboxing===rb.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===rb._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===rb.i24.ALWAYS_DISABLED,readBoundary:(r=t?.sandboxReadBoundary,r===rb.h0i.WORKSPACE||r===rb.h0i.CUSTOM?"workspace":"system")};var r}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>nb)&&(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>nb)&&(this.teamReposPromise=this.teamAdminSettingsProvider.getTeamRepos(),this.lastReposFetchTime=e);const t=this.teamReposPromise;return t.catch((e=>{throw this.teamReposPromise===t&&(this.teamReposPromise=void 0),e}))}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}function ab(){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 lb(e){return(0,s.join)(ab(),(0,ey.r_)(e))}const cb=Ci.z.any().transform(((e,t)=>{if(e instanceof Ze.Gmx)return e;try{return Ze.Gmx.fromJson(e,{ignoreUnknownFields:!1})}catch(r){return t.addIssue({code:Ci.z.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)}),e}})),ub=Ci.z.object({type:Ci.z.literal("command"),command:Ci.z.string().min(1),padding:Ci.z.number().int().min(0).optional(),updateIntervalMs:Ci.z.number().int().positive().optional(),timeoutMs:Ci.z.number().int().positive().optional()}),db=Ci.z.object({allow:Ci.z.array(Ci.z.string()),deny:Ci.z.array(Ci.z.string())}),hb=Ci.z.object({vimMode:Ci.z.boolean(),defaultBehavior:Ci.z.enum(["ide","agent"]).optional()}),pb=Ci.z.object({showLineNumbers:Ci.z.boolean().default(!1),showThinkingBlocks:Ci.z.boolean().default(!1),showStatusIndicators:Ci.z.boolean().default(!1),showStatusLineRunningTime:Ci.z.boolean().default(!1),mode:Ci.z.enum(["zen","standard"]).default("zen")}),fb=Ci.z.object({enabled:Ci.z.boolean().default(!1),mode:Ci.z.enum(["access-key","team-role"]).default("access-key"),region:Ci.z.string().optional(),testModel:Ci.z.string().optional(),teamRoleArn:Ci.z.string().optional(),teamExternalId:Ci.z.string().optional()}),mb=Ci.z.object({id:Ci.z.string(),value:Ci.z.string()}),gb=Ci.z.object({modelId:Ci.z.string(),parameters:Ci.z.array(mb)}),vb=Ci.z.object({ghostMode:Ci.z.boolean(),privacyMode:Ci.z.number().optional(),updatedAt:Ci.z.number()}),yb=Ci.z.object({backendUrl:Ci.z.string(),authCacheKey:Ci.z.string(),teamId:Ci.z.number().optional(),available:Ci.z.boolean(),updatedAt:Ci.z.number()}),wb=Ci.z.object({agentUrl:Ci.z.string(),agentnUrl:Ci.z.string()}),bb=Ci.z.object({backendUrl:Ci.z.string(),authCacheKey:Ci.z.string().optional(),teamId:Ci.z.number().optional(),agentUrlConfig:wb.optional(),cliSandboxDefaultEnabled:Ci.z.boolean().optional(),serverHttp2Config:Ci.z.number().optional(),updatedAt:Ci.z.number()}),Sb=Ci.z.object({email:Ci.z.string().optional(),displayName:Ci.z.string().optional(),teamId:Ci.z.number().optional(),teamName:Ci.z.string().optional(),userId:Ci.z.number().optional(),authId:Ci.z.string().optional(),organizationId:Ci.z.string().optional()}),kb=Ci.z.object({useHttp1ForAgent:Ci.z.boolean().default(!1)}),Eb=Ci.z.object({mode:Ci.z.enum(["disabled","enabled"]).default("disabled"),networkAccess:Ci.z.preprocess((e=>"allowlist"===e?"user_config_with_defaults":"enabled"===e?"allow_all":e),Ci.z.enum(["user_config_only","user_config_with_defaults","allow_all"])).optional(),networkAllowlist:Ci.z.array(Ci.z.string()).default([]).optional(),readBoundary:Ci.z.enum(["system","workspace"]).optional()}),xb=Ci.z.object({attributeCommitsToAgent:Ci.z.boolean().default(!0),attributePRsToAgent:Ci.z.boolean().default(!0)}),Cb=Ci.z.object({conversationId:Ci.z.string(),lastUpdatedAt:Ci.z.number()}),_b=Ci.z.object({permissions:db}),Pb=_b.extend({version:Ci.z.number(),editor:hb,display:pb.default({showLineNumbers:!1,showThinkingBlocks:!1,showStatusIndicators:!1,showStatusLineRunningTime:!1,mode:"zen"}),notifications:Ci.z.boolean().default(!0),hints:Ci.z.boolean().default(!0),modelSlashCommands:Ci.z.boolean().default(!0),rewind:Ci.z.boolean().default(!0),statusLine:ub.optional(),channel:Ci.z.literal("static").or(Ci.z.literal("prod")).or(Ci.z.literal("lab")).or(Ci.z.literal("prod-stable-internal")).optional(),model:cb.optional(),bedrock:fb.optional(),awsAuthRefresh:Ci.z.string().optional(),hasChangedDefaultModel:Ci.z.boolean().default(!1).optional(),maxMode:Ci.z.boolean().default(!1).optional(),maxModeAutoEnabled:Ci.z.boolean().optional(),modelParameters:Ci.z.record(Ci.z.string(),Ci.z.array(mb)).optional(),selectedModel:gb.optional(),modelSelectionHistory:Ci.z.array(Ci.z.string()).max(32).optional(),exploreSubagentModel:Ci.z.enum(["default","inherit"]).default("default"),privacyCache:vb.optional(),autoReviewAvailabilityCache:yb.optional(),serverConfigCache:bb.optional(),authInfo:Sb.optional(),network:kb.default({useHttp1ForAgent:!1}),approvalMode:Ci.z.enum(["allowlist","unrestricted","auto-review"]).default("allowlist").optional(),autoAcceptWebSearch:Ci.z.boolean().default(!1),sandbox:Eb.optional(),showSandboxIntro:Ci.z.boolean().default(!1).optional(),runEverythingSettingsPromptStreak:Ci.z.number().int().nonnegative().optional(),runEverythingSettingsPromptCooldownUntilMs:Ci.z.number().int().nonnegative().optional(),attribution:xb.optional(),webFetchDomainAllowlist:Ci.z.array(Ci.z.string()).default([]).optional(),conversationClassificationScoredConversations:Ci.z.array(Cb).optional()}),Ib=_b.strict().extend({});Pb.merge(Ib),new Set(["asb","staging"]);var Tb=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 Rb=new Set(["mcp.slack.com"]);var Ab=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 Ob{constructor(e,t){this.inner=e,this.resolver=t}getDefinitions(e){return Ab(this,arguments,void 0,(function*(e,t=!0){const r=yield this.inner.getDefinitions(e,t);return Promise.all(r.map((e=>Ab(this,void 0,void 0,(function*(){const t=yield function(e,t){return Tb(this,void 0,void 0,(function*(){if(!("url"in e)||!e.url)return e;const r=yield function(e,t,r){return Tb(this,void 0,void 0,(function*(){let n;try{n=new URL(e).hostname}catch(e){return t}if(!Rb.has(n))return t;const o=yield r.resolve(n);return o?t?Object.assign(Object.assign({},o),t):o: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 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())}))};class jb{constructor(e,t){this.storage=e,this.prefix=t}loadTokens(e){return Mb(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.prefix+e)}))}saveTokens(e,t){return Mb(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.prefix+e,t)}))}loadClientInformation(e){return Mb(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.prefix+e)}))}saveClientInformation(e,t){return Mb(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.prefix+e,t)}))}}class Db{constructor(e,t){this.storage=e,this.prefix=t}isServerApproved(e,t,r){return Mb(this,void 0,void 0,(function*(){return this.storage.isServerApproved(this.prefix+e,t,r)}))}}class Nb{constructor(e){this.loaders=e}load(e){return Mb(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 Np(i)}))}loadClient(e,t){return Mb(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 $b{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 jb(t,s),h=new Db(n,s),p=e===c,m=[new qh,...p?[]:[new Uh(h)],new Qp(r),...l?[new Fh(l)]:[]],g=u?new Yp(new Ob(new Zp(e),u),d,m,{authRedirectUrlGenerator:a}):new ef(e,d,m,a);f.push({prefix:s,loader:g})}this.loader=new Nb(f)}static init(e,t,r,n=!1,o,i){const a=new nf(s.join(r,"mcp-auth.json"));(function(e){return Mb(this,void 0,void 0,(function*(){yield(0,ho.rm)(s.join(e,"mcp-cache.json"),{force:!0})}))})(r).catch((()=>{}));const l=n?{isServerApproved:()=>Promise.resolve(!0)}:new Bh(s.join(r,"mcp-approvals.json"),t);return new $b(t,a,e,l,!0,void 0,o,void 0,i)}load(e){return Mb(this,arguments,void 0,(function*(e,t=!0){return this.loader.load(e,t)}))}loadClient(e,t){return Mb(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 Lb=new _h,Fb={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 Nu((0,Qe.q6)(),Lb,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?lb(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 Ub=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 Bb=(0,d.h)("ControlledConversationActionManager");class zb{get signal(){return this.abortController.signal}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,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 Ze.QFf({action:{case:"cancelAction",value:new Ze.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}submitConversationAction(e){return Ub(this,void 0,void 0,(function*(){if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}yield this.clientStream.write(e)}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){var e;null===(e=this.clientStream)||void 0===e||e.close()}resetStream(){var e;null===(e=this.clientStream)||void 0===e||e.close(),this.clientStream=(0,f.Jt)(),this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:e})}}))}run(e,t){return Ub(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){Bb.error(e,"Error writing conversation action",t)}}}catch(e){n={error:e}}finally{try{a||r||!(o=l.return)||(yield o.call(l))}finally{if(n)throw n.error}}}finally{this.runActive=!1}}))}dispose(){this.abortCallbacks.length=0}}let Wb={warn:console.warn.bind(console),error:console.error.bind(console)};const Hb=new ki.AsyncLocalStorage;function qb(){var e;return null!==(e=Hb.getStore())&&void 0!==e?e:Wb}const Gb={warn(...e){qb().warn(...e)},error(...e){qb().error(...e)}},Vb="x-blob-encryption-key";function Jb(e,t){const r=Object.assign({},t);return void 0!==r[Vb]||(0,lr.TU)(e)&&(r[Vb]=e),r}const Kb=new Map;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())}))};function Yb(e){var t;if("userMessageAction"===e.action.case)return null===(t=e.action.value.userMessage)||void 0===t?void 0:t.text}function Xb(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 Qb(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}const eS="cursor-plugins/local";function tS(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===eS)return r}var rS=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class nS extends Dp{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}dispose(){return rS(this,void 0,void 0,(function*(){this.disposed||(this.disposed=!0,yield this.runtimeManager.closeAllClients())}))}}class oS{constructor(e){this.storagePath=e}isServerDisabled(e){return rS(this,void 0,void 0,(function*(){try{const t=yield(0,ho.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 rS(this,void 0,void 0,(function*(){yield(0,ho.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),yield(0,ho.writeFile)(this.storagePath,JSON.stringify(e,null,2))}))}}class iS{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}getDefinitions(){return rS(this,void 0,void 0,(function*(){let e;try{e=yield this.pluginMcpService.getPluginMcpServers()}catch(e){return Gb.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&dS(r))continue;const e=tf(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}}):Gb.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 sS{constructor(e){this.servers=e}getDefinitions(){return rS(this,void 0,void 0,(function*(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:uS(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}))}}function aS(){return{getDotCursorProtection:()=>rS(this,void 0,void 0,(function*(){return!1})),getShouldBlockMcp:()=>rS(this,void 0,void 0,(function*(){return!1})),getDeleteFileProtection:()=>rS(this,void 0,void 0,(function*(){return!1})),getIsHeadlessDisabled:()=>rS(this,void 0,void 0,(function*(){return!1})),isServerBlocked:()=>rS(this,void 0,void 0,(function*(){return!1})),getTeamRepos:()=>rS(this,void 0,void 0,(function*(){})),getAutoRunControls:()=>rS(this,void 0,void 0,(function*(){return{enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}})),getAdminCommandDenylist:()=>rS(this,void 0,void 0,(function*(){return{rules:[]}})),getMcpToolControls:()=>rS(this,void 0,void 0,(function*(){})),getNetworkAccessControls:()=>rS(this,void 0,void 0,(function*(){return{allowlist:[],denylist:[],available:!0}})),getMcpNetworkControlsConfig:()=>rS(this,void 0,void 0,(function*(){return{enabled:!1}})),getDefaultNetworkAllowlist:()=>rS(this,void 0,void 0,(function*(){return{allowlist:[],available:!0}})),getSandboxingControls:()=>rS(this,void 0,void 0,(function*(){return{sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}})),isAttributionDisabledByAdmin:()=>rS(this,void 0,void 0,(function*(){return!1})),invalidateCache:()=>{}}}function lS(e={}){var t,r,n;const o=null!==(t=e.teamSettingsService)&&void 0!==t?t:aS(),a=null!==(r=e.ignoreApprovals)&&void 0!==r&&r,l=null!==(n=e.importThirdPartyPlugins)&&void 0!==n&&n;return{createLease(t){return rS(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 jp;const g=new oS((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 $b.init(t,r,n,o,a);if(!l&&!c)return;const u=new nf((0,s.join)(n,"mcp-auth.json")),d=o?{isServerApproved:()=>Promise.resolve(!0)}:new Bh((0,s.join)(n,"mcp-approvals.json"),r),h=[new qh,new Uh(d),new Qp(t),new Fh(a)],p=[];return l&&p.push({prefix:"",loader:new ef((0,s.join)(r,".cursor","mcp.json"),u,h)}),c&&p.push({prefix:"",loader:new ef((0,s.join)((0,i.homedir)(),".cursor","mcp.json"),u,h)}),cS(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 nf((0,s.join)(m,"mcp-auth.json")),t=[new qh,new Qp(o)];y.push({prefix:"",loader:new Yp(new sS(w),e,t)})}const b=tS(t.services.pluginBootstrapOutputs);if(b&&(null===(d=e.includePluginMcp)||void 0===d||d)){const e=new Bh((0,s.join)(m,"mcp-approvals.json"),f),t=new nf((0,s.join)(m,"mcp-auth.json")),r=[new qh];a||r.push(new Uh(e)),r.push(new Qp(o),new Fh(g));const n=new lw(b.pluginsService),i=new Yp(new iS(n,l),t,r);y.push({prefix:"",loader:i})}if(v&&y.push({prefix:"",loader:v}),0===y.length)return new jp;const S=cS(y),k=yield S.load(null!==(h=e.initializationCtx)&&void 0!==h?h:(0,Qe.q6)(),e.cache);return new nS(k)}))}}}function cS(e){return 1===e.length?e[0].loader:new Nb(e)}function uS(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 dS(e){return"claude-plugin"===e.pluginSource}var hS=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){return this instanceof pS?(this.v=e,this):new pS(e)};function fS(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===(null==t?void 0:t.case)}function mS(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class gS{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>gS.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=mS(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)=>hS(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=>hS(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 pS?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 pS(g.next())).done);f=!0){s=p.value,f=!1;const t=s;if(e===Mt.symbol&&fS(t)){if(!a){d(o,n);const e=yield pS(m(n,u));a=!0,e.length>0&&(yield yield pS(new Rt.FI({event:{case:"hookContext",value:new Rt.Ng({hookAdditionalContexts:[...e]})}})))}yield yield pS(t)}else yield yield pS(t)}}catch(e){r={error:e}}finally{try{f||t||!(i=g.return)||(yield pS(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 pS(m(n,u)))}}))}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(h)?(()=>hS(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 hS(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=mS(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,Gr.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}})}}gS.CARRIERS_BY_EXEC_ID_MAX=32,Error,so.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 vS=["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 yS(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,vS)}function wS(e){const t=(0,ey.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,ey.sh)(e.parentConversationId);return`${ey.O2}/${r}/subagents/${t}.${e.ext}`}return`${ey.O2}/${t}/${t}.${e.ext}`}function bS(e){const t=(0,ey.sh)(e.conversationId);return`${ey.O2}/${t}.${e.ext}`}function SS(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(wS({conversationId:e.conversationId,ext:t,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&s(wS({conversationId:e.conversationId,ext:t,kind:"primary"})),o&&s(bS({conversationId:e.conversationId,ext:t}));return i}var kS;(()=>{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"}(kS||(kS={}));var ES=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},xS=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},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});function _S(e){switch(e){case Ze.xyI.AGENT:return"agent";case Ze.xyI.ASK:return"ask";case Ze.xyI.PLAN:return"plan";case Ze.xyI.DEBUG:return"debug";case Ze.xyI.TRIAGE:return"triage";case Ze.xyI.PROJECT:return"project";case Ze.xyI.MULTITASK:return"multitask";case Ze.xyI.CUSTOM:return"custom";case Ze.xyI.UNSPECIFIED:default:return"agent"}}function PS(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 IS(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 TS=new TextEncoder,RS=new TextDecoder,AS=new class{serialize(e){const t=JSON.stringify(e,PS);return TS.encode(t)}deserialize(e){const t=RS.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,IS):JSON.parse(t)}};function OS(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 MS(e,t,r){return ES(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=AS.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 jS(e,t){switch(e.type){case"text":return t?DS(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 DS(e){return yS(e)}function NS(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function $S(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?DS(e):e;return r?NS(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=NS(t?DS(e.text):e.text);return jS(Object.assign(Object.assign({},e),{text:r}),!1)}return jS(e,t)})).filter(Boolean).join("\n")}function LS(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?DS(n):n,i="assistant"===e.role?NS(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?DS(r.text):r.text,i="assistant"===e.role?NS(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 FS(e){return e.endsWith("\n")?e:`${e}\n`}function US(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 BS(e){if("system"===e.role||OS(e))return;const t=LS(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 zS{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=wS({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}writeFromStateFull(e,t,r){return ES(this,arguments,void 0,(function*(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const i=xS(o,(0,l.VI)(e.withName("writeFromState")),!1);try{const e=yield function(e,t,r){return ES(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=xS(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=>ES(this,void 0,void 0,(function*(){i++;const r=yield t.getBlob(s,e);if(r)try{const e=Ze.Anz.fromBinary(r);return i+=e.summarizedMessages.length,yield MS(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=xS(n,(0,l.VI)(e.withName("hydratePromptMessages")),!1),y=yield MS(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&&!OS(e)));return a.push(...w),a}catch(e){n.error=e,n.hasError=!0}finally{CS(n)}}))}(i.ctx,this.blobStore,t),{overviewFactory:o}=n,s=US(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=$S(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=LS(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:_S(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=BS(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"),FS(n)))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{CS(o)}}))}writeFromStateIncremental(e,t,r,n){return ES(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=US(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=xS(i,(0,l.VI)(e.withName("writeFromStateIncremental")),!1);if(s===n&&c)try{return yield u(this.resolveFilePath(r,"jsonl"),FS(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 MS(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=BS(e);t&&i.push(t)}if(i.push(...a.jsonlLines),i.length>0){const e=FS(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{CS(i)}}))}}class WS extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class HS extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}function qS(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${GS}`}(t,r);throw new HS(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 GS="To view or modify configured hooks, go to Cursor Settings > Hooks.",VS="Agent note: Do not suggest workarounds to the blocked tool.";function JS(e){return e.includes(VS)?e:`${e}\n\n${VS}`}function KS(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function ZS(e,t){return JS(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${GS}`)}function YS(e){return function(e){return e instanceof WS}(e)||function(e){return e instanceof HS}(e)}var XS=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 QS{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.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 XS(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,Ys.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){var t;this.sessionEnvById.delete(e.sessionId);const r=null!==(t=this.activeSessionIdsByConversationId.get(e.conversationId))&&void 0!==t?t:[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId))}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);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)}}getTranscriptPathIfExists(e){return XS(this,void 0,void 0,(function*(){try{const t=(0,ey.Rv)((0,i.homedir)(),this.workspacePath),r=SS({conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of r)try{return yield(0,ho.access)(e),e}catch(e){}return null}catch(e){return null}}))}getSubagentTranscriptPathIfExists(e){return XS(this,void 0,void 0,(function*(){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,ey.Rv)((0,i.homedir)(),this.workspacePath),n=SS({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return yield(0,ho.access)(e),e}catch(e){}return null}catch(e){return null}}))}hasHooksForStep(e){var t;return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...(null!==(t=this.config.pluginHooks)&&void 0!==t?t:[]).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;const n=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,this.config.userHooks];for(const r of n){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 n of null!==(r=this.config.pluginHooks)&&void 0!==r?r:[]){const r=n.config.hooks[e];if(r&&(t?be(r,t):r).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":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,executionEnv:n}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version},this.globalContext.user_email&&{CURSOR_USER_EMAIL:this.globalContext.user_email}),t&&{CURSOR_TRANSCRIPT_PATH:t}),{CLAUDE_PROJECT_DIR:this.workspacePath}),this.sessionEnv),void 0!==r?this.sessionEnvById.get(r):void 0),n)}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=r.loop_count,o=t.loop_limit;return null!==o&&(void 0===o?n>=5:n>=o)}executeHookForStep(e,t,r){return XS(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c,u,d,h;this.configReadyPromises.length>0&&(yield Promise.all(this.configReadyPromises));const p=function(e){return je.includes(e)}(e),f=t,m=p?null:f.conversation_id?yield this.getTranscriptPathIfExists(f.conversation_id):null;let g;if(e===ue.subagentStop){const e=t;g=e.subagent_id?yield this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const v=p?void 0:null!==(u=f.session_id)&&void 0!==u?u:f.conversation_id,y=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),void 0!==v&&{session_id:v}),{hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.globalContext.user_email}),!p&&{transcript_path:m}),e===ue.subagentStop&&{agent_transcript_path:null!=g?g:null}),w=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,y),b=[],S=(e,t)=>{var n;if(!e)return;const o=be(e,w),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&&b.push({type:"prompt",script:e,source:t}):Re(e)&&b.push({type:"command",script:e,cwd:i,env:null==r?void 0:r.env,source:t})};S(null===(n=this.config.enterpriseHooks)||void 0===n?void 0:n.hooks[e],"enterprise"),S(null===(o=this.config.teamHooks)||void 0===o?void 0:o.hooks[e],"team"),S(null===(i=this.config.projectHooks)||void 0===i?void 0:i.hooks[e],"project"),S(null===(s=this.config.userHooks)||void 0===s?void 0:s.hooks[e],"user"),S(null===(a=this.config.claudeProjectLocalHooks)||void 0===a?void 0:a.hooks[e],"claude-project-local"),S(null===(l=this.config.claudeProjectHooks)||void 0===l?void 0:l.hooks[e],"claude-project"),S(null===(c=this.config.claudeUserHooks)||void 0===c?void 0:c.hooks[e],"claude-user");for(const t of null!==(d=this.config.pluginHooks)&&void 0!==d?d:[]){const n=t.config.hooks[e];if(!(null==n?void 0:n.length))continue;const o=null!==(h=null==r?void 0:r.cwd)&&void 0!==h?h: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,w))Re(e)&&b.push({type:"command",script:e,cwd:o,env:null==r?void 0:r.env,source:"claude-plugin",attribution:i,pluginInstallPath:t.installPath})}if(0!==b.length)return this.executeAllAndMerge(e,b,y)}))}executeAllAndMerge(e,t,r){return XS(this,void 0,void 0,(function*(){const n=t.map(((t,n)=>XS(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=KS(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),i=Fe(e,t);if(i)return{success:!0,data:i,source:o,index:n}}return{success:!1,source:o,index:n}}})))),o=yield Promise.all(n),i=[];for(const e of o)e.success&&void 0!==e.data&&i.push(e.data);return function(e,t){var r;if(0===t.length)return;if(1===t.length)return t[0];const n=Me.includes(e),o=e===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 XS(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=KS(`Hook "${t.command}" execution failed: ${n}`),u=Fe(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=Fe(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=KS(`Hook "${t.command}" failed with exit code ${w.exitCode}${w.stderr?`: ${w.stderr.trim()}`:""}`),n=Fe(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=KS(`Hook "${t.command}" returned no output.`),n=Fe(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=Le({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=Le({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 XS(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=Fe(e,r);return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed},i)),s?{success:!0,data:s,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=KS(`Prompt hook failed: ${s}`),r=Fe(e,t);if(r)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a},i)),{success:!0,data:r,source:n,index:o}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a},i)),{success:!1,source:n,index:o}}finally{p()}}))}executeCommandScript(e){return XS(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,ho.mkdtemp)((0,s.join)((0,i.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(v,"payload.json");yield(0,ho.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,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,ho.rm)(v,{recursive:!0,force:!0})}catch(e){}}}))}}var ek=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 tk(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 rk{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}load(){return ek(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)=>ek(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 nk{constructor(e){this.config=e,this.configuredSteps=rk.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var ok=r("node:perf_hooks");function ik(e,t){void 0!==e&&t.length>0&&e.push(...t)}class sk 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 ak=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function lk({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 sk({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new ak.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 ck=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},uk=function(e){return this instanceof uk?(this.v=e,this):new uk(e)};const dk=(0,d.h)("generic-hooks");function hk(e,t,r,n){try{return lk({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof sk)return dk.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const pk=e=>Math.round(1e3*e)/1e3;function fk(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)=>ck(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));ik(s,hk(e,r,ue.postToolUseFailure,null==h?void 0:h.additional_context))}catch(t){dk.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}})),fireSuccessAsync:(n,c)=>ck(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));ik(s,hk(e,r,ue.postToolUse,null==u?void 0:u.additional_context))}catch(t){dk.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 mk(e,t,r,n,o,i,s,a){return ck(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=JS(r);try{ik(n.hookContextCollector,lk({hookEventName:ue.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof sk))throw t;dk.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))),ik(n.hookContextCollector,lk({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 sk;if(a){const e=KS(`${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}}dk.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(YS(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 gk(e){return e.toolCallId}function vk(e,t,r,n){return{execute(o,i,s){return ck(this,void 0,void 0,(function*(){var a,l,c,u,d,h,p,f,m,g;const{hookContext:v,helpers:y}=fk(o,i,t,r,n,s);let w;try{w=yield mk(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=ok.performance.now();try{const r=yield e.execute(o,i,s),a=pk(ok.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(YS(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);dk.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=pk(ok.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*yk(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}var wk=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 bk{readFile(e){return wk(this,void 0,void 0,(function*(){try{return yield ho.readFile(e,"utf-8")}catch(e){if("ENOENT"===(null==e?void 0:e.code))return;throw e}}))}exists(e){return wk(this,void 0,void 0,(function*(){try{return yield ho.access(e),!0}catch(e){return!1}}))}pathContainsSymlink(e,t){return wk(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,ho.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 Sk{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 kk(e){return!!e&&e.type!==Lo.vc.INSECURE_NONE&&e.type!==Lo.vc.UNSPECIFIED}const Ek="Shell";function xk(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=ZS("Command execution",i.user_message);throw new WS(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 Ck={toolName:Ek,getToolCallId:gk,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=kk(t.sandboxPolicy);Kt(t,yield xk({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 _k{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Ck)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Pk={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 Ik{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Pk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Tk={toolName:"ComputerUse",getToolCallId:gk,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new zd.ks({result:{case:"error",value:new zd.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 Rk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Tk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Ak={toolName:"Delete",getToolCallId:gk,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 Ok{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Ak)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Mk={toolName:"ReadLints",getToolCallId:gk,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Mg.Ek({result:{case:"rejected",value:new Mg.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 jk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Mk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Dk={toolName:"Fetch",getToolCallId:gk,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Sh.uN({result:{case:"error",value:new Sh.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 Nk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Dk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $k={toolName:"Grep",getToolCallId:gk,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 Ph.Ud({result:{case:"error",value:new Ph.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 Lk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,$k)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Fk={toolName:"List",getToolCallId:gk,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 _m.fv({result:{case:"rejected",value:new _m.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 Uk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Fk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var Bk=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const zk=(0,d.h)("hooks-exec:mcp");function Wk(e,t,r,n){try{return lk({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof sk)return zk.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class Hk{constructor(e,t,r,n){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n}execute(e,t,r){return Bk(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{ik(h,lk({hookEventName:ue.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof sk))throw t;zk.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:ZS("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]=hr.Value.fromJson(n));p=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])))}catch(t){zk.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}ik(h,lk({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 sk;if(r){const r=KS(`${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:ZS("MCP tool execution",r),isReadonly:!1})}})}zk.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=ZS("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=ok.performance.now();try{const n=yield this.innerExecutor.execute(e,t,r),o=pk(ok.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){zk.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 zk.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),n}return n}catch(t){const r=pk(ok.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 Bk(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 ik(a,Wk(e,r,ue.postToolUse,null==l?void 0:l.additional_context)),l}catch(t){return void zk.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 Bk(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}));ik(c,Wk(e,r,ue.postToolUseFailure,null==u?void 0:u.additional_context))}catch(t){zk.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}))}}const qk={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 Gk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,qk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Vk={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 Jk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Vk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Kk={toolName:"Read",getToolCallId:gk,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new lv.sV({result:{case:"rejected",value:new lv.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 qS((()=>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=ZS("File read",s.user_message);throw new WS(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 Zk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Kk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Yk={toolName:"RecordScreen",getToolCallId:gk,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new xv.Tj({result:{case:"failure",value:new xv.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 Xk{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,Yk)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var Qk=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 eE(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const tE={toolName:Ek,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:eE(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:e=>Qk(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"";Kt(t,yield xk({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:kk(t.requestedSandboxPolicy)}))})),runPostExecutionHooks:e=>Qk(void 0,void 0,void 0,(function*(){const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:i}=e,s=eE(r);yield o.executeHookForStep(ue.afterShellExecution,Object.assign(Object.assign({},n),{command:t.command,output:s,duration:i,sandbox:kk(t.requestedSandboxPolicy)}))}))};class rE{constructor(e,t,r){this.wrappedExecutor=vk(e,t,r,tE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var nE=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 oE{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 iE={toolName:Ek,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 oE,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=>nE(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",i=kk(t.requestedSandboxPolicy);Kt(t,yield xk({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:i}))})),runPostExecutionHooks:e=>nE(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:i}=e,s=kk(t.requestedSandboxPolicy);yield n.executeHookForStep(ue.afterShellExecution,Object.assign(Object.assign({},r),{command:t.command,output:o.getOutput(),duration:i,sandbox:s}))}))};class sE{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 uk?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}=fk(o,i,t,r,n,s),v=n.runPreExecutionHooks?e=>ck(this,void 0,void 0,(function*(){yield n.runPreExecutionHooks(e)})):void 0,y=yield uk(mk(o,i,t,m,g,n,((e,t)=>n.createRejectedEvent(e,t)),v));if("rejected"===y.type){yield yield uk(y.result);for(const e of yk(n,m))yield yield uk(e);return yield uk(void 0)}const w=ok.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 uk(x.next())).done);E=!0){u=k.value,E=!1;const e=u;b.onEvent(e),yield yield uk(e)}}catch(e){l={error:e}}finally{try{E||a||!(c=x.return)||(yield uk(c.call(x)))}finally{if(l)throw l.error}}}catch(e){S=!0;const t=pk(ok.performance.now()-w),r=e instanceof Error?e.message:String(e);yield uk(g.fireFailureAsync(t,r,"error"));for(const e of yk(n,m))yield yield uk(e);throw e}const C=pk(ok.performance.now()-w);if(n.runPostExecutionHooks)try{yield uk(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){dk.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(!S)if(b.isAborted())yield uk(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 uk(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 uk(g.fireFailureAsync(C,e,"error"))}for(const e of yk(n,m))yield yield uk(e)}))}}}(e,t,r,iE)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var aE=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{constructor(e,t,r){const n=new Map;this.wrappedExecutor=vk(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:gk,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=>aE(this,void 0,void 0,(function*(){const{args:r,toolUseId:n}=e;let o,i=!1;try{(yield(0,ho.stat)(r.path)).size>262144?i=!0:o=yield yu(r.path)}catch(e){}t.set(n,{contentBeforeWrite:o,fileTooLarge:i})})),runCleanup:e=>{t.delete(e)},runPostExecutionHooks:r=>aE(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,Zm.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 yu(e),r=Su(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 cE{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 rE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Mt.symbol?new sE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===jt.symbol?new lE(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ht.symbol?new Hk(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease):e.symbol===Ct.symbol||e.symbol===_t.symbol?new Zk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===tt.symbol?new Uk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ce.symbol?new Lk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ae.symbol?new Nk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ie.symbol?new Ok(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===se.symbol?new jk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===pt.symbol?new Gk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ft.symbol?new Jk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Q.symbol?new _k(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ee.symbol?new Ik(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===oe.symbol?new Rk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ht.symbol?new Xk(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===qt.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new Sk(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 rE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Mt.symbol?yield[t,new sE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===jt.symbol?yield[t,new lE(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ht.symbol?yield[t,new Hk(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease)]:t.symbol===Ct.symbol||t.symbol===_t.symbol?yield[t,new Zk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===tt.symbol?yield[t,new Uk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ce.symbol?yield[t,new Lk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ae.symbol?yield[t,new Nk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ie.symbol?yield[t,new Ok(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===se.symbol?yield[t,new jk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===pt.symbol?yield[t,new Gk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ft.symbol?yield[t,new Jk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Q.symbol?yield[t,new _k(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ee.symbol?yield[t,new Ik(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===oe.symbol?yield[t,new Rk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ht.symbol?yield[t,new Xk(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===qt.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[t,new Sk(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 uE,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())}))},hE=function(e){return this instanceof hE?(this.v=e,this):new hE(e)};const pE={cursor_version:null!==(uE=process.env.AGENT_CLI_STATIC_VERSION)&&void 0!==uE?uE:"1.0.0",user_email:null};function fE(e=process.cwd()){let t=e;const r={getCwd(){return dE(this,void 0,void 0,(function*(){return t}))},clone:e=>fE(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 hE?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,io.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 hE(p.shift()):yield hE(new Promise((e=>{f=e})));if(void 0!==m)throw m}))}};return r}function mE(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function gE(e){return"string"==typeof e&&e.length>0?e:void 0}function vE(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function yE(e){if(Array.isArray(e)&&e.every(vE))return e.map((e=>({id:e.id,value:e.value})))}class wE{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}dispose(){return dE(this,void 0,void 0,(function*(){yield this.sessionHooksRuntime.dispose()}))}}function bE(e={}){return{createHooksRuntime:t=>function(e){return dE(this,arguments,void 0,(function*(e,t={}){const r=yield new rk(new bk,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?tk():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 nk(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({},pE),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 QS(r,o,a,(null!==(e=t.createTerminalExecutor)&&void 0!==e?e:fE)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(s=t.useCommandHookStdinTransport,!0===s?"stdin":"legacy")});var s;return{hookExecutor:i,hooksConfigLease:n,dispose(){return dE(this,void 0,void 0,(function*(){i.clearSessionEnvironment()}))}}},dispose(){return dE(this,void 0,void 0,(function*(){}))}}}))}(t.workspaceState,e)}}var SE=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");function kE(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 EE=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 xE(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 _h,m=(0,i.homedir)(),g=id(m).dirPath;let v,y=!0;return{prepareLocalExtensibility(){return EE(this,void 0,void 0,(function*(){y=h&&(yield function(e){return EE(this,void 0,void 0,(function*(){if(!e)return!1;const t=(0,pr.createClient)(SE.I,e),r=yield async function(e,t){try{const r=await t.getManagedSkills()??[],n=await ow(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return sw.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,Qe.q6)(),{getManagedSkills:()=>EE(this,void 0,void 0,(function*(){var e;return null!==(e=(yield t.getManagedSkills(new rb.X8g({}))).skills)&&void 0!==e?e:[]}))});return"synced"===r.status}))}(e.dashboardTransport))}))},loadLocalExtensibility(t){return EE(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:AE(),getAgentSkills:e=>EE(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 _d(o,f,e,i,l,void 0))):[],a=function(e,t){const r=CE(t);return{getAllCursorRules(t){return EE(this,void 0,void 0,(function*(){return _E(yield e.getAllCursorRules(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===s.length?AE():1===s.length?s[0]:new Cd(s),{allowedRoots:u?n:[],excludedRoots:[]}),h=function(e,t){const r=CE(t);return{getAllCursorRules(t){return EE(this,void 0,void 0,(function*(){return _E(yield e.getAllCursorRules(t),r)}))},getAllAgentSkills(t){return EE(this,void 0,void 0,(function*(){return _E(yield e.getAllAgentSkills(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new Pd(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 Ld(e,l))):[],b=0===w.length?new Od:1===w.length?w[0]:new Ud(w),S=tS(t.services.pluginBootstrapOutputs),k=S&&p?new Td(o,(()=>({importThirdPartyPlugins:c})),void 0,S.pluginsService):void 0,E=S&&p?new Bd((()=>({importThirdPartyPlugins:c})),S.pluginsService):void 0,x=new Cd([a,h,...k?[k]:[]]),C=new Hy([h,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:u?n:[],userHomeDirectory:m}))),_=new Ud([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 EE(this,void 0,void 0,(function*(){if(!v)return;const e=v;v=void 0,yield function(e){return EE(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 kE(e)}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}))}(e)}))}}}function CE(e){const t=Promise.all(e.allowedRoots.map(TE)),r=Promise.all(e.excludedRoots.map(TE));return e=>EE(this,void 0,void 0,(function*(){const[n,o,i]=yield Promise.all([RE(e.fullPath),t,r]);return void 0!==n&&!i.some((e=>PE(n,e)))&&o.some((e=>PE(n,e)))}))}function _E(e,t){return EE(this,void 0,void 0,(function*(){const r=yield Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}))}function PE(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function IE(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}function TE(e){return EE(this,void 0,void 0,(function*(){try{return IE(yield(0,ho.realpath)(e))}catch(t){return IE(e)}}))}function RE(e){return EE(this,void 0,void 0,(function*(){try{return IE(yield(0,ho.realpath)(e))}catch(e){return}}))}function AE(){return{getAllCursorRules(){return EE(this,void 0,void 0,(function*(){return[]}))},reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}var OE=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};function ME(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":Gb.warn("[local-plugins-bootstrap]",t,null!=r?r:{});break;case"error":Gb.error("[local-plugins-bootstrap]",t,null!=r?r:{})}},increment(){},distribution(){},captureException(e,t){Gb.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,null!=t?t:{})}},u=jE(e.marketplaceOptions),d=void 0!==e.dashboardTransport,h=null!==(o=e.loadCursorFirstParty)&&void 0!==o?o:u||d;return{loadPluginBootstrapOutputs(t){return OE(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 OE(this,void 0,void 0,(function*(){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(yield qc(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,pr.createClient)(SE.I,e.dashboardTransport),n=Dl((()=>OE(this,void 0,void 0,(function*(){try{return yield r.getEffectiveUserPlugins(new rb.EwF({}))}catch(e){return{plugins:[]}}}))),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Dl((()=>OE(this,void 0,void 0,(function*(){var e,t;if(void 0===o)return{plugins:[]};try{const n=yield qc(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||zc(t)})).map((({key:e,entry:t})=>{const r=Gc(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=Gc(e.key);return new rb.vwy({name:t.name,marketplaceName:t.marketplaceName})}));l=null!==(t=null===(e=(yield r.resolvePluginsByRef(new rb.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 la(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new la(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:n,userHomeDirectory:a}):void 0,d=jE(u),p=new dw(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:eS,discoveredEntries:o,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,dispose(){return OE(this,void 0,void 0,(function*(){}))}};for(const e of m)Gb.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)Gb.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 jE(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}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())}))};class NE{getAllCursorRules(e){return DE(this,void 0,void 0,(function*(){return[]}))}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}class $E extends $y{constructor(e,t){super(e),this.sessionMcpLease=t}dispose(){const e=Object.create(null,{dispose:{get:()=>super.dispose}});return DE(this,void 0,void 0,(function*(){try{yield e.dispose.call(this)}finally{yield kE(this.sessionMcpLease)}}))}}function LE(e){const t=new _h;return{createResources(r){return DE(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 NE,p=null!==(a=r.workspaceServices.subagentsService)&&void 0!==a?a:new Od,f=null!==(l=r.workspaceServices.mcpLease)&&void 0!==l?l:new jp,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 bh(v,y):new wh(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 $y(n):new $E(n,m)}catch(e){throw yield kE(m),e}}))}}}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 UE=["cursorRulesService","getAgentSkills","subagentsService"],BE=new WeakSet;function zE(e){("object"==typeof e&&null!==e||"function"==typeof e)&&BE.add(e)}function WE(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&BE.has(e)}function HE(e,t){const r=Object.keys(t).filter((e=>!UE.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${UE.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of UE)Object.hasOwn(t,r)&&(e[r]=t[r])}function qE(e,t,r){return FE(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&&(zE(a.cursorRulesService),zE(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&&HE(s,e)}return s}catch(t){try{yield GE(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 GE(e,t){return FE(this,void 0,void 0,(function*(){const r=null==t?void 0:t.preserveSharedContributorsFrom;let n;const o=e=>FE(this,void 0,void 0,(function*(){try{yield kE(e)}catch(e){null!=n||(n=e)}}));if(e.subagentsService===(null==r?void 0:r.subagentsService)||WE(e.subagentsService)||(yield o(e.subagentsService)),e.cursorRulesService===(null==r?void 0:r.cursorRulesService)||WE(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 FE(this,void 0,void 0,(function*(){let t;for(let r=e.length-1;r>=0;r-=1)try{yield kE(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 VE=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 JE(e){return VE(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 kE(o)}catch(e){null!=r||(r=e)}}}if(void 0!==r)throw r}))}const KE=["project","user","team","mdm","plugins"],ZE=new Set([...KE,"all"]);function YE(e){if(void 0===e||0===e.length)return QE([]);for(const t of e)if(!ZE.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({},QE(KE)),{all:!0})}return QE(e)}function XE(e,t){return e[t]}function QE(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 ex=Object.freeze({}),tx=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:ex});var rx=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 nx(){return rx(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:Fb,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({},tx.metadata),e.metadata)),r=Object.assign(Object.assign(Object.assign({},tx),e),{metadata:t});return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:i});let a=yield qE(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 rx(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 VE(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 JE(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 VE(this,void 0,void 0,(function*(){var t,r;if(!g){g=!0;try{yield JE(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 rx(this,void 0,void 0,(function*(){l||(yield u((()=>rx(this,void 0,void 0,(function*(){var e,t;if(l)return;const r=a,o=yield qE(n,i,s);l?yield GE(o,{disposeLocalExtensibility:d}):(a=o,yield GE(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 rx(this,void 0,void 0,(function*(){l||(l=!0,yield u((()=>rx(this,void 0,void 0,(function*(){var e;try{yield GE(a,{disposeLocalExtensibility:d})}finally{yield null===(e=n.lifecycle)||void 0===e?void 0:e.dispose()}})))))}))}}}))}var ox=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 ix{requestApproval(e){return ox(this,void 0,void 0,(function*(){return{approved:!0}}))}}class sx{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}getPermissions(){return ox(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 ox(this,void 0,void 0,(function*(){}))}}class ax{open(e,t){return ox(this,void 0,void 0,(function*(){}))}getDiagnostics(e,t){return ox(this,void 0,void 0,(function*(){return[]}))}}class lx{getCodebaseReference(e,t){return ox(this,void 0,void 0,(function*(){}))}}class cx{constructor(e){this.inner=e}getState(e){return ox(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 ux{constructor(e){this.subagents=e.map((e=>new Rd.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Rd.b$.DEFAULT,isBackground:!1,source:"sdk"})))}getAllSubagents(){return ox(this,void 0,void 0,(function*(){return this.subagents}))}reload(){return ox(this,void 0,void 0,(function*(){return this.subagents}))}}var dx=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())}))},hx=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),px=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 fx=lb;function mx(e,t){return px(this,void 0,void 0,(function*(){const r=(0,s.dirname)(e);yield(0,ho.mkdir)(r,{recursive:!0}),yield(0,ho.writeFile)(e,t,"utf-8")}))}class gx{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=fx(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=wS({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new zS(this.projectDir,e.blobStore,mx,Object.assign({writeText:!1,writeJsonl:!0},t?{pathResolver:t}:{})),this.nestedSubagentTranscriptStore=new zS(this.projectDir,e.blobStore,mx,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=wS({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((()=>px(this,void 0,void 0,(function*(){try{yield e()}catch(e){Gb.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})))),this.writeChain}writeFromState(e,t){return px(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>px(this,void 0,void 0,(function*(){yield this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=yield(0,lr.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 px(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>px(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=wS({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=wS({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(fx(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var vx=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 yx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,wx="User aborted/interrupted manually.";class bx{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 rr}createOrResumeSession(e,t){return vx(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(!yx.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&nr(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 lr.We,r=(0,lr.sh)(e),n=new lr.pH(new lr.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 gx({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 vx(this,void 0,void 0,(function*(){var n;if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,i]=e.withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),i),{status:"background",backgroundReason:Ze.qLf.AGENT_REQUEST,toolCallCount:0}}const i=yield this.executeSubagent(e,t,r,o);return null===(n=this.onSessionCompleted)||void 0===n||n.call(this,t,i),i}))}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}awaitBackgroundWorkers(){return vx(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){Gb.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 vx(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 vx(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 vx(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 vx(this,void 0,void 0,(function*(){var o,i,s;let a,l=0;const c=new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:new Ze.RGk({text:r.prompt})})}}),u=new Ze.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(u.credentials=r.credentials);const d=new zb,h={sendUpdate:(e,r)=>vx(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)=>vx(this,void 0,void 0,(function*(){return function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return $n(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return Fn(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return zn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new hx.tz({result:{case:"rejected",value:new hx.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return Un(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)}))},p={handleCheckpoint:(e,t)=>vx(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,Lt(e.errorMessage)],[Mt,Ft(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:Jb(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),yield n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:wx}:{status:"success"}),{status:"completed",finalMessage:a,toolCallCount:l}}catch(r){const o=r instanceof Error?r.message:String(r);return Gb.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:wx}:{status:"error",error:o}}}))}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:wx}:{status:"error",error:t}}isAwaitBackgroundMode(e){var t;if(!Boolean(e.resumeAgentId&&!nr(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 vx(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 vx(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 vx(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 vx(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 vx(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 Sx=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),kx=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),Ex=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),xx=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),Cx=r("./src/agent/analytics.ts");function _x(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 Px("tool-call-started",e.message.value);case"partialToolCall":return Px("partial-tool-call",e.message.value);case"toolCallCompleted":return Px("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=_x(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 Px(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:Mx(r)}:{}):null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"delete",args:{path:t.path}},r?{result:jx(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:Dx(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:Nx(r)}:{}):null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"read",args:{path:t.path}},r?{result:Lx(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:Fx(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:Ux(r)}:{}):null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"readLints",args:{paths:t.paths}},r?{result:zx(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:Wx(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:qx(r)}:{}):null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"recordScreen",args:{mode:Gx(t.mode)}},r?{result:Vx(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:Hx(r)}:{}):null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"createPlan",args:{plan:t.plan}},r?{result:Jx(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:Zx(e.status)})))}},r?{result:Kx(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:Ix(t)},r?{result:Ax(r)}:{}):null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updatePrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"piReadToolCall":case"piBashToolCall":case"piEditToolCall":case"piWriteToolCall":case"piGrepToolCall":case"piFindToolCall":case"piLsToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function Ix(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:Tx(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:Rx(e.mode)}:{}),e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{})}function Tx(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function Rx(e){switch(e){case Rd.FL.AGENT:return"agent";case Rd.FL.PLAN:return"plan";default:return"unspecified"}}function Ax(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:Ox(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 Ox(e){switch(e){case Ze.qLf.AGENT_REQUEST:return"agentRequest";case Ze.qLf.USER_REQUEST:return"userRequest";case Ze.qLf.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function Mx(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 jx(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 Dx(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 Nx(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]=$x(n);return{status:"success",value:Object.assign(Object.assign({},Object.keys(r).length>0?{workspaceResults:r}:{}),t.activeEditorResult?{activeEditorResult:$x(t.activeEditorResult)}:{})}}return{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}}function $x(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 Lx(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 Fx(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 Ux(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:Bx(e.result.value.directoryTreeRoot)}}:{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;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(Bx))&&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 zx(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:Yx(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 Wx(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 Hx(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 qx(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 Gx(e){switch(e){case xv.$u.START_RECORDING:return"START_RECORDING";case xv.$u.SAVE_RECORDING:return"SAVE_RECORDING";case xv.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function Vx(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 Jx(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 Kx(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:Zx(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 Zx(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function Yx(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}const Xx={type:"object",properties:{},additionalProperties:!0};function Qx(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:tC(e)?e:void 0};var t}(e),n=void 0!==r.structuredContent?hr.Struct.fromJson(r.structuredContent):void 0;return new Tt.iz({result:{case:"success",value:new Tt.QW({content:r.content.map(eC),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 eC(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 tC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var rC=r("./src/agent/errors.ts"),nC=r("./src/agent/executor-common.ts"),oC=r("./src/agent/native/vendored-tree-sitter.ts"),iC=r("./src/agent/platform-package-locator.ts"),sC=r("./src/agent/sdk-config.ts"),aC=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lC=r("./src/agent/utils/logger.ts"),cC=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 uC={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dC=new Map;var hC=r("./src/agent/tools-option.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())}))};class fC{requestApproval(){return pC(this,void 0,void 0,(function*(){return{approved:!0}}))}}function mC(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof $y))throw new rC.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ht),i=Qx(t),s=new fC;e.resources.base.register(ht,{execute(e,t,r){return pC(this,void 0,void 0,(function*(){if(function(e){return e.providerIdentifier===ot}(t)){const o=yield em(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 gC={warn(){},error(){}},vC={log(){}};class yC{requestApproval(e){return pC(this,void 0,void 0,(function*(){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${wC(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 wC(e){switch(e.type){case gh.Shell:return"this shell command";case gh.Mcp:return"this MCP tool call";case gh.Write:return"this file edit";case gh.Delete:return"this file deletion";default:return"this operation"}}function bC(e){return void 0!==e&&"insecure_none"!==e.type}function SC(e,t){return pC(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,vC);YE(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}`);Mu=e}((0,sC.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(nC.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,nC.ly)(a.apiKey),(0,nC.mU)(a.apiKey)]),h=performance.now()-e}const f=a.workingDirectory||process.cwd();(0,oC.configureVendoredTreeSitterWorkspaceDir)(f);for(const e of null!==(r=a.dirs)&&void 0!==r?r:[])(0,oC.configureVendoredTreeSitterWorkspaceDir)(e);const m=(0,ey.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,iC.hQ)({binaryName:v,excludedWorkspaceDir:f}),g||(g=(0,fo.resolveRipgrepFromPath)()),g&&(0,fo.configureRipgrepPath)(g);let w,b=aS();if(a.apiKey)try{w=(0,nC.KU)(a.apiKey);const e=(0,pr.createClient)(SE.I,w),t=performance.now(),r=yield function(e){let t=dC.get(e);return t||(t=function(e){return cC(this,void 0,void 0,(function*(){try{const t=yield function(e){return cC(this,void 0,void 0,(function*(){const t=yield(0,nC.dC)(e,nC.EV);if(!t)return;const r=nC.EV.endsWith("/")?nC.EV.slice(0,-1):nC.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,nC.tF)(),"x-ghost-mode":(0,nC.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lC.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 uC;const r=new aC.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,nC.tF)()})})}catch(e){lC.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,nC.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 lC.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uC}}))}(e),dC.set(e,t),t.then((r=>{r===uC&&dC.get(e)===t&&dC.delete(e)}),(()=>{dC.get(e)===t&&dC.delete(e)}))),t}(a.apiKey);p=performance.now()-t;const n={getDefaultNetworkAllowlist:()=>pC(this,void 0,void 0,(function*(){return r.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})}))};b=new sb(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){lC.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 pC(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=bC(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,iC.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,fo.configureSandboxPrereqs)({sandboxBinaryPath:r})}(t),!(0,fo.isSandboxSupported)(void 0,{ctx:e.initializationCtx}))throw new rC.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=bC(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 ox(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=YE(e.settingSources),g=null!==(r=e.teamSettingsService)&&void 0!==r?r:aS(),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 _h,S=new qu(b,g,p),k=new ax,E=new lx,x=null===(t=e.getSmartModeClassifierAutoModeEnabled)||void 0===t?void 0:t.call(e),C=new sx(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=XE(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||XE(m,"project")||XE(m,"user")||T,D=XE(m,"project")||XE(m,"user")||XE(m,"mdm"),N=XE(m,"team"),$=N&&void 0!==e.dashboardTransport,L=XE(m,"project")||XE(m,"user")||N||$||T,F=t=>nx(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:lS({teamSettingsService:g,initializationCtx:e.initializationCtx,importThirdPartyPlugins:R,ignoreApprovals:!0,includeProjectMcp:XE(m,"project"),includeUserMcp:XE(m,"user"),includePluginMcp:T,inlineMcpServers:e.mcpServers})}:{}),T?{pluginBootstrap:ME({importThirdPartyPlugins:R,dashboardTransport:e.dashboardTransport})}:{}),D?{hooks:bE({includeProjectHooks:XE(m,"project"),includeUserHooks:XE(m,"user"),includeEnterpriseHooks:XE(m,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{}),L?{localExtensibility:xE({includeProjectExtensibility:XE(m,"project"),includeUserExtensibility:XE(m,"user"),includeManagedSkills:$,includeTeamExtensibility:N,includePluginExtensibility:T,teamSettingsService:g,getThirdPartyExtensibilityEnabled:I,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:R})}:{}),{resourceFactory:LE({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 cx(new Hv(e)),createSessionMcpLease:(t,r)=>lS({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 ix;return{pendingDecisionStore:r,fileChangeTracker:new xh(d),permissionsService:new tb(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 wE(new cE(e.resources,n.hookExecutor,(()=>function(e,t){var r,n,o,i;const s=null!==(n=null!==(r=mE(t,gE,"conversationId","conversation_id"))&&void 0!==r?r:e.sessionId)&&void 0!==n?n:"",a=null!==(o=mE(t,gE,"generationId","generation_id"))&&void 0!==o?o:s,l=null!==(i=mE(t,gE,"model"))&&void 0!==i?i:"unknown",c=mE(t,gE,"modelId","model_id"),u=mE(t,yE,"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 ux(null!==(r=e.customSubagents)&&void 0!==r?r:[]),o=t.services.subagentsService;return{subagentsService:void 0===o?n:new Ud([n,o])}}}]}:{})}));if(!j)return F({includeMcp:!1});try{return yield F({includeMcp:!0})}catch(e){return Gb.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:d,projectDir:h,enablePlugins:T,importThirdPartyPlugins:R}),F({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 yC: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,Cx.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)=>pC(this,void 0,void 0,(function*(){return function(e,t){return Hb.run(e,t)}(gC,(()=>pC(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,vC)),[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{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:Xx,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;mC(b,t.customTools);const l=null!==(s=t.blobStore)&&void 0!==s?s:new lr.ve;let d=null!==(c=t.initialState)&&void 0!==c?c:new Ze.Y9z({});const h=void 0!==t.model?new Ze.G4_({modelId:t.model.id,parameters:(null!==(u=t.model.params)&&void 0!==u?u:[]).map((e=>new Ze.SRo({id:e.id,value:e.value})))}):void 0,w=Array.isArray(e.images)?e.images.map((e=>{const t=(0,o.randomUUID)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),i=(0,nC.v8)(r);return new Ex.d(Object.assign(Object.assign({uuid:t},i?{mimeType:i}:{}),{dataOrBlobId:{case:"data",value:r}}))})):[],k=w.length>0?new Ex.xv({selectedImages:w}):void 0,E=function(e){switch(e){case"agent":return Ze.xyI.AGENT;case"plan":return Ze.xyI.PLAN;default:return}}(t.mode),x=new Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:new Ze.RGk(Object.assign({text:e.text,selectedContext:k},void 0!==E?{mode:E}:{}))})}}),C={sendUpdate:(e,t)=>pC(this,void 0,void 0,(function*(){const e=_x(t,g);null!==e&&(yield r.sendUpdate(e))})),query:(e,t)=>pC(this,void 0,void 0,(function*(){return function(e){var t;switch(e.query.case){case"webSearchRequestQuery":return Nn(e.id);case"webFetchRequestQuery":return Ln(e.id);case"switchModeRequestQuery":return Bn(e.id);case"askQuestionInteractionQuery":return Un(e.id,new hx.tz({result:{case:"rejected",value:new hx.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return Wn(e.id,new Rn.bK({result:{case:"success",value:new Rn.Jo},planUri:""}));case"setupVmEnvironmentArgs":return Hn(e.id,new xx.r$({result:{case:"success",value:new xx.JH}}));case"replaceEnvArgs":return qn(e.id,new kx.dV({result:{case:"failure",value:new kx.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return Gn(e.id,new Zn.HL({result:{case:"error",value:new Zn.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Vn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Jn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Kn(e.id,null===(t=e.query.value.args)||void 0===t?void 0:t.description);case void 0:throw new rC.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new rC.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)}))};if(O!==t.apiKey||!M){yield Promise.all([(0,nC.ly)(t.apiKey),(0,nC.mU)(t.apiKey)]);const e=(0,nC.KU)(t.apiKey),r=oo((0,pr.createClient)(Sx.N,e),{injectTraceHeaders:!0});M=new In(r),O=t.apiKey}const _=(0,nC.Vh)(M,(()=>{const e=(0,nC.KU)(t.apiKey),r=oo((0,pr.createClient)(Sx.N,e),{injectTraceHeaders:!0}),n=new In(r);return M=n,O=t.apiKey,n})),P=new bx({agentClient:_,getResources:e=>pC(this,[e],void 0,(function*({agentId:e}){let r=S.get(e);return r||(r=yield R.createSessionRuntime({sessionId:e,mcpServersOverride:v,extraMcpTools:y}),mC(r,t.customTools),r.resources.base.register(tr,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=er(P);b.resources.base.register(tr,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 dx(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){Gb.warn("[hooks-adapter] sessionStart hook failed:",e)}}))},onSessionEnd(e,t){return dx(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){Gb.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()}))},onBeforeSubmitPrompt(e){return dx(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){Gb.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}}))},onTurnCompleted(e){return dx(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 dx(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){Gb.warn("[hooks-adapter] onTurnError stop hook failed:",e)}}))},onTurnAborted(e){return dx(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){Gb.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}}))},dispose(){return dx(this,void 0,void 0,(function*(){yield r.dispose()}))}}}({workspaceRuntime:T,sessionState:b.state,metadata:b.metadata}):void 0,j=new gx({workspacePath:f,conversationId:g,blobStore:l}),D=Object.assign(Object.assign({},void 0!==t.allowedTools?{[hC.$$]:t.allowedTools.join(",")}:{}),void 0!==t.disallowedTools&&t.disallowedTools.length>0?{[hC.VJ]:t.disallowedTools.join(",")}:{}),N=function(e,t,r){var n;const{hooks:o}=r,[i,s]=e.withCancel(),a=new zb;let l=r.initialState;const c={handleCheckpoint(e,t){return Zb(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=Jb(function(e,t){if((0,lr.TU)(t))return t;const r=Kb.get(e);if(void 0!==r)return r;const n=(0,lr.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return Kb.set(e,n),n}(r.conversationId,r.blobEncryptionKey),null===(n=r.runOptions)||void 0===n?void 0:n.headers),p=(()=>Zb(this,void 0,void 0,(function*(){var e,n,s,d,p,f,m,g,v;const y=Xb(r,0,Yb(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;Gb.warn("[agent-session-runner] sessionStart hook failed:",e)}let w=t,b=0;for(;w;){const e=Xb(r,b,Yb(w));try{yield null===(n=null==o?void 0:o.onBeforeSubmitPrompt)||void 0===n?void 0:n.call(o,e)}catch(e){Gb.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=Qb(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=>{Gb.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 Ze.QFf({action:{case:"userMessageAction",value:new Ze.Vtf({userMessage:new Ze.RGk({text:k})})}})):w=void 0}var S,k})))().finally((()=>Zb(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){Gb.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){Gb.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 pC(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((()=>pC(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){lC.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 pC(this,void 0,void 0,(function*(){yield R.reload()}))},dispose(){return pC(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)},"../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:()=>Le,E_S:()=>Fe,Ico:()=>Me,O3I:()=>re,tBH:()=>Q,MEY:()=>$,Fmf:()=>Ne,jIB:()=>Te,VDJ:()=>pe,X5z:()=>de,$HQ:()=>B,YaX:()=>H,PKk:()=>Ue,FC3:()=>G,_NE:()=>U,eaG:()=>ce,q2e:()=>Y});const n=BigInt(0),o=BigInt(8),i=BigInt(16),s=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<o|BigInt(t)}return{version:4,value:r}}function l(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=a(n);if(!o)return;t.push(Number(o.value>>i&s)),t.push(Number(o.value&s))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function c(e){var t;return null!==(t=a(e))&&void 0!==t?t:function(e){const t=j(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=l(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<i|BigInt(t)),n)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),s=t.slice(r+2),a=l(o),c=l(s);if(!a||!c)return;const u=a.length+c.length;return u>7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...c].reduce(((e,t)=>e<<i|BigInt(t)),n)}}(e)}function u(e,t){const r=j(e),n=j(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=c(t.slice(0,r)),o=c(e);if(!n||!o||n.version!==o.version)return!1;const i=Number(t.slice(r+1)),s=4===n.version?32:128;if(!Number.isInteger(i)||i<0||i>s)return!1;const a=BigInt(s-i);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}const d="Blocked by MCP Network Admin Server Controls";function h(e){return/\s/.test(e)}const p="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",f=new RegExp(`^(?:${p}\\.)*${p}$`),m=new RegExp(`^\\*\\.(?:${p}\\.)*${p}$`),g="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${g}(?:\\.${g}){3}$`),y=/^[0-9a-f:]+$/,w=new RegExp(`^(?:${g}(?:\\.${g}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function b(e){const t=j(e);return t.length>0&&t.length<=253&&f.test(t)}function S(e){const t=j(e);return v.test(t)||function(e){const t=j(e);if(!y.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch(e){return!1}}(t)}function k(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return k(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return k(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(b(t)||S(t))}(t.hostname)}catch(e){return!1}}(e);const t=j(e);return"*"===t||!!m.test(t)||(t.includes("/")?function(e){const t=j(e);if(!w.test(t))return!1;const[r]=t.split("/");return void 0!==r&&u(r,t)}(t):b(t)||S(t))}function C(e){if(P.has(e))return P.get(e);P.size>=_&&P.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${j(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(h(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch(e){return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),i=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===i.length||!x(i)||i!==o&&"*"===i?void 0:i}(e);return P.set(e,t),t}const _=2048,P=new Map,I=new Map;function T(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function R(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function A(e,t){return function(e,t,r){const n=O(t);if(!n)return!1;let o;try{o=new URL(e)}catch(e){return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(i=o.hostname,s=n.hostname,!i.includes("*")&&j(i)===j(s)&&(T(a=o.pathname,l=n.pathname)||T(R(a),R(l)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:T(e,t)}(o.search,n.search,r));var i,s,a,l}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function O(e){const t=e.trim();if(0===t.length||h(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=D(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!j(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(j(r.hostname)!==j(o))return}return r}}function M(e,t){if(T(e,t))return!0;let r;return I.has(t)?r=I.get(t):(I.size>=_&&I.clear(),r=D(t),I.set(t,r)),!!r&&u(r.hostname,e)}function j(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function D(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch(e){return}}function N(e){return(null!=(t=e.mcpNetworkAllowlist)?t:[]).flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));var t}function $(e,t){var r,n;if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!O(e))return{allowed:!1,message:null!==(r=t.blockMessage)&&void 0!==r?r:d};const o=N(t);return o.length>0&&o.some((t=>function(e,t){const r=O(t);if(!r)return!1;if(!e.includes("://"))return u(j(r.hostname),e);if(A(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch(e){return}}(e);return void 0!==n&&A(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:null!==(n=t.blockMessage)&&void 0!==n?n:d}}function L(e){const t=null==e?void 0:e.trim();return t&&t.length>0?t:void 0}function F(e,t,r){return void 0!==(null==r?void 0:r.command)&&void 0===r.url&&void 0===t&&!0===(null==e?void 0:e.allowUserOverrideMcpServers)}function U({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:i=!0}){const s=null==e?void 0:e.allowedMcpServers,a=function(e){var t;if(!0!==(null==e?void 0:e.allowUserOverrideMcpServers))return;const r=(null!==(t=e.deniedMcpServers)&&void 0!==t?t:[]).flatMap((e=>{const t=L(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(void 0!==r&&r.includes("*")){const e=C(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=C(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const i=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===i||i.includes("@"))return;const s=C(i.replace(/:\d+$/,""));if(void 0!==s)return s;try{return C(new URL(e).hostname)}catch(e){return}}(t);return void 0===r?[]:[r]}));return r.length>0?r:void 0}(e),l=void 0===t?void 0:function(e,t){return null==e?void 0:e.find((e=>function(e,t){const r=L(e.command),n=L(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&T(r,t.command),i=void 0===n||void 0!==t.url&&M(n,t.url);return o&&i}(e,t)))}(s,t),c=F(e,l,t),u=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){var n,o;return void 0===r?(null!==(o=null===(n=null==e?void 0:e.allowedMcpServers)||void 0===n?void 0:n.length)&&void 0!==o?o:0)>0:void 0!==t||F(e,t,r)}({allowedMcpConfiguration:e,matchedServer:l,server:t})||void 0===t&&void 0!==a,d=void 0===t?i?null==s?void 0:s.flatMap((e=>{var t;return null!==(t=e.networkAllowlist)&&void 0!==t?t:[]})):void 0:c?[]:function(e,t,r){var n;return void 0===e?r:[...null!==(n=e.networkAllowlist)&&void 0!==n?n:[],...void 0!==L(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(l,t,o),h=void 0===t?void 0:c?"allow_all":function(e,t){var r,n;if(void 0!==L(null==e?void 0:e.command)&&void 0!==t.command&&void 0===t.url)return null!==(r="allow_all"===(n=null==e?void 0:e.networkMode)||"allowlist"===n||"deny_all"===n||"no_sandbox"===n?n:void 0)&&void 0!==r?r:"no_sandbox"}(l,t),p=void 0===t||c?a:void 0;return Object.assign(Object.assign(Object.assign(Object.assign({enabled:u,mcpNetworkAllowlist:d},void 0!==h?{mcpNetworkMode:h}:{}),void 0!==p?{mcpNetworkDenylist:p}:{}),void 0!==r?{localAgentNetworkAllowlist:r}:{}),void 0!==n?{blockMessage:n}:{})}function B(e){if(!0===(null==e?void 0:e.enabled)&&"no_sandbox"!==e.mcpNetworkMode)return e}function z(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function W(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function H(e,t,r){var n;if(void 0===t)return!0;if(!0===t.disableAll)return!1;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:M;return t.some((t=>{const r=z(t.command),n=W(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&T(r,e.command),s=void 0===n||void 0!==e.url&&o(n,e.url);return i&&s}))}(e,t,r)}(e,o,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){var n;const o=null!==(n=null==r?void 0:r.matchesServerUrlPattern)&&void 0!==n?n:M;return(null!=t?t:[]).some((t=>{const r=z(t.command),n=W(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&T(r,e.command),s=void 0===n||void 0!==e.url&&o(n,e.url);return i&&s}))}(e,t.deniedMcpServers,r)}function q(e){return(null!=e?e:[]).flatMap((e=>{var t,r;const n=null===(t=e.name)||void 0===t?void 0:t.trim();if(void 0===n||0===n.length)return[];const o=(null!==(r=e.toolAllowlist)&&void 0!==r?r:[]).map((e=>e.trim())).filter((e=>e.length>0));return 0===o.length?[`${n}:*`]:o.map((e=>`${n}:${e}`))}))}function G({autoRunControls:e,allowedMcpServers:t,isMcpSettingsOverhaulEnabled:r}){var n;const o=!0===(null==e?void 0:e.enabled)&&null!==(n=e.mcpToolAllowlist)&&void 0!==n?n:[];return i=r?[...q(t),...o]:[...o],[...new Set(i)];var i}var V=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class J{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}get(e){return V(this,void 0,void 0,(function*(){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(()=>V(this,void 0,void 0,(function*(){try{const r=yield e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch(e){}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})))(),this.refreshInFlight=r}return t}const r=yield e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}))}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}function K(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function Z(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch(e){return{host:null,origin:null,pathname:null}}}(e),n=!1!==(null==t?void 0:t.includePath);return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function Y(e,t){return Z(e,t)}var X=r("crypto");function Q(e,t){const r=null==e?void 0:e.access_token,n="string"==typeof r?r.length:0,o=Boolean(null==e?void 0:e.refresh_token),i="number"==typeof(null==e?void 0:e.expires_in)&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:(null==t?void 0:t.expiresInIsFresh)&&null!==i?Date.now()+Math.round(1e3*i):null,grantedScope:"string"==typeof(null==e?void 0:e.scope)&&e.scope.length>0?e.scope:null}}function ee(e){if(e)return(0,X.createHash)("sha256").update(e).digest("hex").slice(0,12)}function te(e){if(e&&0!==e.length)return ee(JSON.stringify([...e].sort()))}function re(e){var t,r;return{clientIdHash:ee(null==e?void 0:e.client_id),clientSecretHash:ee(null==e?void 0:e.client_secret),redirectUrisHash:te(null==e?void 0:e.redirect_uris),redirectUriCount:null!==(r=null===(t=null==e?void 0:e.redirect_uris)||void 0===t?void 0:t.length)&&void 0!==r?r:0}}function ne(e,t){let r=e;for(const e of t){if("object"!=typeof r||null===r||!(e in r))return;r=r[e]}return r}function oe(e,t){for(const r of t)if("string"==typeof ne(e,r.split(".")))return ne(e,r.split("."))}const ie="[REDACTED]",se=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function ae(e){return e.replace(/((?:access_token|refresh_token|id_token|client_secret|authorization|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${ie}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${ie}`)}function le(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function ce(e,t){return le(ae(e),null==t?void 0:t.maxLength)}function ue(e){if("string"==typeof e)return le(ae(e));if(void 0!==e)try{const t=JSON.stringify(e,((e,t)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||se.test(t)}(e)?ie:"string"==typeof t?ae(t):t));if(!t)return;return le(t)}catch(e){return}}function de(e){var t,r,n,o,i;const s=e instanceof Error?e.name:null!=e?typeof e:void 0,a=e instanceof Error?e.message:null!=e?String(e):void 0,l=void 0!==a?ce(a):void 0,c=oe(e,["code","cause.code"]),u=null!==(t=function(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}(e))&&void 0!==t?t:oe(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),d=null!==(r=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=ne(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e))&&void 0!==r?r:function(e){var t;if(!e)return;const r=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)/),n=null!==(t=null==r?void 0:r[1])&&void 0!==t?t:null==r?void 0:r[2];if(!n)return;const o=Number.parseInt(n,10);return Number.isNaN(o)?void 0:o}(l),h=ue(null!==(i=null!==(o=null!==(n=ne(e,["response","body"]))&&void 0!==n?n:ne(e,["body"]))&&void 0!==o?o:ne(e,["data"]))&&void 0!==i?i:ne(e,["cause","body"])),p=function(e){var t,r;const n=null===(t=e.message)||void 0===t?void 0:t.toLowerCase(),o=null===(r=e.code)||void 0===r?void 0:r.toLowerCase();return(null==n?void 0:n.includes("timed out"))||(null==n?void 0:n.includes("timeout"))||(null==n?void 0:n.includes("etimedout"))||"etimedout"===o?"timeout":(null==n?void 0:n.includes("enotfound"))||(null==n?void 0:n.includes("eai_again"))||(null==n?void 0:n.includes("dns"))||"enotfound"===o||"eai_again"===o?"dns":(null==n?void 0:n.includes("certificate"))||(null==n?void 0:n.includes("tls"))||(null==n?void 0:n.includes("ssl"))?"tls":(null==n?void 0:n.includes("econnreset"))||(null==n?void 0:n.includes("connection reset"))||"econnreset"===o?"connection_reset":(null==n?void 0:n.includes("econnrefused"))||(null==n?void 0:n.includes("connection refused"))||"econnrefused"===o?"connection_refused":void 0}({message:l,code:c});return K({errorName:s,errorMessage:l,errorType:null!=e?typeof e:void 0,httpStatus:d,oauthErrorCode:u,errorResponseSummary:h,networkClassification:p,sdkErrorKind:u?"oauth_error":p?"auth_transport_error":l?"generic_error":void 0})}const he={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function pe(e){var t,r,n,o,i,s,a,l,c,u;const d=null!==(c=e.message)&&void 0!==c?c:he[e.event],h={event:e.event,cursorMcp:{oauth:K(Object.assign({},e.metadata))}},p=null!==(u=e.level)&&void 0!==u?u:"info";"error"!==p?"warn"!==p?"debug"!==p?null===(l=(a=e.logger).info)||void 0===l||l.call(a,d,h):null===(s=(i=e.logger).debug)||void 0===s||s.call(i,d,h):null===(o=(n=e.logger).warn)||void 0===o||o.call(n,d,h):null===(r=(t=e.logger).error)||void 0===r||r.call(t,d,e.error,h)}var fe=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const me=4096;function ge(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function ve(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function ye(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function we(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function be(e,t){var r,n,o,i,s;if(null==e)return{kind:"none",bytes:0,contentLength:we(t.get("content-length"))};if("string"==typeof e){const n=(new TextEncoder).encode(e).length;return{kind:"text",bytes:n,contentLength:null!==(r=we(t.get("content-length")))&&void 0!==r?r:n}}if(e instanceof URLSearchParams){const r=e.toString(),o=(new TextEncoder).encode(r).length;return{kind:"text",bytes:o,contentLength:null!==(n=we(t.get("content-length")))&&void 0!==n?n:o}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:null!==(o=we(t.get("content-length")))&&void 0!==o?o:e.size}:e instanceof ArrayBuffer?{kind:"binary",bytes:e.byteLength,contentLength:null!==(i=we(t.get("content-length")))&&void 0!==i?i:e.byteLength}:ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:null!==(s=we(t.get("content-length")))&&void 0!==s?s:e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:we(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:we(t.get("content-length"))}}function Se(e,t){var r;if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const n="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch(e){return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch(e){return}}}(t):t instanceof URLSearchParams&&null!==(r=t.get("grant_type"))&&void 0!==r?r:void 0;return n?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(n):void 0}function ke(e){var t,r,n,o;const{input:i,init:s}=e,a=Z(ve(i)),l=function(e,t){const r=new Headers(ge(e)?e.headers:void 0);return new Headers(null==t?void 0:t.headers).forEach(((e,t)=>{r.set(t,e)})),r}(i,s),c=ye(l),u=l.get("content-type"),d=ee(null!==(t=l.get("mcp-session-id"))&&void 0!==t?t:void 0),h=l.get("authorization"),p=h&&null!==(r=h.split(/\s+/,1)[0])&&void 0!==r?r:null;return{method:(null!==(o=null!==(n=null==s?void 0:s.method)&&void 0!==n?n:ge(i)?i.method:void 0)&&void 0!==o?o:"GET").toUpperCase(),url:a,headers:{names:c,count:c.length},contentType:u,body:be(null==s?void 0:s.body,l),sessionIdHash:null!=d?d:null,authorizationScheme:p}}function Ee(e,t){var r,n,o,i,s;const a=ye(e.headers),l=we(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:a,count:a.length},contentType:e.headers.get("content-type"),body:Object.assign({kind:null===e.body?"none":"stream",bytes:null===e.body?0:l,contentLength:l},void 0!==t?{errorSummary:t}:{}),sessionIdHash:null!==(n=ee(null!==(r=e.headers.get("mcp-session-id"))&&void 0!==r?r:void 0))&&void 0!==n?n:null,wwwAuthenticateHash:null!==(i=ee(null!==(o=e.headers.get("www-authenticate"))&&void 0!==o?o:void 0))&&void 0!==i?i:null,mcpProtocolVersion:null!==(s=e.headers.get("mcp-protocol-version"))&&void 0!==s?s:null}}function xe(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function Ce(e,t){return fe(this,void 0,void 0,(function*(){try{const r=yield e.clone().text();return r.length>t?r.slice(0,t):r}catch(e){return}}))}function _e(e){return fe(this,void 0,void 0,(function*(){if(!function(e,t){var r,n;const o=ke({input:e,init:t});if(void 0!==Se(o.contentType,null==t?void 0:t.body))return!0;const i=null!==(n=null===(r=o.url.path)||void 0===r?void 0:r.toLowerCase())&&void 0!==n?n:"";return i.endsWith("/token")||i.includes("/oauth/token")||i.includes("/connect/token")}(e.input,e.init))return;const t=yield Ce(e.response,me);if(void 0!==t)try{return ue(JSON.parse(t))}catch(e){return ce(t,{maxLength:me})}}))}function Pe(e){return fe(this,void 0,void 0,(function*(){const t=yield function(e,t){return fe(this,void 0,void 0,(function*(){var r,n;try{if(t.ok)return;const o=null!==(n=null===(r=t.headers.get("content-type"))||void 0===r?void 0:r.toLowerCase())&&void 0!==n?n:"";if(!o.includes("json")&&!o.includes("text"))return;const i=yield Ce(t,me);if(void 0===i)return;return function(e){if("/mcp"!==(t=Z(ve(e.input)).path)&&!0!==(null==t?void 0:t.endsWith("/mcp")))return ce(e.rawText,{maxLength:me});var t;try{const t=JSON.parse(e.rawText);return"object"==typeof t&&null!==t?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?ce(r.message,{maxLength:me}):void 0;return void 0!==n||void 0!==o?JSON.stringify(Object.assign(Object.assign({},void 0!==n?{code:n}:{}),void 0!==o?{message:o}:{})):void 0}(t):void 0}catch(e){return}}({input:e,rawText:i})}catch(e){return}}))}(e.input,e.response);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?yield _e({input:e.input,response:e.response,init:e.init}):void 0}}))}function Ie(e,t,r){var n;try{e()}catch(e){null===(n=t.warn)||void 0===n||n.call(t,"MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function Te(e){const{fetch:t,logger:r,metadata:n,logSuccessfulExchanges:o=!0}=e;return(e,i)=>fe(this,void 0,void 0,(function*(){const s=Date.now();try{const a=yield t(e,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:c}=a.ok?{}:yield Pe({input:e,init:i,response:a});return!o&&a.ok||Ie((()=>{!function(e){var t,r;const{logger:n,response:o}=e,i=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:i,responseErrorSummary:s,oauthTokenErrorBodySummary:a}=e,l=ke({input:t,init:r}),c=Se(l.contentType,null==r?void 0:r.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign({},i),{request:l,response:Ee(n,s)}),void 0!==c?{oauth:{grantType:c}}:{}),void 0!==a?{oauthTokenErrorBodySummary:a}:{})}}}(e);o.ok?null===(t=n.info)||void 0===t||t.call(n,"MCP HTTP exchange completed",i):null===(r=n.warn)||void 0===r||r.call(n,"MCP HTTP exchange completed",i)}({logger:r,input:e,init:i,response:a,durationMs:Date.now()-s,metadata:n,responseErrorSummary:l,oauthTokenErrorBodySummary:c})}),r,"success"),a}catch(t){const o=function(e){var t,r;if(!e||"object"!=typeof e)return;const n=[e.response,null===(t=e.cause)||void 0===t?void 0:t.response];for(const e of n)if(e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status&&"headers"in e&&"function"==typeof(null===(r=e.headers)||void 0===r?void 0:r.get))return e}(t),{responseErrorSummary:a,oauthTokenErrorBodySummary:l}=o?yield Pe({input:e,init:i,response:o}):{};throw Ie((()=>{!function(e){var t;const{logger:r}=e;null===(t=r.warn)||void 0===t||t.call(r,"MCP HTTP exchange failed",function(e){var t;const{input:r,init:n,error:o,durationMs:i,metadata:s,responseFromError:a,responseErrorSummary:l,oauthTokenErrorBodySummary:c}=e,u=de(o),d=ke({input:r,init:n}),h=Se(d.contentType,null==n?void 0:n.body),p=void 0!==a?Ee(a,l):{status:null!==(t=u.httpStatus)&&void 0!==t?t:null,ok:null,headers:{names:[],count:0},contentType:null,body:Object.assign({kind:"none",bytes:null,contentLength:null},void 0!==l?{errorSummary:l}:{}),sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null};return{event:"mcp_http_exchange",outcome:"error",durationMs:i,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},s),{request:d,response:p}),void 0!==h?{oauth:{grantType:h}}:{}),void 0!==c?{oauthTokenErrorBodySummary:c}:{}),{error:xe(u)})}}}(e))}({logger:r,input:e,init:i,error:t,durationMs:Date.now()-s,metadata:n,responseFromError:o,responseErrorSummary:a,oauthTokenErrorBodySummary:l})}),r,"failure"),t}}))}new Set(["InvalidGrantError","InvalidRequestError"]),new Set(["SiblingAlreadyRefreshedError","OAuthRefreshTransientError","AbortError","TimeoutError","ServerError","TemporarilyUnavailableError"]);const Re=["0.0.0.0/0","::/0"];function Ae(e){const t=(null!=e?e:[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));return{hasConfiguredEntries:t.length>0,hasInvalidEntries:r.length!==t.length,entries:r}}function Oe(e){const t=Ae(e.mcpNetworkAllowlist),r=Ae(e.mcpNetworkDenylist),n=e.mcpNetworkMode;if("deny_all"===n||r.entries.includes("*")||r.hasInvalidEntries)return{version:1,default:"deny"};if("allow_all"===n)return Object.assign({version:1,default:"deny",allow:[...Re]},r.entries.length>0?{deny:r.entries}:{});if("allowlist"===n||t.hasConfiguredEntries){const e=function(e){return e.entries.includes("*")?[...Re]:e.entries}(t);return e.length>0?Object.assign({version:1,default:"deny",allow:e},r.entries.length>0?{deny:r.entries}:{}):{version:1,default:"deny"}}return Object.assign({version:1,default:"deny",allow:[...Re]},r.entries.length>0?{deny:r.entries}:{})}function Me(e,t){return n=this,o=void 0,s=function*(){const{resolveSandboxPolicyForWorkspace:n}=yield Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),o={type:"workspace_readwrite",sandboxWorkspaceRoot:t,networkPolicy:Oe(e),networkPolicyStrict:!0},{policy:i}=yield n(t,{perUser:o});return i},new((i=void 0)||(i=Promise))((function(e,t){function r(e){try{l(s.next(e))}catch(e){t(e)}}function a(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i((function(e){e(n)}))).then(r,a)}l((s=s.apply(n,o||[])).next())}));var n,o,i,s}const je=["0.0.0.0/0","::/0"];function De(e){const t=(null!=e?e:[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function Ne(e){const t=!0===e.enabled,r=De(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...je];const t=De(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...je]:t.entries;if(!function(e){var t;return(null!==(t=e.mcpNetworkAllowlist)&&void 0!==t?t:[]).some((e=>e.trim().length>0))}(e))return[...je];const r=N(e);return r.includes("*")?[...je]:r}(e):[],i=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:i})}class $e extends Error{constructor(e,t){super(`MCP server "${e}" requires sandboxing because MCP Network Controls are enabled, but the sandbox is not supported on this platform or system. The server was not started.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]),new Set([429,502,503,504]);const Le=8192;function Fe(e,t){void 0!==t&&t.length>0&&e.searchParams.set("scope",t.join(" "))}function Ue(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!(null==n?void 0:n[1]))return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){var t;if(!(e instanceof Error))return!1;const r=e,n=null===(t=e.cause)||void 0===t?void 0:t.code;return"ECONNREFUSED"===r.code||"ECONNREFUSED"===n||e.message.includes("ECONNREFUSED")}(e)}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]),Error},"../shell-exec/dist/index.js"(e,t,r){"use strict";r.r(t),r.d(t,{BashState:()=>xt,INSECURE_NONE_SANDBOX_POLICY:()=>fr,KnownShellExecutor:()=>Le,NaiveTerminalExecutor:()=>At,OutputSuppressionController:()=>rr,PowerShellState:()=>Tt,SHELL_OUTPUT_SUPPRESSED_NOTICE:()=>tr,SandboxUnsupportedError:()=>Ae,ZshState:()=>$t,configureRipgrepPath:()=>v,configureSandboxPrereqs:()=>Me,createDefaultTerminalExecutor:()=>pr,createIgnoreMapping:()=>lr,createNaiveTerminalExecutor:()=>Ot,getLastSandboxFailureReason:()=>Re,getPowerShellExecutable:()=>It,getRipgrepBinaryPath:()=>S,getSandboxPolicyType:()=>Qe,getShellExecutablePath:()=>cr,getSuggestedShell:()=>hr,isAllowAllNetworkByPolicy:()=>re,isHardcodedWriteProtected:()=>X,isNetworkEnabledByPolicy:()=>te,isRipgrepConfigured:()=>k,isSandboxSupported:()=>Ne,loadSandboxPolicyFromFileOrUndefined:()=>sr,mergeAdditionalReadPaths:()=>st,mergeNetworkPolicies:()=>ct,mergePathsIntersection:()=>tt,mergePathsUnion:()=>rt,mergeReadBoundary:()=>it,networkAllowAllPolicy:()=>oe,networkDisabledPolicy:()=>ne,parseSandboxPolicyJson:()=>ir,primeSandboxSupport:()=>$e,resolvePolicyPaths:()=>ar,resolveRipgrepFromPath:()=>g,resolveSandboxPolicyForWorkspace:()=>ht,spawnInSandbox:()=>je,spawnWithSignal:()=>Ue,withConfiguredRipgrepEnv:()=>b});var n=r("node:path"),o=r("node:fs"),i=r("../utils/dist/lru-cache.js");const s="undefined"!=typeof process&&"win32"===process.platform,a=new i.q({max:512});function l(e){try{return o.statSync(e)}catch(e){return null}}function c(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,o=a.get(r);if(void 0!==o)return o;const i=n.join(".",e);if(l(i))return a.set(r,i),i;const c=process.env.PATH.split(s?";":":");for(const o of c){const i=n.join(o,e);if(l(i)&&(!t||t.test(i)))return a.set(r,i),i}return a.set(r,e),e}function u(e,t,r){if("win32"!==process.platform)return{cmd:c(e),args:t};if(!o.existsSync(e)){const n=[".exe",".bat",".cmd",".ps1"],i=e.toLowerCase();if(n.some((e=>i.endsWith(e)))){const n=c(e,r);if(o.existsSync(n))return u(n,t,r)}for(const i of n){const n=c(`${e}${i}`,r);if(o.existsSync(n))return u(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:n.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:n.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}var d=r("node:fs/promises"),h=r("node:os"),p=r("../context/dist/otel.js"),f=r("../utils/dist/writable-iterable.js");let m;function g(){const e=u("rg",[]).cmd;return"rg"!==e?e:void 0}function v(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");m=e}function y(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function w(e,t){const r=(0,n.dirname)(t);if(!r||"."===r)return e;const o=function(e){const t=y(e);return void 0!==t?e[t]??"":""}(e).split(n.delimiter).filter(Boolean);return function(e,t){const r=y(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...o.filter((e=>e!==r))].join(n.delimiter))}function b(e){return m&&(0,n.isAbsolute)(m)?{...w(e,m),CURSOR_RIPGREP_PATH:m}:e}function S(){if(!m)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return m}function k(){return void 0!==m}var E=r("node:child_process");function x(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;return n}const C=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function _(e){const t={...e};for(const e of C)delete t[e];return t}var P=r("node:crypto");let I;function T(){const e=(0,n.join)((0,h.tmpdir)(),"cursor-sandbox-cache",(I||(I=(0,P.randomBytes)(16).toString("hex")),I));return{NPM_CONFIG_CACHE:(0,n.join)(e,"npm"),PNPM_STORE_PATH:(0,n.join)(e,"pnpm-store"),GOCACHE:(0,n.join)(e,"go-build"),GOMODCACHE:(0,n.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,n.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,n.join)(e,"pip"),UV_CACHE_DIR:(0,n.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,n.join)(e,"bun"),YARN_CACHE_FOLDER:(0,n.join)(e,"yarn"),npm_config_devdir:(0,n.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,n.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,n.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,n.join)(e,"turbo"),GRADLE_USER_HOME:(0,n.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,n.join)(e,"conda"),POETRY_CACHE_DIR:(0,n.join)(e,"poetry"),GEM_SPEC_CACHE:(0,n.join)(e,"gem-specs"),BUNDLE_PATH:(0,n.join)(e,"bundle"),COMPOSER_HOME:(0,n.join)(e,"composer"),HOMEBREW_CACHE:(0,n.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,n.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,n.join)(e,"nx"),NUGET_PACKAGES:(0,n.join)(e,"nuget"),CCACHE_DIR:(0,n.join)(e,"ccache"),CP_HOME_DIR:(0,n.join)(e,"cocoapods")}}var R=r("../context/dist/logger.js"),A=r("../context/dist/core.js"),O=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),M=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class j extends Error{constructor(e,t,r,n,o,i){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=o,this.stderr=i,this.command=r,this.args=n,Error.captureStackTrace&&Error.captureStackTrace(this,j)}}function D(e,t,r){var n;r=null!=r?r:{};const o=new O.Observable((n=>{var o,i;const{encoding:s,timeout:a}=r,l=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(r,["encoding","timeout"]),{cmd:c,args:d}=u(e,t),h=l.stdin;h&&(delete l.stdin,null!==(o=l.stdio)&&void 0!==o||(l.stdio=["pipe","pipe","pipe"])),null!==(i=l.stdio)&&void 0!==i||(l.stdio=["ignore","pipe","pipe"]);const p=(0,E.spawn)(c,d,l);r.processInfo&&void 0!==p.pid&&(r.processInfo.pid=p.pid);let f=null;a&&a>0&&(f=setTimeout((()=>{p.killed||p.kill();const e=new j(`Process timed out after ${a}ms`,-1,c,d);n.error(e)}),a));const m=t=>o=>{if(o.length<1)return;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(o);let i="<< String sent back was too long >>";try{i="string"==typeof o?o.toString():o.toString(s||"utf8")}catch(t){i=`<< Lost chunk of process output for ${e} - length was ${o.length}>>`}n.next({source:t,text:i})},g=new O.Subscription;if(h)if(p.stdin){const e=p.stdin;g.add(h.subscribe({next:t=>e.write(t),error:n.error.bind(n),complete:()=>e.end()}))}else n.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let v=null,y=null,w=!1;return p.stdout?(y=new O.AsyncSubject,p.stdout.on("data",m("stdout")),p.stdout.on("close",(()=>{y.next(!0),y.complete()}))):y=(0,O.of)(!0),p.stderr?(v=new O.AsyncSubject,p.stderr.on("data",m("stderr")),p.stderr.on("close",(()=>{v.next(!0),v.complete()}))):v=(0,O.of)(!0),p.on("error",(e=>{w=!0,f&&clearTimeout(f),n.error(e)})),p.on("close",(e=>{w=!0,f&&clearTimeout(f);const t=(0,O.merge)(y,v).pipe((0,M.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new j(`Process failed with exit code: ${e}`,e,c,d);n.error(t)}))})),g.add(new O.Subscription((()=>{w||(f&&clearTimeout(f),p.kill())}))),g}));let i=o;if(r.retries&&r.retries>0){const e=r.retries,t=null!==(n=r.retryDelay)&&void 0!==n?n:1e3;i=i.pipe((0,M.L5)({count:e,delay:(e,r)=>{if(e instanceof j&&0!==e.exitCode)return(0,O.timer)(t);throw e}}))}return r.split?i:i.pipe((0,M.Tj)((e=>null==e?void 0:e.text)))}function N(e,t,r){return(null==r?void 0:r.split)?(n=D(e,t,Object.assign(Object.assign({},null!=r?r:{}),{split:!0})),new Promise(((e,t)=>{let r="",o="";n.subscribe({next:e=>{"stdout"===e.source?r+=e.text:o+=e.text},error:e=>{if(e instanceof j){const n=new j(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,o);t(n)}else{const n=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(n)}},complete:()=>e([r,o])})}))):function(e){return new Promise(((t,r)=>{let n="";e.subscribe({next:e=>{n+=e},error:e=>{if(e instanceof j){const t=new j(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(D(e,t,Object.assign(Object.assign({},null!=r?r:{}),{split:!1})));var n}var $=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const L=[{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/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"}],F=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".ssh"},{type:"home",pattern:".cursor/sandbox-policies"}];function U(e){const t=F.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function B(e){const t=F.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}F.filter((e=>"git"===e.type)).map((e=>e.pattern)),F.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(F.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(F.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 F)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"}}function ie(){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{}return 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 se(e){const t=ie(),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 ae="darwin"===process.platform,le="linux"===process.platform,ce=(0,R.h)("shell-exec:sandbox");function ue(e){const t=ie();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let de;function he(){return de}function pe(e){"linux"===process.platform&&Object.assign(e,b(e))}let fe=null,me=null,ge=null,ve=null,ye=!1,we=null;function be(e){return{...e,additionalReadonlyPaths:ue(e.additionalReadonlyPaths)}}function Se(e,t){let r;e.ignoreMapping&&(r=function(e){return Pe(e)}(e.ignoreMapping));const i=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=!le||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 Pe(l)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=e.readBoundary??"system",a=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 L){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)){let e=s;try{o.existsSync(s)&&(e=(0,o.realpathSync)(s))}catch{}r.has(e)||(r.add(e),t.push(e))}return t}(),l="workspace"===s?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??[]):[],c=[...a],u=new Set(a);for(const e of l)u.has(e)||(u.add(e),c.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:c,additionalReadonlyPaths:i,networkAccess:te(e.networkPolicy),ignoreMapping:r};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function ke(e){if(null!==fe)return!!fe;try{const t=he();return ce.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(fe=o.existsSync(t),fe?ce.info(e,`[checkBinaryAvailable] Binary path exists: ${fe}`):(me=new Error(`Sandbox binary not found at ${t}`),ce.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!fe):(me=new Error("Sandbox binary path was not configured"),fe=!1,ce.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return me=t,fe=!1,ce.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function Ee(e){if(null!==ve)return ve;const t=e??(0,A.q6)();if(ce.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!ke(t)){const e=me?.message||"Binary check failed";return ge=e,ce.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ve=!1,ve}if("win32"===process.platform)return ge="Windows sandbox helper only provides network proxy, not filesystem isolation",ce.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ve=!1,ve;if("darwin"===process.platform)return ge=null,ce.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ve=!0,ve;const{binaryPath:r,args:n,env:o}=Ce(t,process.cwd());try{const e=Date.now();(0,E.execFileSync)(r,n,{stdio:["ignore","ignore","pipe"],timeout:xe,env:o,shell:!1});const i=Date.now()-e;return ge=null,ce.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ve=!0,ve}catch(e){const r=e;return _e(t,{message:r.message,status:r.status,stderrText:r.stderr?.toString?.()||""})}}const xe=15e3;function Ce(e,t){const r={sandbox:Se(be({type:"workspace_readwrite"}),t)},n=String(he());ce.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),ce.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return pe(o),{binaryPath:n,args:["--policy",se(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}function _e(e,t){const{message:r,status:n,stderrText:o}=t;return ce.error(e,`[sandboxPreflight] Preflight failed: ${r}`),ce.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&ce.error(e,`[sandboxPreflight] Stderr: ${o}`),ge=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"}`,ve=!1,!1}function Pe(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Ie(t):t;o[e]=r;const n=Te(e);n!==e&&(o[n]=r)}return o}function Ie(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Te(e){try{return(0,o.realpathSync)(e)}catch{return e}}function Re(){return ge}class Ae extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Oe="darwin"===process.platform;function Me(e){!function(e){S();const{sandboxBinaryPath:t}=e;de||(de=t)}(e)}function je(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(Ee())return function(e,t=[],r={},n){const o=(0,A.q6)();if(r.env=x(r.env),!ke(o))throw new Error(`Sandbox binary not available: ${me?.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=Se(be(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",se(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"};pe(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(he()),d,p);return ae&&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=Re();throw new Ae(`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 De(e){return Oe?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 Ne(e,t){if(Oe)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return Ee(t?.ctx)}async function $e(e){if(Oe)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return async function(e){return ye&&null!==ve?ve:(null!==we||(we=async function(e){const t=e.ctx??(0,A.q6)();if(!le||!ke(t)){const e=Ee(t);return ye=!0,e}null!==ve&&ce.info(t,`[primeSandboxHelperSupport] Re-probing from ${e.workspaceCwd}; the cached verdict (${ve}) was measured from a different directory`);const r=e.timeoutMs??xe,{binaryPath:n,args:o,env:i}=Ce(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 ge=`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"}`,ce.error(t,`[primeSandboxHelperSupport] Preflight timed out after ${r}ms, treating sandbox as unsupported`),ve=!1,ye=!0,!1;if("failed"===a.kind){const e=_e(t,{message:a.message,status:a.status,stderrText:a.stderrText});return ye=!0,e}return ge=null,ce.info(t,`[primeSandboxHelperSupport] Preflight rooted at ${e.workspaceCwd} succeeded in ${l}ms, sandbox supported!`),ve=!0,ye=!0,!0}(e).finally((()=>{we=null}))),we)}(e)}var Le;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Le||(Le={}));const Fe={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Ue(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=je(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 Be(e){e?.on("error",(()=>{}))}function ze(e,t){e&&(Be(e),e.write(t),e.end())}function We(e,t){e&&(Be(e),e.on("data",(e=>{t(e.toString())})))}function He(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function qe(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}const Ge="__CURSOR_BASH_STATE_START__",Ve="__CURSOR_BASH_STATE_END__",Je=50,Ke=262144;class Ze{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Je,this.maxBufferedBytes=t?.maxBufferedBytes??Ke}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 Ye(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 Ze(e.writable,e.outputLimiterOptions);let r;const n=Promise.all([Xe(e.stdout,"stdout",t),Xe(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 Xe(e,t,r){if(e)for await(const n of e)await r.push(t,n)}function Qe(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function et(...e){return e.some((e=>!0===e))}function tt(...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=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(lt);let r=new Set(t[0].map(lt));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(lt));r=new Set([...r].filter((e=>n.has(e))))}return[...r]}function rt(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(lt(e));return[...t]}const nt=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}}),ot=(...e)=>tt(...e);function it(...e){return nt.merge(...e)}function st(...e){return ot(...e)}function at(e,t){if("workspace"===e&&void 0!==t)return t}function lt(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function ct(...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 ut(...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 dt(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function ht(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"===Qe(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:ut(i?.writeProtectionMapping,B(e))}}}}if(i)return pt(t,{workspaceDir:e,gitDirParent:r})}return pt(t,{workspaceDir:e})}function pt(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 gt(e,t);switch(r){case"workspace_readwrite":return gt(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=ft(e,t),o={policy:mt({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:et(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:dt(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:et(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:dt(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 ft(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 F)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=et(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=et(o?.networkPolicyStrict,i?.networkPolicyStrict,s?.networkPolicyStrict,l.networkPolicyStrict);l.networkPolicyStrict&&p("networkPolicyStrict",3);const g=it(o?.readBoundary,i?.readBoundary,s?.readBoundary),v=st(at(o?.readBoundary,o?.additionalReadPaths),at(i?.readBoundary,i?.additionalReadPaths),at(s?.readBoundary,s?.additionalReadPaths)),y="workspace"===g?v:void 0,w=rt(o?.additionalReadonlyPaths,i?.additionalReadonlyPaths,s?.additionalReadonlyPaths,l.additionalReadonlyPaths),b=w.length>0?w:void 0;let S=ct(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=dt(o?.debugOutputDir,i?.debugOutputDir,s?.debugOutputDir),_=et(o?.captureDenies,i?.captureDenies,s?.captureDenies),P=dt(o?.enableSharedBuildCache,i?.enableSharedBuildCache,s?.enableSharedBuildCache),I=ut(o?.ignoreMapping,i?.ignoreMapping,s?.ignoreMapping,l.ignoreMapping),T=function(e){const t=F.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:ut(o?.writeProtectionMapping,i?.writeProtectionMapping,s?.writeProtectionMapping,l.writeProtectionMapping,T),fieldSources:c}}function mt(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function gt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,i=t?.debug,s=ft(e,t),a=rt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),l={policy:mt({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 vt="win32"===process.platform;function yt(e){return!vt&&!!e?.SUDO_ASKPASS}function wt(e){return yt(e)?"alias sudo='sudo -A'; ":""}function bt(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 St=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kt(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 Et(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 xt{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 xt(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,...Fe,...r?.env};let u='builtin eval "$1"';s||(u+=" < /dev/null");const m=wt(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=Et(y),t=Et(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=kt(this.userTerminalHint);if(!S)throw new Error("Can't find Bash");const k=r?.sandboxWorkspaceRoot??l,E=(await ht(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=Ue(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=Ye({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=`${Ge}\n`,t=`${Ve}\n`;if(C.startsWith(e)&&C.endsWith(t)){let t=C.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=He(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(x.captureDenies)try{const e=await De(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||(ze(j,this.state),We(D,(e=>{C+=e}))),yield*a}catch(e){o.error=e,o.hasError=!0}finally{St(o)}}}var Ct=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 _t{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 _t((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{Ct(n)}}}var Pt=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 It(){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 Tt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Tt(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,...Fe,...r?.env},u=yt(c)?bt(t):t,m=h.tmpdir(),g=n.join(m,`ps-state-out-${(0,P.randomUUID)()}.txt`),v=((e,t,r,n)=>`\n${e}\n\nSet-Location '${t}'\n\n# Execute user command\n${r}\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n\n\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n\n Emit $PWD.Path\n #Log-Timing "working_dir"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing "environment"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name "{0}" -Value "{1}"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing "finalize"\n}\n\nDump-PowerShellState -OutputFile "${n}"\n\nexit $COMMAND_EXIT_CODE\n`)(this.state,a,u,g),y=n.join(m,`ps-script-${(0,P.randomUUID)()}.ps1`);await async function(e,t){await d.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(y,v);const w=["-ExecutionPolicy","Bypass"];s||w.push("-NonInteractive"),w.push("-File",y);const b=It(),S="win32"===process.platform,k=r?.sandboxWorkspaceRoot??a,E=(await ht(k,r?.sandboxPolicy)).policy,x=Ue(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=Ye({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}=He(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{Pt(o)}}}var Rt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 At{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new At(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,...Fe,...r?.env},l=yt(a)?bt(t):t,c=r?.workingDirectory??this.cwd,u=r?.sandboxWorkspaceRoot??c,d=(await ht(u,r?.sandboxPolicy)).policy,h="insecure_none"!==d.type?{...d,sandboxWorkspaceRoot:u}:d,m=Ue(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=Ye({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 De(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{Rt(n)}}}function Ot(e){const t="win32"===process.platform,r=e?.shell??(t?It():void 0),n=process.cwd();return new At(n,{...e,shell:r})}const Mt="__CURSOR_ZSH_STATE_START__",jt="__CURSOR_ZSH_STATE_END__";var Dt=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 Nt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class $t{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new $t(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,...Fe,...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; ${wt(l)}${c}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],d=r?.sandboxWorkspaceRoot??a,h=(await ht(d,r?.sandboxPolicy)).policy,m="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:d}:h,g=Ue(Nt(),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=Ye({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=`${Mt}\n`,t=`${jt}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=He(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(m.captureDenies)try{const e=await De(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];ze(E,this.state),We(x,(e=>{v+=e})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Dt(n)}}}const Lt="__CURSOR_ZSH_STATE_LIGHT_VALID__",Ft='#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state_light.zsh\n# dump_zsh_state_light\n# Or execute directly (captures a subshell\'s state):\n# ./dump_zsh_state_light.zsh\n\n# Lightweight version that skips function tracking for better performance\n\n# Define a function so sourcing won\'t alter caller state; emulate locally inside\nfunction dump_zsh_state_light() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=${EPOCHREALTIME}\n typeset step_start=${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf \'cursor_snap_%s=$(command base64 -d <<\'\'\'CURSOR_SNAP_EOF_%s\'\'\'\n\' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d \'\n\'\n builtin printf \'\nCURSOR_SNAP_EOF_%s\n\' "$var_name"\n builtin printf \')\n\'\n builtin printf \'eval "$cursor_snap_%s"\n\' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n # Emit validity marker so we can detect if dump_zsh_state_light completed\n _emit "__CURSOR_ZSH_STATE_LIGHT_VALID__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump (light) generated on $(command date +\'%Y-%m-%d %H:%M:%S %z\')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE \'_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_AGENT_STORE\' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # \'cmd | head\' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE \'^(errreturn|nounset|pipefail)$\' | command awk \'{printf "builtin setopt %s 2>/dev/null || true\\n", $0}\' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # SKIP FUNCTIONS - this is the key difference for performance\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump (light)"\n _log_timing "finalize"\n}\n';var Ut=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 Bt(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class zt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new zt(e??this.cwd,this.state)}async*execute(e,t,r){const 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,...Fe,...r?.env};let c='builtin eval "$1"';i||(c+=" < /dev/null");const u=wt(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; ${Ft} 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 ht(h,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,v=Ue(Bt(),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=Ye({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}=He(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await De(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];ze(x,this.state),We(C,(e=>{y+=e})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Ut(n)}}}var Wt,Ht,qt=r("node:perf_hooks");!function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}(Wt||(Wt={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(Ht||(Ht={}));const Gt={eventLoopDelayP95Ms:0,eventLoopUtilization:0};let Vt,Jt=0;class Kt{eventLoopMonitor;sampleTimer;lastEventLoopUtilization=qt.performance.eventLoopUtilization();latestSnapshot=Gt;constructor(){this.eventLoopMonitor=(0,qt.monitorEventLoopDelay)({resolution:Ht.EventLoopResolutionMs}),this.lastEventLoopUtilization=qt.performance.eventLoopUtilization(),this.eventLoopMonitor.enable(),this.sample(),this.sampleTimer=setInterval((()=>{this.sample()}),Ht.SampleIntervalMs),this.sampleTimer.unref?.()}dispose(){void 0!==this.sampleTimer&&(clearInterval(this.sampleTimer),this.sampleTimer=void 0,this.eventLoopMonitor.disable(),this.latestSnapshot=Gt,this.lastEventLoopUtilization=qt.performance.eventLoopUtilization())}isUnderPressure(){return this.latestSnapshot.eventLoopDelayP95Ms>=Wt.EventLoopDelayP95Ms||this.latestSnapshot.eventLoopUtilization>=Wt.EventLoopUtilization}formatSuppressionSection(){const e=this.latestSnapshot,t=[`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms (threshold ${Wt.EventLoopDelayP95Ms}ms)`,`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% (threshold ${(100*Wt.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>=Wt.EventLoopDelayP95Ms&&t.push(`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms >= ${Wt.EventLoopDelayP95Ms}ms`),e.eventLoopUtilization>=Wt.EventLoopUtilization&&t.push(`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% >= ${(100*Wt.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-Ht.EventLoopResolutionMs)}computeEventLoopUtilization(){const e=qt.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 Zt=6e4,Yt=65536,Xt=2097152,Qt=262144,er=1e3,tr="\n[This shell is producing too much output to stream. The command will still run.]\n";class rr{bucketChars;bucketStarts;totalChars=0;outputSuppressed=!1;noticeSent=!1;windowMs;minimumThresholdCharsPerSecond;thresholdCharsPerSecondWithoutPressure;minChars;eventLoopPressureTracker;disposed=!1;constructor(e){this.windowMs=e?.windowMs??Zt,this.minimumThresholdCharsPerSecond=e?.minimumThresholdCharsPerSecond??Yt,this.thresholdCharsPerSecondWithoutPressure=e?.thresholdCharsPerSecondWithoutPressure??Xt,this.minChars=e?.minChars??Qt;const t=Math.ceil(this.windowMs/er)+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(){Jt++,void 0===Vt&&(Vt=new Kt);const e=Vt;let t=!1;return{isUnderPressure:()=>e.isUnderPressure(),formatSuppressionSection:()=>e.formatSuppressionSection(),dispose:()=>{t||(t=!0,Jt--,0===Jt&&void 0!==Vt&&(Vt.dispose(),Vt=void 0))}}}()),this.eventLoopPressureTracker}recordChars(e,t){if(this.prune(t),e<=0)return;const r=Math.floor(t/er)*er,n=Math.floor(r/er)%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(er,Math.min(this.windowMs,e-r+er));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 nr=r("../utils/dist/path-utils.js");function or(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 ir(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="custom"===e.readBoundary?"workspace":e.readBoundary,i={...r,networkAccess:e.networkAccess,networkPolicy:or(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:o,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...i}:{type:"workspace_readwrite",...i,additionalReadwritePaths:e.additionalReadwritePaths}}async function sr(e,t){const r=await async function(e,t){try{const r=await(0,d.readFile)(e,"utf-8"),n=JSON.parse(r),o=function(e){if("object"!=typeof e||null===e)return"Expected an object";const t=e;if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary&&"custom"!==t.readBoundary)return'Invalid readBoundary: expected "system", "workspace", or "custom"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=t.networkPolicy;if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}(n);if(o)return{success:!1,error:`Invalid sandbox policy: ${o}`};let i=ir(n);return t&&(i=ar(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 ar(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,nr.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,nr.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,nr.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}function lr(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 cr(e){switch(e){case Le.Zsh:case Le.ZshLight:return u("zsh",[]).cmd;case Le.Bash:return u("bash",[]).cmd;case Le.PowerShell:return It();default:return process.env.SHELL||"/bin/sh"}}function ur(e){try{return u(e,[]).cmd!==e}catch(e){return!1}}function dr(){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 hr(e){if(e===Le.ZshLight)return Le.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?dr():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")?Le.Zsh:t.includes("bash")&&i?Le.Bash:t.includes("pwsh")||t.includes("powershell")?Le.PowerShell:n?Le.Bash:r&&(ur("pwsh")||ur("powershell"))?Le.PowerShell:ur("zsh")?Le.Zsh:ur("bash")&&i?Le.Bash:ur("pwsh")||ur("powershell")?Le.PowerShell:Le.Naive}function pr(e){let t=e;if(!e?.userTerminalHint){const r=dr();r&&(t={...e,userTerminalHint:r})}switch(hr(t?.userTerminalHint??"")){case Le.Zsh:return new _t((()=>async function(e){const t={...process.env,...Fe,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state.zsh\n# dump_zsh_state\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state.zsh\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:functions p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_ZSH_STATE_START__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_AGENT_STORE' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # Functions: dump all functions at once (much faster than individual processing)\n local all_functions\n all_functions=$(builtin typeset -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS_B64"\n _log_timing "functions"\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_zsh_state`],o=Ue(Nt(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=qe(i,r),a=`${Mt}\n`,l=`${jt}\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}=He(c);return new $t(u,d)}(t)));case Le.Bash:return new _t((()=>async function(e){const t={...process.env,...Fe,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Require base64 for safe encoding of emitted sections\n if ! command -v base64 >/dev/null 2>&1; then\n echo "Error: base64 command is required" >&2\n return 1\n fi\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_AGENT_STORE' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS_B64"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS_B64"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS_B64"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(builtin alias -p 2>/dev/null || true)\n _emit_encoded "$aliases" "ALIASES_B64"\n _log_timing "aliases"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],o=kt(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const i=Ue(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal);let s="";i.stdout?.on("data",(e=>{s+=e.toString()})),await new Promise((e=>{i.on("close",(()=>{e(void 0)}))}));const a=qe(s,r),l=`${Ge}\n`,c=`${Ve}\n`;let u;a.startsWith(l)&&a.endsWith(c)?(u=a.slice(l.length),u=u.slice(0,-26)):u=`${process.cwd()}\n`;const{cwd:d,rest:h}=He(u),p="win32"===process.platform,f="win32"===process.platform?process.cwd():d;return new xt(f,h,e?.userTerminalHint,p)}(t)));case Le.PowerShell:return new _t((()=>async function(){return new Tt(process.cwd(),"")}()));case Le.ZshLight:return new _t((()=>async function(e){const t={...process.env,...Fe,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`${Ft} builtin printf '${r}\\n'; dump_zsh_state_light`],o=Ue(Bt(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=qe(i,r),a=`${Lt}\n`,l=s.startsWith(a)?s.slice(a.length):s,{cwd:c,rest:u}=He(l);return new zt(c,u)}(t)));default:return Ot(t)}}process.platform;const fr={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,$,L,F,U,B,z,W,H,q,G,V,J,K,Z,Y,X,Q=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},ee=function(e,t,r,n,o){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?o.call(e,r):o?o.value=r:t.set(e,r),r},te=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const re="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,ne=new Set,oe="object"==typeof process&&process?process:{},ie=(e,t,r,n)=>{"function"==typeof oe.emitWarning?oe.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let se=globalThis.AbortController,ae=globalThis.AbortSignal;if(void 0===se){ae=class{constructor(){this._onabort=[],this.aborted=!1}addEventListener(e,t){this._onabort.push(t)}},se=class{constructor(){this.signal=new ae,t()}abort(e){var t,r;if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);null===(r=(t=this.signal).onabort)||void 0===r||r.call(t,e)}}};let e="1"!==(null===(n=oe.env)||void 0===n?void 0:n.LRU_CACHE_IGNORE_AC_WARNING);const t=()=>{e&&(e=!1,ie("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const le=e=>e&&e===Math.floor(e)&&e>0&&Number.isFinite(e),ce=e=>le(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ue:null:null;class ue extends Array{constructor(e){super(e),this.fill(0)}}class de{static create(e){const t=ce(e);if(!t)return[];ee(o,o,!0,"f",i);const r=new o(e,t);return ee(o,o,!1,"f",i),r}constructor(e,t){if(!te(o,o,"f",i))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}o=de,i={value:!1};class he{get perf(){return te(this,f,"f")}static unsafeExposeInternals(e){return{starts:te(e,P,"f"),ttls:te(e,I,"f"),sizes:te(e,_,"f"),keyMap:te(e,v,"f"),keyList:te(e,y,"f"),valList:te(e,w,"f"),next:te(e,b,"f"),prev:te(e,S,"f"),get head(){return te(e,k,"f")},get tail(){return te(e,E,"f")},free:te(e,x,"f"),isBackgroundFetch:t=>te(e,s,"m",V).call(e,t),backgroundFetch:(t,r,n,o)=>te(e,s,"m",G).call(e,t,r,n,o),moveToTail:t=>te(e,s,"m",K).call(e,t),indexes:t=>te(e,s,"m",z).call(e,t),rindexes:t=>te(e,s,"m",W).call(e,t),isStale:t=>te(e,$,"f").call(e,t)}}get max(){return te(this,a,"f")}get maxSize(){return te(this,l,"f")}get calculatedSize(){return te(this,g,"f")}get size(){return te(this,m,"f")}get fetchMethod(){return te(this,h,"f")}get memoMethod(){return te(this,p,"f")}get dispose(){return te(this,c,"f")}get onInsert(){return te(this,u,"f")}get disposeAfter(){return te(this,d,"f")}constructor(e){s.add(this),a.set(this,void 0),l.set(this,void 0),c.set(this,void 0),u.set(this,void 0),d.set(this,void 0),h.set(this,void 0),p.set(this,void 0),f.set(this,void 0),m.set(this,void 0),g.set(this,void 0),v.set(this,void 0),y.set(this,void 0),w.set(this,void 0),b.set(this,void 0),S.set(this,void 0),k.set(this,void 0),E.set(this,void 0),x.set(this,void 0),C.set(this,void 0),_.set(this,void 0),P.set(this,void 0),I.set(this,void 0),T.set(this,void 0),R.set(this,void 0),A.set(this,void 0),O.set(this,void 0),j.set(this,(()=>{})),D.set(this,(()=>{})),N.set(this,(()=>{})),$.set(this,(()=>!1)),F.set(this,(e=>{})),U.set(this,((e,t,r)=>{})),B.set(this,((e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0})),this[X]="LRUCache";const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:i,updateAgeOnHas:z,allowStale:W,dispose:H,onInsert:q,disposeAfter:G,noDisposeOnSet:V,noUpdateTTL:J,maxSize:K=0,maxEntrySize:Z=0,sizeCalculation:Y,fetchMethod:Q,memoMethod:oe,noDeleteOnFetchRejection:se,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:ue,allowStaleOnFetchAbort:pe,ignoreFetchAbort:fe,perf:me}=e;if(void 0!==me&&"function"!=typeof(null==me?void 0:me.now))throw new TypeError("perf option must have a now() method if specified");if(ee(this,f,null!=me?me:re,"f"),0!==t&&!le(t))throw new TypeError("max option must be a nonnegative integer");const ge=t?ce(t):Array;if(!ge)throw new Error(`invalid max value: ${t}`);if(ee(this,a,t,"f"),ee(this,l,K,"f"),this.maxEntrySize=Z||te(this,l,"f"),this.sizeCalculation=Y,this.sizeCalculation){if(!te(this,l,"f")&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==oe&&"function"!=typeof oe)throw new TypeError("memoMethod must be a function if defined");if(ee(this,p,oe,"f"),void 0!==Q&&"function"!=typeof Q)throw new TypeError("fetchMethod must be a function if specified");if(ee(this,h,Q,"f"),ee(this,R,!!Q,"f"),ee(this,v,new Map,"f"),ee(this,y,new Array(t).fill(void 0),"f"),ee(this,w,new Array(t).fill(void 0),"f"),ee(this,b,new ge(t),"f"),ee(this,S,new ge(t),"f"),ee(this,k,0,"f"),ee(this,E,0,"f"),ee(this,x,de.create(t),"f"),ee(this,m,0,"f"),ee(this,g,0,"f"),"function"==typeof H&&ee(this,c,H,"f"),"function"==typeof q&&ee(this,u,q,"f"),"function"==typeof G?(ee(this,d,G,"f"),ee(this,C,[],"f")):(ee(this,d,void 0,"f"),ee(this,C,void 0,"f")),ee(this,T,!!te(this,c,"f"),"f"),ee(this,O,!!te(this,u,"f"),"f"),ee(this,A,!!te(this,d,"f"),"f"),this.noDisposeOnSet=!!V,this.noUpdateTTL=!!J,this.noDeleteOnFetchRejection=!!se,this.allowStaleOnFetchRejection=!!ue,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!fe,0!==this.maxEntrySize){if(0!==te(this,l,"f")&&!le(te(this,l,"f")))throw new TypeError("maxSize must be a positive integer if specified");if(!le(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");te(this,s,"m",L).call(this)}if(this.allowStale=!!W,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!z,this.ttlResolution=le(n)||0===n?n:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!le(this.ttl))throw new TypeError("ttl must be a positive integer if specified");te(this,s,"m",M).call(this)}if(0===te(this,a,"f")&&0===this.ttl&&0===te(this,l,"f"))throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!te(this,a,"f")&&!te(this,l,"f")){const e="LRU_CACHE_UNBOUNDED";(e=>!ne.has(e))(e)&&(ne.add(e),ie("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,he))}}getRemainingTTL(e){return te(this,v,"f").has(e)?1/0:0}*entries(){for(const e of te(this,s,"m",z).call(this))void 0===te(this,w,"f")[e]||void 0===te(this,y,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield[te(this,y,"f")[e],te(this,w,"f")[e]])}*rentries(){for(const e of te(this,s,"m",W).call(this))void 0===te(this,w,"f")[e]||void 0===te(this,y,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield[te(this,y,"f")[e],te(this,w,"f")[e]])}*keys(){for(const e of te(this,s,"m",z).call(this)){const t=te(this,y,"f")[e];void 0===t||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield t)}}*rkeys(){for(const e of te(this,s,"m",W).call(this)){const t=te(this,y,"f")[e];void 0===t||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield t)}}*values(){for(const e of te(this,s,"m",z).call(this))void 0===te(this,w,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield te(this,w,"f")[e])}*rvalues(){for(const e of te(this,s,"m",W).call(this))void 0===te(this,w,"f")[e]||te(this,s,"m",V).call(this,te(this,w,"f")[e])||(yield te(this,w,"f")[e])}[(a=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,v=new WeakMap,y=new WeakMap,w=new WeakMap,b=new WeakMap,S=new WeakMap,k=new WeakMap,E=new WeakMap,x=new WeakMap,C=new WeakMap,_=new WeakMap,P=new WeakMap,I=new WeakMap,T=new WeakMap,R=new WeakMap,A=new WeakMap,O=new WeakMap,j=new WeakMap,D=new WeakMap,N=new WeakMap,$=new WeakMap,F=new WeakMap,U=new WeakMap,B=new WeakMap,s=new WeakSet,M=function(){const e=new ue(te(this,a,"f")),t=new ue(te(this,a,"f"));ee(this,I,e,"f"),ee(this,P,t,"f"),ee(this,N,((r,n,o=te(this,f,"f").now())=>{if(t[r]=0!==n?o:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{te(this,$,"f").call(this,r)&&te(this,s,"m",Z).call(this,te(this,y,"f")[r],"expire")}),n+1);e.unref&&e.unref()}}),"f"),ee(this,j,(r=>{t[r]=0!==e[r]?te(this,f,"f").now():0}),"f"),ee(this,D,((o,i)=>{if(e[i]){const s=e[i],a=t[i];if(!s||!a)return;o.ttl=s,o.start=a,o.now=r||n();const l=o.now-a;o.remainingTTL=s-l}}),"f");let r=0;const n=()=>{const e=te(this,f,"f").now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>{r=0}),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=o=>{const i=te(this,v,"f").get(o);if(void 0===i)return 0;const s=e[i],a=t[i];return s&&a?s-((r||n())-a):1/0},ee(this,$,(o=>{const i=t[o],s=e[o];return!!s&&!!i&&(r||n())-i>s}),"f")},L=function(){const e=new ue(te(this,a,"f"));ee(this,g,0,"f"),ee(this,_,e,"f"),ee(this,F,(t=>{ee(this,g,te(this,g,"f")-e[t],"f"),e[t]=0}),"f"),ee(this,B,((e,t,r,n)=>{if(te(this,s,"m",V).call(this,t))return 0;if(!le(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!le(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r}),"f"),ee(this,U,((t,r,n)=>{if(e[t]=r,te(this,l,"f")){const r=te(this,l,"f")-e[t];for(;te(this,g,"f")>r;)te(this,s,"m",q).call(this,!0)}ee(this,g,te(this,g,"f")+e[t],"f"),n&&(n.entrySize=r,n.totalCalculatedSize=te(this,g,"f"))}),"f")},z=function*({allowStale:e=this.allowStale}={}){if(te(this,m,"f"))for(let t=te(this,E,"f");te(this,s,"m",H).call(this,t)&&(!e&&te(this,$,"f").call(this,t)||(yield t),t!==te(this,k,"f"));)t=te(this,S,"f")[t]},W=function*({allowStale:e=this.allowStale}={}){if(te(this,m,"f"))for(let t=te(this,k,"f");te(this,s,"m",H).call(this,t)&&(!e&&te(this,$,"f").call(this,t)||(yield t),t!==te(this,E,"f"));)t=te(this,b,"f")[t]},H=function(e){return void 0!==e&&te(this,v,"f").get(te(this,y,"f")[e])===e},Symbol.iterator)](){return this.entries()}find(e,t={}){for(const r of te(this,s,"m",z).call(this)){const n=te(this,w,"f")[r],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,te(this,y,"f")[r],this))return this.get(te(this,y,"f")[r],t)}}forEach(e,t=this){for(const r of te(this,s,"m",z).call(this)){const n=te(this,w,"f")[r],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,te(this,y,"f")[r],this)}}rforEach(e,t=this){for(const r of te(this,s,"m",W).call(this)){const n=te(this,w,"f")[r],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,te(this,y,"f")[r],this)}}purgeStale(){let e=!1;for(const t of te(this,s,"m",W).call(this,{allowStale:!0}))te(this,$,"f").call(this,t)&&(te(this,s,"m",Z).call(this,te(this,y,"f")[t],"expire"),e=!0);return e}info(e){const t=te(this,v,"f").get(e);if(void 0===t)return;const r=te(this,w,"f")[t],n=te(this,s,"m",V).call(this,r)?r.__staleWhileFetching:r;if(void 0===n)return;const o={value:n};if(te(this,I,"f")&&te(this,P,"f")){const e=te(this,I,"f")[t],r=te(this,P,"f")[t];if(e&&r){const t=e-(te(this,f,"f").now()-r);o.ttl=t,o.start=Date.now()}}return te(this,_,"f")&&(o.size=te(this,_,"f")[t]),o}dump(){const e=[];for(const t of te(this,s,"m",z).call(this,{allowStale:!0})){const r=te(this,y,"f")[t],n=te(this,w,"f")[t],o=te(this,s,"m",V).call(this,n)?n.__staleWhileFetching:n;if(void 0===o||void 0===r)continue;const i={value:o};if(te(this,I,"f")&&te(this,P,"f")){i.ttl=te(this,I,"f")[t];const e=te(this,f,"f").now()-te(this,P,"f")[t];i.start=Math.floor(Date.now()-e)}te(this,_,"f")&&(i.size=te(this,_,"f")[t]),e.unshift([r,i])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=te(this,f,"f").now()-e}this.set(t,r.value,r)}}set(e,t,r={}){var n,o,i,l,h,p,f,g;if(void 0===t)return this.delete(e),this;const{ttl:k=this.ttl,start:_,noDisposeOnSet:P=this.noDisposeOnSet,sizeCalculation:j=this.sizeCalculation,status:$}=r;let{noUpdateTTL:L=this.noUpdateTTL}=r;const z=te(this,B,"f").call(this,e,t,r.size||0,j);if(this.maxEntrySize&&z>this.maxEntrySize)return $&&($.set="miss",$.maxEntrySizeExceeded=!0),te(this,s,"m",Z).call(this,e,"set"),this;let W=0===te(this,m,"f")?void 0:te(this,v,"f").get(e);if(void 0===W)W=0===te(this,m,"f")?te(this,E,"f"):0!==te(this,x,"f").length?te(this,x,"f").pop():te(this,m,"f")===te(this,a,"f")?te(this,s,"m",q).call(this,!1):te(this,m,"f"),te(this,y,"f")[W]=e,te(this,w,"f")[W]=t,te(this,v,"f").set(e,W),te(this,b,"f")[te(this,E,"f")]=W,te(this,S,"f")[W]=te(this,E,"f"),ee(this,E,W,"f"),ee(this,m,(g=te(this,m,"f"),++g),"f"),te(this,U,"f").call(this,W,z,$),$&&($.set="add"),L=!1,te(this,O,"f")&&(null===(n=te(this,u,"f"))||void 0===n||n.call(this,t,e,"add"));else{te(this,s,"m",K).call(this,W);const r=te(this,w,"f")[W];if(t!==r){if(te(this,R,"f")&&te(this,s,"m",V).call(this,r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||P||(te(this,T,"f")&&(null===(o=te(this,c,"f"))||void 0===o||o.call(this,t,e,"set")),te(this,A,"f")&&(null===(i=te(this,C,"f"))||void 0===i||i.push([t,e,"set"])))}else P||(te(this,T,"f")&&(null===(l=te(this,c,"f"))||void 0===l||l.call(this,r,e,"set")),te(this,A,"f")&&(null===(h=te(this,C,"f"))||void 0===h||h.push([r,e,"set"])));if(te(this,F,"f").call(this,W),te(this,U,"f").call(this,W,z,$),te(this,w,"f")[W]=t,$){$.set="replace";const e=r&&te(this,s,"m",V).call(this,r)?r.__staleWhileFetching:r;void 0!==e&&($.oldValue=e)}}else $&&($.set="update");te(this,O,"f")&&(null===(p=this.onInsert)||void 0===p||p.call(this,t,e,t===r?"update":"replace"))}if(0===k||te(this,I,"f")||te(this,s,"m",M).call(this),te(this,I,"f")&&(L||te(this,N,"f").call(this,W,k,_),$&&te(this,D,"f").call(this,$,W)),!P&&te(this,A,"f")&&te(this,C,"f")){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(f=te(this,d,"f"))||void 0===f||f.call(this,...t)}return this}pop(){var e;try{for(;te(this,m,"f");){const e=te(this,w,"f")[te(this,k,"f")];if(te(this,s,"m",q).call(this,!0),te(this,s,"m",V).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}return}finally{if(te(this,A,"f")&&te(this,C,"f")){const t=te(this,C,"f");let r;for(;r=null==t?void 0:t.shift();)null===(e=te(this,d,"f"))||void 0===e||e.call(this,...r)}}}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,o=te(this,v,"f").get(e);if(void 0!==o){const e=te(this,w,"f")[o];if(te(this,s,"m",V).call(this,e)&&void 0===e.__staleWhileFetching)return!1;if(!te(this,$,"f").call(this,o))return r&&te(this,j,"f").call(this,o),n&&(n.has="hit",te(this,D,"f").call(this,n,o)),!0;n&&(n.has="stale",te(this,D,"f").call(this,n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=te(this,v,"f").get(e);if(void 0===n||!r&&te(this,$,"f").call(this,n))return;const o=te(this,w,"f")[n];return te(this,s,"m",V).call(this,o)?o.__staleWhileFetching:o}fetch(e){return Q(this,arguments,void 0,(function*(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:m,forceRefresh:g=!1,status:y,signal:b}=t;if(!te(this,R,"f"))return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:y});const S={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:y,signal:b},k=te(this,v,"f").get(e);if(void 0===k){y&&(y.fetch="miss");const t=te(this,s,"m",G).call(this,e,k,S,m);return t.__returned=t}{const t=te(this,w,"f")[k];if(te(this,s,"m",V).call(this,t)){const e=r&&void 0!==t.__staleWhileFetching;return y&&(y.fetch="inflight",e&&(y.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=te(this,$,"f").call(this,k);if(!g&&!o)return y&&(y.fetch="hit"),te(this,s,"m",K).call(this,k),n&&te(this,j,"f").call(this,k),y&&te(this,D,"f").call(this,y,k),t;const i=te(this,s,"m",G).call(this,e,k,S,m),a=void 0!==i.__staleWhileFetching&&r;return y&&(y.fetch=o?"stale":"refresh",a&&o&&(y.returnedStale=!0)),a?i.__staleWhileFetching:i.__returned=i}}))}forceFetch(e){return Q(this,arguments,void 0,(function*(e,t={}){const r=yield this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}))}memo(e,t={}){const r=te(this,p,"f");if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o}=t,i=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(t,["context","forceRefresh"]),s=this.get(e,i);if(!o&&void 0!==s)return s;const a=r(e,s,{options:i,context:n});return this.set(e,a,i),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=te(this,v,"f").get(e);if(void 0!==a){const t=te(this,w,"f")[a],l=te(this,s,"m",V).call(this,t);return i&&te(this,D,"f").call(this,i,a),te(this,$,"f").call(this,a)?(i&&(i.get="stale"),l?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(o||te(this,s,"m",Z).call(this,e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),l?t.__staleWhileFetching:(te(this,s,"m",K).call(this,a),n&&te(this,j,"f").call(this,a),t))}i&&(i.get="miss")}delete(e){return te(this,s,"m",Z).call(this,e,"delete")}clear(){te(this,s,"m",Y).call(this,"delete")}}X=Symbol.toStringTag,q=function(e){var t,r,n;const o=te(this,k,"f"),i=te(this,y,"f")[o],a=te(this,w,"f")[o];return te(this,R,"f")&&te(this,s,"m",V).call(this,a)?a.__abortController.abort(new Error("evicted")):(te(this,T,"f")||te(this,A,"f"))&&(te(this,T,"f")&&(null===(t=te(this,c,"f"))||void 0===t||t.call(this,a,i,"evict")),te(this,A,"f")&&(null===(r=te(this,C,"f"))||void 0===r||r.push([a,i,"evict"]))),te(this,F,"f").call(this,o),e&&(te(this,y,"f")[o]=void 0,te(this,w,"f")[o]=void 0,te(this,x,"f").push(o)),1===te(this,m,"f")?(ee(this,k,ee(this,E,0,"f"),"f"),te(this,x,"f").length=0):ee(this,k,te(this,b,"f")[o],"f"),te(this,v,"f").delete(i),ee(this,m,(n=te(this,m,"f"),--n),"f"),o},G=function(e,t,r,n){const o=void 0===t?void 0:te(this,w,"f")[t];if(te(this,s,"m",V).call(this,o))return o;const i=new se,{signal:a}=r;null==a||a.addEventListener("abort",(()=>i.abort(a.reason)),{signal:i.signal});const l={signal:i.signal,options:r,context:n},c=(n,o=!1)=>{const{aborted:a}=i.signal,c=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(a&&!o?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,c&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),a&&!c&&!o)return u(i.signal.reason);const h=d,p=te(this,w,"f")[t];return(p===d||c&&o&&void 0===p)&&(void 0===n?void 0!==h.__staleWhileFetching?te(this,w,"f")[t]=h.__staleWhileFetching:te(this,s,"m",Z).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,l.options))),n},u=n=>{const{aborted:o}=i.signal,a=o&&r.allowStaleOnFetchAbort,l=a||r.allowStaleOnFetchRejection,c=l||r.noDeleteOnFetchRejection,u=d;if(te(this,w,"f")[t]===d&&(c&&void 0!==u.__staleWhileFetching?a||(te(this,w,"f")[t]=u.__staleWhileFetching):te(this,s,"m",Z).call(this,e,"fetch")),l)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const d=new Promise(((t,n)=>{var s;const a=null===(s=te(this,h,"f"))||void 0===s?void 0:s.call(this,e,o,l);a&&a instanceof Promise&&a.then((e=>t(void 0===e?void 0:e)),n),i.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))}))})).then(c,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),p=Object.assign(d,{__abortController:i,__staleWhileFetching:o,__returned:void 0});return void 0===t?(this.set(e,p,Object.assign(Object.assign({},l.options),{status:void 0})),t=te(this,v,"f").get(e)):te(this,w,"f")[t]=p,p},V=function(e){if(!te(this,R,"f"))return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof se},J=function(e,t){te(this,S,"f")[t]=e,te(this,b,"f")[e]=t},K=function(e){e!==te(this,E,"f")&&(e===te(this,k,"f")?ee(this,k,te(this,b,"f")[e],"f"):te(this,s,"m",J).call(this,te(this,S,"f")[e],te(this,b,"f")[e]),te(this,s,"m",J).call(this,te(this,E,"f"),e),ee(this,E,e,"f"))},Z=function(e,t){var r,n,o,i,a;let l=!1;if(0!==te(this,m,"f")){const o=te(this,v,"f").get(e);if(void 0!==o)if(l=!0,1===te(this,m,"f"))te(this,s,"m",Y).call(this,t);else{te(this,F,"f").call(this,o);const i=te(this,w,"f")[o];if(te(this,s,"m",V).call(this,i)?i.__abortController.abort(new Error("deleted")):(te(this,T,"f")||te(this,A,"f"))&&(te(this,T,"f")&&(null===(r=te(this,c,"f"))||void 0===r||r.call(this,i,e,t)),te(this,A,"f")&&(null===(n=te(this,C,"f"))||void 0===n||n.push([i,e,t]))),te(this,v,"f").delete(e),te(this,y,"f")[o]=void 0,te(this,w,"f")[o]=void 0,o===te(this,E,"f"))ee(this,E,te(this,S,"f")[o],"f");else if(o===te(this,k,"f"))ee(this,k,te(this,b,"f")[o],"f");else{const e=te(this,S,"f")[o];te(this,b,"f")[e]=te(this,b,"f")[o];const t=te(this,b,"f")[o];te(this,S,"f")[t]=te(this,S,"f")[o]}ee(this,m,(a=te(this,m,"f"),--a),"f"),te(this,x,"f").push(o)}}if(te(this,A,"f")&&(null===(o=te(this,C,"f"))||void 0===o?void 0:o.length)){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(i=te(this,d,"f"))||void 0===i||i.call(this,...t)}return l},Y=function(e){var t,r,n;for(const n of te(this,s,"m",W).call(this,{allowStale:!0})){const o=te(this,w,"f")[n];if(te(this,s,"m",V).call(this,o))o.__abortController.abort(new Error("deleted"));else{const i=te(this,y,"f")[n];te(this,T,"f")&&(null===(t=te(this,c,"f"))||void 0===t||t.call(this,o,i,e)),te(this,A,"f")&&(null===(r=te(this,C,"f"))||void 0===r||r.push([o,i,e]))}}if(te(this,v,"f").clear(),te(this,w,"f").fill(void 0),te(this,y,"f").fill(void 0),te(this,I,"f")&&te(this,P,"f")&&(te(this,I,"f").fill(0),te(this,P,"f").fill(0)),te(this,_,"f")&&te(this,_,"f").fill(0),ee(this,k,0,"f"),ee(this,E,0,"f"),te(this,x,"f").length=0,ee(this,g,0,"f"),ee(this,m,0,"f"),te(this,A,"f")&&te(this,C,"f")){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(n=te(this,d,"f"))||void 0===n||n.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){"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}))})}}}};
|