@cursor/sdk 1.0.24 → 1.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/cjs/223.js +1 -0
  2. package/dist/cjs/{833.js → 318.js} +4 -4
  3. package/dist/cjs/642.js +1 -1
  4. package/dist/cjs/856.js +1 -1
  5. package/dist/cjs/agent/options.d.ts +13 -0
  6. package/dist/cjs/agent/options.d.ts.map +1 -1
  7. package/dist/cjs/agent/store/local-agent-store.d.ts.map +1 -1
  8. package/dist/cjs/agent/usage-types.d.ts +31 -0
  9. package/dist/cjs/agent/usage-types.d.ts.map +1 -1
  10. package/dist/cjs/agent.d.ts +16 -0
  11. package/dist/cjs/agent.d.ts.map +1 -1
  12. package/dist/cjs/analytics.d.ts +1 -0
  13. package/dist/cjs/analytics.d.ts.map +1 -1
  14. package/dist/cjs/cloud-agent.d.ts +3 -1
  15. package/dist/cjs/cloud-agent.d.ts.map +1 -1
  16. package/dist/cjs/cloud-api-client.d.ts +28 -0
  17. package/dist/cjs/cloud-api-client.d.ts.map +1 -1
  18. package/dist/cjs/executor-types.d.ts +8 -6
  19. package/dist/cjs/executor-types.d.ts.map +1 -1
  20. package/dist/cjs/index.d.ts +1 -1
  21. package/dist/cjs/index.d.ts.map +1 -1
  22. package/dist/cjs/index.js +1 -1
  23. package/dist/cjs/local-executor.d.ts.map +1 -1
  24. package/dist/cjs/options.d.ts +13 -0
  25. package/dist/cjs/options.d.ts.map +1 -1
  26. package/dist/cjs/platform.d.ts +22 -1
  27. package/dist/cjs/platform.d.ts.map +1 -1
  28. package/dist/cjs/public-api.d.ts +2 -2
  29. package/dist/cjs/public-api.d.ts.map +1 -1
  30. package/dist/cjs/sdk-config.d.ts +14 -0
  31. package/dist/cjs/sdk-config.d.ts.map +1 -1
  32. package/dist/cjs/sqlite.js +1 -1
  33. package/dist/cjs/store/local-agent-store.d.ts.map +1 -1
  34. package/dist/cjs/stubs.d.ts +8 -1
  35. package/dist/cjs/stubs.d.ts.map +1 -1
  36. package/dist/cjs/usage-types.d.ts +31 -0
  37. package/dist/cjs/usage-types.d.ts.map +1 -1
  38. package/dist/esm/{833.js → 318.js} +3 -3
  39. package/dist/esm/357.js +1 -1
  40. package/dist/esm/642.js +1 -1
  41. package/dist/esm/856.js +1 -1
  42. package/dist/esm/agent/options.d.ts +13 -0
  43. package/dist/esm/agent/options.d.ts.map +1 -1
  44. package/dist/esm/agent/store/local-agent-store.d.ts.map +1 -1
  45. package/dist/esm/agent/usage-types.d.ts +31 -0
  46. package/dist/esm/agent/usage-types.d.ts.map +1 -1
  47. package/dist/esm/agent.d.ts +16 -0
  48. package/dist/esm/agent.d.ts.map +1 -1
  49. package/dist/esm/analytics.d.ts +1 -0
  50. package/dist/esm/analytics.d.ts.map +1 -1
  51. package/dist/esm/cloud-agent.d.ts +3 -1
  52. package/dist/esm/cloud-agent.d.ts.map +1 -1
  53. package/dist/esm/cloud-api-client.d.ts +28 -0
  54. package/dist/esm/cloud-api-client.d.ts.map +1 -1
  55. package/dist/esm/executor-types.d.ts +8 -6
  56. package/dist/esm/executor-types.d.ts.map +1 -1
  57. package/dist/esm/index.d.ts +1 -1
  58. package/dist/esm/index.d.ts.map +1 -1
  59. package/dist/esm/index.js +1 -1
  60. package/dist/esm/local-executor.d.ts.map +1 -1
  61. package/dist/esm/options.d.ts +13 -0
  62. package/dist/esm/options.d.ts.map +1 -1
  63. package/dist/esm/platform.d.ts +22 -1
  64. package/dist/esm/platform.d.ts.map +1 -1
  65. package/dist/esm/public-api.d.ts +2 -2
  66. package/dist/esm/public-api.d.ts.map +1 -1
  67. package/dist/esm/sdk-config.d.ts +14 -0
  68. package/dist/esm/sdk-config.d.ts.map +1 -1
  69. package/dist/esm/sqlite.js +1 -1
  70. package/dist/esm/store/local-agent-store.d.ts.map +1 -1
  71. package/dist/esm/stubs.d.ts +8 -1
  72. package/dist/esm/stubs.d.ts.map +1 -1
  73. package/dist/esm/usage-types.d.ts +31 -0
  74. package/dist/esm/usage-types.d.ts.map +1 -1
  75. package/package.json +7 -7
  76. package/dist/cjs/84.js +0 -1
  77. package/dist/cjs/prefetched-blobs.d.ts +0 -13
  78. package/dist/cjs/prefetched-blobs.d.ts.map +0 -1
  79. package/dist/esm/.tsbuildinfo.schemas +0 -1
  80. package/dist/esm/prefetched-blobs.d.ts +0 -13
  81. package/dist/esm/prefetched-blobs.d.ts.map +0 -1
  82. /package/dist/cjs/{833.js.LICENSE.txt → 318.js.LICENSE.txt} +0 -0
  83. /package/dist/esm/{833.js.LICENSE.txt → 318.js.LICENSE.txt} +0 -0
package/dist/cjs/84.js DELETED
@@ -1 +0,0 @@
1
- "use strict";exports.id=84,exports.ids=[84],exports.modules={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>LE});var n=r("node:buffer"),o=r("node:crypto"),i=r("node:fs"),s=r("node:os"),a=r("node:path"),l=r.t(a,2),c=r("../context/dist/otel.js"),u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class d{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}run(){return e=this,t=void 0,n=function*(){var e,t,r,n;const o={stack:[],error:void 0,hasError:!1};try{const l=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,c.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,u=[];try{for(var i,s=!0,a=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.checkpointStream);!(e=(i=yield a.next()).done);s=!0){n=i.value,s=!1;const e=n;u.push(this.checkpointHandler.handleCheckpoint(l,e.checkpoint,e.metadata))}}catch(e){t={error:e}}finally{try{s||e||!(r=a.return)||(yield r.call(a))}finally{if(t)throw t.error}}yield Promise.all(u)}catch(e){o.error=e,o.hasError=!0}finally{u(o)}},new((r=void 0)||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}));var e,t,r,n}}var h=r("../context/dist/logger.js"),p=r("../metrics/dist/index.js"),f=r("../proto/dist/generated/agent/v1/exec_pb.js"),m=r("../utils/dist/writable-iterable.js");const g=/https?:\/\/\S+/gi,v=/[)"'<>,.;:\]}]$/;function y(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&v.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),i=o.indexOf("//")+2,s=o.slice(i).search(/[/?#]/),a=-1===s?o.length:i+s,l=o.lastIndexOf("@",a-1);return l<i?o+r:o.slice(0,i)+o.slice(l+1)+r}const w=/ \[git: ([^\]]*)\]/;function b(e,t,r){if("object"!=typeof t||null===t)return e;if(w.test(e))return e;const n=t,o=[];if("string"==typeof n.gitErrorCode&&n.gitErrorCode.length>0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let i=`${e} [git: ${o.join(" ")}]`;var s,a;return!0===(null==r?void 0:r.includeStderr)&&"string"==typeof n.stderr&&n.stderr.length>0&&(i+=`\n--- git stderr ---\n${a=n.stderr,s=a.replace(g,y),s.length<=2048?s:`${s.slice(0,2048)}… [truncated to 2048 chars]`}`),i}var S=function(e){return this instanceof S?(this.v=e,this):new S(e)},k=function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){o[e]&&(n[e]=function(t){return new Promise((function(r,n){i.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=o[e](t)).value instanceof S?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},E=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}};const x=(0,h.h)("SimpleControlledExecManager"),C=(0,p.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),_=(0,p.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,p.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]});class T extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function I(e){return e instanceof T?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class R{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return function(r){return k(this,arguments,(function*(){const i=performance.now(),s=[],a=yield S(r.exec.execute(e,o,{execId:t.execId,hookContextCollector:s,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts})),l=r.serializeResult(n,a);l.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-i)),s.length>0&&(l.hookAdditionalContexts=s),yield yield S(l)}))}(this)}}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return function(r){return k(this,arguments,(function*(){var i,s,a,l;const c=performance.now(),u=r.exec.execute(e,o,{execId:t.execId,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for(var d,h=!0,p=E(u);!(i=(d=yield S(p.next())).done);h=!0){l=d.value,h=!1;const e=l,t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-c)),yield yield S(t)}}catch(e){s={error:e}}finally{try{h||i||!(a=p.return)||(yield S(a.call(p)))}finally{if(s)throw s.error}}}))}(this)}}class O{constructor(e){var t;this.handlers=[],this.runningExecs=new Map;const r=null!==(t=null==e?void 0:e.includeGitStderrInThrows)&&void 0!==t&&t;this.includeGitStderrInThrows="function"==typeof r?r:()=>r}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){var r;const[n,o]=e.withCancel();this.runningExecs.set(t.id,o);const i=null!==(r=t.message.case)&&void 0!==r?r:"unknown";for(const e of this.handlers){const r=e.handle(n,t);if(void 0===r)continue;const o=r,s=(0,m.Jt)();let a;const l=()=>{a=setTimeout((()=>{s.write(new f.$Y({message:{case:"heartbeat",value:new f.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const c=performance.now(),u=()=>{return e=this,r=void 0,u=function*(){var e,r,l,u;try{try{for(var d,h=!0,p=E(o);!(e=(d=yield p.next()).done);h=!0){u=d.value,h=!1;const e=u;yield s.write(e)}}catch(e){r={error:e}}finally{try{h||e||!(l=p.return)||(yield l.call(p))}finally{if(r)throw r.error}}yield s.write(new f.$Y({message:{case:"streamClose",value:new f.D9({id:t.id})}})),_.increment(n,1,{exec_case:i})}catch(e){if(e instanceof m.W2)return;P.increment(n,1,{exec_case:i}),yield s.write(new f.$Y({message:{case:"throw",value:new f.Fu({id:t.id,error:e instanceof Error?b(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:I(e)})}}))}finally{const e=performance.now()-c;C.histogram(n,e,{exec_case:i}),clearTimeout(a),s.close(),this.runningExecs.delete(t.id)}},new((l=void 0)||(l=Promise))((function(t,n){function o(e){try{s(u.next(e))}catch(e){n(e)}}function i(e){try{s(u.throw(e))}catch(e){n(e)}}function s(e){var r;e.done?t(e.value):(r=e.value,r instanceof l?r:new l((function(e){e(r)}))).then(o,i)}s((u=u.apply(e,r||[])).next())}));var e,r,l,u};return u(),s}this.runningExecs.delete(t.id);const s=`No handler found for server message of type ${t.message.case}`;return x.error(e,s,{messageCase:t.message.case}),P.increment(e,1,{exec_case:i}),function(){return k(this,arguments,(function*(){yield yield S(new f.$Y({message:{case:"throw",value:new f.Fu({id:t.id,error:s})}})),yield yield S(new f.$Y({message:{case:"streamClose",value:new f.D9({id:t.id})}}))}))}()}static fromResources(e,t){const r=new O(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var j=function(e){return this instanceof j?(this.v=e,this):new j(e)},M=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,h.h)("ExecutorResource"),U=(0,p.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 M(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=D(n,(0,c.VI)(e.withName("ExecutorResource.execute")),!1),i=o.ctx;void 0!==(null==r?void 0:r.execId)&&o.span.setAttribute("exec.id",r.execId);const s=(0,c.mJ)(i),a=s?new f.Kg(s):void 0,l=this.execManager.createExecInstance(i,(e=>{const n=this.serializeArgs(e,t);return new f.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,spanContext:a,acceptHookAdditionalContexts:void 0!==(null==r?void 0:r.hookContextCollector)})})),u=yield function(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 j?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 j(t.next());if(e.done)return yield j(void 0);yield yield j(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}(l);if(void 0===u)throw new Error("No exec result");const{firstItem:d,rest:h}=u;(()=>M(this,void 0,void 0,(function*(){var e,t,r;try{try{for(var n,o=!0,s=$(h);!(e=(n=yield s.next()).done);o=!0)n.value,o=!1}catch(e){t={error:e}}finally{try{o||e||!(r=s.return)||(yield r.call(s))}finally{if(t)throw t.error}}}catch(e){F.info(i,"Ignoring exec stream shutdown during detached drain",{error:e})}})))().catch((()=>{}));const p=this.deserializeResult(d);if(void 0===p)throw new Error("No result value");if(void 0!==(null==r?void 0:r.hookContextCollector)&&d.hookAdditionalContexts.length>0){r.hookContextCollector.push(...d.hookAdditionalContexts);for(const e of d.hookAdditionalContexts)U.increment(i,1,{hook_event_name:e.hookEventName})}return p}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,c.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,p=(0,c.mJ)(h),m=p?new f.Kg(p):void 0,g=this.execManager.createExecInstance(h,(e=>{const n=this.serializeArgs(e,t);return new f.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,spanContext:m,acceptHookAdditionalContexts:void 0!==(null==r?void 0:r.hookContextCollector)||!0===(null==r?void 0:r.deliverAgentStoreConflictNotices)})}));try{for(var l,u=!0,d=$(g);!(n=(l=yield L(d.next())).done);u=!0){s=l.value,u=!1;const e=s,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 f.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 f.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 R(e,Z("agentStoreConflictArgs"),K("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","gap"]);const X=W((e=>new B(e,V("backgroundShellSpawnArgs"),J("backgroundShellSpawnResult"))),((e,t)=>{t.register(new R(e,Z("backgroundShellSpawnArgs"),K("backgroundShellSpawnResult")))})),Q=W((e=>new B(e,V("writeShellStdinArgs"),J("writeShellStdinResult"))),((e,t)=>{t.register(new R(e,Z("writeShellStdinArgs"),K("writeShellStdinResult")))}));function ee(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 te="local",re=W((e=>new B(e,V("canvasDiagnosticsArgs"),J("canvasDiagnosticsResult"))),((e,t)=>{t.register(new R(e,Z("canvasDiagnosticsArgs"),K("canvasDiagnosticsResult")))}));Error;const ne=W((e=>new B(e,V("computerUseArgs"),J("computerUseResult"))),((e,t)=>{t.register(new R(e,Z("computerUseArgs"),K("computerUseResult")))})),oe=(W((e=>new B(e,V("conversationSearchArgs"),J("conversationSearchResult"))),((e,t)=>{t.register(new R(e,Z("conversationSearchArgs"),K("conversationSearchResult")))})),W((e=>new B(e,V("deleteArgs"),J("deleteResult"))),((e,t)=>{t.register(new R(e,Z("deleteArgs"),K("deleteResult")))}))),ie=W((e=>new B(e,V("diagnosticsArgs"),J("diagnosticsResult"))),((e,t)=>{t.register(new R(e,Z("diagnosticsArgs"),K("diagnosticsResult")))})),se=W((e=>new B(e,V("fetchArgs"),J("fetchResult"))),((e,t)=>{t.register(new R(e,Z("fetchArgs"),K("fetchResult")))})),ae=W((e=>new B(e,V("gitDiffRequest"),J("gitDiffResponse"))),((e,t)=>{t.register(new R(e,Z("gitDiffRequest"),K("gitDiffResponse")))})),le=W((e=>new B(e,V("grepArgs"),J("grepResult"))),((e,t)=>{t.register(new R(e,Z("grepArgs"),K("grepResult")))})),ce={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"},ue={PreToolUse:ce.preToolUse,PermissionRequest:null,PostToolUse:ce.postToolUse,UserPromptSubmit:ce.beforeSubmitPrompt,Stop:ce.stop,SubagentStop:ce.subagentStop,SessionStart:ce.sessionStart,SessionEnd:ce.sessionEnd,PreCompact:ce.preCompact,Notification:null},de=Object.fromEntries(Object.entries(ue).filter((e=>null!==e[1])).map((([e,t])=>[t,e]))),he={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},pe=["Glob"],fe=["Notification","PermissionRequest"],me={warn:()=>{},info:()=>{}};function ge(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 ve(e,t,r=me){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=me){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=he[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):pe.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=ge(t,o);e&&n.push(e)}return n}function ye(e,t=me){const r={};for(const[n,o]of Object.entries(e)){const e=n;if(fe.includes(e)){t.warn(`Claude Code event "${e}" is not supported in Cursor and will be ignored`);continue}const i=ue[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=ve(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 we(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 be=e=>"string"==typeof e,Se=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),ke=(e,t=[])=>({isValid:e,errors:t});function Ee(e,t,r){void 0===e||be(e)||r.push(`${t} must be a string if provided`)}const xe=e=>{const t=[];return Se(e)?ke(!0):(t.push("Expected an object"),ke(!1,t))},Ce=e=>{const t=[],r=xe(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),ke(0===t.length,t)};function _e(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 Pe=new Set([ce.sessionStart,ce.beforeSubmitPrompt,ce.preToolUse,ce.postToolUse,ce.postToolUseFailure]);function Te(e){return"prompt"===e.type}const Ie={[ce.beforeShellExecution]:Ce,[ce.beforeMCPExecution]:Ce,[ce.afterShellExecution]:e=>{const t=xe(e);return t.isValid,t},[ce.afterMCPExecution]:e=>{const t=xe(e);return t.isValid,t},[ce.beforeReadFile]:e=>{const t=[],r=xe(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),ke(0===t.length,t)},[ce.afterFileEdit]:e=>{const t=xe(e);return t.isValid,t},[ce.beforeTabFileRead]:e=>{const t=[],r=xe(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),ke(0===t.length,t)},[ce.afterTabFileEdit]:e=>xe(e),[ce.beforeSubmitPrompt]:e=>{const t=xe(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||be(e.additional_context)||r.push("additional_context must be a string if provided"),ke(0===r.length,r)},[ce.stop]:e=>{const t=xe(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),ke(0===r.length,r)},[ce.afterAgentResponse]:e=>{const t=xe(e);return t.isValid,t},[ce.afterAgentThought]:e=>{const t=xe(e);return t.isValid,t},[ce.sessionStart]:e=>{const t=xe(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Se(e.env))for(const[t,n]of Object.entries(e.env))be(t)||r.push(`env key "${t}" must be a string`),be(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||be(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||be(e.user_message)||r.push("user_message must be a string if provided"),ke(0===r.length,r)},[ce.sessionEnd]:e=>{const t=xe(e);return t.isValid?ke(!0,[]):t},[ce.preCompact]:e=>{const t=xe(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return ke(!0,[]);const r=[];if(!Se(e))return r.push("PreCompact response must be an object"),ke(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),ke(0===r.length,r)},[ce.subagentStart]:e=>{const t=xe(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||be(n.user_message)||r.push("user_message must be a string if provided"),ke(0===r.length,r)},[ce.subagentStop]:e=>{const t=xe(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"),ke(0===r.length,r)},[ce.preToolUse]:e=>{const t=[],r=xe(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ee(e.additional_context,"additional_context",t),ke(0===t.length,t)},[ce.postToolUse]:e=>{const t=[],r=xe(e);return r.isValid?(Ee(e.additional_context,"additional_context",t),ke(0===t.length,t)):r},[ce.postToolUseFailure]:e=>{const t=xe(e);if(!t.isValid)return t;const r=[];return Ee(e.additional_context,"additional_context",r),ke(0===r.length,r)},[ce.workspaceOpen]:e=>{const t=xe(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{be(e)?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),ke(0===r.length,r)}},Re=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===ce.preToolUse?function(e,t){if(!Ue(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(!Fe(t))return r;const n=Be(e);if(!ze(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),Ue(n.updatedInput)&&(o.updated_input=n.updatedInput,i=!0),i?o:r}(t,r):e===ce.stop?We(t,r,"Stop"):e===ce.subagentStop?We(t,r,"SubagentStop"):t,function(e,t,r,n){var o;if(!Pe.has(e)||!Ue(r)||void 0!==r.additional_context)return r;const i=Ue(t)?null!==(o=function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t))&&void 0!==o?o:function(e,t,r){if(!Fe(r))return;const n=de[e];if(void 0===n)return;const o=Be(t);return ze(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,Ie[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},Ae=[ce.beforeShellExecution,ce.beforeMCPExecution,ce.beforeReadFile,ce.beforeTabFileRead,ce.subagentStart,ce.preToolUse],Oe=[ce.workspaceOpen];function je(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 Me(e,t){if(e||t)return Object.assign(Object.assign({},e||{}),t||{})}function De(e){return Ae.includes(e)}function Ne({step:e,command:t,failClosed:r,kind:n}){const o=De(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:$e(e,i),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:i,shouldNotifyUser:o&&!r}}function $e(e,t){return De(e)?{permission:"deny",user_message:t}:e===ce.beforeSubmitPrompt||e===ce.sessionStart?{continue:!1,user_message:t}:e===ce.stop?{}:void 0}function Le(e){try{return{value:JSON.parse(e)}}catch(e){return}}function Fe(e){var t;return null!==(t=null==e?void 0:e.enableClaudeNestedHookSpecificOutputCompatibility)&&void 0!==t&&t}function Ue(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Be(e){if(!Ue(e))return;const t=e.hookSpecificOutput;return Ue(t)?t:void 0}function ze(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function We(e,t,r){if(!Ue(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(!Fe(t))return n;const o=Be(e),i=ze(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 He=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"],qe=e=>{const t=[];if(!Se(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),ke(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{be(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&&(be(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)=>{be(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(be(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),ke(0===t.length,t)},Ge=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),ke(!1,r);for(let n=0;n<e.length;n++){const o=qe(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return ke(0===r.length,r)},Ve=e=>{const t=[];if(!Se(e))return t.push("Hooks config must be an object"),ke(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Se(e.hooks))return t.push("Config hooks must be an object"),ke(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(ce),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Ge(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return ke(0===t.length,t)};var Je=r("../proto/dist/generated/agent/v1/agent_pb.js");const Ke=W((e=>new B(e,V("executeHookArgs"),J("executeHookResult"))),((e,t)=>{t.register(new R(e,Z("executeHookArgs"),K("executeHookResult")))}));class Ze{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){var r,n,o;return null!==(o=null===(n=(r=this.hookExecutor).hasFailClosedHooksForStep)||void 0===n?void 0:n.call(r,e,t))&&void 0!==o&&o}execute(e,t){return r=this,n=void 0,i=function*(){var e,r,n,o,i,s,a,l,c,u,d,h,p,m,g,v,y,w,b,S,k,E,x,C,_,P,T,I,R,A,O;const j=t.request;if(!j)return new f.S1({response:void 0});switch(j.request.case){case"preCompact":{const t=j.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:""},_e(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(ce.preCompact,o);return new f.S1({response:new f.w5({response:{case:"preCompact",value:new Je.$_({userMessage:null==i?void 0:i.user_message})}})})}case"subagentStart":{const e=j.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:""},_e(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(ce.subagentStart,t);return new f.S1({response:new f.w5({response:{case:"subagentStart",value:new Je.W0({permission:null==r?void 0:r.permission,userMessage:null==r?void 0:r.user_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"subagentStop":{const e=j.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:""},_e(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(ce.subagentStop,t);return new f.S1({response:new f.w5({response:{case:"subagentStop",value:new Je.AH({followupMessage:null==r?void 0:r.followup_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"beforeSubmitPrompt":{const e=j.request.value,t=yield this.hookExecutor.executeHookForStep(ce.beforeSubmitPrompt,Object.assign(Object.assign({conversation_id:null!==(d=e.conversationId)&&void 0!==d?d:"",generation_id:null!==(h=e.generationId)&&void 0!==h?h:"",model:null!==(p=e.model)&&void 0!==p?p:""},_e(e)),{prompt:e.prompt,attachments:(M=e.attachments,M.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode}));return new f.S1({response:new f.w5({response:{case:"beforeSubmitPrompt",value:new Je.u1({continue:null==t?void 0:t.continue,userMessage:null==t?void 0:t.user_message,additionalContext:null==t?void 0:t.additional_context})}})})}case"afterAgentResponse":{const e=j.request.value;return yield this.hookExecutor.executeHookForStep(ce.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:""},_e(e)),{text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0})),new f.S1({response:new f.w5({response:{case:"afterAgentResponse",value:new Je.FW}})})}case"afterAgentThought":{const e=j.request.value;return yield this.hookExecutor.executeHookForStep(ce.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:""},_e(e)),{text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0})),new f.S1({response:new f.w5({response:{case:"afterAgentThought",value:new Je.H}})})}case"stop":{const e=j.request.value,t=yield this.hookExecutor.executeHookForStep(ce.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:""},_e(e)),{status:e.status,loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}));return new f.S1({response:new f.w5({response:{case:"stop",value:new Je.rT({followupMessage:null==t?void 0:t.followup_message})}})})}case"preToolUse":{const e=j.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!==_?_:""},_e(e)),{tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd}),n=yield this.hookExecutor.executeHookForStep(ce.preToolUse,r);return new f.S1({response:new f.w5({response:{case:"preToolUse",value:new Je.Wn({permission:null==n?void 0:n.permission,userMessage:null==n?void 0:n.user_message,agentMessage:null==n?void 0:n.agent_message,updatedInput:(null==n?void 0:n.updated_input)?JSON.stringify(n.updated_input):void 0,additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUse":{const e=j.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!==(T=e.generationId)&&void 0!==T?T:"",model:null!==(I=e.model)&&void 0!==I?I:""},_e(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(ce.postToolUse,r);return new f.S1({response:new f.w5({response:{case:"postToolUse",value:new Je.uB({additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUseFailure":{const e=j.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:""},_e(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(ce.postToolUseFailure,r);return new f.S1({response:new f.w5({response:{case:"postToolUseFailure",value:new Je.U1({additionalContext:null==n?void 0:n.additional_context})}})})}default:return new f.S1({response:void 0})}var M},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 Ye=r("../context/dist/core.js");(0,Ye.cF)(Symbol("execHookConversationId"),void 0),(0,Ye.cF)(Symbol("execHookGenerationId"),void 0),(0,Ye.cF)(Symbol("execHookModel"),void 0);const Xe=(0,Ye.cF)(Symbol("execHookWorkspaceRoots"),void 0),Qe=W((e=>new B(e,V("lsArgs"),J("lsResult"))),((e,t)=>{t.register(new R(e,Z("lsArgs"),K("lsResult")))})),et="custom-user-tools";function tt(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 rt;function nt(e){return void 0===e||void 0===e.serverIdentifiers}new Set(["cursor-dev-control","cursor-ide-browser"]),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"}(rt||(rt={}));const ot=W((e=>new B(e,V("mcpArgs"),J("mcpResult"))),((e,t)=>{t.register(new R(e,Z("mcpArgs"),K("mcpResult")))})),it=W((e=>new B(e,V("listMcpResourcesExecArgs"),J("listMcpResourcesExecResult"))),((e,t)=>{t.register(new R(e,Z("listMcpResourcesExecArgs"),K("listMcpResourcesExecResult")))})),st=W((e=>new B(e,V("readMcpResourceExecArgs"),J("readMcpResourceExecResult"))),((e,t)=>{t.register(new R(e,Z("readMcpResourceExecArgs"),K("readMcpResourceExecResult")))})),at=W((e=>new B(e,V("mcpStateExecArgs"),J("mcpStateExecResult"))),((e,t)=>{t.register(new R(e,Z("mcpStateExecArgs"),K("mcpStateExecResult")))})),lt=W((e=>new B(e,V("mcpAllowlistPrecheckArgs"),J("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Z("mcpAllowlistPrecheckArgs"),K("mcpAllowlistPrecheckResult")))})),ct=W((e=>new B(e,V("miniSweAgentBashArgs"),J("miniSweAgentBashResult"))),((e,t)=>{t.register(new R(e,Z("miniSweAgentBashArgs"),K("miniSweAgentBashResult")))})),ut=W((e=>new B(e,V("piBashArgs"),J("piBashResult"))),((e,t)=>{t.register(new R(e,Z("piBashArgs"),K("piBashResult")))})),dt=W((e=>new B(e,V("piEditArgs"),J("piEditResult"))),((e,t)=>{t.register(new R(e,Z("piEditArgs"),K("piEditResult")))})),ht=W((e=>new B(e,V("piFindArgs"),J("piFindResult"))),((e,t)=>{t.register(new R(e,Z("piFindArgs"),K("piFindResult")))})),pt=W((e=>new B(e,V("piGrepArgs"),J("piGrepResult"))),((e,t)=>{t.register(new R(e,Z("piGrepArgs"),K("piGrepResult")))})),ft=W((e=>new B(e,V("piLsArgs"),J("piLsResult"))),((e,t)=>{t.register(new R(e,Z("piLsArgs"),K("piLsResult")))})),mt=W((e=>new B(e,V("piReadArgs"),J("piReadResult"))),((e,t)=>{t.register(new R(e,Z("piReadArgs"),K("piReadResult")))})),gt=W((e=>new B(e,V("piWriteArgs"),J("piWriteResult"))),((e,t)=>{t.register(new R(e,Z("piWriteArgs"),K("piWriteResult")))})),vt=W((e=>new B(e,V("readArgs"),J("readResult"))),((e,t)=>{t.register(new R(e,Z("readArgs"),K("readResult")))})),yt=W((e=>new B(e,V("redactedReadArgs"),J("redactedReadResult"))),((e,t)=>{t.register(new R(e,Z("redactedReadArgs"),K("redactedReadResult")))}));var wt=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),bt=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),St=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),kt=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Et=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const xt=W((e=>new B(e,V("shellArgs"),J("shellResult"))),((e,t)=>{t.register(new R(e,Z("shellArgs"),K("shellResult")))})),Ct=W((e=>new z(e,V("shellStreamArgs"),J("shellStream"))),((e,t)=>{t.register(new A(e,Z("shellStreamArgs"),K("shellStream")))})),_t=W((e=>new B(e,V("writeArgs"),J("writeResult"))),((e,t)=>{t.register(new R(e,Z("writeArgs"),K("writeResult")))}));var Pt=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())}))},Tt=function(e){return this instanceof Tt?(this.v=e,this):new Tt(e)};function It(e,t){var r,n;return new kt.jn({command:null!==(r=t.command)&&void 0!==r?r:"",workingDirectory:null!==(n=t.workingDirectory)&&void 0!==n?n:"",error:e,isReadonly:!0})}function Rt(e){return{execute(t,r){return Pt(this,void 0,void 0,(function*(){return new kt.W4({result:{case:"permissionDenied",value:It(e,r)}})}))}}}function At(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 Tt?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 Tt(new kt.FI({event:{case:"permissionDenied",value:It(e,r)}}))}))}}}function Ot(e){return{execute(t,r){return Pt(this,void 0,void 0,(function*(){return new wt.Lt({result:{case:"permissionDenied",value:It(e,r)}})}))}}}function jt(e){return{execute(t,r){return Pt(this,void 0,void 0,(function*(){return new bt.Pi({result:{case:"permissionDenied",value:new bt.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}))}}}function Mt(e){return{execute(t,r){return Pt(this,void 0,void 0,(function*(){return new St.iz({result:{case:"permissionDenied",value:new St.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}))}}}function Dt(e){return{execute(t,r){return Pt(this,void 0,void 0,(function*(){return new wt.nt({result:{case:"error",value:new wt.Gv({error:e})}})}))}}}const Nt=W((e=>new B(e,V("recordScreenArgs"),J("recordScreenResult"))),((e,t)=>{t.register(new R(e,Z("recordScreenArgs"),K("recordScreenResult")))})),$t=W((e=>new B(e,V("requestContextArgs"),J("requestContextResult"))),((e,t)=>{t.register(new R(e,Z("requestContextArgs"),K("requestContextResult")))})),Lt=W((e=>new B(e,V("shellAllowlistPrecheckArgs"),J("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Z("shellAllowlistPrecheckArgs"),K("shellAllowlistPrecheckResult")))})),Ft=W((e=>new B(e,V("forceBackgroundShellArgs"),J("forceBackgroundShellResult"))),((e,t)=>{t.register(new R(e,Z("forceBackgroundShellArgs"),K("forceBackgroundShellResult")))}));function Ut(e,t){e.hookApprovalRequirement=void 0!==t?new kt.In(t):void 0}function Bt(e){return e.hookApprovalRequirement}function zt(e){return(null==e?void 0:e.kind)===kt.b.FORCE_PROMPT}W((e=>new B(e,V("smartModeClassifierArgs"),J("smartModeClassifierResult"))),((e,t)=>{t.register(new R(e,Z("smartModeClassifierArgs"),K("smartModeClassifierResult")))}));var Wt=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");class Ht 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 qt(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 Wt.vS({result:{case:"error",value:new Wt.od({agentId:l,error:a.error})}}):"aborted"===a.status?new Wt.vS({result:{case:"error",value:new Wt.od({agentId:l,error:null!==(o=a.error)&&void 0!==o?o:"Subagent was aborted by the user"})}}):"background"===a.status?new Wt.vS({result:{case:"success",value:new Wt.HJ({agentId:l,finalMessage:a.finalMessage,toolCallCount:null!==(i=a.toolCallCount)&&void 0!==i?i:0,backgroundReason:a.backgroundReason,transcriptPath:a.transcriptPath})}}):new Wt.vS({result:{case:"success",value:new Wt.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 Ht&&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 Wt.vS({result:{case:"error",value:new Wt.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 Gt=W((e=>new B(e,V("subagentArgs"),J("subagentResult"))),((e,t)=>{t.register(new R(e,Z("subagentArgs"),K("subagentResult")))}));W((e=>new B(e,V("subagentAwaitArgs"),J("subagentAwaitResult"))),((e,t)=>{t.register(new R(e,Z("subagentAwaitArgs"),K("subagentAwaitResult")))})),W((e=>new B(e,V("forceBackgroundSubagentArgs"),J("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new R(e,Z("forceBackgroundSubagentArgs"),K("forceBackgroundSubagentResult")))}));class Vt{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 Jt(e){return"string"==typeof e&&e.trim().length>0}const Kt=W((e=>new B(e,V("webFetchAllowlistPrecheckArgs"),J("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Z("webFetchAllowlistPrecheckArgs"),K("webFetchAllowlistPrecheckResult")))})),Zt=e=>String(e).replace(/[\r\n]/g,""),Yt="x-inference-authentication-jwt",Xt={textDelta:e=>new Je.Uq({message:{case:"textDelta",value:new Je.Pt({text:e})}}),toolCallStarted:(e,t,r)=>new Je.Uq({message:{case:"toolCallStarted",value:new Je.xu({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new Je.Uq({message:{case:"toolCallCompleted",value:new Je.LL({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r)=>new Je.Uq({message:{case:"toolCallDelta",value:new Je.I0({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t)=>new Je.Uq({message:{case:"thinkingDelta",value:new Je.cH({text:e,thinkingStyle:t})}}),thinkingCompleted:e=>new Je.Uq({message:{case:"thinkingCompleted",value:new Je.tr({thinkingDurationMs:e})}}),userMessageAppended:e=>new Je.Uq({message:{case:"userMessageAppended",value:new Je.v$({userMessage:e})}}),partialToolCall:(e,t,r)=>new Je.Uq({message:{case:"partialToolCall",value:new Je.fx({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new Je.Uq({message:{case:"tokenDelta",value:new Je.Fy({tokens:e})}}),summary:e=>new Je.Uq({message:{case:"summary",value:new Je.EC({summary:e})}}),summaryStarted:()=>new Je.Uq({message:{case:"summaryStarted",value:new Je.lW}}),heartbeat:()=>new Je.Uq({message:{case:"heartbeat",value:new Je.RV}}),summaryCompleted:e=>new Je.Uq({message:{case:"summaryCompleted",value:new Je.ZM({hookMessage:e})}}),shellOutputDelta:e=>new Je.Uq({message:{case:"shellOutputDelta",value:new Je.Nn({event:e})}}),turnEnded(e){var t;return new Je.Uq({message:{case:"turnEnded",value:new Je.lJ(e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(null!==(t=e.reasoningTokens)&&void 0!==t?t:0)}:{})}})},stepStarted:e=>new Je.Uq({message:{case:"stepStarted",value:new Je.dw({stepId:BigInt(e)})}}),stepCompleted:(e,t)=>new Je.Uq({message:{case:"stepCompleted",value:new Je.Lr({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),promptSuggestion:e=>new Je.Uq({message:{case:"promptSuggestion",value:new Je.yf({suggestion:e})}}),activeBranchChange:(e,t)=>new Je.Uq({message:{case:"activeBranchChange",value:new Je.PS({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new Je.Uq({message:{case:"feedbackRequest",value:new Je.ap({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};var Qt=r("../agent-kv/dist/index.js");function er(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 tr=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),rr=r("../proto/dist/generated/agent/v1/mcp_pb.js"),nr=r("@bufbuild/protobuf"),or=r("@connectrpc/connect"),ir=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_ef7275568c8b1f1f499006dc986c70d2/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),sr=r("../proto/dist/generated/aiserver/v1/utils_pb.js");class ar 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 lr extends ar{get kind(){return"RetriableError"}}class cr extends ar{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class ur extends ar{get kind(){return"NonRetriableError"}}class dr extends ar{get kind(){return"CancelledError"}}const hr=new Set([sr.yM.NOT_LOGGED_IN,sr.yM.AGENT_REQUIRES_LOGIN,sr.yM.AUTH_TOKEN_NOT_FOUND,sr.yM.AUTH_TOKEN_EXPIRED,sr.yM.INVALID_AUTH_ID,sr.yM.UNAUTHORIZED,sr.yM.GITHUB_NO_USER_CREDENTIALS,sr.yM.GITHUB_USER_NO_ACCESS]),pr=new Set([sr.yM.FREE_USER_USAGE_LIMIT,sr.yM.FREE_USER_RATE_LIMIT_EXCEEDED,sr.yM.PRO_USER_ONLY,sr.yM.PRO_USER_USAGE_LIMIT,sr.yM.PRO_USER_RATE_LIMIT_EXCEEDED,sr.yM.RATE_LIMITED,sr.yM.RATE_LIMITED_CHANGEABLE,sr.yM.GENERIC_RATE_LIMIT_EXCEEDED]),fr=new Set([sr.yM.USAGE_PRICING_REQUIRED,sr.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),mr=new Set([sr.yM.BAD_API_KEY,sr.yM.BAD_USER_API_KEY,sr.yM.OUTDATED_CLIENT]),gr=new Set([sr.yM.USER_ABORTED_REQUEST,sr.yM.DEBOUNCED]),vr=new Set([sr.yM.CUSTOM_MESSAGE]),yr=["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"],wr=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH"]),br=new RegExp(`\\b(${[...wr].join("|")})\\b`);function Sr(e,t={}){const{requestId:r}=t;if(e instanceof ar)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;const c=function(e){var t,r;const n=e.findDetails(sr.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,sr.vj);return null==n?void 0:n[0]}catch(e){return}}(e),u={cause:e,requestId:t,displayInfo:{title:null===(r=null==c?void 0:c.details)||void 0===r?void 0:r.title,detail:null===(n=null==c?void 0:c.details)||void 0===n?void 0:n.detail,isRetryable:null===(o=null==c?void 0:c.details)||void 0===o?void 0:o.isRetryable,connectCode:e.code,errorCode:null==c?void 0:c.error,errorDetails:c}};if(e.code===or.Code.Canceled||e.code===or.Code.Aborted)return Er(e)?new lr(e.message,u):new dr(e.message,u);if(void 0!==(null==c?void 0:c.error)){const t=c.error;if(gr.has(t))return new dr(kr(e,c),u);const r=null===(s=null===(i=c.details)||void 0===i?void 0:i.analyticsMetadata)||void 0===s?void 0:s.actionRequired;if(void 0!==r&&""!==r)return new cr(kr(e,c),r,u);if(hr.has(t))return new cr(kr(e,c),"login",u);if(pr.has(t))return new cr(kr(e,c),"upgrade",u);if(fr.has(t))return new cr(kr(e,c),"payment",u);if(mr.has(t))return new cr(kr(e,c),"config",u);if(vr.has(t)&&!0!==(null===(a=c.details)||void 0===a?void 0:a.isRetryable))return new ur(kr(e,c),u);if(!1===(null===(l=c.details)||void 0===l?void 0:l.isRetryable))return new ur(kr(e,c),u)}return e.code===or.Code.Unauthenticated?new cr(e.message,"login",u):new lr(e.message,u)}(e,r);const n=(0,Qt.y_)(e);if(void 0!==n)return new ur(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 dr(e.message,{cause:e,requestId:r});if(Er(e))return new lr(e.message,{cause:e,requestId:r})}const o=e instanceof Error?e.message:String(e);return new lr(o,{cause:e instanceof Error?e:void 0,requestId:r})}function kr(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 Er(e){let t=e;for(;t instanceof Error;){const e=`${t.name}: ${t.message}`;if(yr.some((t=>e.includes(t)))||br.test(e))return!0;const r=t.code;if("string"==typeof r&&(yr.some((e=>r.includes(e)))||wr.has(r)))return!0;t=t.cause}return!1}function xr(e){return!0===e.isTransport||(e.cause instanceof Error?Er(e.cause):yr.some((t=>e.message.includes(t)))||br.test(e.message))}var Cr=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},_r=function(e,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},Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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}),Tr=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 Ir extends Error{constructor(e){super(e),this.name="LostConnection"}}class Rr{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}run(e){return Cr(this,void 0,void 0,(function*(){var t,r,n,o;const i={stack:[],error:void 0,hasError:!1};try{_r(i,(0,c.VI)(e.withName("ClientExecController.run")),!1);const u=[];try{try{for(var s,a=!0,l=Tr(this.serverStream);!(t=(s=yield l.next()).done);a=!0){o=s.value,a=!1;const t=o;if(t instanceof tr.Nv){this.controlledExecManager.handleControlMessage(t);continue}const r=(()=>Cr(this,void 0,void 0,(function*(){var r,n,o,i,s;const a={stack:[],error:void 0,hasError:!1};try{let h,p;if(t.spanContext){const r=t.spanContext;h=(0,c.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:null!==(s=r.traceFlags)&&void 0!==s?s:1},"exec.handle",e),p=(0,c.fU)(h)}else h=e;_r(a,p?new c.r2(h,p):void 0,!1);const f=this.controlledExecManager.handle(h,t);try{for(var l,u=!0,d=Tr(f);!(r=(l=yield d.next()).done);u=!0){i=l.value,u=!1;const e=i;yield this.clientStream.write(e)}}catch(e){n={error:e}}finally{try{u||r||!(o=d.return)||(yield o.call(d))}finally{if(n)throw n.error}}}catch(e){a.error=e,a.hasError=!0}finally{Pr(a)}})))();u.push(r)}}catch(e){r={error:e}}finally{try{a||t||!(n=l.return)||(yield n.call(l))}finally{if(r)throw r.error}}yield Promise.all(u)}catch(e){if(e instanceof or.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ir(e.message);if(e instanceof or.ConnectError&&e.code===or.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 Ir(e.message)}else{if(e instanceof m.W2)throw new Ir(e.message);if(e instanceof or.ConnectError&&e.code===or.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ir(e.message)}}}}catch(e){i.error=e,i.hasError=!0}finally{Pr(i)}}))}}var Ar=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())}))},Or=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jr=(0,h.h)("ClientInteractionController"),Mr=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Dr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}run(e){return Ar(this,void 0,void 0,(function*(){var t,r,n,o;const i={stack:[],error:void 0,hasError:!1};try{const u=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(i,(0,c.VI)(e.withName("ClientInteractionController.run")),!1);e=u.ctx;let d,h=Promise.resolve();try{for(var s,a=!0,l=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.interactionStream);!(t=(s=yield l.next()).done);a=!0){o=s.value,a=!1;const t=o;"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):"interactionUpdate"===t.case&&(h=h.then((()=>this.handleInteractionUpdate(e,t.value))).catch((t=>{jr.error(e,"Error handling interaction update",t),null!=d||(d=t)})))}}catch(e){r={error:e}}finally{try{a||t||!(n=l.return)||(yield n.call(l))}finally{if(r)throw r.error}}if(yield h,void 0!==d)throw d}catch(e){i.error=e,i.hasError=!0}finally{Or(i)}}))}handleInteractionUpdate(e,t){return Ar(this,void 0,void 0,(function*(){yield this.interactionListener.sendUpdate(e,t)}))}handleInteractionQuery(e,t){var r;const n=void 0!==t.query.case&&Mr.has(t.query.case);n&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&(null===(r=this.stallSuspender)||void 0===r||r.setPaused(!0))),this.interactionListener.query(e,t).then((e=>this.queryResponseStream.write(e))).catch((t=>{jr.error(e,"Error handling interaction query",t)})).finally((()=>{var e;n&&(this.pendingHumanQueries--,0===this.pendingHumanQueries&&(null===(e=this.stallSuspender)||void 0===e||e.setPaused(!1)))}))}}const Nr=(0,h.h)("@anysphere/agent-client:stall-detector"),$r=(0,p.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type"]}),Lr=(0,p.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type"]}),Fr=(0,p.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall"}),Ur=(0,p.Pu)("agent_client.stream.total",{description:"Total number of streams monitored"});class Br{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 zr{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(),Ur.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(Zr),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"});Nr.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(Zr);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(Nr.warn(this.ctx,d,o),$r.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,Fr.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});Nr.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"),Lr.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 Wr=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Hr=(0,h.h)("@anysphere/agent-client:turn-runner");function qr(e,t,r,n){return Wr(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 dr("Cancelled during backoff"));const n=setTimeout((()=>{null==t||t.removeEventListener("abort",o),e()}),i+s);function o(){clearTimeout(n),r(new dr("Cancelled during backoff"))}null==t||t.addEventListener("abort",o,{once:!0})}))}))}var Gr=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())}))},Vr=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},Jr=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}),Kr=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 Zr=(0,Ye.cF)(Symbol("agentStreamMetadata"),void 0),Yr=(0,h.h)("@anysphere/agent-client:abort"),Xr=(0,h.h)("@anysphere/agent-client:retry"),Qr=e=>{var t,r;const n=[];switch(n.push(e.message.case),e.message.case){case"conversationAction":n.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":n.push(e.message.value.message.case);break;case"interactionResponse":n.push(e.message.value.result.case);break;case"interactionUpdate":switch(n.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":n.push(null===(t=e.message.value.message.value.toolCall)||void 0===t?void 0:t.tool.case);break;case"toolCallDelta":n.push(null===(r=e.message.value.message.value.toolCallDelta)||void 0===r?void 0:r.delta.case)}break;case"interactionQuery":n.push(e.message.value.query.case)}return n.filter((e=>void 0!==e)).join(":")};function en(e,t,r){return Gr(this,void 0,void 0,(function*(){var n,o,i,s,a,l,c;try{for(n=!0,o=Kr(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,Xt.shellOutputDelta({case:"stdout",value:new kt.o0({data:t.event.value.data})}));break;case"stderr":yield r.sendUpdate(e,Xt.shellOutputDelta({case:"stderr",value:new kt.Db({data:t.event.value.data})}));break;case"exit":yield r.sendUpdate(e,Xt.shellOutputDelta({case:"exit",value:new kt.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}}}))}function tn(e,t,r){return{sendUpdate:(n,o)=>Gr(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)&&Xr.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})})),query:(n,o)=>Gr(this,void 0,void 0,(function*(){if(t!==r())throw new dr("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}}const rn=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0;function nn(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function on(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}function sn(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 an(e){return e instanceof Error?e.name:void 0}function ln(e){const t={errorName:an(e)};let r=e;for(let e=0;e<10&&void 0!==r;e++){if(nn(r)){const e=on(r),n=sn(e),o=an(e);return Object.assign(Object.assign({},t),{underlyingConnectError:{code:r.code,codeName:or.Code[r.code],cause:void 0!==n||void 0!==o?{code:n,name:o}:void 0}})}r=on(r)}return t}function cn(e,t,r,n,o,i,s,a,l){const c=i||s,u=l?2:10,d=e instanceof ar?e:Sr(e,{requestId:o});return t?c?!s&&n>=u?{action:"throw",error:new lr("Connection stalled repeatedly",{cause:d.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 lr("Connection stalled",{cause:d.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0}})}:d instanceof dr&&!a&&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(nn(t)&&(t.code===or.Code.Canceled||t.code===or.Code.Aborted))return!0;t=on(t)}return!1}(d)?c?!s&&n>=u?{action:"throw",error:new lr("Connection failed repeatedly",{cause:d.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:d}:d instanceof dr||d instanceof cr||d instanceof ur?{action:"throw",error:d}:d instanceof lr&&xr(d)?c?!s&&n>=u?{action:"throw",error:new lr("Connection failed repeatedly",{cause:d.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:d}:c?!s&&r>=3?{action:"throw",error:d}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:{action:"throw",error:d}}class un{constructor(e,t){this.client=e,this.endpointUrl=t,this.hasStartedStream=!1}run(e,t,r,n,o,i,s,a,l,c,u){return Gr(this,void 0,void 0,(function*(){return!0===u.useSharedTurnRunner?this.runWithSharedTurnRunner(e,t,r,n,o,i,s,a,l,c,u):this.runWithLegacyRetryLoop(e,t,r,n,o,i,s,a,l,c,u)}))}runWithSharedTurnRunner(e,t,r,n,o,i,s,a,l,u,d){return Gr(this,void 0,void 0,(function*(){var h,p;const f={stack:[],error:void 0,hasError:!1};try{const m=null!==(p=d.generationUUID)&&void 0!==p?p:crypto.randomUUID(),g={value:!1},v={sources:[],abortReasonName:void 0,abortReasonMessage:void 0};let y=0,w=0;try{null===(h=d.onNetworkPhaseStart)||void 0===h||h.call(d)}catch(t){Xr.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const b=Vr(f,(0,c.VI)(e.withName("networkPhase")),!1);e=b.ctx,yield function(e){return Wr(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)=>qr(e,t,S.isRunningInTest,S.fixedRetryDelayMs);let P,T,I=e.state,R=e.action,A=0,O=k,j=0,M=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)=>Wr(this,void 0,void 0,(function*(){var n;yield b.handleCheckpoint(e,t,r),P=t,T=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,T=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:I,isResume:"resumeAction"===R.action.case,attemptRequestId:O}),e.logging&&Hr.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:I,nextAttempt:A,reason:"resume_action"}),e.logging&&Hr.info(w,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:A,reason:"resume_action"}))):(e.logging&&Hr.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:I,nextAttempt:A,reason:"resume_action"}),e.logging&&Hr.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:I,action:R,checkpointHandler:$,attempt:A,attemptRequestId:O,notifyConnected:N}),N(),void(e.logging&&Hr.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:j,transportErrorRetries:M,endlessRetries:r});if(e.logging){const o="retry"===n.action?`RETRY (countAsServerError=${n.countAsServerError}, countAsTransportError=${n.countAsTransportError})`:`THROW ${n.error.kind}`;Hr.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:j,transportErrorRetries:M,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&&Hr.warn(w,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(t),requestId:O,originalRequestId:C})}}throw e.logging&&Hr.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:j,transportErrorRetries:M})),n.error}const o=A+1;if("ineligible_terminal_turn"===T)return void(e.logging&&Hr.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&&j++,n.countAsTransportError&&M++,A=o,void 0!==P&&(I=P,R=new Je.QF({action:{case:"resumeAction",value:new Je.qK}}),null===(p=E.onResumeFromCheckpoint)||void 0===p||p.call(E)),yield _(A,w.signal)}}}))}({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:m,notifyInitialResume:!0,logging:{tag:"nal_agent_retries",includeErrorObjects:!0,diagnostics:e=>Object.assign({stallAborted:g.value,abortSources:[...v.sources],abortReasonName:v.abortReasonName},ln(e))},cancellation:{toCancelledError:()=>new dr("Request cancelled")},hooks:{beginAttempt:()=>{g.value=!1,v.sources=[],v.abortReasonName=void 0,v.abortReasonMessage=void 0,w=++y},runAttempt:t=>Gr(this,[t],void 0,(function*({state:t,action:r,checkpointHandler:l,attempt:c,attemptRequestId:h,notifyConnected:p}){const f=tn(o,w,(()=>y));yield this.runInternal(e,t,r,n,f,i,s,a,l,u,d,h,m,g,v,p,c)})),classify:(e,t)=>{var r;return cn(e,g.value,t.serverErrorRetries,t.transportErrorRetries,t.attemptRequestId,null!==(r=d.enableAgentRetries)&&void 0!==r&&r,t.endlessRetries,v.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:g.value,abortSources:[...v.sources],abortReasonName:v.abortReasonName,abortReasonMessage:v.abortReasonMessage})},reconnectTrigger:(e,t,r)=>{var n,o,i;const s=ln(e),a=e instanceof ar?e:Sr(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:g.value,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,endpointUrl:this.endpointUrl}},onResumeFromCheckpoint:()=>a.resetStream()}})}catch(e){f.error=e,f.hasError=!0}finally{Jr(f)}}))}runWithLegacyRetryLoop(e,t,r,n,o,i,s,a,l,u,d){return Gr(this,void 0,void 0,(function*(){var h,p,f,m,g,v,y,w,b,S,k,E,x;const C={stack:[],error:void 0,hasError:!1};try{const _=null!==(w=d.generationUUID)&&void 0!==w?w:crypto.randomUUID();let P=_;const{onConnectionStateChange:T}=d;let I=t,R=r,A=0,O=0,j=0;const M={value:!1},D={value:!1},N={value:!1},$={value:void 0},L={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},F=(e,t)=>{null==T||T({state:"reconnecting",attempt:e,trigger:t}),M.value=!0},U=()=>{M.value&&(null==T||T({state:"connected"}),M.value=!1)},B=t=>{if(!N.value)return!1;if("ineligible_terminal_turn"===$.value)return Xr.warn(e,"[nal_agent_retries] 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)}),!0;const r=l.getLatestCheckpoint();return!!r&&(I=r,R=new Je.QF({action:{case:"resumeAction",value:new Je.qK}}),a.resetStream(),!1)},z={handleCheckpoint:(e,t,r)=>Gr(this,void 0,void 0,(function*(){var n;yield l.handleCheckpoint(e,t,r),N.value=!0,$.value=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"})),getLatestCheckpoint:()=>l.getLatestCheckpoint()};let W=0;try{null===(h=d.onNetworkPhaseStart)||void 0===h||h.call(d)}catch(t){Xr.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const H=Vr(C,(0,c.VI)(e.withName("networkPhase")),!1);for(e=H.ctx;!e.canceled;){D.value=!1,N.value=!1,$.value=void 0,L.sources=[],L.abortReasonName=void 0,L.abortReasonMessage=void 0;const t=++W;A>0?(P=crypto.randomUUID(),yield null===(p=d.onRetryStarting)||void 0===p?void 0:p.call(d,A,{actionCase:R.action.case,conversationState:I,isResume:"resumeAction"===R.action.case,attemptRequestId:P}),Xr.info(e,`[nal_agent_retries] Retrying attempt ${A}`,{attempt:A,actionCase:R.action.case,requestId:P,originalRequestId:_})):Xr.info(e,"[nal_agent_retries] Initial request",{attempt:A,actionCase:R.action.case,requestId:P}),"resumeAction"===R.action.case&&d.onRetryResuming&&(yield d.onRetryResuming({checkpointState:I,nextAttempt:A,reason:"resume_action"}),Xr.info(e,"[nal_agent_retries] Resuming from checkpoint",{nextAttempt:A,reason:"resume_action"}));const r=tn(o,t,(()=>W));try{return yield this.runInternal(e,I,R,n,r,i,s,a,z,u,d,P,_,D,L,U,A),void Xr.info(e,"[nal_agent_retries] Request successful",{attempt:A,actionCase:R.action.case,requestId:P,originalRequestId:_})}catch(t){const r=null!==(b=null===(f=d.endlessRetries)||void 0===f?void 0:f.call(d))&&void 0!==b&&b,n=ln(t),o=cn(t,D.value,O,j,P,null!==(S=d.enableAgentRetries)&&void 0!==S&&S,r,L.sources.length>0,d.isRunningInTest),i="retry"===o.action?`RETRY (countAsServerError=${o.countAsServerError}, countAsTransportError=${o.countAsTransportError})`:`THROW ${o.error.kind}`;if(Xr.warn(e,`[AGENT_ERROR_DIAGNOSTICS] requestId=${P} originalRequestId=${_} decision=${i}`,Object.assign({decision:i,willRetry:"retry"===o.action,enableAgentRetries:null!==(k=d.enableAgentRetries)&&void 0!==k&&k,endlessRetries:r,isRunningInTest:null!==(E=d.isRunningInTest)&&void 0!==E&&E,stallAborted:D.value,serverErrorRetries:O,transportErrorRetries:j,attempt:A,requestId:P,originalRequestId:_,abortSources:[...L.sources],abortReasonName:L.abortReasonName},n)),"throw"===o.action){if(0===A){const t={attempt:A,actionCase:R.action.case,error:o.error,requestId:P,originalRequestId:_,enableAgentRetries:null!==(x=d.enableAgentRetries)&&void 0!==x&&x,endlessRetries:r,stallAborted:D.value,abortSources:[...L.sources],abortReasonName:L.abortReasonName,abortReasonMessage:L.abortReasonMessage};try{yield null===(m=d.onErrorNotRetried)||void 0===m?void 0:m.call(d,t)}catch(t){Xr.warn(e,"[nal_agent_retries] onErrorNotRetried callback failed",{error:String(t),requestId:P,originalRequestId:_})}}throw Xr.warn(e,"[nal_agent_retries] Error not retryable",{attempt:A,actionCase:R.action.case,error:o.error,serverErrorRetries:O,transportErrorRetries:j}),o.error}const s=A+1;if(B(t))return;const a=t instanceof ar?t:Sr(t,{requestId:P});F(s,{errorClass:a.name,connectCode:null===(g=n.underlyingConnectError)||void 0===g?void 0:g.code,connectCodeName:null===(v=n.underlyingConnectError)||void 0===v?void 0:v.codeName,errorCode:null===(y=a.displayInfo)||void 0===y?void 0:y.errorCode,countAsServerError:o.countAsServerError,countAsTransportError:o.countAsTransportError,stallAborted:D.value,originatingRequestId:_,attemptRequestId:P,endpointUrl:this.endpointUrl}),o.countAsServerError&&O++,o.countAsTransportError&&j++,A=s,yield qr(A,e.signal,d.isRunningInTest,d.fixedRetryDelayMs)}}throw new dr("Request cancelled")}catch(e){C.error=e,C.hasError=!0}finally{Jr(C)}}))}runInternal(e,t,r,n,o,i,s,a,l,u,h,p,g,v,y,w,b){return Gr(this,arguments,void 0,(function*(e,t,r,n,o,i,s,a,l,u,h,p,g,v,y,w,b,S="agent.request.attempt"){var k,E,x,C,_,P,T;const I={stack:[],error:void 0,hasError:!1};try{const R=e,A=Vr(I,(0,c.VI)(e.withName(S)),!1);A.span.setAttribute("agent.attempt",b),A.span.setAttribute("agent.request_id",p),A.span.setAttribute("agent.original_request_id",g),e=A.ctx,e=(0,c.Mf)(e,"agent.request_id",p),e=(e=(0,c.Mf)(e,"agent.original_request_id",g)).with(Zr,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const j=new Set(y.sources);let M=void 0!==y.abortReasonName||void 0!==y.abortReasonMessage;const D=(t,r)=>{if(j.has(t))return;j.add(t),y.sources=[...j];const n=(e=>{const t="string"==typeof(null==e?void 0:e.abortReasonName)?e.abortReasonName:void 0,r="string"==typeof(null==e?void 0:e.abortReasonMessage)?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);M||void 0===n||(M=!0,y.abortReasonName=n.abortReasonName,y.abortReasonMessage=n.abortReasonMessage),Yr.error(e,"Agent client stream abort",new Error(t),Object.assign({abortSource:t,requestId:p,conversationId:h.conversationId},null!=r?r:{}))};if(e.signal.aborted){const t=e.signal.reason;D("ctx_signal_abort",er(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;D("ctx_signal_abort",er(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",er(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",er(t)),$()}),{once:!0});if(e.canceled||N.canceled){const t={ctxCanceled:e.canceled,softCancel:N.canceled};throw D("pre_run_cancel",t),new dr("User aborted request")}const L=(0,c.VI)(e.withName("createControlledExecManager")),F=O.fromResources(i);L[Symbol.dispose]();const[U,B]=e.withCancel(),z=new Br,{failThresholdMs:W,advisoryThresholdMs:H}=(e=>{var t;const r=null!==(t=rn(null==e?void 0:e.failTimeoutMs))&&void 0!==t?t:3e4,n=rn(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=Vr(I,new zr(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,J;const K=(0,ir.Jt)(),Z=new m.F8(K,(e=>(q.reset("outbound_write",Qr(e)),e))),Y=Vr(I,(0,c.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=u.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?nr.Value.fromJson(e.inputSchema):void 0}))),ee=new Je.Mp({conversationState:t,action:r,modelDetails:n,requestedModel:h.requestedModel,mcpTools:new rr.Or({mcpTools:Q}),conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,harness:h.harness,suggestNextPrompt:h.suggestNextPrompt,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:null!==(_=h.subagentModelOverrides)&&void 0!==_?_:[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,preFetchedBlobs:null!==(P=h.preFetchedBlobs)&&void 0!==P?P:[],clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsSendToUser:h.clientSupportsSendToUser,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool});if(X=Z.write(new tr.KS({message:{case:"runRequest",value:ee}})),N.canceled){const t={ctxCanceled:e.canceled,softCancel:N.canceled};throw D("post_write_cancel",t),Y[Symbol.dispose](),new dr("User aborted request")}const te=Object.assign(Object.assign(Object.assign({"x-request-id":p,"x-original-request-id":g},function(e){return Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.parentRequestId?{"x-parent-request-id":Zt(e.parentRequestId)}:{}),void 0!==e.rootParentRequestId?{"x-root-parent-request-id":Zt(e.rootParentRequestId)}:{}),void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":Zt(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("$")?{}:{[Yt]:n}}()),null!==(T=h.headers)&&void 0!==T?T:{});V=(0,c.VI)(e.withName("handshakeEstablishment")),V.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0,G=this.client.run(V.ctx,K,{signal:U.signal,headers:te,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===J&&(J=performance.now())}});const re=performance.now(),ne=e=>{var t,r;V&&(V.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==J&&V.span.setAttribute("handshake.preNetworkMs",J-re),V[Symbol.dispose](),V=void 0),w();const n=performance.now();null===(t=h.onFirstMessage)||void 0===t||t.call(h,n-re),void 0!==J&&(null===(r=h.onFirstMessageNetwork)||void 0===r||r.call(h,n-J))},oe=h.onFirstNonHeartbeatResponse?()=>{h.onFirstNonHeartbeatResponse(performance.now()-re,b)}:void 0,{interactionStream:ie,execStream:se,checkpointStream:ae,kvStream:le,done:ce}=function(e,t,r,n,o,i,s){const a=(0,ir.Jt)(),l=(0,ir.Jt)(),c=(0,ir.Jt)(),u=(0,ir.Jt)();let d=!1,h=!1;return{interactionStream:a,execStream:l,checkpointStream:c,kvStream:u,done:function(){return Gr(this,void 0,void 0,(function*(){var p,f,m,g;let v,y,w=!1,b=!1;try{try{for(var S,k=!0,E=Kr(t);!(p=(S=yield E.next()).done);k=!0){g=S.value,k=!1;const t=g,o="interactionUpdate"===t.message.case&&"heartbeat"===t.message.value.message.case;if(d||(d=!0,n(o)),o)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!h){h=!0;try{null==s||s()}catch(t){Xr.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",Qr(t))}if("interactionUpdate"===t.message.case&&"turnEnded"===t.message.value.message.case&&(w=!0),"interactionUpdate"!==t.message.case&&"interactionQuery"!==t.message.case||(yield a.write(t.message).catch((()=>{}))),"execServerMessage"!==t.message.case&&"execServerControlMessage"!==t.message.case||(yield l.write(t.message.value)),"conversationCheckpointUpdate"===t.message.case){const e=w?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0),yield c.write({checkpoint:t.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===t.message.case&&(yield u.write(t.message.value))}}catch(e){f={error:e}}finally{try{k||p||!(m=E.return)||(yield m.call(E))}finally{if(f)throw f.error}}r.onStreamEnded()}catch(e){v=e}finally{if(y=v,w&&b&&void 0!==v&&!(null==o?void 0:o.aborted)&&!(null==i?void 0:i.aborted)&&function(e){const t=e instanceof ar?e:Sr(e);return t instanceof lr&&xr(t)}(v)&&(Xr.warn(e,"Ignoring transport close after terminal agent stream",{caughtError:v instanceof Error?`${v.name}: ${v.message}`:String(v)}),r.onStreamEnded(),y=void 0),w||(null==o?void 0:o.aborted)||(null==i?void 0:i.aborted)){if(!w&&!(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=${d}`;Xr.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===v?(Xr.warn(e,t),y=new lr(t,{isTransport:!0})):v instanceof Error&&"[aborted] aborted"===v.message?(Xr.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new lr(t,{cause:v,isTransport:!0})):Xr.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:v instanceof Error?`${v.name}: ${v.message}`:String(v)})}a.close(),l.close(),c.close(),u.close()}if(void 0!==y)throw y}))}()}}(e,G,q,ne,N.signal,e.signal,oe);let ue;const de={handleCheckpoint:(e,t,r)=>Gr(this,void 0,void 0,(function*(){var n;yield l.handleCheckpoint(e,t,r),ue=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"})),getLatestCheckpoint:()=>l.getLatestCheckpoint()};Y[Symbol.dispose]();const he=5e3;let pe;const fe=()=>{pe=setTimeout((()=>{Z.write(new tr.KS({message:{case:"clientHeartbeat",value:new tr.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),fe()}),he)},me=()=>{void 0!==pe&&(clearTimeout(pe),pe=void 0)};fe();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,s=new kt.a({command:(null===(C=n.shellCommand)||void 0===C?void 0:C.command)||"",parsingResult:new kt.HO,skipApproval:!0}),a=i.get(Ct).execute(e,s,{execId:n.execId}),l=new Dr(ie,o,new m.F8(Z,(e=>new tr.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:e=>Gr(this,void 0,void 0,(function*(){yield Promise.all([z.track("handleShellStream",en(e,a,o)),z.track("interactionController",l.run(e))])}))}}else{const e=new Dr(ie,o,new m.F8(Z,(e=>new tr.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:t=>Gr(this,void 0,void 0,(function*(){yield z.track("interactionController",e.run(t))}))}}void 0!==X&&(yield Promise.race([X,ce.catch((()=>{}))]));const l=new m.F8(Z,(e=>{if(e instanceof f.yT)return new tr.KS({message:{case:"execClientMessage",value:e}});if(e instanceof f.$Y)return new tr.KS({message:{case:"execClientControlMessage",value:e}});throw new Error("Unknown exec message")})),c=new Rr(se,l,F),b=new Qt.hC(le,new m.F8(Z,(e=>new tr.KS({message:{case:"kvClientMessage",value:e}}))),s),S=new d(ae,de,e);let k,E;const x={promise:new Promise(((e,t)=>{k=e,E=t})),resolve:k,reject:E};N.canceled?(x.resolve(),ie.close()):N.signal.addEventListener("abort",(()=>{x.resolve(),ie.close()}),{once:!0}),c.run(N).then(x.resolve).catch(x.reject);const _=Promise.allSettled([z.track("streamSplitter",ce.finally((()=>{me(),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,new m.F8(Z,(e=>new tr.KS({message:{case:"conversationAction",value:e}})))))]);let P,T;const I={promise:new Promise(((e,t)=>{P=e,T=t})),resolve:P,reject:T};_.then(I.resolve).catch(I.reject),e.canceled?I.reject(new dr("User aborted request")):e.signal.addEventListener("abort",(()=>I.reject(new dr("User aborted request"))),{once:!0}),N.canceled?(B(),I.reject(new dr("User aborted request"))):N.signal.addEventListener("abort",(()=>{B(),I.reject(new dr("User aborted request"))}),{once:!0});const A=yield I.promise,O=A[0],j=A[1],M=A[3],D=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===M.status)throw new ur("Checkpoint persistence failed",{cause:M.reason instanceof Error?M.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:D(M),isRetryable:!1}});const $="ineligible_terminal_turn"===ue;if($){const t=Object.assign(Object.assign({},"rejected"===O.status?{streamSplitter:D(O)}:{}),"rejected"===j.status?{execHandler:D(j)}:{});Object.keys(t).length>0&&Xr.warn(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===O.status&&!$)throw O.reason;if("rejected"===j.status&&!$)throw j.reason;N.canceled||(yield this.processUnprocessedMessages(R,a,de,n,o,i,s,u,h,p,g,v,y,q,w))}finally{me(),V&&(V[Symbol.dispose](),V=void 0)}}catch(e){I.error=e,I.hasError=!0}finally{Jr(I)}}))}processUnprocessedMessages(e,t,r,n,o,i,s,a,l,c,u,d,h,p,f){return Gr(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 Je.QF({action:{case:"userMessageAction",value:new Je.Vt({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 dn=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),hn=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),pn=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),fn=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),mn=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),gn=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),vn=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");Error;const yn=e=>new Je.Y5({id:e,result:{case:"webSearchRequestResponse",value:new vn.lI({result:{case:"approved",value:new vn.XJ}})}}),wn=(e,t)=>new Je.Y5({id:e,result:{case:"webSearchRequestResponse",value:new vn.lI({result:{case:"rejected",value:new vn.yc({reason:null!=t?t:""})}})}}),bn=e=>new Je.Y5({id:e,result:{case:"webFetchRequestResponse",value:new gn.fS({result:{case:"approved",value:new gn.Hs}})}}),Sn=(e,t)=>new Je.Y5({id:e,result:{case:"webFetchRequestResponse",value:new gn.fS({result:{case:"rejected",value:new gn.m$({reason:null!=t?t:""})}})}}),kn=(e,t)=>new Je.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new Je.zT({result:t})}}),En=e=>new Je.Y5({id:e,result:{case:"switchModeRequestResponse",value:new mn.w$({result:{case:"approved",value:new mn.q5}})}}),xn=(e,t)=>new Je.Y5({id:e,result:{case:"switchModeRequestResponse",value:new mn.w$({result:{case:"rejected",value:new mn.rA({reason:null!=t?t:""})}})}}),Cn=(e,t)=>new Je.Y5({id:e,result:{case:"createPlanRequestResponse",value:new hn.gz({result:t})}}),_n=(e,t)=>new Je.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Pn=(e,t)=>new Je.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),Tn=(e,t)=>new Je.Y5({id:e,result:{case:"prManagementResult",value:t}}),In=(e,t)=>new Je.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new fn.h({result:{case:"rejected",value:new fn.OI({reason:null!=t?t:"Authentication was rejected"})}})}}),Rn=(e,t)=>new Je.Y5({id:e,result:{case:"connectScmRequestResponse",value:new dn.qG({result:{case:"rejected",value:new dn.lB({reason:null!=t?t:"Connecting GitHub was skipped"})}})}}),An=(e,t)=>new Je.Y5({id:e,result:{case:"generateImageRequestResponse",value:new pn.vW({result:{case:"approved",value:new pn.l3({description:null!=t?t:""})}})}});var On=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js");Error;var jn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),Mn=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),Dn=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Nn=(0,or.createContextKey)(void 0,{description:"anysphere.callerContext"});function $n(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function Ln(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:jn.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):null==t||t.setStatus({code:jn.s.OK}),null==t||t.end(),null==r||r())};return{next(){return Dn(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 Dn(this,void 0,void 0,(function*(){return i(),n.return?n.return(e):{done:!0,value:void 0}}))},throw(e){return Dn(this,void 0,void 0,(function*(){if(i(e),n.throw)return n.throw(e);throw e}))}}}}}function Fn(...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 Un(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const i=e[o];return"function"!=typeof i?i:(s,a,l={})=>{var u;const d=(0,c.fR)(s.withName(`rpc.${String(o)}`),{kind:Mn.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),h=(0,c.fU)(d);let p;try{let o;if(r&&(o=function(e){var t,r;const n=new Headers;try{const o=(0,c.fU)(e),i=null===(t=null==o?void 0:o.spanContext)||void 0===t?void 0:t.call(o);if((null==i?void 0:i.traceId)&&i.spanId){const e=null!==(r=i.traceFlags)&&void 0!==r?r:0,t=`00-${i.traceId}-${i.spanId}-${e.toString(16).padStart(2,"0")}`;if(n.set("traceparent",t),n.set("backend-traceparent",t),i.traceState){const e="function"==typeof i.traceState.serialize?i.traceState.serialize():String(i.traceState);n.set("tracestate",e)}}}catch(e){}return n}(d)),n){const e=n(d);e&&(o=Fn(o,e))}const s=Fn(l.headers,o),{signal:m,cleanup:g}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(d.signal,l.signal):{signal:l.signal,cleanup:void 0};p=g;const v=(null!==(u=l.contextValues)&&void 0!==u?u:(0,or.createContextValues)()).set(Nn,d),y=Object.assign(Object.assign({},l),{headers:s,signal:m,contextValues:v}),w=i.call(e,a,y);return $n(w)?Ln(w,h,p):null!==(f=w)&&"object"==typeof f&&"then"in f&&"function"==typeof f.then?w.then((e=>$n(e)?Ln(e,h,p):(null==h||h.setStatus({code:jn.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:jn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e})):(null==h||h.setStatus({code:jn.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:jn.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==h||h.end(),null==p||p(),e}var f}}})}var Bn=r("../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/index.js");const zn=process.env.HTTPS_PROXY||process.env.https_proxy||void 0;let Wn;try{Wn=void 0!==zn&&zn.length>0?new Bn.kT(zn):void 0}catch(AS){Wn=void 0}Error,r("@connectrpc/connect-node"),new Je.Gm({modelId:"gpt-5",displayModelId:"gpt-5",displayName:"GPT-5",displayNameShort:"GPT-5",aliases:["gpt-5"]});var Hn=r("node:fs/promises"),qn=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Gn=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),Vn=r("../utils/dist/path-utils.js");const Jn="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Kn="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Zn=/\$\(|`|<\(|>\(/,Yn=/[;&|]/;let Xn,Qn,eo,to;function ro(){if(void 0===Xn){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Xn=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Xn}function no(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 oo(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function io(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function so(){if(void 0===to){const e=(process.env[Jn]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Jn} (expected "allow" or "deny"); using "deny".`);const r=oo("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Kn]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=oo(Kn)),to={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:oo("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:io("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return to}function ao(e,t,r={}){const n=[no(e),no(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 lo(e,t){const r=function(){const e=so();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Qn&&(Qn=ao("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Qn);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Zn.test(e))return r;const i=(void 0===eo&&(eo=ao("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),eo);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||i?.test(t)||Yn.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=so();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}var co=r("../proto/dist/generated/agent/v1/sandbox_pb.js"),uo=r("../shell-exec/dist/index.js");function ho(e){if(!e)return;let t;return"allow"===e.default?t=co.h1.ALLOW:"deny"===e.default&&(t=co.h1.DENY),new co.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new co.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function po(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 co.h1.ALLOW:t.default="allow";break;case co.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,uo.networkAllowAllPolicy)():(0,uo.networkDisabledPolicy)())}function fo(e){if(!e)return{type:"insecure_none"};switch(e.type){case co.vc.INSECURE_NONE:case co.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case co.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:po(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};case co.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:po(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};default:return{type:"insecure_none"}}}function mo(e){if(e)return"insecure_none"===e.type?new co.Mw({type:co.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new co.Mw({type:co.vc.WORKSPACE_READWRITE,networkAccess:(0,uo.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:ho(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):"workspace_readonly"===e.type?new co.Mw({type:co.vc.WORKSPACE_READONLY,networkAccess:(0,uo.isNetworkEnabledByPolicy)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ho(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):new co.Mw({type:co.vc.INSECURE_NONE})}async function go(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function vo(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}var yo=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 wo=(0,h.h)("local-exec:background-shell");function bo(e,t,r){return"permissionsConfig"===r.type&&r.isReadonly?new wt.Lt({result:{case:"permissionDenied",value:new kt.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new wt.Lt({result:{case:"rejected",value:new kt.pZ({command:e,workingDirectory:t,reason:vo(r)})}})}class So{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 ko(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 Eo(e){e().catch((()=>{}))}const xo=65536;class Co{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=Gn.L3.compile(e.config.pattern,Gn.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>xo){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=xo)this.observe(e.slice(t,t+xo));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 _o{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=a.join(this.projectDir,"terminals",`${t}.txt`);try{return new Co({shellId:t,outputPath:i,config:o,conversationId:r??te,toolCallId:n,registry:this.backgroundWorkRegistry})}catch(r){return void(void 0!==e&&wo.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 Po{async spawn(e,t){const r=new AbortController,n=new So(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){}return Eo((()=>ko(n,o))),n}async adopt(e){const t=new So(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,Eo((()=>ko(t,e.eventIterator))),t}}function To(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Io(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: ${To(e.cwd)}\n`,n+=`command: ${To(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${To(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}class Ro{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=a.join(this.projectDir,"terminals");await(0,Hn.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,s){let l,c,u,d=!1,h=!1;const p=Date.now(),f=new Date(p).toISOString();let m,g="running",v=!1,y=Promise.resolve();const w=async e=>{if(c)try{await c.write(e)}catch(e){}},b=t.shellId,S=a.join(r,`${b}.txt`),k=async()=>{if(!l)return;const e=Date.now()-p,r=Io({pid:m,cwd:t.workingDirectory,command:t.command,title:t.description,status:g,startedAt:f,runningForMs:e});try{await l.write(r,0,"utf8")}catch(e){}},E=()=>(y=y.then(k).catch((()=>{})),y),x=()=>{void 0!==u&&(clearInterval(u),u=void 0)},C=async e=>{if(h)return;h=!0,m=e;const r=Date.now()-p,n=Io({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:g,startedAt:f,runningForMs:r});await(0,Hn.writeFile)(S,n,"utf8"),u=setInterval((()=>{E()}),5e3)},_=async()=>{l||(l=await i.promises.open(S,"r+")),c||(c=await i.promises.open(S,"a"))},P=async(e,t)=>{if(!v){if(v=!0,x(),h||await C(),await _(),void 0!==t){const e=Date.now()-p,r=`\n---\n${t}\n`+(s.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await w(r)}g=e,await E()}};try{for await(const t of o(e,s)){if("stdout"===t.type)h||(await C(),await _()),await w(t.data);else if("stderr"===t.type)h||(await C(),await _()),await w(t.data);else if("stdin_ready"!==t.type||d)"exit"===t.type&&await P(t.aborted?"aborted":0===t.code?"succeeded":"failed",`exit_code: ${t.code??"unknown"}`);else{d=!0,h||(await C(t.pid),await _());const e=t.stdin;if(e){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)?e.toString():String(e);if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;w(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}yield t}if(!v){const e=s.signal?.aborted??!1;await P(e?"aborted":"failed")}}catch(e){const t=s.signal?.aborted??!1,r=To(e instanceof Error?e.message:"Unknown error");if(await P(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await y,l)try{await l.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=a.join(this.projectDir,"terminals");await(0,Hn.mkdir)(t,{recursive:!0});const r=a.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let s="running";const l=Date.now()-n,c=Io({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:s,startedAt:o,runningForMs:l})+(e.initialOutput??"");await(0,Hn.writeFile)(r,c,"utf8");const u=await i.promises.open(r,"r+");let d;try{d=await i.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=Promise.resolve();const m=async()=>{const t=Date.now()-n,r=Io({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:s,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},g=()=>(f=f.then(m).catch((()=>{})),f);let v=setInterval((()=>{g()}),5e3);const y=()=>{void 0!==v&&(clearInterval(v),v=void 0)},w=async()=>{if(!h){h=!0,y(),await f;try{await u.close()}catch{}try{await d.close()}catch{}}},b=async e=>{try{await d.write(e)}catch(e){}},S=async(t,r)=>{if(!p){if(p=!0,y(),void 0!==r){const t=Date.now()-n,o=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(o)}s=t,await g()}},k={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await S(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await b(e.data):"exit"===e.type&&(await S(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await w())}return t.done&&await w(),t}catch(t){const r=e.abortController.signal.aborted;throw await S(r?"aborted":"failed"),await w(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await S(t?"aborted":"failed")}return await w(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:k})}}class Ao{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:ee(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??te,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 Oo{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){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 jo{constructor(e,t,r,n,o,i,s){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=i&&void 0!==s?new Oo(i,s):i,l=o??function(e){const t=new Po;return new Ro(t,e)}(n),c=new _o(l,n,a);this.backgroundShellManager=new Ao(c,a)}getManager(){return this.backgroundShellManager}dispose(){this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?fo(t.sandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(),s=(0,Vn.o1)(i);if(!t.parsingResult)return new wt.Lt({result:{case:"error",value:new wt.Of({command:n,workingDirectory:s,error:"Parsing result is required"})}});let a=o;if(wo.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:t.parsingResult.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:s},o);if("block"===r.kind)return wo.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),bo(n,s,r.reason);wo.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:s,timeout:0,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Bt(t)},o);if("block"===r.kind)return wo.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),bo(n,s,r.reason);a=r.policy,wo.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:a.type})}if(ro()&&(a=lo(n,t.parsingResult),"insecure_none"!==a.type)){const e=await this.ignoreService.getCursorIgnoreMapping();a={...a,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=a?{perRepo:a}:void 0,i={ctx:e,command:n,workingDirectory:s,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,description:t.description,outputNotification:t.outputNotification},l=await this.backgroundShellManager.spawn(i,this.coreExecutor);return new wt.Lt({result:{case:"success",value:new wt.Po({shellId:r,command:n,workingDirectory:s,pid:l.pid})}})}catch(e){return new wt.Lt({result:{case:"error",value:new wt.Of({command:n,workingDirectory:s,error:e instanceof Error?e.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{yo(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var Mo=r("node:async_hooks"),Do=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),No=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js"),$o=r("node:util"),Lo=r("zod");const Fo={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Uo=Lo.z.object({command:Lo.z.string().optional(),args:Lo.z.array(Lo.z.string()).optional(),env:Lo.z.record(Lo.z.string(),Lo.z.string()).optional(),url:Lo.z.string().optional(),headers:Lo.z.record(Lo.z.string(),Lo.z.string()).optional(),cwd:Lo.z.string().optional(),envFile:Lo.z.string().optional(),auth:Lo.z.object({CLIENT_ID:Lo.z.string(),CLIENT_SECRET:Lo.z.string().optional(),scopes:Lo.z.array(Lo.z.string()).optional()}).optional(),enabledTools:Lo.z.array(Lo.z.string()).optional()}),Bo=Lo.z.object({mcpServers:Lo.z.record(Lo.z.string(),Uo).optional()}),zo=Lo.z.enum(["canvas"]),Wo=Lo.z.array(zo).transform((e=>[...new Set(e)].sort()));class Ho extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function qo(e){const t=e.trim();if(!t)throw new Ho("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Ho("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Ho("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Ho("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 Ho("Missing plugin name before @",e);if(!i)throw new Ho("Missing source after @",e);if(!r.test(o))throw new Ho("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Ho("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 Ho("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 Ho("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 Ho("Missing Git URL after 'url:'",e);try{new URL(t)}catch(t){throw new Ho("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 Ho("Missing marketplace name",e);if(!r.test(a))throw new Ho("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:l,raw:e}}function Go(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 Vo(e){return e.sourceInfo.name}function Jo(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Ko(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function Zo(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}var Yo=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const Xo=10485760,Qo=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,ei=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json"],ti=[".cursor-plugin",".claude-plugin"],ri=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ni=Lo.z.object({source:Lo.z.literal("github"),repo:Lo.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Lo.z.string().optional(),sha:Lo.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),oi=Lo.z.object({source:Lo.z.literal("url"),url:Lo.z.string().url().endsWith(".git","URL must end with .git"),ref:Lo.z.string().optional(),sha:Lo.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ii=Lo.z.object({source:Lo.z.literal("git-subdir"),url:Lo.z.string().url().endsWith(".git","URL must end with .git"),path:Lo.z.string().min(1),ref:Lo.z.string().optional(),sha:Lo.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),si=Lo.z.union([Lo.z.string(),ni,oi,ii]),ai=Lo.z.object({name:Lo.z.string().min(1,"Author name is required"),email:Lo.z.string().email().optional()}),li=Lo.z.enum(["string","number","integer","boolean","object","array","null"]),ci=Lo.z.union([li,Lo.z.array(li).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Lo.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function ui(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Lo.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:Lo.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:Lo.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:Lo.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:Lo.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:Lo.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:Lo.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const di=Lo.z.lazy((()=>Lo.z.object({type:ci.optional(),title:Lo.z.string().optional(),description:Lo.z.string().optional(),default:Lo.z.unknown().optional(),enum:Lo.z.array(Lo.z.any()).nonempty().optional(),const:Lo.z.unknown().optional(),properties:Lo.z.record(Lo.z.string(),di).optional(),required:Lo.z.array(Lo.z.string()).optional(),additionalProperties:Lo.z.union([Lo.z.boolean(),di]).optional(),items:Lo.z.union([di,Lo.z.array(di)]).optional(),minLength:Lo.z.number().int().nonnegative().optional(),maxLength:Lo.z.number().int().nonnegative().optional(),minimum:Lo.z.number().optional(),maximum:Lo.z.number().optional(),exclusiveMinimum:Lo.z.number().optional(),exclusiveMaximum:Lo.z.number().optional(),multipleOf:Lo.z.number().positive().optional(),minItems:Lo.z.number().int().nonnegative().optional(),maxItems:Lo.z.number().int().nonnegative().optional(),uniqueItems:Lo.z.boolean().optional(),minProperties:Lo.z.number().int().nonnegative().optional(),maxProperties:Lo.z.number().int().nonnegative().optional()}).strict().superRefine(ui)));function hi(e){const t=di.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:Lo.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 pi=Lo.z.unknown().superRefine(((e,t)=>{const r=hi(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),fi=(Lo.z.object({name:Lo.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Qo.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Lo.z.string().optional(),source:si,description:Lo.z.string().optional(),version:Lo.z.string().optional(),author:ai.optional(),publisher:Lo.z.string().min(1).optional(),homepage:Lo.z.string().url().optional(),repository:Lo.z.string().url().optional(),license:Lo.z.string().optional(),keywords:Lo.z.array(Lo.z.string()).optional(),capabilities:Wo.optional(),logo:Lo.z.string().optional(),category:Lo.z.string().optional(),tags:Lo.z.array(Lo.z.string()).optional(),strict:Lo.z.boolean().default(!0),commands:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),agents:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),skills:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),rules:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),hooks:Lo.z.union([Lo.z.string(),Lo.z.record(Lo.z.unknown())]).optional(),variables:pi.optional(),mcpServers:Lo.z.union([Lo.z.string(),Lo.z.record(Lo.z.unknown()),Lo.z.array(Lo.z.union([Lo.z.string(),Lo.z.record(Lo.z.unknown())]))]).optional()}),Lo.z.object({description:Lo.z.string().optional(),version:Lo.z.string().optional(),pluginRoot:Lo.z.string().optional()}),Lo.z.object({name:Lo.z.string().min(1).regex(Qo,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Lo.z.string().optional(),description:Lo.z.string().optional(),version:Lo.z.string().optional(),author:ai.optional(),publisher:Lo.z.string().min(1).optional(),homepage:Lo.z.string().url().optional(),repository:Lo.z.string().url().optional(),license:Lo.z.string().optional(),logo:Lo.z.string().optional(),keywords:Lo.z.array(Lo.z.string()).optional(),capabilities:Wo.optional(),commands:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),agents:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),skills:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),rules:Lo.z.union([Lo.z.string(),Lo.z.array(Lo.z.string())]).optional(),hooks:Lo.z.union([Lo.z.string(),Lo.z.record(Lo.z.unknown())]).optional(),variables:pi.optional(),mcpServers:Lo.z.union([Lo.z.string(),Lo.z.record(Lo.z.unknown()),Lo.z.array(Lo.z.union([Lo.z.string(),Lo.z.record(Lo.z.unknown())]))]).optional()}));function mi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gi(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function vi(e,t){if(mi(e)&&"string"==typeof e.name){const t=gi(e.name);if(t.length>0)return t}return function(e){var t;const r=void 0!==e.repoName?gi(e.repoName):"";return r.length>0?r:`cursor-marketplace-${null!==(t=e.fallbackId)&&void 0!==t?t:(0,o.randomUUID)()}`}(t)}function yi(e){if(mi(e)&&mi(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return Object.assign({name:t},void 0!==r?{email:r}:{})}return{name:"Unknown"}}function wi(e){return"string"==typeof e?e:void 0}function bi(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Si(e){return"string"==typeof e?e:bi(e)}function ki(e){if(!mi(e)||!mi(e.metadata))return;const t={description:wi(e.metadata.description),version:wi(e.metadata.version),pluginRoot:wi(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Ei(e){if(!mi(e))return;const t=wi(e.name);if(void 0===t||0===t.length)return;const r=wi(e.email);return Object.assign({name:t},void 0!==r?{email:r}:{})}function xi(e){if("string"==typeof e||mi(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||mi(e)));return t.length>0?t:void 0}}function Ci(e){if("string"==typeof e||mi(e))return e}function _i(e){if(void 0===e)return;const t=hi(e);return t.success?t.data:void 0}function Pi(e,t={}){if(e.length>Xo)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!mi(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!mi(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:mi(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:wi(n.ref),sha:wi(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:wi(n.ref),sha:wi(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:wi(n.ref),sha:wi(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:wi(n.ref),sha:wi(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=wi(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?gi(e.name):"")||function(e){var t;if("string"==typeof e){const t=gi((0,a.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const r=gi(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=gi((0,a.basename)(e.path));return t.length>0?t:void 0}let r=e.url;try{r=new URL(e.url).pathname}catch(e){}for(;r.endsWith("/");)r=r.slice(0,-1);r.toLowerCase().endsWith(".git")&&(r=r.slice(0,-4));const n=gi((0,a.basename)(r));return n.length>0?n:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Wo.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const s=i.success?i.data:void 0;return{entry:Object.assign({name:o,displayName:wi(e.displayName),source:r,description:wi(e.description),version:wi(e.version),author:Ei(e.author),publisher:wi(e.publisher),homepage:wi(e.homepage),repository:wi(e.repository),license:wi(e.license),keywords:bi(e.keywords),logo:wi(e.logo),category:wi(e.category),tags:bi(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Si(e.commands),agents:Si(e.agents),skills:Si(e.skills),rules:Si(e.rules),hooks:Ci(e.hooks),variables:_i(e.variables),mcpServers:xi(e.mcpServers)},void 0!==s&&{capabilities:s})}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:vi(r,t),owner:yi(r),description:wi(r.description),plugins:n,metadata:ki(r),skippedPluginEntries:o}}}function Ti(e){if(e.length>Xo)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=fi.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,error:`Invalid plugin manifest: ${r.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:r.error}}function Ii(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 Ri(e){return!e.includes("..")&&!(0,a.isAbsolute)(e)&&!e.includes("://")}new Yo.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Ai=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Oi=/\$\{([^:}]+)(?::-([^}]*))?\}/g;function ji(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 Mi(e,r)}function Mi(e,t){if("string"==typeof e)return e.replace(Oi,((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=>Mi(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Mi(o,t);return r}return e}function Di(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}var Ni=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 $i=[".mcp.json","mcp.json"],Li=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Fi(e,t){if(!function(e){return Li.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 Ui(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Bi(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return $i.map((e=>void 0!==t?`${t}/${e}`:e))}function zi(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=Di(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Di(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?Di(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Di(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 ji(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 Wi(e,t,r){try{const n=(0,Ai.qg)(e),o=Bo.safeParse(n),i=!0===(null==r?void 0:r.skipExpansion);if(o.success&&o.data.mcpServers&&Object.keys(o.data.mcpServers).length>0)return i?o.data:zi(o.data,t,r);const s={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Fi(e,t)&&Ui(t)&&(s[e]=t);if(Object.keys(s).length>0){const e=Bo.safeParse({mcpServers:s});if(e.success)return i?e.data:zi(e.data,t,r)}return null}catch(e){return null}}function Hi(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}function qi(e,t,r){return Ni(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:$i,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=Wi(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 Ni(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=>Ni(this,void 0,void 0,(function*(){const n=e.replace(/^\.\//,"");if(!Ri(n))return;const o=yield t(n);if(null===o)return;const l=Wi(o,s,r.parserOptions);(null==l?void 0:l.mcpServers)&&Object.keys(l.mcpServers).length>0&&Hi(a,l.mcpServers,i(n))})),c=e=>{var t;const n=Wi(JSON.stringify(e),s,r.parserOptions);(null==n?void 0:n.mcpServers)&&Object.keys(n.mcpServers).length>0&&Hi(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 Gi(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 Vi=r("node:stream"),Ji=r("node:stream/promises"),Ki=r("node:zlib");function Zi(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 Yi(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var Xi=r("../../node_modules/.pnpm/tar@7.5.7/node_modules/tar/dist/esm/index.js"),Qi=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 es=".cache-complete";function ts(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function rs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function ns(e){return Yi(e)}class os{constructor(e,t){var r,n;const o=null!==(r=null!=e?e:process.env.HOME)&&void 0!==r?r:"";this.cacheRoot=null!==(n=null==t?void 0:t.cacheRoot)&&void 0!==n?n:(0,a.join)(o,".cursor","plugins/cache")}getCacheDir(e){return function(e,t){return function(e,t,r,n){const o=[e,t,r];return void 0!==n&&o.push(n),(0,a.join)(...o)}(e,ts(t.marketplaceSlug),rs(t.pluginId),void 0!==t.version?ns(t.version):void 0)}(this.cacheRoot,e)}isCached(e){return Qi(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{const e=(0,a.join)(t,es);return(yield(0,Hn.stat)(e)).isFile()}catch(e){return!1}}))}extractToCache(e){return Qi(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,Hn.mkdir)(t,{recursive:!0});const r=Vi.Readable.from(e.tarball);return yield(0,Ji.pipeline)(r,(0,Ki.createGunzip)(),(0,Xi.o6)({cwd:t,strip:1})),yield this.markCacheComplete(e),t}))}listCachedVersions(e){return Qi(this,void 0,void 0,(function*(){const t=ts(e.marketplaceSlug),r=rs(e.pluginId),n=(0,a.join)(this.cacheRoot,t,r);try{return(yield(0,Hn.readdir)(n,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(e){return[]}}))}removeVersion(e){return Qi(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{yield(0,Hn.rm)(t,{recursive:!0,force:!0})}catch(e){}}))}pruneOldVersions(e){return Qi(this,void 0,void 0,(function*(){const t=yield this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>ns(e))));for(const n of t)r.has(n)||(yield this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n}))}))}markCacheComplete(e){return Qi(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,Hn.writeFile)((0,a.join)(t,es),"")}))}}function is(e,t){var r;const n=null!==(r=e.releaseTag)&&void 0!==r?r:t;if(e.releaseRepo&&e.releaseAsset&&n)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:n}}var ss=r("node:child_process");const as=(0,$o.promisify)(ss.execFile);function ls(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function cs(e){return"function"==typeof e?e():e}function us(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(delete r.GIT_CONFIG_NOSYSTEM,!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 as("git",[...ls(),...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 ds=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const hs=/^[0-9a-f]{7,40}$/i,ps=/^[0-9a-f]{40}$/i;function fs(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 ms(e,t,r){return ds(this,void 0,void 0,(function*(){const n=t.trim();if(ps.test(n))return{fullSha:n.toLowerCase()};if(hs.test(n)){try{const t=yield function(e,t,r){return ds(this,void 0,void 0,(function*(){var n;const{stdout:o}=yield us(["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=fs(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 us(["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=fs(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 us(["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=fs(o);if(!i)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:i.toLowerCase()}}))}var gs=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 vs=ri.map((e=>e.split("/")[0]));let ys;function ws(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 bs(e){const t=[];for(const r of e){const e=ws(r);if(null===e)return"all";t.push(e)}return t}function Ss(e,t){return gs(this,void 0,void 0,(function*(){const r="all"===e?"all":bs(e),n=t&&"all"!==r&&(yield function(){return process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(null!=ys||(ys=(()=>gs(this,void 0,void 0,(function*(){try{const{stdout:e}=yield us(["--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}})))()),ys)}());return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...vs,...o])]):[]};var o}))}function ks(e){return e.toLowerCase().includes("filtering not recognized by server")}function Es(e,t,r){return gs(this,void 0,void 0,(function*(){yield us(["sparse-checkout","set","--cone","--",...t],Object.assign(Object.assign({},r),{cwd:e}))}))}function xs(e){return gs(this,void 0,void 0,(function*(){try{yield(0,Hn.access)((0,a.join)(e,".git","info","sparse-checkout"))}catch(e){return!1}try{const{stdout:t}=yield us(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch(e){return!1}}))}function Cs(e,t,r){return gs(this,void 0,void 0,(function*(){if("all"!==t&&0===t.length)return;if(!(yield xs(e)))return;const n=Object.assign(Object.assign({},r),{cwd:e,sshBatchMode:!0});if("all"===t)return void(yield us(["sparse-checkout","disable"],n));const o=bs(t);"all"!==o?yield us(["sparse-checkout","add","--",...o],n):yield us(["sparse-checkout","disable"],n)}))}const _s=/\.git$/i,Ps=new Set(["account","dashboard"]);function Ts(e){return e.replace(_s,"")}function Is(e){let t;try{t=decodeURIComponent(e)}catch(e){return}return t.length>0&&!t.includes("/")?t:void 0}function Rs(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function As(e){return e.toLowerCase().split(".").includes("gitlab")}function Os(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function js(e){const t=e.toLowerCase();return As(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Ms(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}function Ds(e){return Rs(e)?"github":As(e)?"gitlab":Os(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Ns(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch(e){return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ms(r)&&"git"===n[0]&&(n=n.slice(1)),n.length>=3&&"scm"===n[0].toLowerCase()&&(n=n.slice(1));const o=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Ts(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===o?null:{provider:Ds(r),owner:o.owner,repo:o.repo,host:r}}function $s(e){const t=Ls(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean);return r.length>=3&&"scm"===r[0].toLowerCase()}function Ls(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch(e){return null}}function Fs(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Ns(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(As(r.host)){const e=Ls(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=Ts(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=Ls(e.trim());if(null!==t&&Os(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Is(t),o=Is(r);if(void 0===n||void 0===o||Ps.has(n.toLowerCase()))return;const i=Ts(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=Ls(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=Ts(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!Ms(e.host)&&null===js(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=Bs(r.host.replace(/^www\./i,""));return{url:`https://${e}/${$s(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=js(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function Us(e){const t=Fs(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 Bs(e){return Rs(e)?"github.com":e}function zs(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,s.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function Ws(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}var Hs=r("../utils/dist/promise-extras.js");function qs(e,t){const r=(0,a.resolve)(e),n=(0,a.resolve)(e,t),o=(0,a.relative)(r,n);if(o.startsWith("..")||(0,a.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}var Gs=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 Vs=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 Js(e){const t=Yi(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":Vs.has(t.toLowerCase())?`_${t}`:t}const Ks=18e5,Zs=6e5,Ys=["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"],Xs=["enotempty: directory not empty, rename","/_staging/"],Qs=["upload-pack: not our ref","server does not allow request for unadvertised object"];function ea(e){const t=String(e).toLowerCase().replaceAll("\\","/");return Ys.some((e=>t.includes(e)))?"user_git_access":Xs.every((e=>t.includes(e)))?"local_cache_race":Qs.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function ta(e){return"object"==typeof e&&null!==e&&(!0===e.killed||ta(e.cause))}function ra(e){return ta(e)?"killed_by_budget":ea(e)}function na(e){const t=Fs(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=Ns(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:Bs(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const oa=new Map;class ia{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?Ks:void 0}localTimeoutMs(){return this.sparsePluginClones?Zs:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}cloneResolvedRef(e,t,r,n){return Gs(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({},cs(null===(o=this.options)||void 0===o?void 0:o.extraGitConfig)),{"safe.directory":e})},{sparse:l,sparseDirs:c}=yield Ss(null!==(s=null==n?void 0:n.materialize)&&void 0!==s?s:"all",this.sparsePluginClones);yield us(["init"],Object.assign(Object.assign({},a),{timeoutMs:this.localTimeoutMs()})),l&&(yield Es(e,c,{sshBatchMode:null==n?void 0:n.sshBatchMode,extraGitConfig:cs(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.localTimeoutMs()}));const{stderr:u}=yield us(["fetch","--depth","1",...l?["--filter=blob:none"]:[],t,r],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()}));return yield us(["checkout","FETCH_HEAD"],Object.assign(Object.assign({},a),{timeoutMs:this.remoteTimeoutMs()})),{strategy:l?"sparse":"full",filterIgnoredByServer:l&&ks(null!=u?u:"")}}))}createStagingDir(){return Gs(this,void 0,void 0,(function*(){const e=(0,a.join)(this.cacheRoot,"_staging",(0,o.randomUUID)());return yield(0,Hn.mkdir)(e,{recursive:!0}),e}))}moveToCanonicalDir(e,t){return Gs(this,void 0,void 0,(function*(){return yield(0,Hn.mkdir)((0,a.dirname)(t),{recursive:!0}),yield(0,Hn.rm)(t,{recursive:!0,force:!0}),yield(0,Hn.rename)(e,t),t}))}cleanStaleStagingDirs(){return Gs(this,void 0,void 0,(function*(){const e=(0,a.join)(this.cacheRoot,"_staging");try{const t=yield(0,Hn.readdir)(e,{withFileTypes:!0}),r=Date.now();yield Promise.all(t.filter((e=>e.isDirectory())).map((t=>Gs(this,void 0,void 0,(function*(){try{const n=(0,a.join)(e,t.name),o=yield(0,Hn.stat)(n);r-o.mtimeMs>ia.STALE_STAGING_THRESHOLD_MS&&(yield(0,Hn.rm)(n,{recursive:!0,force:!0}))}catch(e){}})))))}catch(e){}}))}getLegacyCloneDir(e,t){return(0,a.join)(this.cacheRoot,Js(e),Js(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=na(e);return(0,a.join)(this.cacheRoot,Js(r),...n.map(Js),Js(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=na(e);return(0,a.join)(this.cacheRoot,Js(t),...r.map(Js))}pruneSiblingCloneDirs(e,t,r){return Gs(this,void 0,void 0,(function*(){const n=this.getCanonicalRepoRootDir(e),o=Js(t);try{const e=yield(0,Hn.readdir)(n,{withFileTypes:!0});yield Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Hn.rm)((0,a.join)(n,e.name),{recursive:!0,force:!0}))))}catch(e){}if(void 0!==r)try{yield(0,Hn.rm)(r,{recursive:!0,force:!0})}catch(e){}}))}ensureCloned(e,t,r){return Gs(this,arguments,void 0,(function*(e,t,r,n=Fo,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,Hs.wj)(i,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}))}ensureMaterialized(e,t){return Gs(this,arguments,void 0,(function*(e,t,r=Fo){const n=this.serializedOnRepo((0,a.dirname)(e),(()=>Gs(this,void 0,void 0,(function*(){var n;const o=performance.now();try{yield Cs(e,t,{extraGitConfig:cs(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:ra(n)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:ra(n)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o,{outcome:"error"}),n}}))));return this.sparsePluginClones?n:(0,Hs.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}))}serializedOnRepo(e,t){return Gs(this,void 0,void 0,(function*(){const r=`${this.cacheRoot}:${e}`,n=oa.get(r),o=(null!=n?n:Promise.resolve()).catch((()=>{})).then(t);oa.set(r,o);try{return yield o}finally{oa.get(r)===o&&oa.delete(r)}}))}ensureClonedImpl(e,t,r,n,o){return Gs(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:Us(t);if(null!==d)try{u=(yield ms(d,c,{sshBatchMode:!0,extraGitConfig:cs(null===(i=this.options)||void 0===i?void 0:i.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&ta(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:ea(e)}),d=null,u=(yield ms(t,c,{extraGitConfig:cs(null===(s=this.options)||void 0===s?void 0:s.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else u=(yield ms(t,c,{extraGitConfig:cs(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 xs(h);return e&&(yield Cs(h,o,{extraGitConfig:cs(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 Gs(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,Hn.utimes)(u,e,e).catch((()=>{}))}),ia.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&&ta(e))throw e;s.log("error","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:i,error:String(e),errorCategory:ra(e)}),yield(0,Hn.rm)(u,{recursive:!0,force:!0}),yield(0,Hn.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=ra(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,Hn.rm)(u,{recursive:!0,force:!0})}catch(e){}}}))}isCloneComplete(e){return Gs(this,void 0,void 0,(function*(){try{if(!(yield(0,Hn.stat)(e)).isDirectory())return!1;const t=yield(0,Hn.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(yield(0,Hn.stat)((0,a.join)(e,".git","info","sparse-checkout"))).isFile()}catch(e){return!1}}catch(e){return!1}}))}getPluginDir(e,t){return qs(e,t)}copyPluginToDir(e,t){return Gs(this,void 0,void 0,(function*(){yield(0,Hn.mkdir)(t,{recursive:!0}),yield(0,Hn.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}))}readManifest(e){return Gs(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 Gs(this,arguments,void 0,(function*(e,t={}){for(const r of ri){const n=(0,a.join)(e,r);let o;try{o=yield(0,Hn.readFile)(n,"utf-8")}catch(e){continue}const i=Pi(o,t);if(i.success)return i.data}return null}))}(e,t);return this.manifestCache.set(n,o),o}))}resolvePluginPath(e,t){return Gs(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=Ii(o.source,null===(r=n.metadata)||void 0===r?void 0:r.pluginRoot);return i&&Ri(i)?i:null}))}discoverPlugins(e){return Gs(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=Ii(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":Ri(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):[]}))}}ia.STALE_STAGING_THRESHOLD_MS=3e5,ia.STAGING_HEARTBEAT_INTERVAL_MS=6e4;var sa=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 aa=(0,$o.debuglog)("cursor-plugins");function la(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 ca(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 ua(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)&&!Sa(e,t.gitUrl)?e:n:e}function da(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 ha(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=ca(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 pa="backend-git://";function fa(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${pa}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function ma(e){if(!e.startsWith(pa))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 ga="backend-release://";function va(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${ga}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function ya(e){if(!e.startsWith(ga))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 wa=/^[0-9a-f]{7,40}$/i;function ba(e){let t;try{t=na(e)}catch(e){return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Sa(e,t){if(e.trim()===t.trim())return!0;const r=ba(e),n=ba(t);return null!==r&&r===n}const ka=104857600;function Ea(e,t,r,n,i,l){return sa(this,void 0,void 0,(function*(){const c=yield function(e){return sa(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>ka)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||!xa(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||!xa(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>ka)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${m.byteLength})`);if(e.expectedSha256){const t=(0,o.createHash)("sha256").update(m).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return m}))}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:l}),u=c.byteLength;yield(0,Hn.mkdir)(n,{recursive:!0});const d=yield(0,Hn.mkdtemp)((0,a.join)((0,s.tmpdir)(),"release-asset-")),h=(0,a.join)(d,"asset.tar.gz"),p=(0,a.join)(d,"extracted");try{yield(0,Hn.writeFile)(h,c),yield(0,Hn.mkdir)(p,{recursive:!0});let e=0,t=0;yield Xi.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,Hn.readdir)(p,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let s=p;if(1===o.length&&0===i.length){const e=(0,a.join)(p,o[0].name);(yield(0,Hn.readdir)(e)).some((e=>ti.includes(e)))&&(s=e)}const l=yield(0,Hn.readdir)(s);yield Promise.all(l.map((e=>(0,Hn.cp)((0,a.join)(s,e),(0,a.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{yield(0,Hn.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}))}function xa(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Ca{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:Fo,this.extraGitConfig=h.extraGitConfig,this.githubToken=h.githubToken,this.sparsePluginClones=null!==(l=h.sparsePluginClones)&&void 0!==l&&l,this.marketplaceCache=h.marketplaceCacheRoot?new ia(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 sa(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)=>sa(this,void 0,void 0,(function*(){const r=`${e}\0${t}`;let n=S.get(r);if(!n){const o=cs(this.extraGitConfig),i=this.sparsePluginClones?3e4:void 0,s=e.startsWith("git@")||e.startsWith("ssh://")?null:Us(e),a=(e,r)=>sa(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 ms(e,t,n):yield ms(e,t)).fullSha}));if(null!==s)try{n=yield a(s,!0)}catch(t){if(this.sparsePluginClones&&ta(t))throw t;n=yield a(e,!1)}else n=yield a(e,!1);S.set(r,n)}return n})),E=e=>sa(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=ca(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=la({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=ua(k,g),C=ha(t,y),_=is(r,C),P=null!==(u=null==g?void 0:g.gitRef)&&void 0!==u?u:C;let T,I,R=x;try{if(void 0!==_)T=`release/${_.releaseTag}`;else{const e=yield E({preferredGitUrl:x,sourceGitUrl:k,gitRef:C,pluginId:S});T=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}I=void 0!==_?va({repo:_.releaseRepo,asset:_.releaseAsset,tag:_.releaseTag}):fa(R,C,null!==(d=r.gitPath)&&void 0!==d?d:void 0);const A=da(g);let O=A,j=P;if((null==g?void 0:g.gitUrl)&&A){const e=Sa(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});j=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 M=(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:j}):void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${S} from ${j} at ${r.gitPath}`,{pluginId:S,marketplaceId:null!==(p=null==M?void 0:M.id)&&void 0!==p?p:"unknown",gitPath:null!==(f=r.gitPath)&&void 0!==f?f:void 0,gitRef:j}),w.push({pluginId:S,pluginDbId:void 0!==r.id?String(r.id):void 0,configuredVariables:t.configuredVariables,isTeamRequired:t.isTeamRequired,name:v,version:T,downloadUrl:I,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:M,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=ma(e.downloadUrl);return!(!r||!Sa(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}installPlugin(e,t){return sa(this,void 0,void 0,(function*(){if(e.inlineContentJson)yield function(e){return t=this,r=void 0,o=function*(){var t,r;const{targetDir:n,inlineContentJson:o,pluginName:i}=e,s=JSON.parse(o);yield(0,Hn.mkdir)(n,{recursive:!0});const l={};if(s.rules&&s.rules.length>0){const e=(0,a.join)(n,"rules");yield(0,Hn.mkdir)(e,{recursive:!0});const t=[];for(const r of s.rules){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${Yi(r.name)}.md`,o=[];o.push(`description: ${Ws(r.name)}`),r.globs&&r.globs.length>0&&o.push(`globs: ${Ws(r.globs.join(", "))}`),o.push(`alwaysApply: ${!0===r.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;yield(0,Hn.writeFile)((0,a.join)(e,n),i+r.content,"utf-8"),t.push(`rules/${n}`)}t.length>0&&(l.rules=t)}if(s.commands&&s.commands.length>0){const e=(0,a.join)(n,"commands");yield(0,Hn.mkdir)(e,{recursive:!0});const t=[];for(const r of s.commands){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${Yi(r.name)}.md`,o=r.description?`---\ndescription: ${Ws(r.description)}\n---\n\n`:"";yield(0,Hn.writeFile)((0,a.join)(e,n),o+r.content,"utf-8"),t.push(`commands/${n}`)}t.length>0&&(l.commands=t)}if(s.hooks&&s.hooks.length>0){const e=(0,a.join)(n,"hooks");yield(0,Hn.mkdir)(e,{recursive:!0});const o={};for(const e of s.hooks){const n=e.hookStep;n&&!1!==e.isActive&&zs(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,Hn.writeFile)((0,a.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:o},null,2),"utf-8")}if(s.mcpServers&&s.mcpServers.length>0){const e={};for(const t of s.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&(yield(0,Hn.writeFile)((0,a.join)(n,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8"))}const c=Object.assign({name:i},l),u=(0,a.join)(n,".cursor-plugin");yield(0,Hn.mkdir)(u,{recursive:!0}),yield(0,Hn.writeFile)((0,a.join)(u,"plugin.json"),JSON.stringify(c,null,2),"utf-8")},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{if(null===ya(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)&&ta(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 sa(this,arguments,void 0,(function*(e,t,r=Fo,n,o){var i;const l=null!==(i=null==o?void 0:o.sparsePluginClones)&&void 0!==i&&i,c=l?Ks:void 0,u=ya(e.downloadUrl);if(u){if(e.gitPath){const r=yield(0,Hn.mkdtemp)((0,a.join)((0,s.tmpdir)(),"release-plugin-"));try{yield Ea(u.repo,u.asset,u.tag,r,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);const n=qs(r,e.gitPath);yield(0,Hn.mkdir)(t,{recursive:!0}),yield(0,Hn.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,Hn.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else yield Ea(u.repo,u.asset,u.tag,t,null==o?void 0:o.expectedReleaseAssetSha256,null==o?void 0:o.githubToken);return}const d=ma(e.downloadUrl);if(!d)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const h=yield(0,Hn.mkdtemp)((0,a.join)((0,s.tmpdir)(),"backend-plugin-"));try{let o;if(yield function(e,t,r){return sa(this,arguments,void 0,(function*(e,t,r,n=Fo,o,i="all",s=!1){const a=performance.now(),l=wa.test(t),c="HEAD"===t.toUpperCase(),u=Object.assign(Object.assign({},o),{"safe.directory":r}),d=s?Ks:void 0,h=s?Zs:void 0,{sparse:p,sparseDirs:f}=yield Ss(i,s),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,v=e=>sa(this,void 0,void 0,(function*(){p&&(yield Es(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0}))})),y=(e,n)=>sa(this,void 0,void 0,(function*(){let o="";return c?(({stderr:o}=yield us(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield v(d)):l?(yield us(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield us(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),yield v(h),({stderr:o}=yield us(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),yield us(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=yield us(["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:Us(e);let b="";if(null!==w)try{b=yield y(w,!0)}catch(t){if(s&&ta(t))throw t;yield(0,Hn.rm)(r,{recursive:!0,force:!0}),yield(0,Hn.mkdir)(r,{recursive:!0}),b=yield y(e,g)}else b=yield y(e,g);p&&ks(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);aa("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?bs([d.gitPath]):[],l),d.gitPath)o=qs(h,d.gitPath);else{const t=yield function(e,t){return sa(this,void 0,void 0,(function*(){var r;for(const n of ri){const o=(0,a.join)(e,n);let i;try{i=yield(0,Hn.readFile)(o,"utf-8")}catch(e){continue}const s=Pi(i);if(!s.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${n}: ${s.error}`};const l=s.data,c=l.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${n}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const u=Ii(c.source,null===(r=l.metadata)||void 0===r?void 0:r.pluginRoot);return u&&Ri(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 Cs(h,bs([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=qs(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 Cs(h,"all",{extraGitConfig:n,timeoutMs:c}),o=h}}yield(0,Hn.mkdir)(t,{recursive:!0}),yield(0,Hn.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,Hn.rm)(h,{recursive:!0,force:!0}).catch((()=>{}))}}))}(e,t,this.pluginLogger,cs(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}}))}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch(e){}}tryInstallFromMarketplaceCache(e,t){return sa(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?bs([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,bs([c]),this.pluginLogger));const u=s.getPluginDir(l,c);return yield s.copyPluginToDir(u,t),!0}))}discoverMarketplacePlugins(e,t,r){return sa(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 _a(e,t,r,n,o){return new Ca(e,t,r,n,o)}var Pa=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Ta=()=>({});function Ia(e,t){return Pa(e,Object.assign(Object.assign({},t),{engines:Object.assign(Object.assign({},null==t?void 0:t.engines),{js:Ta,javascript:Ta})}))}function Ra(e,t,r){return Pa.stringify({content:e,data:{}},t,r)}function Aa(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}var Oa=r("../../node_modules/.pnpm/js-yaml@4.1.0/node_modules/js-yaml/dist/js-yaml.mjs"),ja=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const Ma=[".md",".mdc",".markdown"],Da=[...Ma,".txt"],Na=/^---\s*\n([\s\S]*?)\n---/,$a="";function La(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function Fa(e){var t,r;const n=e.match(Na);if(!n)return{};try{const e=Oa.Ay.load(n[1],{schema:Oa.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const o=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,i=Ua(null!==(t=e.environments)&&void 0!==t?t:null==o?void 0:o.environments);return{disabledEnvironments:Ua(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 Ua(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 Ba(e){return La((0,a.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function za(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 Wa{constructor(e){this.fetcher=e}discoverComponents(){return ja(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=$i.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,Ma,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,Ma,i):l.has("agents")?this.discoverMarkdownComponents(`${o}agents`,Ma,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,Da,i):l.has("commands")?this.discoverMarkdownComponents(`${o}commands`,Da,i):Promise.resolve([]),void 0!==(null==s?void 0:s.rules)?this.discoverFromManifestPaths(o,s.rules,!1,Ma,i):l.has("rules")?this.discoverMarkdownComponents(`${o}rules`,Ma,i):Promise.resolve([]),this.discoverMcpServers(o,null==s?void 0:s.mcpServers,c)]);return{skills:za(d?[d,...h]:h),agents:za(p),hooks:f,commands:za(m),rules:za(g),mcpServers:v}}))}discoverHooksFromJson(e){return ja(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:La(r),path:e,description:t?$a:`Hook: ${r}`})))}catch(e){return[]}}))}discoverHooksFromManifest(e,t){return ja(this,arguments,void 0,(function*(e,t,r=!1){var n;if("string"==typeof t){if(!Ri(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:La(e),path:"manifest",description:r?$a:`Hook: ${e}`})))}))}discoverFromManifestPaths(e,t){return ja(this,arguments,void 0,(function*(e,t,r=!1,n=Ma,o=!1){var i,s;if("string"==typeof t){if(!Ri(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(!Ri(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=Ba(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t),n=o?$a:void 0;if(!o){const{content:t}=yield this.fetcher.fetchFile(e),o=Fa(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:La(r),path:e};void 0!==n&&(t.description=n),a.push(t)}continue}if(r){const t={name:La(r),path:e};void 0!==n&&(t.description=n),a.push(t)}}else{if(!(yield this.fetcher.fileExists(t)))continue;let e=Ba(t),r=o?$a:void 0;if(!o){const{content:n}=yield this.fetcher.fetchFile(t),o=Fa(n);e=null!==(s=o.name)&&void 0!==s?s:e,r=o.description}if(e){const n={name:La(e),path:t};void 0!==r&&(n.description=r),a.push(n)}}}catch(e){}return a}))}discoverMarkdownComponents(e){return ja(this,arguments,void 0,(function*(e,t=Ma,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=>ja(this,void 0,void 0,(function*(){try{let t=Ba(e.name),n=r?$a:void 0;if(!r){const{content:r}=yield this.fetcher.fetchFile(e.path),o=Fa(r);t=o.name?La(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 ja(this,arguments,void 0,(function*(e,t=!1){try{const r=`${e}SKILL.md`,n=(0,a.basename)(e.replace(/[\\/]+$/,""));let o=La(t?n||Ba(r):n),i=t?$a:void 0;if(!t){const{content:e}=yield this.fetcher.fetchFile(r),t=Fa(e);if(o=t.name?La(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 ja(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=>ja(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=La(e.name);return t?{name:t,path:r,description:$a}:null}const{content:n}=yield this.fetcher.fetchFile(r),o=Fa(n),i=o.name?La(o.name):La(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 ja(this,void 0,void 0,(function*(){const n=yield qi((t=>ja(this,void 0,void 0,(function*(){try{const{content:r}=yield this.fetcher.fetchFile(`${e}${t}`);return r}catch(e){return null}}))),t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:"fill",toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}});return void 0===(null==n?void 0:n.mcpServers)?[]:Object.keys(n.mcpServers).map((e=>{var t,r;return{name:La(e),path:null!==(r=null===(t=n.mcpServerSourcePaths)||void 0===t?void 0:t[e])&&void 0!==r?r:"manifest"}}))}))}}var Ha=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 qa(e){var t;const r=null!==(t=null!=e?e:process.env.HOME)&&void 0!==t?t:"";return(0,a.join)(r,".claude")}var Ga=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 Va(e){return Ga(this,void 0,void 0,(function*(){try{return(yield(0,Hn.lstat)(e)).isSymbolicLink()}catch(e){return!1}}))}function Ja(e){return Ga(this,void 0,void 0,(function*(){if(yield Va(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Hn.readFile)(e,"utf-8")}))}function Ka(e){return Ga(this,void 0,void 0,(function*(){if((yield(0,Hn.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}))}function Za(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 Ya(e){return Ga(this,void 0,void 0,(function*(){var t;for(const r of ei){const n=(0,a.join)(e,r);try{if(yield Va(n))continue;if(!(yield(0,Hn.stat)(n)).isFile())continue;yield Ka(n);const e=Ti(yield Ja(n));if(!e.success)continue;const r=e.data,o=r.commands,i=r.agents,s=r.skills,a=r.rules,l=r.hooks,c=r.mcpServers,u=void 0!==o||void 0!==i||void 0!==s||void 0!==a||void 0!==l||void 0!==c,d="string"==typeof r.displayName?r.displayName:void 0,h="string"==typeof r.description?r.description:void 0,p=null===(t=r.author)||void 0===t?void 0:t.name,f=r.variables,m=r.capabilities,g=void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m;if(!u&&!g)continue;return Object.assign(Object.assign({manifestFilePath:n},u&&{manifestOptions:{commands:o,agents:i,skills:s,rules:a,hooks:l,mcpServers:c}}),g&&{metadata:{displayName:d,description:h,authorName:p,variables:f,capabilities:m}})}catch(e){}}}))}function Xa(e,t){return Ga(this,void 0,void 0,(function*(){const r=function(e,t){var r;const n=new Map,o=(0,a.resolve)(e),i=(0,a.resolve)(null!==(r=null==t?void 0:t.symlinkTargetRoot)&&void 0!==r?r:o),s=(0,Hn.realpath)(i).catch((()=>i));function l(e){const t=(0,a.resolve)(e);try{return qs(o,t)}catch(t){throw new Error(`Path escapes plugin directory: ${e}`)}}function c(e){return Ga(this,void 0,void 0,(function*(){const t=l(e),r=yield s,n=yield(0,Hn.realpath)(t);try{return qs(r,n)}catch(t){throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}))}return{listDirectory(t,r){return Ga(this,void 0,void 0,(function*(){const n=l(t?(0,a.join)(e,t):e);try{const e=yield c(n);if(null==r?void 0:r.has(e))return[];null==r||r.add(e);const o=yield(0,Hn.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,a.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=yield c(r);o=(yield(0,Hn.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 Ga(this,void 0,void 0,(function*(){const r=n.get(t);if(void 0!==r)return{content:r};const o=l((0,a.join)(e,t)),i=yield c(o);yield Ka(i);const s=yield(0,Hn.readFile)(i,"utf-8");return n.set(t,s),{content:s}}))},fileExists(t){return Ga(this,void 0,void 0,(function*(){try{const r=l((0,a.join)(e,t)),n=yield c(r);return(yield(0,Hn.stat)(n)).isFile()}catch(e){return!1}}))}}}(e),n=new Wa(r),o=yield n.discoverComponents({manifest:t}),[i,s,l,c]=yield Promise.all([Qa(r,o.skills,e),tl(r,o.agents,e),rl(r,o.commands,e),el(r,o.rules,e)]);return{skills:i,agents:s,commands:l,rules:c}}))}function Qa(e,t,r){return Ga(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=ol({content:Di(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function el(e,t,r){return Ga(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=ol({content:Di(t,r),relativePath:o.path});i&&n.push(Object.assign(Object.assign({},i),{name:o.name}))}catch(e){}return n}))}function tl(e,t,r){return Ga(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=il({content:Di(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function rl(e,t,r){return Ga(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),i=sl({content:Di(t,r),relativePath:o.path});i&&n.push(i)}catch(e){}return n}))}function nl(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 ol({content:e,relativePath:t}){var r,n,o,i,s;try{const a=Ia(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=Ua(null!==(i=a.data.environments)&&void 0!==i?i:null===(r=a.data.metadata)||void 0===r?void 0:r.environments),m=Ua(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:nl(a.data.globs),alwaysApply:!0===a.data.alwaysApply,content:e,environments:f,disabledEnvironments:m}}catch(e){return null}}function il({content:e,relativePath:t}){var r,n;try{const o=Ia(e),i=o.content.trim();if(!i)return null;let s;"string"==typeof o.data.tools?s=o.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(o.data.tools)&&(s=o.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const l=null!==(r=o.data.permissionMode)&&void 0!==r?r:o.data.permissionmode,c=(0,a.basename)(t);return{path:t,name:"string"==typeof o.data.name?o.data.name:(0,a.basename)(c,(0,a.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof o.data.description?o.data.description:void 0,tools:s,model:"string"==typeof o.data.model?o.data.model:"inherit",prompt:i,permissionMode:(n=l,"readonly"===(null!=n?n:"").trim().toLowerCase()?"readonly":"default")}}catch(e){return null}}function sl({content:e,relativePath:t}){try{const r=Ia(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,a.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,a.basename)(i,(0,a.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch(e){return null}}function al(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}function ll(e,t,r){return Ga(this,void 0,void 0,(function*(){const n=null!=r?r:al(t);return function(e){return Ni(this,arguments,void 0,(function*(e,t={}){var r;const n=null!==(r=t.toSourcePath)&&void 0!==r?r:e=>e;let o,i;for(const t of ei){const r=yield e(t);if(null===r)continue;const s=Ti(r);if(s.success){void 0!==s.data.mcpServers&&(o=s.data.mcpServers,i=n(t));break}}return qi(e,o,i,t)}))}(function(e){return t=>Ga(this,void 0,void 0,(function*(){if(!Ri(t))return null;const r=(0,a.join)(e,t);try{return(yield Va(r))?null:(yield(0,Hn.stat)(r)).isFile()?(yield Ka(r),yield Ja(r)):null}catch(e){return null}}))}(e),{fallbackFileNames:Bi(),manifestPrecedence:"override",toSourcePath:t=>(0,a.join)(e,t),installPathForExpansion:e,parserOptions:n})}))}function cl(e,t){return Ga(this,void 0,void 0,(function*(){var r;const n=yield ll(e);if(n)return n;for(const n of ri){const o=(0,a.join)(e,n);try{if(!(yield(0,Hn.stat)(o)).isFile())continue;const n=yield(0,Hn.readFile)(o,"utf-8"),i=JSON.parse(n).plugins;if(!Array.isArray(i))continue;const s=t.name,l=i.find((e=>e.name===s));if(!(null===(r=null==l?void 0:l.mcpServers)||void 0===r?void 0:r.length))continue;for(const t of l.mcpServers){const r=t.replace(/^\.\//,"");if(!Ri(r))continue;const n=(0,a.join)(e,r);try{yield Ka(n);const t=Wi(yield Ja(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 ul(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:Di(e.command,t)}):"prompt"in e&&"string"==typeof e.prompt?Object.assign(Object.assign({},e),{prompt:Di(e.prompt,t)}):e)));return Object.assign(Object.assign({},e),{hooks:r})}function dl(e,t,r,n){return Ga(this,void 0,void 0,(function*(){if("object"==typeof r){const o=hl(r,t);return o&&"config"in o?Object.assign({config:ul(o.config,e)},void 0!==n&&{sourcePath:n}):o}let o,i,s;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Ri(t))return;o=t.endsWith(".json")?(0,a.join)(e,t):(0,a.join)(e,t,"hooks.json")}else o=(0,a.join)(e,"hooks","hooks.json");try{if(yield Va(o))return;if(!(yield(0,Hn.stat)(o)).isFile())return}catch(e){return}try{yield Ka(o),i=yield(0,Hn.readFile)(o,"utf-8")}catch(e){return}try{s=JSON.parse(i)}catch(e){return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const l=hl(s,t);return l&&"config"in l?{config:ul(l.config,e),sourcePath:o}:l}))}function hl(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=Ve(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=ye(r),o=Ve(n);return o.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}}function pl(e,t,r,n){return Ga(this,void 0,void 0,(function*(){var o,i,s,a,l,c,u,d;const h=yield Ya(e),p=null!==(u=al(r))&&void 0!==u?u:(null==n?void 0:n.configuredVariables)?{configuredVariables:n.configuredVariables}:void 0,[f,m,g]=yield Promise.all([Xa(e,null==h?void 0:h.manifestOptions),ll(e,r,p),dl(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 fl(e,t){return Ga(this,void 0,void 0,(function*(){var r,n,o,i,s,a;const l=yield Ya(e),[c,u,d]=yield Promise.all([Xa(e,null==l?void 0:l.manifestOptions),cl(e,t),dl(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 ml(e,t,r){return Ga(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 pl(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 gl(e,t){return Ga(this,arguments,void 0,(function*(e,t,r={}){var n,o;const i=null!==(n=r.log)&&void 0!==n?n:Fo,s=performance.now(),l=yield function(e){return Ha(this,void 0,void 0,(function*(){const t=qa(e),r=(0,a.join)(t,"plugins","installed_plugins.json");try{const e=yield(0,Hn.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir);if(!(null==l?void 0:l.plugins))return i.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-s).toFixed(1)}ms)`),[];const c=yield function(e){return Ha(this,void 0,void 0,(function*(){const t=qa(e),r=(0,a.join)(t,"settings.json");try{const e=yield(0,Hn.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir),u=e?(0,a.resolve)(e):void 0,d=function(e,t,r,n){var o;const i=null==e?void 0:e.plugins;if(!i||"object"!=typeof i)return[];const s=null!==(o=null==t?void 0:t.enabledPlugins)&&void 0!==o?o:{},a={};(null==r?void 0:r.enabledPlugins)&&Object.assign(a,r.enabledPlugins);const l=void 0!==n?Aa(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)&&Aa(t.projectPath)===l&&!0===a[e]))),r||!0!==s[e]||(r=t.find((e=>"user"===e.scope))),(null==r?void 0:r.installPath)&&!c.has(e)&&(u.push({pluginId:e,installPath:r.installPath}),c.add(e))}return u}(l,c,u?yield function(e){return Ha(this,void 0,void 0,(function*(){const t={enabledPlugins:{}};let r=!1;const n=(0,a.join)(e,".claude","settings.json");try{const e=yield(0,Hn.readFile)(n,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch(e){}const o=(0,a.join)(e,".claude","settings.local.json");try{const e=yield(0,Hn.readFile)(o,"utf-8"),n=JSON.parse(e);n.enabledPlugins&&(Object.assign(t.enabledPlugins,n.enabledPlugins),r=!0)}catch(e){}return r?t:null}))}(u):null,u),h=[],p=r.onError;for(const{pluginId:e,installPath:t}of d)try{const r=performance.now(),n=qo(e),o=yield fl(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(qo(e),r)}catch(t){p({name:null!==(o=e.split("@")[0])&&void 0!==o?o:e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return i.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-s).toFixed(1)}ms (${d.length} resolved, ${h.length} loaded)`),h}))}Error;function vl(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 yl(e,t={}){return Object.assign(Object.assign({},e),{model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools})}(0,a.join)((0,s.homedir)(),".claude","plugins","marketplaces");var wl=r("node:url");function bl(e,t){const r=[];for(const o of e){const e=Go(o.identifier),i=`plugin:${e}`,s=Vo(o.identifier),l=Jo(o.identifier),c=Ko(o.identifier),u=Zo(o.identifier);for(const d of t(o)){const t=(0,a.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:s,marketplace:l,pluginId:c,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}const Sl=Lo.z.object({path:Lo.z.string(),name:Lo.z.string().optional(),description:Lo.z.string().optional(),globs:Lo.z.array(Lo.z.string()).optional(),alwaysApply:Lo.z.boolean().optional(),content:Lo.z.string(),environments:Lo.z.array(Lo.z.string()).optional(),disabledEnvironments:Lo.z.array(Lo.z.string()).optional()}),kl=Sl.extend({name:Lo.z.string()}),El=Lo.z.object({path:Lo.z.string(),name:Lo.z.string(),description:Lo.z.string().optional(),tools:Lo.z.array(Lo.z.string()).optional(),model:Lo.z.string().optional(),prompt:Lo.z.string(),permissionMode:Lo.z.enum(["default","readonly"]).optional()}),xl=Lo.z.object({path:Lo.z.string(),name:Lo.z.string(),description:Lo.z.string().optional(),argumentHint:Lo.z.string().optional(),content:Lo.z.string()}),Cl=Lo.z.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),_l=Lo.z.object({config:Cl,sourcePath:Lo.z.string().optional()}),Pl=Lo.z.custom((e=>"object"==typeof e&&null!==e));Lo.z.object({schemaVersion:Lo.z.number().int(),displayName:Lo.z.string().optional(),description:Lo.z.string().optional(),authorName:Lo.z.string().optional(),skills:Lo.z.array(Sl),rules:Lo.z.array(kl),agents:Lo.z.array(El),commands:Lo.z.array(xl),mcpConfig:Bo.extend({mcpServerSourcePaths:Lo.z.record(Lo.z.string(),Lo.z.string()).optional()}).optional(),hooks:_l.optional(),hooksError:Lo.z.string().optional(),capabilities:Lo.z.array(Lo.z.string()),variablesSchema:Pl.optional()}),Error;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())}))};function Il(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 Rl extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function Al(e){return Tl(this,void 0,void 0,(function*(){try{return yield(0,Hn.readFile)(function(e){return(0,a.join)(e,".cursor","settings.json")}(e),"utf-8")}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}))}function Ol(e){return Tl(this,void 0,void 0,(function*(){const t=yield Al(e);return void 0===t?{}:function(e){const t=[],r=(0,Ai.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,Ai._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Rl(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const n=r;return void 0===n.plugins||"object"==typeof n.plugins&&null!==n.plugins&&!Array.isArray(n.plugins)?n:{}}(t)}))}function jl(e){return Tl(this,void 0,void 0,(function*(){const t=yield Ol(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||Il(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}))}function Ml(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var Dl=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),Nl=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),$l=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ll=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");const Fl="utf8",Ul="utf8bom",Bl="latin1",zl={"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 Wl(e){const t=e.toLowerCase();return"latin-1"===t?Bl:"utf-8"===t?Fl:"utf-8-bom"===t||"utf-8 bom"===t?Ul:t}var Hl,ql=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())}))},Gl=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)}))}}},Vl=function(e){return this instanceof Vl?(this.v=e,this):new Vl(e)},Jl=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:Vl(e[n](t)),done:!1}:o?o(t):t}:o}};!function(e){e.CRLF="CRLF",e.LF="LF"}(Hl||(Hl={}));const Kl=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Zl=new Set(Kl),Yl=new $o.TextDecoder("utf-8",{fatal:!0}),Xl=new $o.TextDecoder("latin1"),Ql=Buffer.from([239,187,191]),ec=new Map,tc=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...Kl]),rc=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i;function nc(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function oc(e){const t=nc(e);return Zl.has(t)}function ic(e){const t=nc(e);return{encoding:"binary",lineEnding:Hl.LF,isBinaryFile:!0,isImageFile:rc.test(t),isVideoFile:Zl.has(t)}}function sc(e,t){return ql(this,void 0,void 0,(function*(){const r=yield(0,Hn.readFile)(e),n=uc(r);if(n.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const o=ec.get(e);let i;i=t||o||n.encoding;const{text:s,encoding:a}=function(e,t){const r=Wl(t);if(r===Fl||r===Ul||"ascii"===r){const t=gc(e);return r===Ul&&t.encoding===Fl?{text:t.text,encoding:Ul}:t}if(r===Bl)return{text:Xl.decode(e),encoding:Bl};try{const t=function(e){return zl[e]||e}(r);if($l.encodingExists(t))return{text:$l.decode(e,t),encoding:r}}catch(e){}return gc(e)}(r,i),l=function(e){return e.startsWith("\ufeff")?e.slice(1):e}(s);return mc(e,a===Fl&&vc(r)?Ul:a),n.lineEnding===Hl.CRLF?l.replaceAll("\r\n","\n"):l}))}function ac(e,t,r,n){return ql(this,void 0,void 0,(function*(){let o;try{o=r?yield function(e,t){return ql(this,void 0,void 0,(function*(){try{return yield lc(e)}catch(e){}const r=nc(e);if(tc.has(r))return ic(e);try{return yield function(e){return ql(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=Gl(pc(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 lc(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:fc()}))}(t)}catch(e){return fc()}}))}(e,r):yield lc(e)}catch(t){const r=nc(e);o=tc.has(r)?ic(e):fc()}const i=ec.get(e);if(!o.isBinaryFile){let t;t=Wl(n||i||o.encoding);const r=t===Ul||t===Fl&&!n&&(yield function(e){return ql(this,void 0,void 0,(function*(){try{return vc(yield hc(e))}catch(e){return!1}}))}(e));o=Object.assign(Object.assign({},o),{encoding:r?Ul:t}),mc(e,o.encoding)}const s=cc(t);if(o.lineEnding===Hl.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===Ul?Buffer.concat([Ql,$l.encode(t,Fl,{defaultEncoding:Fl})]):$l.encode(t,o.encoding,{defaultEncoding:Fl}),format:o}}))}function lc(e){return ql(this,void 0,void 0,(function*(){const t=uc(yield hc(e));return t.isBinaryFile?Object.assign(Object.assign({},t),{isVideoFile:oc(e)}):Object.assign(Object.assign({},t),{isVideoFile:!1})}))}function cc(e){if(""===e)return 1;let t=1;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}function uc(e){if(0===e.length)return fc();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:dc(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:dc(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:Hl.LF,isBinaryFile:!0,isImageFile:(n=e,!(n.length<4)&&(n.length>=8&&137===n[0]&&80===n[1]&&78===n[2]&&71===n[3]&&13===n[4]&&10===n[5]&&26===n[6]&&10===n[7]||255===n[0]&&216===n[1]&&255===n[2]||n.length>=12&&82===n[0]&&73===n[1]&&70===n[2]&&70===n[3]&&87===n[8]&&69===n[9]&&66===n[10]&&80===n[11]||n.length>=6&&71===n[0]&&73===n[1]&&70===n[2]&&56===n[3]&&(55===n[4]||57===n[4])&&97===n[5])),isVideoFile:!1};var n;const o=Ll.detect(e);let i=o.confidence>.7?o.encoding:"utf-8";return"ascii"===i&&(i="utf-8"),{encoding:null!=i?i:"utf-8",lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function dc(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?Hl.LF:t/(t+r)*100>=5?Hl.CRLF:Hl.LF}function hc(e){return ql(this,void 0,void 0,(function*(){const t=yield(0,Hn.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 pc(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 Vl?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 Vl((0,Hn.readdir)(e,{withFileTypes:!0}));for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,a.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield Vl(yield*Jl(Gl(pc(r))))):n.isFile()&&(yield yield Vl(r))}}catch(e){return yield Vl(void 0)}}))}function fc(){return{encoding:Fl,lineEnding:"win32"===process.platform?Hl.CRLF:Hl.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function mc(e,t){if(ec.has(e)&&ec.delete(e),ec.set(e,t),ec.size<=100)return;const r=ec.keys().next().value;void 0!==r&&ec.delete(r)}function gc(e){try{return{text:Yl.decode(e),encoding:Fl}}catch(t){return{text:Xl.decode(e),encoding:Bl}}}function vc(e){return e.length>=Ql.length&&e[0]===Ql[0]&&e[1]===Ql[1]&&e[2]===Ql[2]}class yc{constructor({ttlMs:e,now:t=Date.now}){if(this.entries=new Map,!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);this.ttlMs=e,this.now=t}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 wc=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 bc(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:o=[],caseSensitive:i=!1,cursorIgnoreFiles:s=[],sandboxPolicy:a={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:c=!1,source:u="ripwalk"}){const d=["--files","--hidden","--no-require-git","--no-config","--color=never"];c&&d.push("--follow"),l&&d.push("--no-ignore-vcs"),i&&d.push("--case-sensitive");for(const e of s)d.push("--cursor-ignore",e);for(const e of n)d.push("--iglob",e);for(const e of o)d.push("--iglob",`!${e}`);r.length>0&&d.push("--",...r);let h,p=!1;const f=new Promise((e=>{h=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,uo.spawnInSandbox)((0,uo.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,d,t,a),!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){p=!0,h(!0);break}if(e.done)break;o++,yield e.value}if(o>0);else if(!p){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}`:""}`)}}p||h(!1)}catch(e){r.error=e,r.hasError=!0}finally{wc(r)}}(),didTimeout:f}}function Sc({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 kc{constructor(e=2e4){this.cache=new yc({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(Sc(e))}walk(e,t){const r=Sc(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=bc(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 Ec(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}async function xc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Cc(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 _c(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 Pc=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];var Tc=r("../utils/dist/lru-cache.js"),Ic=r("../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js");async function Rc(e){if(!(0,a.isAbsolute)(e))return null;const t=await(0,Vn.DN)(e);return null===t?null:t}class Ac{constructor(e,t,r){this.ignoreServicePromise=jc.init((0,Ye.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 Oc=Math.min(8,Math.max(1,Math.floor(s.availableParallelism()/2)));class jc{constructor(e,t,r,n,o){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.gitIgnoreCache=new Tc.q({max:2e3}),this.cursorIgnoreCache=new Tc.q({max:2e3}),this.gitRootCache=new Tc.q({max:1e3}),this.gitRemoteUrlCache=new Tc.q({max:200}),this.hasGitDirCache=new Tc.q({max:1e3}),this.gitParsedIgnoreCache=new Map,this.cursorParsedIgnoreCache=new Map}static getRipwalkCache(){return jc.ripwalkCache??=new kc,jc.ripwalkCache}getIgnoreInstance(e,t,r){let n=r.get(e);return n||(n=Do().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,Vn.DN)(e)??(0,Vn.o1)(e)}static async init(e,t,r,n){const o=await(0,Hs.PH)(r,(async e=>{const t=await(0,Vn.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),i={},s={},a=(await(0,Hs.PH)(o,(r=>Ec(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([n?n.getTeamRepos():Promise.resolve(void 0),jc.initializeIgnoreMapping(a,".gitignore",i),jc.initializeIgnoreMapping(o,".cursorignore",s)]),new jc(t,i,s,n,o)}static async preloadHierarchy(e,t,r,n){let o=(0,Vn.o1)(e);const i=(0,a.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,a.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await jc.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,a.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,a.join)(e,t);try{await(0,Hn.access)(n,Hn.constants.F_OK);const t=await sc(n),o=jc.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=jc.deduplicateRootDirectories(e),o=await jc.promiseQueue.enqueueList(n,(e=>jc.findFilesWithRipgrep(e,t))),i=Array.from(o.values()).flat();await Promise.all(i.map((async e=>{try{const t=await sc(e),n=jc.parseIgnoreRules(t),o=(0,a.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const s=new Set;for(const e of n)await jc.preloadHierarchy(e,t,r,s)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t){const r=(0,Ye.q6)(),n=[],o={root:e,includeGlobs:[`**/${t}`],excludeGlobs:Pc,source:"ignore_scan"},i=jc.getRipwalkCache().walk(r,o);for await(const t of i.lines)n.push((0,a.join)(e,t));return n}async handleManualLookupWhenNoWorkspaceDirs(e,t){const r={};let n=(0,a.dirname)(e);const o=(0,a.parse)(n).root;for(;;){const e=(0,a.join)(n,t);try{const t=await sc(e),o=jc.parseIgnoreRules(t);o.length>0&&(r[n]=o)}catch{}if(n===o)break;n=(0,a.dirname)(n)}return this.testIgnored(e,r,((e,t)=>Do().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e){return this.checkCursorIgnored(e)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore");const t=this.cursorIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const r=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,a.dirname)((0,Vn.o1)(e));const o=[],i=(0,a.parse)(n).root;for(;n!==i;){if(this.rootDirectories.some((e=>(0,Vn.ZU)({basePath:e,targetPath:n})))){n=(0,a.dirname)(n);continue}if(void 0!==r[n])break;o.push(n);const e=(0,a.dirname)(n);if(e===n)break;n=e}o.length>0&&(await jc.promiseQueue.enqueueList(o,(e=>jc.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,Vn.ZU)({basePath:n,targetPath:e}))continue;const t=(0,a.relative)(n,e);if(""===t)continue;const i=r(n,o),s=(0,Vn.oL)(t),l=i.test(s);if(l.ignored&&!l.unignored)return!0;const c=i.test(`${s}/`);if(c.ignored&&!c.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>this.getIgnoreInstance(e,t,r)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Vn.ZU)({basePath:t,targetPath:e}))continue;const o=(0,a.join)(e,".cursorignore");try{await(0,Hn.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,Vn.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear()}async handleCursorIgnoreCreated(e){const t=(0,a.dirname)(e),r=await sc(e),n=jc.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,a.dirname)(e),r=await sc(e),n=jc.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,a.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Vn.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let s=t;const l=(0,a.parse)(s).root;for(;s!==l;){o.push(s),void 0===this.hasGitDirCache.get(s)&&i.push(s);const e=(0,a.dirname)(s);if(e===s)break;s=e}if(i.length>0){const e=i.map((e=>(0,Hn.access)((0,a.join)(e,".git"),Hn.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=await this.findGitRootsForFile(e);if(0===t.length)return!1;const r=await(this.teamSettingsService?.getTeamRepos());if(!r||!r.repos)return!1;for(const n of t){let t;this.gitRemoteUrlCache.has(n)?t=this.gitRemoteUrlCache.get(n):(t=await xc((0,Ye.q6)(),this.gitExecutor,n),void 0!==t&&this.gitRemoteUrlCache.set(n,t));const o=r.repos.filter((e=>void 0!==t&&this.doesRepoUrlMatch(e.url,t)));if(0===o.length)continue;const i=(0,a.relative)(n,e)||".";for(const e of o)for(const t of e.patterns||[])if(this.matchGlob(t.pattern,i))return!0}return!1}doesRepoUrlMatch(e,t){if(e.trim().toLowerCase().replace(/\.git$/i,""),e.includes("*")){if("*"===e.trim())return!0;const r=_c(e).toLowerCase(),n=_c(t).toLowerCase();return this.matchRepoUrlGlob(r,n)}return _c(e).toLowerCase()===_c(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return Ic(r)(t)}catch{return r===t}}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),s=this.normalizePathForComparison(r);let l=!1,c="";if(s.startsWith(n)?(l=!0,c=""):n.startsWith(s)&&(l=!0,c=(0,a.relative)(r,e)),!l)continue;const u=t.repos.filter((e=>this.doesRepoUrlMatch(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=c?(0,a.join)(c,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],n=(0,Ye.q6)();for(const e of this.rootDirectories){const o=(0,Vn.o1)(e);try{await(0,Hn.access)((0,a.join)(o,".git"),Hn.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,a.dirname)(o);const s=(0,a.parse)(i).root;for(;i!==s&&""!==i;){try{await(0,Hn.access)((0,a.join)(i,".git"),Hn.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,a.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:r,noIgnoreVcs:!0,source:"ignore_scan"},i=jc.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,a.join)(o,e),n=(0,a.dirname)(r),i=(0,a.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await xc(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}jc.promiseQueue=new Hs.TJ({max:Oc});var Mc=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 Dc=[{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}],Nc=/[/\\]\.cursor[/\\]rules[/\\]/i,$c=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Lc=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Fc(e,t){const r=e.replace(/\\/g,"/"),n=(0,a.basename)(r);if(Lc.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Nc.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Dc)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $c)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Uc{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Uc.ripwalkCache??=new kc,Uc.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,c.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]};if((0,a.resolve)(this.root)===(0,a.resolve)(this.userHomeDirectory))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ec(e,this.gitExecutor,(0,a.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const o=this.getThirdPartyExtensibilityEnabled(),i=this.buildIncludeGlobs(o),s={root:this.root,includeGlobs:i,excludeGlobs:Pc,followSymlinks:!0,source:"nested_extensibility"},l={rules:[],skills:[],markdown:[],agents:[]},u=Uc.getRipwalkCache();try{const e=u.walk(r.ctx,s);try{for await(const t of e.lines){const e=Fc(t,o);e&&l[e].push((0,a.resolve)(this.root,t))}}finally{u.delete(s)}}catch{}return r.span.setAttribute("nested_extensibility.rules",l.rules.length),r.span.setAttribute("nested_extensibility.skills",l.skills.length),r.span.setAttribute("nested_extensibility.markdown",l.markdown.length),r.span.setAttribute("nested_extensibility.agents",l.agents.length),l}catch(e){t.error=e,t.hasError=!0}finally{Mc(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Bc=new Set(["node_modules",".git",".svn",".hg","__pycache__",".cache","dist","build",".next",".nuxt"]);async function zc({rootDir:e,includeFile:t,maxDepth:r=10,skipDirectories:n=Bc,containmentRootDir:o}){const i=[],s=[{dir:e,depth:0}],l=new Set,c=void 0!==o?await(0,Hn.realpath)(o):null,u=e=>{if(null===c)return!0;const t=(0,a.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,a.isAbsolute)(t)};for(;s.length>0;){const e=s.pop();if(void 0===e)continue;const{dir:o,depth:c}=e;if(c>r)continue;try{const e=await(0,Hn.realpath)(o);if(!u(e))continue;if(l.has(e))continue;l.add(e)}catch{continue}const d=await(0,Hn.readdir)(o,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,a.join)(o,e.name);let l=e.isDirectory(),u=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Hn.stat)(r);l=e.isDirectory(),u=e.isFile()}catch{continue}if(l){if(n.has(e.name))continue;s.push({dir:r,depth:c+1})}else u&&t(e.name)&&i.push(r)}}return i.sort(((e,t)=>e.localeCompare(t))),i}const Wc=new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]);function Hc(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&&Wc.has(o)}function qc(e){return{dirPath:(0,a.join)(e,".cursor","skills-cursor"),scope:"builtin",source:"builtin"}}function Gc(e,t){const r=[];return t&&r.push({dirPath:(0,a.join)(e,".claude","skills"),scope:"project",source:"workspace"},{dirPath:(0,a.join)(e,".codex","skills"),scope:"project",source:"workspace"}),r.push({dirPath:(0,a.join)(e,".agents","skills"),scope:"project",source:"workspace"},{dirPath:(0,a.join)(e,".cursor","skills"),scope:"project",source:"workspace"}),r}function Vc(e,t){const r=[];return t&&r.push({dirPath:(0,a.join)(e,".claude","skills"),scope:"user",source:"user"},{dirPath:(0,a.join)(e,".codex","skills"),scope:"user",source:"user"}),r.push({dirPath:(0,a.join)(e,".agents","skills"),scope:"user",source:"user"},{dirPath:(0,a.join)(e,".cursor","skills"),scope:"user",source:"user"}),r}var Jc=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},Kc=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 Zc=(0,h.h)("local-exec:cursor-rules");function Yc(e){return eu(e.data?.environments??e.data?.metadata?.environments)??[]}function Xc(e){return eu(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Qc(e){return eu(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eu(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 tu(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 ru(e){return e.slice(0,1536)}async function nu(e){const t=await sc(e);return{skillFilePath:e,content:t,parsed:Ia(t)}}function ou(e){return!0===e.data?.alwaysApply}function iu({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---`:Ra("",null!==(n=e.data)&&void 0!==n?n:{}).trim()}(e)}(r);if(ou(r))return new Nl.DX({fullPath:e,content:t,frontmatter:n,type:new Nl.f5({type:{case:"global",value:new Nl.i9}}),environments:Yc(r),disabledEnvironments:Xc(r),scopedTo:Qc(r)});const o="string"==typeof r.data?.description?ru(r.data.description):void 0;return o?new Nl.DX({fullPath:e,content:t,frontmatter:n,type:new Nl.f5({type:{case:"agentFetched",value:new Nl.Xo({description:o})}}),environments:Yc(r),disabledEnvironments:Xc(r),scopedTo:Qc(r)}):new Nl.DX({fullPath:e,parseError:"Description is required",frontmatter:n,scopedTo:Qc(r),type:new Nl.f5({type:{case:"agentFetched",value:new Nl.Xo}})})}function su({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?ru(r.data.description):"",o=nl(r.data?.paths??r.data?.globs);return new Dl.N({fullPath:e,content:t,description:n,globs:o??[],parseError:n?void 0:"Description is required",environments:Yc(r),disabledEnvironments:Xc(r),scopedTo:Qc(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function au({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Nl.DX({fullPath:e,parseError:t,type:new Nl.f5({type:{case:"agentFetched",value:new Nl.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new Dl.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`}))}function lu(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 cu(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function uu(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=cu(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=cu(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 du{constructor(e){this.cursorRulesServices=e,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Jc(t,(0,c.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,$o.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=lu(e.fullPath);i.has(t)||(i.add(t),s.push(e))}return s}catch(e){t.error=e,t.hasError=!0}finally{Kc(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()}),du.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()}}du.CHANGE_COALESCE_MS=1e3;class hu{constructor(e,t,r,n,o,i,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=o,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Uc(r,t,(0,s.homedir)(),o),this.ignoreService=l??new Ac(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{Zc.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,$o.debuglog)("Failed to load cursor rules:",e),[]))),i){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=i.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,Ye.q6)(),n=Jc(t,(0,c.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,a.basename)(e))return hu.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Kc(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,$o.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return hu.ripwalkCache??=new kc,hu.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1),o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,$o.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{Kc(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=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,a.basename)(t);if(".cursorrules"===o){const e=(0,a.resolve)(this.rootDirectory),t=await Ec(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=uu(await sc(t));if(e)return[{filename:(0,a.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,a.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Kc(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=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,a.resolve)(this.rootDirectory),i=await Ec(n.ctx,this.gitExecutor,o)||o,s=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,o);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const h=(await Promise.all([s,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);return[...p.values()].map((e=>this.toCursorRule(e)))}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,a.join)(t,".cursorrules");if((await(0,Hn.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await sc(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Jc(t,(0,c.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Kc(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Nl.i9};else{const r=nl(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Nl.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Nl.Xo({description:ru(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Nl._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 Nl.DX({fullPath:e.path,content:e.body,type:new Nl.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=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const s=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,a.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];s&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const l=(0,a.dirname)(i);if(l===i)break;i=l}const l=(await Promise.all(o)).flat();return n.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Jc(n,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,a.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Hn.stat)(e)).isFile()){const t=await sc(e);return[{filename:(0,a.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Kc(n)}}async isCursorIgnored(e){try{const t=await Rc((0,a.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=uu(await sc(e));if(t)return{filename:(0,a.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,a.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,a.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,a.join)(t,".cursorignore");const e={root:(0,a.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=hu.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,a.join)(e.root,t);o.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Jc(r,(0,c.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Hn.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}}class pu{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 Uc(e,n,r,s))):[],this.foldersToWatch=this.computeFoldersToWatch();const u=performance.now(),d=this.loadAll(e,c).then((t=>{try{Zc.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,$o.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=d.then((e=>e.rules)),this._agentSkills=d.then((e=>e.agentSkills)),this.setupWatchers(this.foldersToWatch)}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,a.join)(r,".cursor","rules"));for(const n of Gc(r,e))t.add(n.dirPath)}for(const r of Vc(this.userHomeDirectory,e))t.add(r.dirPath);return t.add(qc(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,Ye.q6)(),n=Jc(t,(0,c.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Kc(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,$o.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{Jc(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1);const n=t.endsWith("SKILL.md")?t:(0,a.join)(t,"SKILL.md"),o=nu(n);o.catch((()=>{}));const i=async(e,t)=>{const r=(await e).filter((e=>e.fullPath!==n));if(Hc(n))return r;try{await(0,Hn.stat)(n);const e=await o;if(tu(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=>iu(e))).catch((e=>((0,$o.debuglog)("Failed to load Agent Skills at path:",e),[]))),this._agentSkills=i(this._agentSkills,(e=>ou(e.parsed)?void 0:su(e))).catch((e=>((0,$o.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{Kc(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=Jc(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],i=[],s=new Set,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{(0,$o.debuglog)("cursor-rules-service")("Failed to discover nested agent skills: %O",e)}))))),l=await Promise.all(this.foldersToWatch.map((async e=>{const t=(await async function(e){return await zc({rootDir:e,includeFile:e=>"SKILL.md"===e})}(e)).filter((e=>!Hc(e)));return Promise.all(t.map((async e=>{try{return await nu(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})))})));for(const e of l)for(const t of e)if(s.add(t.skillFilePath),"error"in t)au({rules:o,agentSkills:i,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tu(t.parsed,this.surface))continue;o.push(iu(t)),ou(t.parsed)||i.push(su(t))}const u=(await a).flatMap((e=>e?.skills??[])).filter((e=>!Hc(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 nu(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)au({rules:o,agentSkills:i,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tu(e.parsed,this.surface))continue;o.push(iu(e)),ou(e.parsed)||i.push(su(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{Kc(r)}}}function fu(e){let t;switch(e.type){case"global":t=new Nl.f5({type:{case:"global",value:new Nl.i9}});break;case"fileGlobbed":t=new Nl.f5({type:{case:"fileGlobbed",value:new Nl.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Nl.f5({type:{case:"agentFetched",value:new Nl.Xo({description:ru(e.description??"")})}});break;case"manuallyAttached":t=new Nl.f5({type:{case:"manuallyAttached",value:new Nl._u}});break;default:e.type,t=new Nl.f5({type:{case:"manuallyAttached",value:new Nl._u}})}return new Nl.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 mu{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{Zc.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,$o.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,$o.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=Jc(r,(0,c.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return bl(e,(e=>e.skills))}(e),s=function(e){return bl(e,(e=>e.rules))}(e);for(const e of[...r,...s])o.push(fu(e));for(const t of e){const e=`plugin:${Go(t.identifier)}`,r=Vo(t.identifier),n=Jo(t.identifier),o=Ko(t.identifier),s=Zo(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===Ia(l.content).data?.["disable-model-invocation"]}catch{}i.push(new Dl.N({fullPath:(0,a.join)(t.installPath,l.path),content:l.content,description:ru(l.description??""),environments:l.environments??[],disabledEnvironments:l.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:s,disableModelInvocation:c}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Kc(r)}}}var gu=r("../proto/dist/generated/agent/v1/subagents_pb.js");const vu=(0,$o.debuglog)("local-subagents");class yu{async getAllSubagents(){return[]}async reload(){return[]}}function wu(e){return"true"===(e??"").trim().toLowerCase()}function bu(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=wu(o["force-default-model"]),c="true"===(o.readonly??"").trim().toLowerCase()?gu.b$.READONLY:gu.b$.DEFAULT,u=wu(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 Su(e){const t=(0,a.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function ku(e){return(0,a.basename)(e,(0,a.extname)(e)).replace(/[\s_]+/g,"-")}async function Eu(e,t){return await zc({rootDir:e,includeFile:Su,containmentRootDir:t})}class xu{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=>(vu("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(vu("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,a.resolve)(this.workspacePath),t=[{dirPath:(0,a.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&t.push({dirPath:(0,a.join)(e,".claude","agents"),source:"claude"}),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Eu(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,a.basename)(r);try{if(!(await(0,Hn.stat)(r)).isFile())continue}catch(e){vu("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=bu(await sc(r));if(!o)continue;t.push(new gu.zz({fullPath:r,name:o.name||ku(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){vu("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Cu=new Set(["claude-code-tutor"]);class _u{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(vu("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Cu.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 Pu{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&&(vu("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=Vo(o.identifier),i=Jo(o.identifier),s=Ko(o.identifier),l=Zo(o.identifier);for(const c of o.agents){const u=yl(c,t),d=(0,a.join)(o.installPath,u.path);n.push({name:u.name,description:null!==(r=u.description)&&void 0!==r?r:"",prompt:u.prompt,fullPath:d,permissionMode:"readonly"===u.permissionMode?"readonly":"default",plugin:e,marketplace:i,pluginId:s,marketplaceId:l})}}return n}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?gu.b$.READONLY:gu.b$.DEFAULT;t.push(new gu.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 Tu=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");function Iu(e,t,r){return new Promise(((n,o)=>{const i={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0};(0,ss.execFile)(e,t.map(String),{...i,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Tu.w3.UNSPECIFIED,Tu.w3.LEFT,Tu.w3.MIDDLE,Tu.w3.RIGHT,Tu.w3.BACK,Tu.w3.FORWARD,Tu.Dh.UNSPECIFIED,Tu.Dh.UP,Tu.Dh.DOWN,Tu.Dh.LEFT,Tu.Dh.RIGHT,(0,p.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,p.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,p.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.h)("computer-use");const Ru=(0,$o.promisify)(ss.execFile);function Au(e,t){const r=e/t;return{display:{width:e,height:t},api:{width:1280,height:Math.round(1280/r)}}}async function Ou(e){const{stdout:t}=await Ru("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:Au(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}var ju,Mu,Du,Nu,$u;!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"}(ju||(ju={})),nr.proto3.util.setEnumType(ju,"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"}(Mu||(Mu={})),nr.proto3.util.setEnumType(Mu,"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"}(Du||(Du={})),nr.proto3.util.setEnumType(Du,"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"}(Nu||(Nu={})),nr.proto3.util.setEnumType(Nu,"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"}($u||($u={})),nr.proto3.util.setEnumType($u,"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 Lu extends nr.Message{constructor(e){super(),this.executionTimestampMs=nr.protoInt64.zero,this.commandDurationMs=nr.protoInt64.zero,this.cursorTypeAfter=ju.UNSPECIFIED,nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Lu).fromBinary(e,t)}static fromJson(e,t){return(new Lu).fromJson(e,t)}static fromJsonString(e,t){return(new Lu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Lu,e,t)}}Lu.runtime=nr.proto3,Lu.typeName="agent.v1.InputEvent",Lu.fields=nr.proto3.util.newFieldList((()=>[{no:1,name:"execution_timestamp_ms",kind:"scalar",T:3},{no:2,name:"action",kind:"message",T:Tu.ho},{no:3,name:"command_duration_ms",kind:"scalar",T:3},{no:4,name:"position_before",kind:"message",T:Tu.xp},{no:5,name:"position_after",kind:"message",T:Tu.xp},{no:6,name:"cursor_type_after",kind:"enum",T:nr.proto3.getEnumType(ju)}]));class Fu extends nr.Message{constructor(e){super(),this.videoTimestampMs=nr.protoInt64.zero,this.x=0,this.y=0,this.cursorType=ju.UNSPECIFIED,this.velocity=0,nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Fu).fromBinary(e,t)}static fromJson(e,t){return(new Fu).fromJson(e,t)}static fromJsonString(e,t){return(new Fu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Fu,e,t)}}Fu.runtime=nr.proto3,Fu.typeName="agent.v1.CursorPathKeyframe",Fu.fields=nr.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:nr.proto3.getEnumType(ju)},{no:5,name:"velocity",kind:"scalar",T:2}]));class Uu extends nr.Message{constructor(e){super(),this.style=Mu.UNSPECIFIED,this.keyframes=[],nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Uu).fromBinary(e,t)}static fromJson(e,t){return(new Uu).fromJson(e,t)}static fromJsonString(e,t){return(new Uu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Uu,e,t)}}Uu.runtime=nr.proto3,Uu.typeName="agent.v1.CursorPath",Uu.fields=nr.proto3.util.newFieldList((()=>[{no:1,name:"style",kind:"enum",T:nr.proto3.getEnumType(Mu)},{no:2,name:"keyframes",kind:"message",T:Fu,repeated:!0}]));class Bu extends nr.Message{constructor(e){super(),this.startMs=nr.protoInt64.zero,this.endMs=nr.protoInt64.zero,this.centerX=0,this.centerY=0,this.suggestedZoom=0,this.actionType="",this.actionIndex=0,this.importanceScore=0,this.context="",nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Bu).fromBinary(e,t)}static fromJson(e,t){return(new Bu).fromJson(e,t)}static fromJsonString(e,t){return(new Bu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Bu,e,t)}}Bu.runtime=nr.proto3,Bu.typeName="agent.v1.ZoomCandidate",Bu.fields=nr.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 zu extends nr.Message{constructor(e){super(),this.startMs=nr.protoInt64.zero,this.endMs=nr.protoInt64.zero,this.durationMs=nr.protoInt64.zero,this.classification=Du.UNSPECIFIED,this.suggestedSpeed=0,this.precedingActionType="",this.followingActionType="",nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new zu).fromBinary(e,t)}static fromJson(e,t){return(new zu).fromJson(e,t)}static fromJsonString(e,t){return(new zu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(zu,e,t)}}zu.runtime=nr.proto3,zu.typeName="agent.v1.IdlePeriod",zu.fields=nr.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:nr.proto3.getEnumType(Du)},{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 Wu extends nr.Message{constructor(e){super(),this.videoTimestampMs=nr.protoInt64.zero,this.x=0,this.y=0,this.clickType=Nu.UNSPECIFIED,this.actionIndex=0,this.hasModifiers=!1,nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Wu).fromBinary(e,t)}static fromJson(e,t){return(new Wu).fromJson(e,t)}static fromJsonString(e,t){return(new Wu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Wu,e,t)}}Wu.runtime=nr.proto3,Wu.typeName="agent.v1.ClickEffectKeyframe",Wu.fields=nr.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:nr.proto3.getEnumType(Nu)},{no:5,name:"action_index",kind:"scalar",T:5},{no:6,name:"has_modifiers",kind:"scalar",T:8}]));class Hu extends nr.Message{constructor(e){super(),this.videoTimestampMs=nr.protoInt64.zero,this.displayText="",this.eventType=$u.UNSPECIFIED,this.displayDurationMs=nr.protoInt64.zero,this.actionIndex=0,nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Hu).fromBinary(e,t)}static fromJson(e,t){return(new Hu).fromJson(e,t)}static fromJsonString(e,t){return(new Hu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Hu,e,t)}}Hu.runtime=nr.proto3,Hu.typeName="agent.v1.KeystrokeEvent",Hu.fields=nr.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:nr.proto3.getEnumType($u)},{no:4,name:"display_duration_ms",kind:"scalar",T:3},{no:5,name:"action_index",kind:"scalar",T:5}]));class qu extends nr.Message{constructor(e){super(),this.videoPath="",this.videoDurationMs=nr.protoInt64.zero,this.videoWidth=0,this.videoHeight=0,this.actionCount=0,this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.cursorPaths=[],nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new qu).fromBinary(e,t)}static fromJson(e,t){return(new qu).fromJson(e,t)}static fromJsonString(e,t){return(new qu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(qu,e,t)}}qu.runtime=nr.proto3,qu.typeName="agent.v1.DecisionInput",qu.fields=nr.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:Bu,repeated:!0},{no:11,name:"idle_periods",kind:"message",T:zu,repeated:!0},{no:12,name:"click_effects",kind:"message",T:Wu,repeated:!0},{no:13,name:"keystroke_events",kind:"message",T:Hu,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:Uu,repeated:!0}]));class Gu extends nr.Message{constructor(e){super(),this.candidateIndex=0,nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Gu).fromBinary(e,t)}static fromJson(e,t){return(new Gu).fromJson(e,t)}static fromJsonString(e,t){return(new Gu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Gu,e,t)}}Gu.runtime=nr.proto3,Gu.typeName="agent.v1.ZoomSelection",Gu.fields=nr.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 Vu extends nr.Message{constructor(e){super(),this.candidateIndex=0,nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Vu).fromBinary(e,t)}static fromJson(e,t){return(new Vu).fromJson(e,t)}static fromJsonString(e,t){return(new Vu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Vu,e,t)}}Vu.runtime=nr.proto3,Vu.typeName="agent.v1.SpeedupSelection",Vu.fields=nr.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"speed_override",kind:"scalar",T:2,opt:!0}]));class Ju extends nr.Message{constructor(e){super(),this.cursorStyle=Mu.UNSPECIFIED,this.selectedZooms=[],this.selectedSpeedups=[],this.showClickEffects=!1,this.selectedClickEffects=[],this.showKeystrokes=!1,this.cuts=[],nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ju).fromBinary(e,t)}static fromJson(e,t){return(new Ju).fromJson(e,t)}static fromJsonString(e,t){return(new Ju).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Ju,e,t)}}Ju.runtime=nr.proto3,Ju.typeName="agent.v1.DecisionOutput",Ju.fields=nr.proto3.util.newFieldList((()=>[{no:1,name:"cursor_style",kind:"enum",T:nr.proto3.getEnumType(Mu)},{no:2,name:"selected_zooms",kind:"message",T:Gu,repeated:!0},{no:3,name:"selected_speedups",kind:"message",T:Vu,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:Ku,repeated:!0}]));class Ku extends nr.Message{constructor(e){super(),this.startMs=nr.protoInt64.zero,this.endMs=nr.protoInt64.zero,this.reason="",nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Ku).fromBinary(e,t)}static fromJson(e,t){return(new Ku).fromJson(e,t)}static fromJsonString(e,t){return(new Ku).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Ku,e,t)}}Ku.runtime=nr.proto3,Ku.typeName="agent.v1.VideoCut",Ku.fields=nr.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 Zu extends nr.Message{constructor(e){super(),this.rawVideoPath="",this.durationMs=nr.protoInt64.zero,this.displayWidth=0,this.displayHeight=0,this.apiWidth=0,this.apiHeight=0,this.recordingStartEpochMs=nr.protoInt64.zero,this.inputEvents=[],this.cursorPaths=[],this.zoomCandidates=[],this.idlePeriods=[],this.clickEffects=[],this.keystrokeEvents=[],this.polishedVideoPath="",nr.proto3.util.initPartial(e,this)}static fromBinary(e,t){return(new Zu).fromBinary(e,t)}static fromJson(e,t){return(new Zu).fromJson(e,t)}static fromJsonString(e,t){return(new Zu).fromJsonString(e,t)}static equals(e,t){return nr.proto3.util.equals(Zu,e,t)}}Zu.runtime=nr.proto3,Zu.typeName="agent.v1.RecordingDataPackage",Zu.fields=nr.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:Lu,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:Uu,repeated:!0},{no:30,name:"zoom_candidates",kind:"message",T:Bu,repeated:!0},{no:31,name:"idle_periods",kind:"message",T:zu,repeated:!0},{no:32,name:"click_effects",kind:"message",T:Wu,repeated:!0},{no:33,name:"keystroke_events",kind:"message",T:Hu,repeated:!0},{no:40,name:"decision_input",kind:"message",T:qu},{no:41,name:"decision_output",kind:"message",T:Ju},{no:50,name:"polished_video_path",kind:"scalar",T:9}]));class Yu{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 Xu={left_ptr:ju.ARROW,arrow:ju.ARROW,default:ju.ARROW,top_left_arrow:ju.ARROW,hand:ju.POINTER,hand1:ju.POINTER,hand2:ju.POINTER,pointer:ju.POINTER,pointing_hand:ju.POINTER,xterm:ju.TEXT,ibeam:ju.TEXT,text:ju.TEXT,watch:ju.WAIT,wait:ju.WAIT,progress:ju.WAIT,left_ptr_watch:ju.WAIT,crosshair:ju.CROSSHAIR,cross:ju.CROSSHAIR,tcross:ju.CROSSHAIR,move:ju.MOVE,fleur:ju.MOVE,size_all:ju.MOVE,sb_v_double_arrow:ju.RESIZE_NS,v_double_arrow:ju.RESIZE_NS,ns_resize:ju.RESIZE_NS,row_resize:ju.RESIZE_NS,top_side:ju.RESIZE_NS,bottom_side:ju.RESIZE_NS,sb_h_double_arrow:ju.RESIZE_EW,h_double_arrow:ju.RESIZE_EW,ew_resize:ju.RESIZE_EW,col_resize:ju.RESIZE_EW,left_side:ju.RESIZE_EW,right_side:ju.RESIZE_EW,top_left_corner:ju.RESIZE_NWSE,bottom_right_corner:ju.RESIZE_NWSE,nwse_resize:ju.RESIZE_NWSE,size_fdiag:ju.RESIZE_NWSE,top_right_corner:ju.RESIZE_NESW,bottom_left_corner:ju.RESIZE_NESW,nesw_resize:ju.RESIZE_NESW,size_bdiag:ju.RESIZE_NESW,not_allowed:ju.NOT_ALLOWED,no_drop:ju.NOT_ALLOWED,forbidden:ju.NOT_ALLOWED,circle:ju.NOT_ALLOWED,grab:ju.GRAB,openhand:ju.GRAB,grabbing:ju.GRABBING,closedhand:ju.GRABBING};class Qu{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 Yu(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=ju.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 Iu("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 Iu("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Xu[t]??ju.ARROW}try{const e=await Iu("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Xu))if(e.toLowerCase().includes(t))return r}catch{}return ju.ARROW}catch{return ju.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,h.h)("computer-use-lazy");const ed=1048576,td=52428800;var rd;!function(e){e.Write="write",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(rd||(rd={}));var nd=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 od{constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path,o=(0,Vn.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await go(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new bt.Pi({result:{case:"rejected",value:new bt.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new bt.Pi({result:{case:"permissionDenied",value:new bt.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const s=await this.pendingDecisionProvider.requestApproval({type:rd.Delete,details:{path:o},toolCallId:t.toolCallId});if(!s.approved)return new bt.Pi({result:{case:"rejected",value:new bt.iq({path:o,reason:s.reason||""})}});let a;try{a=await(0,Hn.stat)(o)}catch(e){return"ENOENT"===e.code?new bt.Pi({result:{case:"fileNotFound",value:new bt.n0({path:o})}}):new bt.Pi({result:{case:"error",value:new bt.GU({path:o,error:e.message})}})}if(!a.isFile()){const e=a.isDirectory()?"directory":"other";return new bt.Pi({result:{case:"notFile",value:new bt.LX({path:o,actualType:e})}})}const l=a.size;let u;if(l<=td)try{u=await sc(o)}catch{}const d=u??"";try{await(0,Hn.unlink)(o)}catch(e){return"EACCES"===e.code?new bt.Pi({result:{case:"permissionDenied",value:new bt.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new bt.Pi({result:{case:"fileBusy",value:new bt.vX({path:o})}}):new bt.Pi({result:{case:"error",value:new bt.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 bt.Pi({result:{case:"success",value:new bt.fl({path:o,deletedFile:o,fileSize:BigInt(l),prevContent:d})}})}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}}class id{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===et));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 rr.I0({serverIdentifier:et,serverName:et,instructions:`User-defined tools for this session (server "${et}"). 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 sd extends id{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var ad=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),ld=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 cd{async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new ad.uN({result:{case:"success",value:new ad.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new ad.uN({result:{case:"error",value:new ad.fk({url:n,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{ld(r)}}}class ud{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,Hn.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 ql(this,void 0,void 0,(function*(){const{buffer:o}=yield ac(e,t,r,n);yield(0,Hn.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 dd=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 hd=(0,$o.promisify)(ss.execFile);class pd{async exec(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(o,(0,c.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:s}=await hd("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{dd(o)}}}var fd=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const md=-(2**31),gd=2**31-1;function vd(e){return Number.isNaN(e)?0:e<md?md:e>gd?gd:e}function yd(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return vd(Math.trunc(e))}const wd="agent-tools",bd=52428800;var Sd=r("../mcp-core/dist/index.js"),kd=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())}))},Ed=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xd extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Cd extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class _d{constructor(e){this.disabledService=e}load(e,t,r,n,o){return kd(this,void 0,void 0,(function*(){if(yield this.disabledService.isServerDisabled(t))throw new xd(t);return yield o(e,r)}))}}class Pd{constructor(e){this.approvalService=e}load(e,t,r,n,o){return kd(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(i,(0,c.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!(yield this.approvalService.isServerApproved(t,r,n)))throw new Cd(t);return yield o(e,r)}catch(e){i.error=e,i.hasError=!0}finally{Ed(i)}}))}}class Td{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}isServerApproved(e,t,r){return kd(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 kd(this,void 0,void 0,(function*(){try{const e=yield(0,Hn.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 kd(this,void 0,void 0,(function*(){return this.approvalsPromise}))}addApproval(e){return kd(this,void 0,void 0,(function*(){const t=yield this.approvalsPromise;t.includes(e)||(t.push(e),yield this.saveApprovals(t))}))}addApprovals(e){return kd(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 kd(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 kd(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 kd(this,void 0,void 0,(function*(){yield(0,Hn.mkdir)(a.dirname(this.approvalsPath),{recursive:!0}),yield(0,Hn.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}))}saveApprovals(e){return kd(this,void 0,void 0,(function*(){yield this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}))}}var Id=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())}))},Rd=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},Ad=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 Od{load(e,t,r,n,o){return Id(this,void 0,void 0,(function*(){const n=o(e,r);return new Md(e,t,n,r)}))}}function jd(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Md{constructor(e,t,r,n){var o,i;this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=null===(i=null===(o=(0,c.fU)(e))||void 0===o?void 0:o.spanContext())||void 0===i?void 0:i.traceId,this.toolsPromise=this.clientPromise.then((t=>Id(this,void 0,void 0,(function*(){return null===t?[]:yield t.getTools(e)})))),this.resourcesPromise=this.clientPromise.then((t=>Id(this,void 0,void 0,(function*(){return null===t?[]:(yield t.listResources(e)).resources})))),this.promptsPromise=this.clientPromise.then((t=>Id(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 Id(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Rd(r,(0,c.VI)(e.withName("CachedMcpClient.getTools")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=jd(this.toolsPromise);return void 0!==o?o:yield this.toolsPromise}catch(e){r.error=e,r.hasError=!0}finally{Ad(r)}}))}callTool(e,t,r,n,o){return Id(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const s=Rd(i,(0,c.VI)(e.withName("CachedMcpClient.callTool")),!1),a=yield this.getClient(s.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(s.ctx,t,r,n,o)}catch(e){i.error=e,i.hasError=!0}finally{Ad(i)}}))}getInstructions(e){return Id(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Rd(t,(0,c.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=yield this.getClient(r.ctx);if(null===n)return;return yield n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Ad(t)}}))}getClient(e){return Id(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Rd(r,(0,c.VI)(e.withName("CachedMcpClient.getClient")),!1);return n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined"),yield this.clientPromise}catch(e){r.error=e,r.hasError=!0}finally{Ad(r)}}))}listResources(e){return Id(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Rd(r,(0,c.VI)(e.withName("CachedMcpClient.listResources")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=jd(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:yield this.resourcesPromise}}catch(e){r.error=e,r.hasError=!0}finally{Ad(r)}}))}readResource(e,t){return Id(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=Rd(r,(0,c.VI)(e.withName("CachedMcpClient.readResource")),!1),o=yield this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{Ad(r)}}))}listPrompts(e){return Id(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=Rd(r,(0,c.VI)(e.withName("CachedMcpClient.listPrompts")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=jd(this.promptsPromise);return void 0!==o?o:yield this.promptsPromise}catch(e){r.error=e,r.hasError=!0}finally{Ad(r)}}))}getPrompt(e,t,r){return Id(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=Rd(n,(0,c.VI)(e.withName("CachedMcpClient.getPrompt")),!1),i=yield this.getClient(o.ctx);return null===i?{messages:[]}:i.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{Ad(n)}}))}getState(e){return Id(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=Rd(t,(0,c.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=yield this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return yield n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Ad(t)}}))}close(){return Id(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 Dd(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 Nd=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function $d(e,t){if("string"==typeof e)return function(e,t){return e.replace(Nd,((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=>$d(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=$d(o,t);return r}return e}const Ld=Lo.z.object({type:Lo.z.literal("stdio").optional(),command:Lo.z.string(),args:Lo.z.array(Lo.z.string()).optional(),env:Lo.z.record(Lo.z.string(),Lo.z.string()).optional(),cwd:Lo.z.string().optional()}),Fd=Lo.z.object({CLIENT_ID:Lo.z.string(),CLIENT_SECRET:Lo.z.string().optional(),scopes:Lo.z.array(Lo.z.string()).optional()}),Ud=Lo.z.object({caBundle:Lo.z.string().trim().min(1).max(131072)}).strict(),Bd=Lo.z.object({type:Lo.z.enum(["http","sse"]).optional(),url:Lo.z.string(),headers:Lo.z.record(Lo.z.string(),Lo.z.string()).optional(),auth:Fd.optional(),tls:Ud.optional()}),zd=Lo.z.union([Ld,Bd]),Wd=Lo.z.object({mcpServers:Lo.z.record(Lo.z.string(),zd)});function Hd(e){return t=this,r=arguments,o=function*(e,t=e=>process.env[e]){try{const r=yield(0,Hn.readFile)(e,"utf8"),n=$d((0,Ai.qg)(r),t);return Wd.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 qd=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");const Gd={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"consent"}},Vd=new Map([["gmailmcp.googleapis.com",Object.assign(Object.assign({},Gd),{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({},Gd),{scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]})],["calendarmcp.googleapis.com",Object.assign(Object.assign({},Gd),{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({},Gd),{scopes:["https://www.googleapis.com/auth/documents"]})],["sheetsmcp.googleapis.com",Object.assign(Object.assign({},Gd),{scopes:["https://www.googleapis.com/auth/spreadsheets"]})],["slidesmcp.googleapis.com",Object.assign(Object.assign({},Gd),{scopes:["https://www.googleapis.com/auth/presentations"]})]]);new Set([...Vd].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e)));const Jd=["cursor"],Kd="http://localhost:8787/callback";function Zd(e){return`${e}://anysphere.cursor-mcp/oauth/callback`}function Yd(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([...Jd])).map(Zd))t.add(e);return t.add("https://www.cursor.com/agents/mcp/oauth/callback"),t.add(Kd),e&&r&&t.add(e),Array.from(t)}var Xd=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),Qd=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),eh=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),th=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),rh=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),nh=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"),oh=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))},ih=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},sh=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 ah=["authorization_code","refresh_token"],lh=["code"];class ch{constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,o.randomUUID)(),this._oauthState=function(e,t,r){const n=Object.assign({id:e,owner:t},r?{attemptId:r}:{});return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}saveClientInformation(e){return oh(this,void 0,void 0,(function*(){this._clientInformation=e,yield this._saveClientInformation(e)}))}tokens(){return this._tokens}saveTokens(e){return oh(this,void 0,void 0,(function*(){this._tokens=e,yield this._saveTokens(e)}))}prepareForRefresh(){return oh(this,void 0,void 0,(function*(){var e;yield null===(e=this._prepareForRefresh)||void 0===e?void 0:e.call(this)}))}releaseRefreshLeaseOnError(e){return oh(this,void 0,void 0,(function*(){var t;yield null===(t=this._releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(this,e)}))}invalidateCredentials(e){return oh(this,void 0,void 0,(function*(){var t;switch(e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0;break;default:return e}yield null===(t=this._invalidateCredentials)||void 0===t?void 0:t.call(this,e)}))}redirectToAuthorization(e){(0,Sd.E_)(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 Vd.get(e.toLowerCase())}(n))||void 0===r?void 0:r.authorizationParams;if(void 0!==o)for(const[t,r]of Object.entries(o))e.searchParams.set(t,r)}(e,this._serverUrl),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}saveCodeVerifier(e){return oh(this,void 0,void 0,(function*(){this._codeVerifier=e}))}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}function uh(e){return oh(this,void 0,void 0,(function*(){var t;const{serverName:r,config:n,tokenStorage:o,authRedirectUrl:i}=e,s=function(e,t){if(e)return Object.assign(Object.assign({client_id:e.CLIENT_ID},e.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{}),{redirect_uris:Yd(t),grant_types:[...ah],response_types:[...lh],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 ch({identifier:r,redirectUrl:i,serverUrl:n.url,clientMetadata:{redirect_uris:Yd(i),token_endpoint_auth_method:"none",grant_types:[...ah],response_types:[...lh],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 dh=new Set;let hh=!1;function ph(){for(const e of dh)try{process.kill(e,"SIGKILL")}catch(e){}}class fh{constructor(e,t,r){this._callToolLock=Promise.resolve(),this._stateEnteredAtMs=Date.now(),this.serverName=e,this.client=t,this.tools=new Sd.B1,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,Sd.VD)({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 Qd.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}setupElicitationHandler(){this.client.setRequestHandler(nh.$9,(e=>oh(this,void 0,void 0,(function*(){if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=yield this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:e.params.requestedSchema});return{action:t.action,content:t.content}}catch(e){return{action:"decline"}}}))))}static fromStreamableHttp(e,t,r,n,o,i,s,a){return oh(this,void 0,void 0,(function*(){const l=new URL(t.url);o=null!=o?o:Kd;const c=yield r.loadTokens(),u=yield uh({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,Sd.jI)({fetch:d,logger:s.logger,metadata:Object.assign(Object.assign({},s.metadata),{transportType:e})}),p=fh.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 fh(e,p,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:s,callback:t=>oh(this,void 0,void 0,(function*(){try{if(!u.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");yield(0,Xd.j2)(u,Object.assign({serverUrl:l.toString(),authorizationCode:t},void 0!==d?{fetchFn:d}:{})),a&&(0,Sd.VD)({logger:a,event:"mcp_oauth_callback_completion",metadata:Object.assign(Object.assign({identifier:e},(0,Sd.q2)(l.toString())),(0,Sd.tB)(u.tokens(),{expiresInIsFresh:!0}))}),c.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}))},authProvider:u,sessionId:r,config:t});return c},m=()=>oh(this,void 0,void 0,(function*(){const r=new eh.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 fh(e,p,{initialState:{kind:"ready"},authProvider:u,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof Xd.D_)return a&&(0,Sd.VD)({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,Sd.q2)(l.toString())),(0,Sd.X5)(t))}),f();throw t}}));if("sse"===t.type)return m();const g=new rh.j(l,{authProvider:u,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=n?n:{})},fetch:h("streamableHttp")});try{return yield p.connect(g),new fh(e,p,{initialState:{kind:"ready"},authProvider:u,sessionId:g.sessionId,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof Xd.D_)return a&&(0,Sd.VD)({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,Sd.q2)(l.toString())),(0,Sd.X5)(t))}),f(g.sessionId);if((0,Sd.PK)(t))return m();throw t}}))}static fromCachedSession(e,t,r,n,o){return oh(this,arguments,void 0,(function*(e,t,r,n,o,i=Kd,s,a,l){const c=new URL(t.url),u=yield uh({serverName:e,config:t,tokenStorage:n,authRedirectUrl:i}),d=null!=s?s:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=new rh.j(c,{authProvider:u,sessionId:r.sessionId,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:void 0!==d&&void 0!==a?(0,Sd.jI)({fetch:d,logger:a.logger,metadata:Object.assign(Object.assign({},a.metadata),{transportType:"streamableHttp"})}):d}),p=fh.createClient();return yield p.connect(h),new fh(e,p,{initialState:{kind:"ready"},authProvider:u,sessionId:h.sessionId,config:t,oauthLifecycleLogger:l})}))}get sessionId(){return this._sessionId}static fromCommand(e,t,r,n,o){return oh(this,void 0,void 0,(function*(){var i,s,a;const l={stack:[],error:void 0,hasError:!1};try{ih(l,(0,c.VI)(e.withName("McpSdkClient.fromCommand")),!1);const d=new th.oQ(Object.assign({command:r.command,args:null!==(i=r.args)&&void 0!==i?i:[],env:n,cwd:r.cwd,stderr:"ignore"},(null==o?void 0:o.spawn)&&{spawn:o.spawn})),h=fh.createClient(),p=h.connect(d),f=null!==(s=null==o?void 0:o.connectTimeoutMs)&&void 0!==s?s:6e4;let m;const g=new Promise(((e,r)=>{m=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{yield Promise.race([p,g])}catch(e){throw p.catch((()=>{})),yield d.close().catch((()=>{})),e}finally{void 0!==m&&clearTimeout(m)}const v=null!==(a=d.pid)&&void 0!==a?a:void 0;return"number"==typeof v&&(u=v,dh.add(u),hh||(hh=!0,process.on("exit",ph))),new fh(t,h,{initialState:{kind:"ready"},config:r,stdioChildPid:v})}catch(e){l.error=e,l.hasError=!0}finally{sh(l)}var u}))}close(){return oh(this,void 0,void 0,(function*(){var e;void 0!==this._stdioChildPid&&(e=this._stdioChildPid,dh.delete(e)),yield this.client.close()}))}getTools(e){return oh(this,void 0,void 0,(function*(){var t,r,n;const o={stack:[],error:void 0,hasError:!1};try{if(ih(o,(0,c.VI)(e.withName("McpSdkClient.getTools")),!1),"requires_authentication"===this.stateValue.kind)return[];try{return yield this.tools.get((()=>oh(this,void 0,void 0,(function*(){let e;const t=[];for(;;){const r=yield this.client.listTools({cursor:e});if(t.push(...r.tools.map((e=>Object.assign(Object.assign({},e),{inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),e=r.nextCursor,void 0===e)break}return t}))))}catch(e){if(e instanceof Xd.D_&&"ready"===this.stateValue.kind){const o=this.stateValue,i=null!==(n=null===(r=null===(t=this._authProvider)||void 0===t?void 0:t.lastRedirectUrl)||void 0===r?void 0:r.toString())&&void 0!==n?n:"";this.stateValue={kind:"requires_authentication",url:i,callback:e=>oh(this,void 0,void 0,(function*(){}))},this._logStateTransition(o,this.stateValue,"runtime_unauthorized",Object.assign({},(0,Sd.X5)(e))),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){o.error=e,o.hasError=!0}finally{sh(o)}}))}callTool(e,t,r,n,o){return oh(this,void 0,void 0,(function*(){var i,s,a;const l={stack:[],error:void 0,hasError:!1};try{ih(l,(0,c.VI)(e.withName("McpSdkClient.callTool")),!1).span.setAttribute("toolName",t);const u=this._callToolLock;let d;this._callToolLock=new Promise((e=>{d=e}));try{yield u,this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;try{const e=yield this.client.callTool({name:t,arguments:r});return{content:e.content,isError:void 0!==e.error}}catch(e){if(e instanceof Xd.D_&&"ready"===this.stateValue.kind){const t=this.stateValue,r=null!==(a=null===(s=null===(i=this._authProvider)||void 0===i?void 0:i.lastRedirectUrl)||void 0===s?void 0:s.toString())&&void 0!==a?a:"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>oh(this,void 0,void 0,(function*(){}))},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",Object.assign({},(0,Sd.X5)(e))),this._stateEnteredAtMs=Date.now()}throw e}finally{this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{d()}}catch(e){l.error=e,l.hasError=!0}finally{sh(l)}}))}getInstructions(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(ih(t,(0,c.VI)(e.withName("McpSdkClient.getInstructions")),!1),"requires_authentication"===this.stateValue.kind)return;return yield this.client.getInstructions()}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}listResources(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{if(ih(t,(0,c.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();if(!(null==r?void 0:r.resources))return{resources:[]};let n;const o=[];for(;;){const e=yield this.client.listResources({cursor:n});if(o.push(...e.resources),n=e.nextCursor,void 0===n)break}return{resources:o}}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}readResource(e,t){return oh(this,void 0,void 0,(function*(){const r={stack:[],error:void 0,hasError:!1};try{return ih(r,(0,c.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(yield this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}))}listPrompts(e){return oh(this,void 0,void 0,(function*(){var t;const r={stack:[],error:void 0,hasError:!1};try{if(ih(r,(0,c.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind)return[];if(!(null!==(t=this.client.getServerCapabilities())&&void 0!==t?t:{prompts:!1}).prompts)return[];const n=yield this.client.listPrompts();return(null==n?void 0:n.prompts)?n.prompts.map((e=>{var t;return{name:e.name,description:e.description,arguments:null===(t=e.arguments)||void 0===t?void 0:t.map((e=>({name:e.name,description:e.description,required:e.required})))}})):[]}catch(e){r.error=e,r.hasError=!0}finally{sh(r)}}))}getPrompt(e,t,r){return oh(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{return ih(n,(0,c.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(yield this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{sh(n)}}))}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}getState(e){return oh(this,void 0,void 0,(function*(){return this.stateValue}))}updateState(e,t){const r=this.stateValue;this.stateValue=e,this._logStateTransition(r,e,null!=t?t:"explicit_update"),this._stateEnteredAtMs=Date.now()}}class mh extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}class gh 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 vh{constructor(e){this.tools=e}execute(e,t,r,n){return oh(this,void 0,void 0,(function*(){const o=this.tools[e];if(!o)throw new mh(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 yh{getClients(e){return oh(this,void 0,void 0,(function*(){return{}}))}getClient(e,t){return oh(this,void 0,void 0,(function*(){}))}getInstructions(e){return oh(this,void 0,void 0,(function*(){return[]}))}getToolSet(e){return oh(this,void 0,void 0,(function*(){return new vh({})}))}getTools(e){return oh(this,void 0,void 0,(function*(){return[]}))}getToolsForServers(e,t){return oh(this,void 0,void 0,(function*(){return[]}))}}class wh{constructor(e){this.manager=e}getClients(e){return oh(this,void 0,void 0,(function*(){return this.manager.getClients()}))}getClient(e,t){return oh(this,void 0,void 0,(function*(){return this.manager.getClient(t)}))}getInstructions(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=ih(t,(0,c.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return yield this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}getToolSet(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=ih(t,(0,c.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return yield this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}getTools(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=ih(t,(0,c.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(yield this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}getToolsForServers(e,t){return oh(this,void 0,void 0,(function*(){const r=new Set(t);return(yield this.getTools(e)).filter((e=>r.has(e.clientKey)))}))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}reconcileSelection(e,t,r){return oh(this,void 0,void 0,(function*(){var n;for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{yield null===(n=null==t?void 0:t.close)||void 0===n?void 0:n.call(t)}catch(e){}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=yield r(e,n);this.manager.setClient(n,t)}}))}}class bh{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}closeAllClients(){return oh(this,void 0,void 0,(function*(){const e=Object.values(this.clients);yield Promise.all(e.map((e=>oh(this,void 0,void 0,(function*(){var t;try{yield null===(t=e.close)||void 0===t?void 0:t.call(e)}catch(e){}})))))}))}getToolSet(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=ih(t,(0,c.VI)(e.withName("McpManager.getToolSet")),!1),n=yield(0,Hs.PH)(Object.entries(this.clients),(([e,t])=>t.getTools(r.ctx).then((r=>r.map((r=>Object.assign(Object.assign({},r),{clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:4}),o=Array.from(n.values()).flat(),i={};for(const e of o)i[`${e.clientName}-${e.name}`]={definition:Object.assign(Object.assign({},e),{clientKey:e.clientKey,providerIdentifier:e.clientName,toolName:e.name}),execute:(t,n,o)=>oh(this,void 0,void 0,(function*(){const i=null==o?void 0:o.createProvider(e.clientName,e.name,n);return yield e.client.callTool(r.ctx,e.name,t,n,i)}))};return new vh(i)}catch(e){t.error=e,t.hasError=!0}finally{sh(t)}}))}getInstructions(e){return oh(this,void 0,void 0,(function*(){const t={stack:[],error:void 0,hasError:!1};try{const r=ih(t,(0,c.VI)(e.withName("McpManager.getInstructions")),!1),n=yield(0,Hs.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new rr.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{sh(t)}}))}}Error;var Sh=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 kh(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 Eh{constructor(e){this.options=e,(0,Sd.VD)({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,Sd.q2)(this.options.serverUrl)}:{})}loadTokens(){return Sh(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadTokens();return(0,Sd.VD)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Sd.tB)(e))}),e}))}saveTokens(e){return Sh(this,void 0,void 0,(function*(){yield this.options.inner.saveTokens(e),(0,Sd.VD)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Sd.tB)(e,{expiresInIsFresh:!0}))})}))}prepareForRefresh(){return Sh(this,void 0,void 0,(function*(){var e,t;(0,Sd.VD)({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 Sh(this,void 0,void 0,(function*(){var t,r;(0,Sd.VD)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Sd.X5)(e))}),yield null===(r=(t=this.options.inner).releaseRefreshLeaseOnError)||void 0===r?void 0:r.call(t,e)}))}loadClientInformation(){return Sh(this,void 0,void 0,(function*(){const e=yield this.options.inner.loadClientInformation();return(0,Sd.VD)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Sd.O3)(e))}),e}))}saveClientInformation(e){return Sh(this,void 0,void 0,(function*(){yield this.options.inner.saveClientInformation(e),(0,Sd.VD)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,Sd.O3)(e))})}))}invalidateCredentials(e){return Sh(this,void 0,void 0,(function*(){void 0!==this.options.inner.invalidateCredentials&&((0,Sd.VD)({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:Object.assign(Object.assign({},this.baseMetadata),{scope:e})}),yield this.options.inner.invalidateCredentials(e))}))}}class xh{constructor(e,t){this.storage=e,this.identifier=t}loadTokens(){return Sh(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.identifier)}))}saveTokens(e){return Sh(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.identifier,e)}))}loadClientInformation(){return Sh(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.identifier)}))}saveClientInformation(e){return Sh(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.identifier,e)}))}}class Ch{constructor(e){this.inner=e}loadTokens(){return Sh(this,void 0,void 0,(function*(){}))}loadClientInformation(){return Sh(this,void 0,void 0,(function*(){}))}saveTokens(e){return Sh(this,void 0,void 0,(function*(){return this.inner.saveTokens(e)}))}saveClientInformation(e){return Sh(this,void 0,void 0,(function*(){return this.inner.saveClientInformation(e)}))}invalidateCredentials(e){return Sh(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 _h=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())}))},Ph=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},Th=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 Ih=(0,h.h)("DefinitionMcpLoader");function Rh(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?a.join(s.homedir(),t.slice(1)):t.startsWith("./")||"."===t?a.resolve(null!=r?r:process.cwd(),t):t}function Ah(e){return"function"==typeof e.getMcpNetworkControlsConfig}function Oh(e){var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0}function jh(e){if(void 0!==e)return(0,o.createHash)("sha256").update((0,Sd.Fm)(e)).digest("hex")}class Mh{constructor(e){this.configPath=e,this.configPromise=Hd(e)}clearCache(){this.configPromise=Hd(this.configPath)}getDefinitions(e){return _h(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 Dh{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}load(e){return _h(this,arguments,void 0,(function*(e,t=!0){var r,n,o;const i={stack:[],error:void 0,hasError:!1};try{Ph(i,(0,c.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(yield this.closeAllCachedClients(),null===(n=(r=this.source).clearCache)||void 0===n||n.call(r));const s=yield this.source.getDefinitions(e,t);yield this.evictClientsOnSandboxPolicyChange(e,s);const a={};return yield(0,Hs.PH)([...s],(r=>_h(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){Ih.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}(e,r,t)}}))),{max:null!==(o=this.options.maxConcurrency)&&void 0!==o?o:Math.max(s.length,1)}),new bh(a,this.options.elicitationFactory)}catch(e){i.error=e,i.hasError=!0}finally{Th(i)}}))}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}evictClientsOnSandboxPolicyChange(e,t){return _h(this,void 0,void 0,(function*(){const r=this.middlewares.find(Ah);if(!r)return;let n;try{n=JSON.stringify(yield Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((e=>_h(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,Sd.Fm)(o)]}))))))}catch(e){return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(Ih.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),yield this.closeAllCachedClients())}))}closeAllCachedClients(){return _h(this,void 0,void 0,(function*(){const e=[...this.clientCache.values()];this.clientCache.clear(),yield(0,Hs.PH)(e,(e=>_h(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 _h(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{Ph(n,(0,c.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=yield this.source.getDefinitions(e);if(yield this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const i=o.find((e=>e.identifier===t));if(!i)throw new Error(`MCP server "${t}" not found in config`);let s;try{s=yield this.loadDefinitionClient(e,i,r)}catch(t){throw this.handleDefinitionLoadError(e,i,t),t}return r||this.clientCache.set(t,s),s}catch(e){n.error=e,n.hasError=!0}finally{Th(n)}}))}loadDefinitionClient(e,t,n){return _h(this,void 0,void 0,(function*(){var o,i;const s=null!==(o=t.authStorageKey)&&void 0!==o?o:t.identifier,a=new xh(this.tokenStorage,s),l=kh(e,Ih),u=new Eh({inner:a,logger:l,identifier:s,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),d=n?new Ch(u):u;return function(e,t,n,o){return _h(this,arguments,void 0,(function*(e,t,n,o,i={middlewares:[],configPath:""},s){const a={stack:[],error:void 0,hasError:!1};try{const{middlewares:l,configPath:u}=i,d=Ph(a,(0,c.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let h=(e,n)=>_h(this,void 0,void 0,(function*(){const i={stack:[],error:void 0,hasError:!1};try{const a=Ph(i,(0,c.VI)(e.withName("loadServer.next")),!1);a.span.setAttribute("serverName",t);const u=a.ctx;if("command"in n){a.span.setAttribute("kind","command");const e=l.find(Ah);return yield function(e,t,n,o){return _h(this,void 0,void 0,(function*(){var i,s,a;const l=n.cwd?Rh({filePath:n.cwd}):void 0;let c,u;if(n.args&&n.args.length>0)c=Rh({filePath:n.command,baseDir:l}),u=n.args.map((e=>Rh({filePath:e,baseDir:l})));else{const e=(0,qd.A)(n.command);c=Rh({filePath:e[0],baseDir:l}),u=e.slice(1).map((e=>Rh({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,Sd.$H)(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);Ih.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=${Oh(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${Oh(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${Oh(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist)}, sandboxPolicyHash=${null!==(a=jh(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:Oh(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist),mcpNetworkDenylistCount:Oh(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist),localAgentNetworkAllowlistCount:Oh(null===(i=e.networkControlsConfig)||void 0===i?void 0:i.localAgentNetworkAllowlist),sandboxPolicyHash:jh(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:p}));try{return yield fh.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 Sd.c8(t,e);throw e}}return!0===(null==h?void 0:h.enabled)&&"no_sandbox"===h.mcpNetworkMode&&Ih.info(e,`Starting local MCP server "${t}" without MCP sandboxing`),fh.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 _h(this,void 0,void 0,(function*(){const i=kh(e,Ih),s=function(e,t){return{logger:{debug:(t,r)=>Ih.debug(e,t,r),info:(t,r)=>Ih.info(e,t,r),warn:(t,r)=>Ih.warn(e,t,r),error:(t,r,n)=>Ih.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t);return fh.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{Th(i)}}));for(const e of l){const r=h;h=(n,o)=>_h(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{Th(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){Ih.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return i||function(e){return e instanceof xd||e instanceof Cd||e instanceof Nh}(r)}}class Nh 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 $h{constructor(e){this.blockingService=e}getMcpNetworkControlsConfig(e){return _h(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 _h(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 Nh(t,null!==(l=u.reason)&&void 0!==l?l:"teamPolicy",u.message);return o(e,r)}))}}class Lh extends Dh{constructor(e,t,r=[],n,o){super(new Mh(e),t,r,{authRedirectUrlGenerator:n,elicitationFactory:o}),this.configPath=e,this.elicitationFactory=o}static init(e,t,r=[]){return new Lh(t,e,r)}}function Fh(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 Uh=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 Bh{constructor(e){this.mcpAuthPath=e;const t=Bh.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,Bh.mcpAuthPromises.set(e,t),t.catch((()=>{Bh.mcpAuthPromises.get(e)===t&&Bh.mcpAuthPromises.delete(e)}))}Bh.saveLocks.has(e)||Bh.saveLocks.set(e,Promise.resolve())}loadMcpAuth(){return Uh(this,void 0,void 0,(function*(){try{const e=yield(0,Hn.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 Uh(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 Uh(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>Uh(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 Uh(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 Uh(this,void 0,void 0,(function*(){var t;const r=null!==(t=Bh.saveLocks.get(this.mcpAuthPath))&&void 0!==t?t:Promise.resolve();let n;Bh.saveLocks.set(this.mcpAuthPath,new Promise((e=>{n=e})));try{return yield r,yield e()}finally{n()}}))}saveClientInformation(e,t){return Uh(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>Uh(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 Uh(this,void 0,void 0,(function*(){yield this.withSaveLock((()=>Uh(this,void 0,void 0,(function*(){const t=yield this.mcpAuthPromise;e in t&&(delete t[e],yield this.saveMcpAuth(t))}))))}))}saveMcpAuth(e){return Uh(this,void 0,void 0,(function*(){yield(0,Hn.mkdir)(a.dirname(this.mcpAuthPath),{recursive:!0}),yield(0,Hn.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}))}}Bh.mcpAuthPromises=new Map,Bh.saveLocks=new Map;var zh=r("../proto/dist/generated/agent/v1/utils_pb.js");let Wh;function Hh(){if(void 0===Wh){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 Wh===e&&(Wh=void 0),t}));Wh=e}return Wh}const qh=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},Gh=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Vh=e=>qh().encode(e);var Jh=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 Kh=1048576,Zh=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Yh=(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}},Xh=e=>Jh(void 0,void 0,void 0,(function*(){if(Gh(e))return(e=>Jh(void 0,void 0,void 0,(function*(){const t=(e=>{if(!Gh(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&&!Yh(t.width,t.height,1280).needsResize&&e.length<=Kh)return{data:Zh(e),mimeType:"image/webp"};const r=yield(n=e,qh().decode(n));var n;const o=(yield Hh()).fromBitmap({data:Buffer.from(r.data),width:r.width,height:r.height});let{width:i,height:s,needsResize:a}=Yh(o.bitmap.width,o.bitmap.height,1280);a&&o.resize({w:i,h:s});let l=yield Vh({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});for(;l.length>Kh&&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 Vh({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});return{data:Zh(l),mimeType:"image/webp"}})))(e);const t=yield Hh(),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}=Yh(r.width,r.height);if(!s&&e.length<=Kh)return{data:Zh(e),mimeType:n};let a=o,l=i;s&&r.resize({w:a,h:l});let c=yield r.getBuffer(n);for(;c.length>Kh&&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:Zh(c),mimeType:n}}));var Qh=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},ep=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const tp=(0,p.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),rp=(0,p.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),np=(0,p.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),op=(0,p.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),ip=(0,p.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),sp=(0,p.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),ap=(0,h.h)("McpFileSystemWriter"),lp="mcpFsStructuredLogOptIn";function cp(e,t){return t?.includeStructuredLogs?{...e??{},[lp]:!0}:e}const up={debug(e,t,r,n){ap.debug(e,t,cp(r,n))},info(e,t,r,n){ap.info(e,t,cp(r,n))},warn(e,t,r,n){ap.warn(e,t,cp(r,n))},error(e,t,r,n,o){ap.error(e,t,r,cp(n,o))}},dp="mcps",hp="tools",pp="~staging",fp="~prev",mp="mcp_auth",gp="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.",vp="# >>> CURSOR MANAGED BLOCK >>>",yp="# <<< CURSOR MANAGED BLOCK <<<",wp=["# 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 bp(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function Sp(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function kp(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function Ep(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function xp(e){if(Array.isArray(e))return e.map((e=>xp(e)));if(null!==e&&"object"==typeof e){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>e<t?-1:e>t?1:0)).map((([e,t])=>[e,xp(t)]));return Object.fromEntries(t)}return e}function Cp(e){return JSON.stringify(xp(e))}function _p(e){const t=e.map((e=>({value:e,key:Cp(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function Pp(e){const t=_p(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=_p(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=_p(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return Cp({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 Tp{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=>{up.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),up.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,a.join)(e,".gitignore"),r=`${vp}\n${wp}\n${yp}\n`;let n;await(0,Hn.mkdir)(e,{recursive:!0});try{n=await(0,Hn.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==e?.code)throw e}if(void 0===n)return void await(0,Hn.writeFile)(t,r);const o=n.indexOf(vp),i=n.indexOf(yp,o+30);if(-1===o||-1===i)await(0,Hn.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Hn.writeFile)(t,e)}})((0,a.join)((0,s.homedir)(),".cursor")).catch((e=>{up.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,a.join)(this.projectDir,dp);try{const e=await(0,Hn.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(pp))).map((e=>(0,Hn.rm)((0,a.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==e?.code&&up.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:nt(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:nt(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){up.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,Ye.q6)();return e&&(t=t.with(h._O,e)),t}getLogContext(e){return e.with(h._O,this.ctx.get(h._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return kp(this.mcpAuthCopyOverrides?.authToolDescription)??gp}shouldExposeVirtualMcpAuthToolForStatus(e){return this.exposeVirtualMcpAuthTool&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===e)}getErrorStatusMessage(){return kp(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 Settings; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=kp(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, do that first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:mp},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool?this.getNeedsAuthStatusMessage(e):kp(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Add 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){up.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${n}`);const o=await this.mcpLease.getTools(e).catch((e=>(up.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 up.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 bp(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||up.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?bp(r.getTools(e),[]).then((e=>(0===e.length&&up.info(o,`Direct client getTools() returned 0 tools for "${t}" (state=${i.kind})`),e))):Promise.resolve([]),s?bp(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?bp(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?bp(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:Ep(i)}}buildServerDataMap(e,t,r,n,o){const i=new Map(r.map((e=>[e.clientKey,e.clientTools]))),s=new Map;for(const e of r){const t=Dp(e.clientKey);s.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,a.join)(this.projectDir,dp,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const e of t){let t=s.get(e.clientKey);if(!t){const r=Dp(e.clientKey);t={serverIdentifier:e.clientKey,serverName:e.providerIdentifier,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:r,folderPath:(0,a.join)(this.projectDir,dp,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},s.set(e.clientKey,t)}t.tools.push(e)}for(const[t,r]of s)if(0===r.tools.length){const o=i.get(t);if(o&&o.length>0){const i=n?.[t],s=void 0!==i?o.filter((e=>i.includes(e.toolName))):o;if(void 0!==i&&0===s.length){up.info(e,`Skipping direct client tool fallback for "${t}": settings report 0 enabled tools`);continue}up.info(e,`Using direct client tool fallback for "${t}": lease had 0 tools, client has ${o.length}, writing ${s.length}`),r.tools=s}}if(void 0!==o)for(const e of o){const t=e.serverIdentifier?.trim();let r=t?Array.from(s.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(s.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of s.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.status)&&(e.tools.some((e=>e.toolName===mp))||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:mp,name:mp,description:l.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var l;return s}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,i="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||i?n.has(o.sanitizedId)?up.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):up.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.status)&&!r.some((e=>e.toolName===mp))){const t=e.tools.find((e=>e.toolName===mp));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??[])];up.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=>(up.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 up.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=>{up.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):up.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)),up.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=Dp(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{Qh(r,(0,c.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!nt(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=>(up.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(up.warn(n,`getClients() threw, defaulting to {}: ${e}`),{}))),this.getEnabledToolsByServer(e)]),a=Object.keys(i);up.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){up.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{ep(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,a.join)(e.folderPath,hp,`${Sp(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Qh(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,a.join)(this.projectDir,dp);await(0,Hn.mkdir)(i,{recursive:!0});const s=new Map;for(const e of t)try{s.set(e.serverIdentifier,Pp(e))}catch(t){up.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),s.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==s.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&up.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,Hn.stat)((0,a.join)(i,e.sanitizedId))}catch{up.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!s.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Dp(e);r.has(n)?(up.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),s.set(e,this.cachedFingerprints.get(e))):(up.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,Hn.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(pp)&&!e.endsWith(fp))));for(const r of e)if(r.endsWith(pp))await(0,Hn.rm)((0,a.join)(i,r),{recursive:!0,force:!0});else if(r.endsWith(fp)){const e=r.slice(0,-5);if(t.has(e))await(0,Hn.rm)((0,a.join)(i,r),{recursive:!0,force:!0});else try{await(0,Hn.rename)((0,a.join)(i,r),(0,a.join)(i,e)),t.add(e)}catch{await(0,Hn.rm)((0,a.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);s.has(t)||s.set(t,`__preserved_${e}`)}else u.add(e)}catch(e){up.error(o,"Error clearing mcps directory",e)}const d=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));up.info(o,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-l.length,totalServerCount:t.length},{includeStructuredLogs:!0})}const h=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t<l.length;t++){const r=h[t];if("rejected"===r.status){const n=l[t],o=this.cachedFingerprints.get(n.serverIdentifier);void 0!==o?s.set(n.serverIdentifier,o):s.delete(n.serverIdentifier),up.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,Hn.rm)((0,a.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r<p.length;r++){const n=p[r];if("rejected"===n.status){const o=d[r];up.error(e,"Error removing server directory",n.reason,{sanitizedId:o,removalIndex:r,removalAttemptCount:p.length,removedServerCount:d.length,removedServerSanitizedIds:d,changedServerCount:l.length,unchangedServerCount:t.length-l.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=s}catch(e){n.error=e,n.hasError=!0}finally{ep(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Qh(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=`${t.sanitizedId}${pp}`,i=`${t.sanitizedId}${fp}`,s=(0,a.join)(r,o),l=(0,a.join)(r,i),u=(0,a.join)(r,t.sanitizedId);await(0,Hn.rm)(s,{recursive:!0,force:!0});try{await(0,Hn.rename)(l,u)}catch{await(0,Hn.rm)(l,{recursive:!0,force:!0})}await this.writeServerDirectory(e,t,{basePath:r,dirName:o});try{try{await(0,Hn.rename)(u,l)}catch{}await(0,Hn.rename)(s,u)}catch(r){up.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0});try{await(0,Hn.rename)(l,u)}catch{}throw await(0,Hn.rm)(s,{recursive:!0,force:!0}),r}await(0,Hn.rm)(l,{recursive:!0,force:!0}).catch((()=>{}))}catch(e){n.error=e,n.hasError=!0}finally{ep(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Qh(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,a.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,Hn.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,a.join)(o,hp);await(0,Hn.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=Sp(r.toolName),n=(0,a.join)(e,`${t}.json`),o=tt(r);await(0,Hn.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,a.join)(o,"resources");await(0,Hn.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=Sp(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,a.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,Hn.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,a.join)(o,"prompts");await(0,Hn.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=Sp(r.name),n=(0,a.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,Hn.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,a.join)(o,"INSTRUCTIONS.md");await(0,Hn.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,a.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,Hn.writeFile)(e,r)}const i=(0,a.join)(o,"SERVER_METADATA.json"),s={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,Hn.writeFile)(i,JSON.stringify(s,null,2))}catch(e){n.error=e,n.hasError=!0}finally{ep(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;Qh(r,(0,c.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&up.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=Sp(t.toolName),n=(0,a.join)(e.folderPath,hp,`${r}.json`);return new rr.E$({toolName:t.toolName,definitionPath:n})}));return new rr.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 rr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{ep(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&&up.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){up.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&up.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){up.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{Qh(t,(0,c.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,a.join)(this.projectDir,dp),s=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Dp(e.serverIdentifier),r=(0,a.join)(i,t),n=e.tools.map((e=>{const t=Sp(e.name);return new rr.E$({toolName:e.name,definitionPath:(0,a.join)(r,hp,`${t}.json`)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.status)&&!e.tools.some((e=>e.name===mp))){const e=Sp(mp);n.push(new rr.E$({toolName:mp,definitionPath:(0,a.join)(r,hp,`${e}.json`)}))}return new rr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),l=s.reduce(((e,t)=>e+t.tools.length),0);return up.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${s.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,s,"snapshot"),new rr.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:s})}catch(e){t.error=e,t.hasError=!0}finally{ep(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<Tp.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{up.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,a.join)(this.projectDir,dp),i=new Set,s=new Map;for(const e of t){const t=Dp(e.serverIdentifier);i.add(t),s.set(t,e.tools.length)}let l=[];try{l=await(0,Hn.readdir)(o),l=l.filter((e=>!e.endsWith(pp)&&!e.endsWith(fp)))}catch(e){if("ENOENT"!==e?.code)throw e}const c=new Set(l);let u=!0,d=0,h=0,p=0;const f=0===(m=i.size)?"0":m<=3?"1-3":m<=6?"4-6":m<=10?"7-10":"11+";var m;for(const t of i)c.has(t)||(u=!1,d++,tp.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),up.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of c)i.has(t)||(u=!1,h++,tp.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!c.has(t))continue;const l=s.get(t)??0,d=(0,a.join)(o,t,hp);let h=0;try{h=(await(0,Hn.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==l&&(u=!1,p++,tp.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),up.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:l,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}rp.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),np.gauge(e,i.size,this.getMetricTags({mcp_source:r})),op.gauge(e,c.size,this.getMetricTags({mcp_source:r})),ip.gauge(e,d,this.getMetricTags({mcp_source:r})),sp.gauge(e,p,this.getMetricTags({mcp_source:r})),up.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||up.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())}}Tp.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var Ip=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Rp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ap=(0,h.h)("local-exec:mcp");function Op(e,t){const r=a.relative(e,t);return""===r||!a.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${a.sep}`)}function jp(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function Mp(e){return new St._Z({content:{case:"text",value:new St.zN({text:e})}})}function Dp(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 Np(e,t,r){const n=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t);if(n)return await go(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new St.iz({result:{case:"error",value:new St.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:rd.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 St.iz({result:{case:"approved",value:new St.Ke}}):null:new St.iz({result:{case:"rejected",value:new St.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new St.iz({result:{case:"error",value:new St.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new St.iz({result:{case:"permissionDenied",value:new St.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}})??void 0}class $p{constructor(e,t,r,n,o=4e4,i,s){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=i,this.ensureMcpServersLoaded=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Ip(r,(0,c.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(n,[i]));const s=await this.toolSet.getTools(n),l=Array.from(new Set(s.map((e=>e.clientKey)))).sort(),u=s.find((e=>e.providerIdentifier===t.providerIdentifier&&e.toolName===t.toolName)),d=await Np(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 mh&&t.providerIdentifier.length>0&&!s.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new gh(t.providerIdentifier,l)),r instanceof gh)return new St.iz({result:{case:"serverNotFound",value:new St.JL({name:r.serverName,availableServers:r.availableServers})}});if(r instanceof mh)return new St.iz({result:{case:"toolNotFound",value:new St.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(Mp(t.text))}else if("resource"===t){const t=e;t.resource?.text&&f.push(Mp(t.resource.text))}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),n=await Xh(r);f.push(new St._Z({content:{case:"image",value:new St.do({data:n.data,mimeType:n.mimeType})}}))}else if("image"!==t){const t=Dd(e);f.push(Mp(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 St._Z({content:{case:"text",value:new St.zN({text:"",outputLocation:o})}})),s=!0):i.push(t);return i},new((n=void 0)||(n=Promise))((function(e,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(s,a)}l((o=o.apply(t,r||[])).next())}));var t,r,n,o}({contentItems:f,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=a.join(t,wd),n=a.join(r,`${(0,o.randomUUID)()}.txt`);await(0,Hn.mkdir)(a.dirname(n),{recursive:!0});const i=e.slice(0,bd),s=i.split("\n").length,l=Buffer.byteLength(i,"utf8");return await(0,Hn.writeFile)(n,i,"utf8"),new zh.pV({filePath:n,sizeBytes:BigInt(l),lineCount:BigInt(s)})}(e,this.projectDir)});if(void 0===m)throw new Error("Failed to materialize MCP text output");const g=p.structuredContent&&"object"==typeof p.structuredContent&&!Array.isArray(p.structuredContent)?nr.Struct.fromJson(p.structuredContent):void 0,v=new St.QW({content:m,isError:p.isError,structuredContent:g});return new St.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{Rp(r)}}}class Lp{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Ip(r,(0,c.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new St.kP({result:{case:"error",value:new St.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new St.kP({result:{case:"success",value:new St.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 St.kP({result:{case:"success",value:new St.T2({resources:i})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new St.kP({result:{case:"error",value:new St.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{Rp(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 St.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class Fp{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(Xe),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=Ip(r,(0,c.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new St.ZD({result:{case:"error",value:new St.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:rd.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:nr.Value.fromJson(t.server),uri:nr.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:nr.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new St.ZD({result:{case:"rejected",value:new St.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),s=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!s)return new St.ZD({result:{case:"error",value:new St.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await s.getState(n)).kind)return new St.ZD({result:{case:"error",value:new St.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await s.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new St.ZD({result:{case:"notFound",value:new St.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=a.resolve(e),n=await(0,Hn.realpath)(r),o=a.resolve(r,t.replace(/^\/+/,""));if(!Op(r,o))throw new Error("downloadPath must stay within the workspace");let i=a.dirname(o);for(;;)try{if(!Op(n,await(0,Hn.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==jp(e))throw e;const t=a.dirname(i);if(t===i)throw e;i=t}if(await(0,Hn.mkdir)(a.dirname(o),{recursive:!0}),!Op(n,await(0,Hn.realpath)(a.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,Hn.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==jp(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,Hn.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,Hn.writeFile)(e,t)}return new St.ZD({result:{case:"success",value:new St.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType})}})}if(r.text)return new St.ZD({result:{case:"success",value:new St.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 St.ZD({result:{case:"success",value:new St.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"blob",value:e}})}})}return new St.ZD({result:{case:"error",value:new St.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return Ap.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new St.ZD({result:{case:"error",value:new St.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{Rp(r)}}}async function Up(e,t){const r=Dp(t),n=(0,a.join)(e,"mcps",r,"tools");let o;try{o=await(0,Hn.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,Hn.readFile)((0,a.join)(n,e),"utf8"))}catch{return}}))),s=new Set;for(const e of i)e&&s.add(e);return{toolNames:Array.from(s).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Bp=(0,h.h)("local-exec:mcp-disk-freshness-on-access"),zp="/mcps/",Wp=(0,p.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Hp=(0,p.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),qp=(0,p.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Gp=(0,p.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),Vp=new Map;function Jp(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Kp({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 Bp.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=s.servers.find((e=>Dp(e.serverIdentifier)===n));if(void 0===a)return;let l;try{l=await o(r,a.serverIdentifier)}catch(t){return void Bp.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"};Wp.increment(e,1,{...c,outcome:l}),Hp.histogram(e,s.length,c),qp.histogram(e,a.length,c),Gp.histogram(e,s.length+a.length,c),"mismatch"===l&&Bp.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 Zp(e,t,r,n=Up){if(void 0===r||(void 0===(o=r)||!Jp(o).includes(zp)))return;var o;const i=function(e){const t=Jp(e),r=t.indexOf(zp);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=Vp.get(s);void 0!==c&&clearTimeout(c);const u=e,d=setTimeout((()=>{Vp.delete(s),(async()=>{if(l){const e=await t.getState(u);for(const r of e.servers){const o=Dp(r.serverIdentifier);await Kp({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Kp({ctx:u,mcpStateAccessor:t,projectDir:i.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Bp.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);Vp.set(s,d)}var Yp=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},Xp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Qp(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}function ef(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Vn.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,a.resolve)(e,t),r);return void 0===n||n===e}const tf=(0,h.h)("local-exec/grep");function rf(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function nf(e){try{return(0,i.existsSync)(e)}catch{return"check_failed"}}function of(e,t,r,n){return{...af(e),...n,cwd:t,cwdExists:nf(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function sf(e){return new Error(`Path does not exist: ${e}`)}function af(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,i.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,i.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,a.dirname)(e);try{t.parentDirExists=(0,i.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,i.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,a.dirname)(r);try{t.grandparentDirExists=(0,i.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,i.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,i.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const e=r.concat("node_modules.asar");try{t.asarExists=(0,i.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,i.existsSync)(n),t.asarUnpackedDirExists){const e=(0,a.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,i.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class lf{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,Vn.o1)(e,this.singleWorkspacePath);return r===t?".":(0,a.relative)(t,r)}async buildArgs(e,t,r){const n=[],o=await this.ignoreService.listCursorIgnoreFilesByRoot(e);for(const e of o)n.push("--cursor-ignore",e);if("content"===r)n.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&n.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&n.push("--after-context",String(t.contextAfter)),n.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&n.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)n.push("-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${r}`);n.push("-c","--with-filename")}!0===t.caseInsensitive?n.push("--ignore-case"):n.push("--case-sensitive"),t.type&&n.push("--type",t.type),t.glob&&n.push("--iglob",t.glob),t.multiline&&n.push("--multiline","--multiline-dotall");const i=t.sort??"modified";if("none"!==i){const e=!0===t.sortAscending?"--sort":"--sortr";n.push(e,i)}return n.push("--no-config","--color=never"),n.push("--hidden"),n.push("--follow"),n.push("--regexp",t.pattern),n.push("--"),n.push(t.path?this.computeRelativeTarget(t.path,e):"."),n}async filterBlockedFiles(e,t){const r=[];for(const n of e){const e=await Rc((0,Vn.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=Yp(i,(0,c.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),a=await this.buildArgs(t,r,"files_with_matches"),l=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{files:u,totalFiles:d,clientTruncated:h,ripgrepTruncated:p}=function(e,t,r){const n=e.trim(),o=""!==n?Qp(n):[],i=o.length,s=o.slice(0,t),a=o.length>t;return{files:s,totalFiles:vd(i),clientTruncated:a,ripgrepTruncated:i>=r}}(l.stdout,lf.CLIENT_LIMIT_LINES,lf.HARD_MAX_OUTPUT_LINES),f=[];for(const e of u){const r=await Rc((0,Vn.o1)(e,t));null===r||await this.isPostRipgrepBlocked(r)||f.push(e)}const m=u.length-f.length,g=new fd.T7({files:f,totalFiles:vd(d-m),clientTruncated:h,ripgrepTruncated:p});return new fd.vD({result:{case:"files",value:g}})}catch(e){i.error=e,i.hasError=!0}finally{Xp(i)}}async runCountMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=Yp(i,(0,c.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),a=await this.buildArgs(t,r,"count"),l=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{counts:u,totalFiles:d,totalMatches:h,clientTruncated:p,ripgrepTruncated:f}=function(e,t,r){const n=e.trim(),o=""!==n?Qp(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:vd(s),totalMatches:vd(a),clientTruncated:c,ripgrepTruncated:s>=r}}(l.stdout,lf.CLIENT_LIMIT_LINES,lf.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 fd.xA({counts:m.map((e=>new fd.sS({file:e.file,count:vd(e.count)}))),totalFiles:vd(d-v),totalMatches:vd(h-y),clientTruncated:p,ripgrepTruncated:f});return new fd.vD({result:{case:"count",value:w}})}catch(e){i.error=e,i.hasError=!0}finally{Xp(i)}}async runContentMode(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const s=Yp(i,(0,c.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),a=await this.buildArgs(t,r,"content"),l=await this.executeRg(s.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{byFile:u,totalLines:d,totalMatchedLines:h,clientTruncated:p,ripgrepTruncated:f}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{Yp(o,(0,c.VI)(n.withName("parseContentOutput")),!1);const i=""===e.trim()?[]:Qp(e);i.length>0&&""===i[i.length-1]&&i.pop();const s=new Map,a=new Set;let l=0,u=0;for(const e of i){if(void 0===e)continue;if("--"===e)continue;const[r,n]=e.split("\0",2);if(void 0===r||void 0===n)continue;const o=/^(\d+)([:-])(.*)$/.exec(n);if(!o)continue;const i=o[1],c=o[2],d=o[3]??"",h=parseInt(i,10);if(!Number.isFinite(h))continue;const p="-"===c;if(!1===p&&l++,a.has(r)||a.add(r),u>=t)continue;const f=s.get(r)??{file:r,matches:[]};f.matches.push({lineNumber:h,content:d,isContextLine:p}),s.set(r,f),u++}const d=a.size;return{byFile:s,totalLines:vd(i.length),totalMatchedLines:vd(l),totalFiles:vd(d),clientTruncated:u>=t,ripgrepTruncated:i.length>=r}}catch(e){o.error=e,o.hasError=!0}finally{Xp(o)}}(l.stdout,lf.CLIENT_LIMIT_LINES,lf.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 fd.Zp({matches:g.map((e=>new fd.uI({file:e.file,matches:e.matches.map((e=>new fd.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:vd(d-y),totalMatchedLines:vd(h-w),clientTruncated:p,ripgrepTruncated:f});return new fd.vD({result:{case:"content",value:b}})}catch(e){i.error=e,i.hasError=!0}finally{Xp(i)}}async executeIndexedGrepWithTimeout(e,t,r,n){if(void 0===this.grepProvider.executeIndexedGrep)return;const[o,i]=e.withTimeoutAndCancel(lf.INDEXED_GREP_CONTEXT_TIMEOUT_MS),s={phase:"provider"},a=performance.now();try{return await(0,Hs.wj)(this.grepProvider.executeIndexedGrep(o,t,r,s),lf.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${lf.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Hs.MU)return void tf.warn(e,"indexed_grep.timeout_fallback",{...n,totalMs:Math.round(performance.now()-a),...s});throw t}finally{i()}}async executeRg(e,t,r,n,o,i){const s=(0,c.VI)(e.withName("LocalGrepExecutor.executeRg")),a="utf8",l=8388608;return n=n??lf.HARD_MAX_OUTPUT_LINES,new Promise(((c,u)=>{let d=!1,h=!1;const p=()=>{h||(h=!0,s.span.end())};let f,m;try{const e=o;f=(0,uo.spawnInSandbox)((0,uo.getRipgrepBinaryPath)(),r,{cwd:t},e),0}catch(r){if(p(),rf(r)){const n=r,o=(0,uo.getRipgrepBinaryPath)();if(tf.error(e,"rg_diagnostics.spawn_throw",void 0,of(o,t,n,i)),!1===nf(t))return u(sf(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 ${lf.MAIN_TIMEOUT_MS/1e3}s`)),f.kill()}catch{}}),lf.MAIN_TIMEOUT_MS),f.stdout?.on("data",(e=>{if(y+=e.length,void 0!==n&&!0!==S){let t=-1,r=0;for(let o=0;o<e.length;o++)if(10===e[o]&&(r++,b+r>=n)){t=o+1,S=!0;try{f.kill()}catch{}break}b+=r;const o=t>=0?e.subarray(0,t):e;y<=l&&g.push(o)}else!0!==S&&y<=l&&g.push(e)})),f.stderr?.on("data",(e=>{w+=e.length,w<=l&&v.push(e)})),f.on("error",(r=>{if(clearTimeout(m),p(),rf(r)){const n=(0,uo.getRipgrepBinaryPath)(),o=r;if(tf.error(e,"rg_diagnostics.spawn_enoent",void 0,of(n,t,o,i)),!1===nf(t))return void u(sf(t))}u(r)})),f.on("close",(e=>{d=!0,clearTimeout(m);const t=Buffer.concat(g).toString(a),r=Buffer.concat(v).toString(a);p(),c({stdout:t,stderr:r,exitCode:e??0})}))}))}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const i=Yp(n,(0,c.VI)(e.withName("LocalGrepExecutor.execute")),!1),s=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content",u={toolCallId:t.toolCallId,execId:r?.execId,outputMode:l,targetPath:t.path,workspacePaths:s},d=fo(t.sandboxPolicy);try{const r=this.grepProvider.getWorktreeGuardInfo?.(s);if((0,Vn.fl)({targetPath:t.path,workspacePaths:s,mainWorktreePath:r?.mainWorktreePath}))return new fd.Ud({result:{case:"error",value:new fd.ts({error:Vn.PS})}});if(t.path){const r=await Rc((0,Vn.o1)(t.path,this.singleWorkspacePath));if(null===r)return new fd.Ud({result:{case:"error",value:new fd.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 fd.Ud({result:{case:"error",value:new fd.ts({error:`Path '${t.path}' is filtered out by .cursorignore`})}});void 0!==this.mcpStateAccessor&&Zp(e,this.mcpStateAccessor,r)}let n={};const c=await this.executeIndexedGrepWithTimeout(i.ctx,s,t,u);if(void 0!==c)n=c;else for(const e of s){if(!1===nf(e))return new fd.Ud({result:{case:"error",value:new fd.ts({error:`Path does not exist: ${e}`})}});let r;if("content"===l)r=await this.runContentMode(i.ctx,e,t,d,u);else if("files_with_matches"===l)r=await this.runFilesMode(i.ctx,e,t,d,u);else{if("count"!==l)throw new Error(`Unknown output mode: ${l}`);r=await this.runCountMode(i.ctx,e,t,d,u)}n[e]=r}const h=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,a.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,a.resolve)(t),i=t=>ef(e,t,r),s=o.result;switch(s.case){case"content":{const e=s.value,r=[];let o=0,a=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,a+=t.matches.filter((e=>!e.isContextLine)).length);n[t]=new fd.vD({result:{case:"content",value:new fd.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-o),totalMatchedLines:Math.max(0,e.totalMatchedLines-a)})}});break}case"files":{const e=s.value,r=e.files.filter((e=>i(e)));n[t]=new fd.vD({result:{case:"files",value:new fd.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=s.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;n[t]=new fd.vD({result:{case:"count",value:new fd.xA({...e,counts:r,totalFiles:Math.max(0,e.totalFiles-(e.counts.length-r.length)),totalMatches:Math.max(0,e.totalMatches-o)})}});break}default:n[t]=o}}return n}(n,s),p=new fd._0({pattern:t.pattern,path:t.path,outputMode:l,workspaceResults:h});return new fd.Ud({result:{case:"success",value:p}})}catch(e){if(t.path){const e=(0,Vn.o1)(t.path,this.singleWorkspacePath);try{await(0,Hn.stat)(e)}catch(t){return new fd.Ud({result:{case:"error",value:new fd.ts({error:`Path does not exist: ${e}`})}})}}return new fd.Ud({result:{case:"error",value:new fd.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{Xp(n)}var o}}lf.MAIN_TIMEOUT_MS=25e3,lf.INDEXED_GREP_TIMEOUT_MS=25e3,lf.INDEXED_GREP_CONTEXT_TIMEOUT_MS=lf.INDEXED_GREP_TIMEOUT_MS+100,lf.HARD_MAX_OUTPUT_LINES=1e4,lf.CLIENT_LIMIT_LINES=2e3;var cf=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),uf=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},df=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 hf{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{uf(r,(0,c.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Vn.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Hn.stat)(n)}catch(e){return"ENOENT"===e.code?function(e){const t=Zi(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new cf.fv({result:{case:"error",value:new cf.uj({path:n,error:"No active terminals."})}}):new cf.fv({result:{case:"error",value:new cf.uj({path:n,error:`Path does not exist: ${n}`})}}):new cf.fv({result:{case:"error",value:new cf.uj({path:n,error:e.message})}})}if(!r.isDirectory())return new cf.fv({result:{case:"error",value:new cf.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=fo(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 cf.fv({result:{case:"timeout",value:new cf.ze({directoryTreeRoot:a})}}):new cf.fv({result:{case:"success",value:new cf.PC({directoryTreeRoot:a})}})}catch(e){return new cf.fv({result:{case:"error",value:new cf.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{df(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return uf(o,(0,c.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{df(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{uf(i,(0,c.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const s=(0,a.resolve)(t),l=new cf.vq({absPath:s,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(s,l);const d={charactersUsed:s.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=bc(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:n,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,a.resolve)(t,e),n=await Rc(r);null===n||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,s,u,d,o)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){i.error=e,i.hasError=!0}finally{df(i)}}addPathToTree(e,t,r,n,o){const i=(0,a.basename)(e),s=(0,a.dirname)(e);this.ensureDirectoryPath(s,t,r,n.budgetExceeded);const l=r.get(s);if(!l)return;const c=i.length;if(!n.budgetExceeded&&n.charactersUsed+c<=o){const e=new cf.ur({name:i});l.childrenFiles.push(e),n.charactersUsed+=c}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=s;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,a.dirname)(e);if(n===e)break;e=n}}const o=(0,a.extname)(e);let i=s;for(;i.startsWith(t);){const e=r.get(i);e&&(e.fullSubtreeExtensionCounts[o]??=0,e.fullSubtreeExtensionCounts[o]=vd(e.fullSubtreeExtensionCounts[o]+1),e.numFiles??=0,e.numFiles=vd(e.numFiles+1));const t=(0,a.dirname)(i);if(t===i)break;i=t}}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,a.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new cf.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const s=r.get(o);s&&s.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,a.basename)(e.absPath).localeCompare((0,a.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}var pf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ff=1e4,mf={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class gf{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<ff){const r=Math.min(e.length,ff-t);this.fullOutput+=e.slice(0,r)}this.totalChars>ff&&(this.fullOutput="")}getOutput(){return this.totalChars<=ff?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=ff))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-ff}}}function vf(e,t){const r=ed-e.length;return r<=0?e:e+t.slice(0,r)}function yf(e,t){return null!==e?e:null===t?-1:-s.constants.signals[t]}class wf{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 kt.xC({...o,aborted:i,abortReason:r.abortReason})}:{case:"success",value:new kt.QR(o)};return new kt.W4({result:s,sandboxPolicy:mo(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const i=performance.now(),s=r,a=(await(0,uo.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 gf;let a,c,u="",d="",h=!1,p=!1,f="",m=()=>{};const g=(0,uo.withConfiguredRipgrepEnv)({...process.env,...mf,CURSOR_AGENT:"1"}),v={shell:!0,cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform},y="insecure_none"===l.type?(0,ss.spawn)(t.command,[],v):(0,uo.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:yd(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=kt.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=kt.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=vf(u,t),s.append(t)})),y.stderr?.on("data",(e=>{const t=e.toString();d=vf(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:yf(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:a})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,i=(0,Vn.o1)(t.workingDirectory||this.defaultCwd),s=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new kt.W4({result:{case:"spawnError",value:new kt.mJ({command:o,workingDirectory:i,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?fo(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:i,timeout:s,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new kt.W4({result:{case:"permissionDenied",value:new kt.jn({command:o,workingDirectory:i,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new kt.W4({result:{case:"rejected",value:new kt.pZ({command:o,workingDirectory:i,reason:vo(l.reason)})}});a=l.policy,ro()&&(a=lo(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{pf(r)}}}var bf=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),Sf=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const kf=51200;function Ef(e){return Buffer.byteLength(e,"utf8")}function xf(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function Cf(e){return new Sf.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 _f(e,t){const r=t?.maxLines??2e3,n=t?.maxBytes??kf,o=e.split("\n"),i=o.length;if(Ef(o[0]??"")>n)return{content:"",truncation:Cf({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=Ef(t)+i;if(l+c>n){a="bytes";break}s.push(t),l+=c}return{content:s.join("\n"),truncation:Cf({truncated:void 0!==a,truncatedBy:a,totalLines:i,outputLines:s.length,outputBytes:l,maxLines:r,maxBytes:n})}}function Pf(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var Tf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 If(e){const{content:t,truncation:r}=function(e){const t=kf,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=Ef(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=Ef(o[0]),a=!0}break}o.unshift(n),s+=c}return{content:o.join("\n"),truncation:Cf({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,Hn.mkdtemp)((0,a.join)((0,s.tmpdir)(),"pi-bash-")),o=(0,a.join)(n,"output.log");await(0,Hn.writeFile)(o,e,"utf8");const i=r.totalLines-r.outputLines+1,l=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${xf(r.outputBytes)} of line ${l} (${xf(kf)} limit). Full output: ${o}]`:`[Showing lines ${i}-${l} of ${r.totalLines}. Full output: ${o}]`}`,fullOutputPath:o,truncation:r}}class Rf{constructor(e){this.shellExecutor=e}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiBashExecutor.execute")),!1),i=await this.shellExecutor.execute(o.ctx,function(e,t){const r=void 0!==e.timeout&&e.timeout>0?Math.round(1e3*e.timeout):2147483647,n=e.command.trim().split(/\s+/)[0]??"";return new kt.a({command:e.command,timeout:r,toolCallId:t?.execId??"",fileOutputThresholdBytes:BigInt(0),parsingResult:new kt.HO({parsingFailed:!1,executableCommands:[{name:n,fullText:e.command,args:[]}]})})}(t,r),r);switch(i.result.case){case"success":{const e=await If(`${i.result.value.stdout}${i.result.value.stderr}`);return new bf.AH({result:{case:"success",value:new bf.cV(e)}})}case"failure":{const e=await If(`${i.result.value.stdout}${i.result.value.stderr}`);return new bf.AH({result:{case:"success",value:new bf.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{Tf(n)}}error(e){return new bf.AH({result:{case:"error",value:new bf.bD({error:e})}})}}var Af=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function Of(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;case"userRejected":return e.reason??"User rejected the operation";case"permissionsConfig":return e.isReadonly?"Blocked by readonly permissions configuration":"Blocked by permissions configuration";case"cursorFiles":return"Path is blocked because it is a Cursor internal file";case"unsafeResolution":return e.message;case"needsApproval":return e.approvalReason}}var jf=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function Mf(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function Df(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 Nf(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 $f(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 Lf=new Map;async function Ff(e,t){const r=await async function(e){try{return await(0,Hn.realpath)(e)}catch{return e}}(e),n=Lf.get(r)??Promise.resolve();let o;const i=new Promise((e=>{o=e})),s=n.then((()=>i));Lf.set(r,s),await n;try{return await t()}finally{o(),Lf.get(r)===s&&Lf.delete(r)}}function Uf(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,wl.fileURLToPath)(r)),("~"===r||r.startsWith("~/"))&&(r=(0,a.join)((0,s.homedir)(),r.slice(2))),(0,a.normalize)((0,a.isAbsolute)(r)?r:(0,a.resolve)(t??process.cwd(),r))}var Bf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zf{constructor(e,t,r){this.permissionsService=e,this.writeExecutor=t,this.workspacePath=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiEditExecutor.execute")),!1),i=Uf(t.path,this.workspacePath);return Ff(i,(async()=>{const e=await this.permissionsService.shouldBlockRead(i);if(e)return this.error(`Read blocked: ${Of(e)}`);try{if((await(0,Hn.stat)(i)).isDirectory())return this.error(`Path is a directory: ${i}`);const e=(await(0,Hn.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=Mf(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=Mf(o.oldText),i=Nf(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:Mf(o.newText)})}if(!n)return{matches:r,matchedContent:e};const o=Df(e),i=[];for(const e of t){const t=Df(Mf(e.oldText)),r=Nf(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:Df(Mf(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,jf.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:h,patch:h,firstChangedLine:$f(a,u)}}(t.path,e,t.edits),s=await this.writeExecutor.execute(o.ctx,new Et.hY({path:i,fileText:n.newContent,toolCallId:r?.execId??""}),r);switch(s.result.case){case"success":return new Af.u7({result:{case:"success",value:new Af.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 Af.u7({result:{case:"rejected",value:new Af.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{Bf(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 Af.u7({result:{case:"error",value:new Af.Nd({error:e})}})}}var Wf=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),Hf=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 qf(e){return e.split(a.sep).join("/")}class Gf{constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiFindExecutor.execute")),!1);const n=Uf(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Find blocked: ${Of(o)}`);try{if(!(await(0,Hn.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,Hn.readdir)(o,{withFileTypes:!0});for(const s of i){if(n.length>=t)return;if(".git"===s.name||"node_modules"===s.name)continue;const i=(0,a.join)(o,s.name);await r(i)&&(n.push(i+(s.isDirectory()?a.sep:"")),s.isDirectory()&&await e(i))}}(e),n}(n,e,(async e=>!await this.permissionsService.shouldBlockRead(e))),o=t.pattern.includes("/")&&!t.pattern.startsWith("**/")?`**/${t.pattern}`:t.pattern,i=r.map((e=>({raw:e,relative:qf((0,a.relative)(n,e))}))).filter((({relative:e})=>(0,No.xF)(e,o,{dot:!0})));if(0===i.length)return this.success("No files found matching pattern");const s=_f(i.map((e=>e.relative)).join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=r.length>=e?e:void 0,c=[];return void 0!==l&&c.push(`${e} results limit reached. Use limit=${2*e} for more, or refine pattern`),s.truncation.truncated&&c.push(`${xf(kf)} limit reached`),this.success(c.length>0?`${s.content}\n\n[${c.join(". ")}]`:s.content,{resultLimitReached:l,truncation:s.truncation.truncated?s.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown find error")}}catch(e){r.error=e,r.hasError=!0}finally{Hf(r)}}success(e,t){return new Wf.bT({result:{case:"success",value:new Wf.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new Wf.bT({result:{case:"error",value:new Wf.Uy({error:e})}})}}var Vf=r("node:readline"),Jf=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),Kf=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 Zf{constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiGrepExecutor.execute")),!1);const n=Uf(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Search blocked: ${Of(o)}`);try{const e=(await(0,Hn.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,ss.spawn)((0,uo.getRipgrepBinaryPath)(),r,{stdio:["ignore","pipe","pipe"]}),i=[];let s="",a=!1;const l=Math.max(1,t.limit??100),c=(0,Vf.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=_f(h,{maxLines:Number.MAX_SAFE_INTEGER}),m=[];return a&&m.push(`${l} matches limit reached. Use limit=${2*l} for more, or refine pattern`),f.truncation.truncated&&m.push(`${xf(kf)} 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{Kf(r)}}async formatMatches(e,t,r,n){const o=[];let i=!1;for(const s of e){const e=r?(0,a.relative)(t,s.filePath):(0,a.basename)(s.filePath);if(0===n&&void 0!==s.lineText){const t=Pf(s.lineText);i=i||t.wasTruncated,o.push(`${e}:${s.lineNumber}: ${t.text}`);continue}const l=(await(0,Hn.readFile)(s.filePath,"utf8")).replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n"),c=Math.max(1,s.lineNumber-n),u=Math.min(l.length,s.lineNumber+n);for(let t=c;t<=u;t++){const r=Pf(l[t-1]??"");i=i||r.wasTruncated,o.push(t===s.lineNumber?`${e}:${t}: ${r.text}`:`${e}-${t}- ${r.text}`)}}return{output:o.join("\n"),linesTruncated:i}}success(e,t){return new Jf.mr({result:{case:"success",value:new Jf.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new Jf.mr({result:{case:"error",value:new Jf.hP({error:e})}})}}var Yf=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),Xf=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 Qf{constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiLsExecutor.execute")),!1);const n=Uf(t.path||".",this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`List blocked: ${Of(o)}`);try{if(!(await(0,Hn.stat)(n)).isDirectory())return this.error(`Not a directory: ${n}`);const e=Math.max(1,t.limit??500),r=(await(0,Hn.readdir)(n)).sort(((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))),o=[];let i=!1;for(const t of r){if(o.length>=e){i=!0;break}try{const e=(0,a.join)(n,t);if(await this.permissionsService.shouldBlockRead(e))continue;const r=await(0,Hn.stat)(e);o.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===o.length)return this.success("(empty directory)");const s=_f(o.join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=[];return i&&l.push(`${e} entries limit reached. Use limit=${2*e} for more`),s.truncation.truncated&&l.push(`${xf(kf)} limit reached`),this.success(l.length>0?`${s.content}\n\n[${l.join(". ")}]`:s.content,{entryLimitReached:i?e:void 0,truncation:s.truncation.truncated?s.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown ls error")}}catch(e){r.error=e,r.hasError=!0}finally{Xf(r)}}success(e,t){return new Yf.pX({result:{case:"success",value:new Yf.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new Yf.pX({result:{case:"error",value:new Yf.iG({error:e})}})}}var em=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),tm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class rm{constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiReadExecutor.execute")),!1);const n=function(e,t){const r=Uf(e,t);if((0,i.existsSync)(r))return r;for(const e of function(e){const t=(0,a.dirname)(e),r=e.slice(t.length+1),n=new Set;return n.add(e),n.add((0,a.join)(t,r.normalize("NFD"))),n.add((0,a.join)(t,r.replace(/'/g,"’"))),n.add((0,a.join)(t,r.replace(/ /g," "))),n.add((0,a.join)(t,r.replace(/'/g,"’").normalize("NFD"))),[...n]}(r))if((0,i.existsSync)(e))return e;return r}(t.path,this.workspacePath),o=await this.permissionsService.shouldBlockRead(n);if(o)return this.error(`Read blocked: ${Of(o)}`);try{if((await(0,Hn.stat)(n)).isDirectory())return this.error(`Path is a directory: ${n}`);const e=(await(0,Hn.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}=_f(o),a=r+1;let l=i;if(s.firstLineExceedsLimit)l=`[Line ${a} is ${xf(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${xf(kf)} 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 em.Q({result:{case:"success",value:new em.yP({output:l,truncation:s.truncated?s:void 0})}})}catch(e){return this.error(e instanceof Error?e.message:"Unknown read error")}}catch(e){r.error=e,r.hasError=!0}finally{tm(r)}}error(e){return new em.Q({result:{case:"error",value:new em.tB({error:e})}})}}var nm=r("../proto/dist/generated/agent/v1/pi_write_exec_pb.js"),om=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class im{constructor(e,t){this.writeExecutor=e,this.workspacePath=t}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiWriteExecutor.execute")),!1),i=Uf(t.path,this.workspacePath);return Ff(i,(async()=>{const e=await this.writeExecutor.execute(o.ctx,new Et.hY({path:i,fileText:t.content,toolCallId:r?.execId??""}),r);switch(e.result.case){case"success":return new nm.hO({result:{case:"success",value:new nm.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new nm.hO({result:{case:"rejected",value:new nm.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new nm.hO({result:{case:"error",value:new nm.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new nm.hO({result:{case:"error",value:new nm.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){n.error=e,n.hasError=!0}finally{om(n)}}}var sm=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function am(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class lm{constructor(e){this.drainer=e}async execute(e,t){try{const e=await this.drainer.drain({cursor:am(t.cursor),advance:!1!==t.advance});return new sm.Ev({result:{case:"success",value:new sm.iS({events:e.events.map((e=>new sm.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 sm.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new sm.Ev({result:{case:"error",value:new sm.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class cm{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new wt.nt({result:{case:"error",value:new wt.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new wt.nt({result:{case:"success",value:new wt.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var um=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)}))}}},dm=function(e){return this instanceof dm?(this.v=e,this):new dm(e)},hm=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 dm?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 pm{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=um(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 hm(this,arguments,(function*(){for(const t of e)yield yield dm(t)}))}()}const e=(0,m.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return function(){return hm(this,arguments,(function*(){var n,o,i,s;for(const e of t)yield yield dm(e);try{try{for(var a,l=!0,c=um(e);!(n=(a=yield dm(c.next())).done);l=!0){s=a.value,l=!1;const e=s;yield yield dm(e)}}catch(e){o={error:e}}finally{try{l||n||!(i=c.return)||(yield dm(i.call(c)))}finally{if(o)throw o.error}}}finally{r.forks.delete(e)}}))}()}}function fm(e,t){const r=new qn.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 mm=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),gm=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class vm{constructor(e){this.getCanvasDiagnostics=e}async execute(e,t){try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?ym(t.path,"diagnostics unavailable"):new mm.GL({result:{case:"success",value:new mm.uX({path:t.path,diagnostics:e.map(wm)})}})}catch(e){return ym(t.path,e instanceof Error?e.message:String(e))}}}function ym(e,t){return new mm.GL({result:{case:"error",value:new mm.HW({path:e,error:t})}})}function wm(e){return new gm.oQ({severity:bm(e.severity),range:new zh.Q6({start:new zh.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new zh.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function bm(e){switch(e){case 1:return gm.h_.ERROR;case 2:return gm.h_.WARNING;case 3:return gm.h_.INFORMATION;case 4:return gm.h_.HINT;default:return gm.h_.UNSPECIFIED}}class Sm{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 Sm(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new Sm(e)}static fromString(e){return new Sm(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 km=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 Em{constructor(e,t){this.workspacePath=e,this.diagnosticsProvider=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n;!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,n]=e.withTimeoutAndCancel(1e4);try{const r=(0,Vn.o1)(t.path,this.workspacePath);try{const e=await(0,Hn.stat)(r);if(!e.isFile()&&!e.isDirectory())return new gm.Ek({result:{case:"fileNotFound",value:new gm.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new gm.Ek({result:{case:"fileNotFound",value:new gm.Mu({path:t.path})}});if("EACCES"===e.code)return new gm.Ek({result:{case:"permissionDenied",value:new gm.RP({path:t.path})}});throw e}const n=(0,Vn.o1)(r,this.workspacePath),o=new Sm(n);await this.diagnosticsProvider.open(e,o);const i=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new gm.Ek({result:{case:"success",value:new gm.a1({path:t.path,diagnostics:i,totalDiagnostics:i.length})}})}catch(r){return e.canceled?new gm.Ek({result:{case:"error",value:new gm.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new gm.Ek({result:{case:"error",value:new gm.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{km(r)}}convertDiagnostic(e){return new gm.oQ({severity:this.convertSeverity(e.severity),range:e.range?new zh.Q6({start:new zh.yX({line:e.range.start.line,column:e.range.start.character}),end:new zh.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 gm.h_.ERROR;case 2:return gm.h_.WARNING;case 3:return gm.h_.INFORMATION;case 4:return gm.h_.HINT;default:return gm.h_.UNSPECIFIED}}}Error,r("../../node_modules/.pnpm/which@4.0.0/node_modules/which/lib/index.js");const xm="win32"===process.platform;function Cm(e,t){return xm&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==a.sep&&(e+=a.sep),t.startsWith(e))}process.platform;var _m=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 Pm(e){return _m(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 _m(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,ss.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=>_m(this,void 0,void 0,(function*(){const t=i.get(e);if(!0!==t)if(!1!==t)if(function(e){return new Tm(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 Tm(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 Tm{constructor(e,t){this.name=e,this.extname=a.extname(e).toLowerCase(),this.getContent=t}get lines(){var e;if(void 0===this.cachedLines){const t=null===(e=this.getContent)||void 0===e?void 0:e.call(this);this.cachedLines=t?t.split("\n"):[]}return this.cachedLines}get data(){var e;return null===(e=this.getContent)||void 0===e?void 0:e.call(this)}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?<!-)\.)+(com|edu|gov|in|me|net|org|fm|io)/.test(this.name)}goLock(){return/(Gopkg|glide)\.lock/.test(this.name)}packageResolved(){return/Package\.resolved/.test(this.name)}poetryLock(){return/poetry\.lock/.test(this.name)}pdmLock(){return/pdm\.lock/.test(this.name)}uvLock(){return/uv\.lock/.test(this.name)}pixiLock(){return/pixi\.lock/.test(this.name)}esyLock(){return/(^|\/)(\w+\.)?esy\.lock$/.test(this.name)}npmShrinkwrapOrPackageLock(){return/npm-shrinkwrap\.json/.test(this.name)||/package-lock\.json/.test(this.name)}pnpmLock(){return/pnpm-lock\.yaml/.test(this.name)}bunLock(){return/(?:^|\/)bun\.lockb?$/.test(this.name)}terraformLock(){return/(?:^|\/)\.terraform\.lock\.hcl$/.test(this.name)}generatedYarnPlugnplay(){return/(^|\/)\.pnp\..*$/.test(this.name)}godeps(){return/Godeps\//.test(this.name)}generatedByZephir(){return/\.zep\.(c|h|php)$/.test(this.name)}htmlcov(){return/(?:^|\/)htmlcov\//.test(this.name)}gradleWrapper(){return/(?:^|\/)gradlew(?:\.bat)?$/i.test(this.name)}mavenWrapper(){return/(?:^|\/)mvnw(?:\.cmd)?$/i.test(this.name)}pipenvLock(){return/Pipfile\.lock/.test(this.name)}generatedPascalTlb(){return/_tlb\.pas$/i.test(this.name)}generatedSqlxQuery(){return/(?:^|\/)\.sqlx\/query-[a-f\d]{64}\.json$/.test(this.name)}sourceMapByName(){return/\.(css|js)\.map$/i.test(this.name)}maybeMinified(){return[".js",".css"].includes(this.extname)}minifiedFiles(){return!(!this.maybeMinified()||0===this.lines.length)&&this.lines.reduce(((e,t)=>e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*((null==r?void 0:r.length)||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*((null==n?void 0:n.length)||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("<doc>")&&(this.lines[2]||"").includes("<assembly>")&&(this.lines[this.lines.length-2]||"").includes("</doc>")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include <jni.h>")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){var e;if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>/<!-- Generated by pkgdown: do not edit by hand -->/.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>/<!--\s+Generated by Doxygen\s+[.0-9]+\s*-->/i.test(e))))return!0;const t=this.lines.slice(0,31).join(" ").match(/<meta(\s+[^>]+)>/gi);if(!t)return!1;for(const r of t){const t=this.extractHtmlMeta(r);if("generator"===(null===(e=t.name)||void 0===e?void 0:e.toLowerCase())&&(t.content||t.value)){const e=t.content||t.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(e))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}r("node:events"),Error;const Im=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,Rm=/^(a|b|i|w|c|o|1|2)\//,Am=e=>{const t=e?.match(Im);return t?.map((e=>e.replace(Rm,"").replace(/("|')$/,"")))},Om=/^\\?['"]|\\?['"]$/g,jm=e=>{let t=Mm(e,"-+").trim();return t=Nm(t),t.replace(Om,"").replace(Rm,"")},Mm=(e,t)=>{if(e=Lm(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=$m(t);return e.replace(new RegExp(`^${r}+`),"")},Dm=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,Nm=e=>{const t=Dm.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},$m=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${Lm(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,Lm=e=>`${e??""}`,Fm=(0,h.h)("local-git-diff");async function Um(e,t,r={}){const n=await new Promise(((n,o)=>{const i=(0,ss.spawn)("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 Bm(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]=Am(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=jm(e)}],[/^\+\+\+\s/,e=>{c(),n.to=jm(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 sr.o$({diffs:t.map((e=>function(e){const t=new sr.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new sr.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:sr.Wf.UNSPECIFIED})}const zm=["main","master","develop"];class Wm{async execute(e,t){return async function(e,t,r){const n=function(e){switch(e){case sr.ek.NAME_STATUS:return sr.ek.NAME_STATUS;case sr.ek.NAME_STATUS_AND_NUMSTAT:return sr.ek.NAME_STATUS_AND_NUMSTAT;case sr.ek.FILE_DIFFS:return sr.ek.FILE_DIFFS;case sr.ek.DIFFS_WITH_BEFORE_AND_AFTER:return sr.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return sr.ek.FILE_DIFFS}}(r.outputFormat),o=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await Um(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of zm){const r=`origin/${t}`;try{return await Um(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await Um(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await Um(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 Um(t,["merge-base",e,r.ref.length>0?r.ref:"HEAD"])).trim()),e})(),i=["diff","--no-color"];r.includeSpaceChanges||i.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&i.push(`-U${r.unifiedContextLines}`),i.push(o),r.ref.length>0&&i.push(r.ref),r.targetPaths.length>0&&(i.push("--"),i.push(...r.targetPaths));const s=await Um(t,i,{shouldNotTrimOutput:!0}),l=Bm(s);let c=[];if(r.maxUntrackedFiles>0){c=await async function(e,t){let r=(await Um(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 Hn.readFile(a.join(e,t),"utf8"),path:t}}catch{return}})))).filter((e=>void 0!==e))}(t,r.maxUntrackedFiles);for(const e of c){const r=await Um(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});l.diffs.push(...Bm(r).diffs)}}if(n!==sr.ek.FILE_DIFFS)for(const e of l.diffs)e.chunks=[];if(n===sr.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 Um(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 Um(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}else try{i.afterFileContents=await Hn.readFile(a.join(t,i.to),"utf8")}catch{try{i.afterFileContents=await Um(t,["show",`${n}:${i.to}`],{shouldNotTrimOutput:!0})}catch{i.afterFileContents=""}}else i.afterFileContents=""}catch(t){Fm.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 Pm({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 Um(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){Fm.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=(0,ss.spawn)("git",["patch-id","--stable"],{cwd:e});let i="",s="";o.stdout.on("data",(e=>{i+=e.toString()})),o.stderr.on("data",(e=>{s+=e.toString()})),o.on("close",(e=>{0===e?r(i):n(new Error(`git patch-id failed with code ${e}: ${s}`))})),o.on("error",n),o.stdin.end(t)}))).trim().split(/\s+/)[0]||void 0}(t,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(s,function(e){const t=[];for(const r of e){const e=r.contents.split("\n"),n=e.length;t.push(`diff --git a/${r.path} b/${r.path}`),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(c))):void 0,f=!0===r.returnHeadSha?(await Um(t,["rev-parse","HEAD"])).trim():void 0,m=!0===r.returnHeadSha?(await Um(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,g=new sr.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 Hm=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class qm{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName});return new Hm.M({allowlisted:r})}}const Gm=8388608;var Vm=r("../proto/dist/generated/agent/v1/read_exec_pb.js"),Jm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Km=(0,h.h)("LocalReadExecutor"),Zm=async(e,t,r,n)=>{const o=setTimeout((()=>{Km.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function Ym(e){return e>=32&&e<=126||9===e||10===e||13===e}const Xm=Buffer.from("\n---\n");const Qm=[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 eg(e){const t=(0,a.extname)(e).toLowerCase(),r=""===t?"Binary files without an extension are not supported by the read executor":`Binary files of type ${t} are not supported by the read executor`;return new Vm.sV({result:{case:"invalidFile",value:new Vm.cW({path:e,reason:r})}})}function tg(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 rg(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 ng(e,t){const r=rg(e,t);return{text:r.text,truncated:r.truncated}}function og(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=rg(n,"\n")),n=rg(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function ig(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 sg extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function ag(e,t,r,n){const o=void 0!==r.offset||void 0!==r.limit,s=(r.offset??1)<0,a=r.offset??1,l=Math.max(0,a-1),c=void 0===r.limit?void 0:l+r.limit,u=s?Math.abs(a):0,d=[];let h=0,p=!1;const f=[];let m=0,g=!1;const v=[];let y=0,w=!1,b={text:"",truncated:!1},S=0,k=0,E=0,x=!1,C=!1;const _=e=>{let t=e;return!x&&t.length>0&&(x=!0,65279===t.charCodeAt(0)&&(C=!0,t=t.slice(1))),t},P=(e,t)=>{const r=S;if(t&&(e.text.endsWith("\r")?k++:E++),((e,t)=>{if(p&&h>=Gm)return;const r=d.length>0?1:0;let n=Gm-h;if(r>0){if(n<=0)return void(p=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};d.push(o),h+=r+o.line.text.length,(e.truncated||o.line.truncated)&&(p=!0)})(e,t),s){if(u>0){for(v.push({line:e,hasNewline:t}),y+=e.text.length+1;v.length>u;){const e=v.shift();void 0!==e&&(y-=e.line.text.length+1)}for(;v.length>1&&y>Gm;){const e=v.shift();void 0!==e&&(y-=e.line.text.length+1,w=!0)}}}else o&&r>=l&&(void 0===c||r<c)&&((e,t)=>{if(g&&m>=Gm)return;const r=f.length>0?1:0;let n=Gm-m;if(r>0){if(n<=0)return void(g=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};f.push(o),m+=r+o.line.text.length,e.truncated&&(g=!0),o.line.truncated&&(g=!0)})(e,t);S++};for await(const r of async function*(e,t,r){if("strictUtf8"===r.kind){const r=new $o.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n=(0,i.createReadStream)(t,{highWaterMark:65536,signal:e.signal});try{for await(const e of n){const t=r.decode(e,{stream:!0});t.length>0&&(yield t)}const e=r.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new sg;throw e}return}const n=(0,i.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe($l.decodeStream(r.decoderEncoding));for await(const e of n)yield"string"==typeof e?e:String(e)}(e,t,n)){const e=_(r).split("\n");for(let t=0;t<e.length;t++)b=ng(b,e[t]),t<e.length-1&&(P(b,!0),b={text:"",truncated:!1})}P(b,!1);const T=k+E,I=T>0&&k/T*100>=5;!function(e,t){if(ec.has(e)&&ec.delete(e),ec.set(e,t),ec.size<=100)return;const r=ec.keys().next().value;void 0!==r&&ec.delete(r)}(t,"utf8"===n.cacheEncoding&&C?"utf8bom":n.cacheEncoding);let R={text:"",truncated:p};if(R=og(R,d,I),!o)return{content:R.text,totalLines:S,truncated:R.truncated,rangeApplied:!1};if(""===R.text)return{content:"",totalLines:S,truncated:!1,rangeApplied:!1};if(s){const e=r.limit??u;let t={text:"",truncated:w};return t=og(t,v.slice(0,e),I),{content:t.text,totalLines:S,truncated:t.truncated,rangeApplied:!0}}if(l>=S)return{content:R.text,totalLines:S,truncated:R.truncated,rangeApplied:!1};let A={text:"",truncated:g};return A=og(A,f,I),{content:A.text,totalLines:S,truncated:A.truncated,rangeApplied:!0}}class lg{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalReadExecutor.execute")),!1);const n=t.path,o=(0,Vn.o1)(n,this.workspacePath);if(await Zm(e,"permissionsService.shouldBlockRead",3e3,(()=>this.permissionsService.shouldBlockRead(o))))return new Vm.sV({result:{case:"permissionDenied",value:new Vm.lW({path:o})}});void 0!==this.mcpStateAccessor&&Zp(e,this.mcpStateAccessor,o);try{const r=await Zm(e,"stat",3e3,(()=>(0,Hn.stat)(o)));if(r.isDirectory())return new Vm.sV({result:{case:"invalidFile",value:new Vm.cW({path:o,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Vm.sV({result:{case:"invalidFile",value:new Vm.cW({path:o,reason:"Path is neither a file nor a directory"})}});const n=function(e){return null!==function(e){const t=Zi(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=Zi(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(o);if(n||i)return await this.readTerminalFile(e,o,r,t,i&&!n);const s=await Zm(e,"getFormatForFile",3e3,(()=>lc(o))),l=s.isImageFile,c=function(e){return".pdf"===(0,a.extname)(e).toLowerCase()}(o),u=oc(o);if(l){const t=await Zm(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,Hn.readFile)(o);return Xh(e)}));return new Vm.sV({result:{case:"success",value:new Vm.mE({path:o,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c){const t=await Zm(e,"readPdfBinary",3e3,(()=>(0,Hn.readFile)(o)));return new Vm.sV({result:{case:"success",value:new Vm.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(s.isBinaryFile&&u){const t=await Zm(e,"readBinaryFile",3e3,(()=>(0,Hn.readFile)(o)));return new Vm.sV({result:{case:"success",value:new Vm.mE({path:o,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(s.isBinaryFile)return eg(o);{const n=this.useStreamingRead;if(n&&await Zm(e,"useStreamingRead",3e3,(()=>n()))){const n=await Zm(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=function(e,t,r){const n=function(e,t,r){return ig(r??ec.get(e)??t.encoding)}(e,t,r),o=function(e){const t=ig(e);return"utf8bom"===t?"utf8":t}(n);return"utf8"===o?{kind:"strictUtf8",cacheEncoding:"utf8"}:$l.encodingExists(o)?{kind:"iconv",decoderEncoding:o,cacheEncoding:n}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,n.encodingHint);try{return await ag(e,t,n,o)}catch(r){if(r instanceof sg)return await ag(e,t,n,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,o,s,t)));return new Vm.sV({result:{case:"success",value:new Vm.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 Zm(e,"readText",3e3,(()=>sc(o,t.encodingHint))),a=await Zm(e,"countLines",3e3,(()=>cc(i))),l=tg(i,a,t);let c=l.content,u=!1;return c.length>Gm&&(c=c.substring(0,Gm),u=!0),new Vm.sV({result:{case:"success",value:new Vm.mE({path:o,output:{case:"content",value:c},totalLines:a,fileSize:BigInt(r.size),truncated:u,rangeApplied:l.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new Vm.sV({result:{case:"fileNotFound",value:new Vm.Ko({path:o})}}):"EACCES"===t.code||"EPERM"===t.code?new Vm.sV({result:{case:"permissionDenied",value:new Vm.lW({path:o})}}):new Vm.sV({result:{case:"error",value:new Vm.F_({path:o,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Jm(r)}}async readTerminalFile(e,t,r,n,o){const i=await Zm(e,"readTerminalFile",3e3,(()=>(0,Hn.readFile)(t)));if(o&&(s=i,Qm.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(s,e)))))return eg(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*Xm.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(Xm,r-Xm.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+Xm.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&&Ym(t)&&r++,0===t&&Ym(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=cc(a),c=tg(a,l,n);a=c.content;let u=!1;return a.length>Gm&&(a=a.substring(0,Gm),u=!0),new Vm.sV({result:{case:"success",value:new Vm.mE({path:t,output:{case:"content",value:a},totalLines:l,fileSize:BigInt(r.size),truncated:u,rangeApplied:c.rangeApplied})}})}}var cg=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),ug=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 dg=(0,$o.promisify)(ss.execFile);class hg{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 Hn.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 Hn.mkdir(this.stagingDir,{recursive:!0}),await Hn.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return a.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:cg.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:cg.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:cg.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 Hn.access(e),!0}catch{return!1}}async getUniqueArtifactVideoPath(e){const t=a.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;await this.pathExists(a.join(this.artifactsDir,o));)o=`${r}-${i}${n}`,i++;return a.join(this.artifactsDir,o)}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${a.basename(r)}.mp4`)}else o=`${a.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await dg("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 dg("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e]),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),i=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(i))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||i<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:i}}async renderPolished(e){const t=a.join(e,"recording"),r=a.join(t,"recording_full.mp4");return await this.polishedRenderer.renderRecordingSession({stagingSessionDir:e,outputVideoPath:r,fps:hg.PROXY_TARGET_FPS,includeBrandTag:!0}),await Hn.access(r,Hn.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await dg("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 ${hg.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${hg.PROXY_TARGET_FPS}fps`)}return hg.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=a.join(t,"recording");await Hn.mkdir(r,{recursive:!0});const n=a.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await Ou(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${hg.DEFAULT_REFRESH_RATE}Hz`),o=hg.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${hg.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${hg.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",hg.PROXY_PRESET,"-crf",String(hg.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],s=(0,ss.spawn)("ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),l=new Promise(((e,t)=>{let r="",n=!1;s.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);s.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),s.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);s.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),s.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:s,videoStartedPromise:l}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,ss.spawn)("ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let i="";o.stderr?.on("data",(e=>{i.length<2e4&&(i+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${i.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:s,renderProxies:l}=e,c=a.join(t,"recording"),u=a.join(c,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:s.display.width,displayHeight:s.display.height,apiWidth:s.api.width,apiHeight:s.api.height,inputEvents:h,renderProxies:l??null};await Hn.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(t.killed||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(e){clearTimeout(o),n(new Error(`Failed to send SIGTERM: ${e instanceof Error?e.message:String(e)}`))}}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new cg.Tj({result:{case:"failure",value:new cg.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===cg.$u.UNSPECIFIED)return new cg.Tj({result:{case:"failure",value:new cg.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case cg.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){e=!0;try{await this.cleanupRecording(this.activeRecording),await Hn.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 Hn.mkdir(o,{recursive:!0});const{resolutionString:i,resolution:s}=await Ou(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 Qu({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 cg.Tj({result:{case:"startSuccess",value:new cg.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 Hn.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new cg.Tj({result:{case:"failure",value:new cg.yH({error:e instanceof Error?e.message:String(e)})}})}}case cg.$u.SAVE_RECORDING:{if(!this.activeRecording)return new cg.Tj({result:{case:"failure",value:new cg.yH({error:"No active recording to save"})}});const e=this.activeRecording;try{const r=await e.inputEventLogger.stop(),n=e.inputEventLogger.getRecordingStartTime();this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e);const o=e.ffmpegStartedEpochMs??n,i=e.sessionDir,{finalVideoPath:s,requestedFilePathRejectedReason:l}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:i}),c=a.join(i,"recording"),u=a.join(c,"recording_render_proxy_1080p.mp4");try{await Hn.access(u,Hn.constants.R_OK)}catch{return this.activeRecording=null,new cg.Tj({result:{case:"failure",value:new cg.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:hg.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:hg.PROXY_TARGET_FPS,codec:"h264",profile:hg.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 Hn.copyFile(u,s);else{const e=await this.renderPolished(i);await Hn.rename(e,s)}return this.activeRecording=null,new cg.Tj({result:{case:"saveSuccess",value:new cg.ol({path:s,recordingDurationMs:nr.protoInt64.parse(d.toString()),requestedFilePathRejectedReason:l})}})}catch(t){return await this.cleanupRecording(e),this.invokeStoppedCallbackOnce(),this.activeRecording=null,new cg.Tj({result:{case:"failure",value:new cg.yH({error:t instanceof Error?t.message:String(t)})}})}}case cg.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new cg.Tj({result:{case:"failure",value:new cg.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 Hn.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new cg.Tj({result:{case:"discardSuccess",value:new cg.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;return this.activeRecording=null,new cg.Tj({result:{case:"failure",value:new cg.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 cg.Tj({result:{case:"failure",value:new cg.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{ug(r)}}}hg.PROXY_TARGET_WIDTH=1920,hg.PROXY_TARGET_FPS=60,hg.PROXY_CRF=17,hg.PROXY_PRESET="veryfast",hg.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",hg.DEFAULT_REFRESH_RATE=60;var pg=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");async function fg(e){const t=await(0,Hn.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=a.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await fg(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function mg(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(...mg(t,e,i))}))}return n}async function gg(e){if(!await(0,Hn.access)(e,Hn.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await fg(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>mg(e,"",r===t.length-1))).join("\n")}async function vg(e,t){return gg(a.join(e,"agent-notes",t))}async function yg(e){return gg(a.join(e,"agent-notes","shared"))}const wg=new Set(["origin.cursor.com","origin-staging.cursor.com"]);function bg(e){return void 0!==function(e){var t;const r=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch(e){return}}}(e):void 0;if(void 0===r||!wg.has(r.hostname.toLowerCase()))return;const n=function(e){const t=e.replace(/\/+$/,"").replace(/\.git$/i,"");return t&&"/"!==t?t.startsWith("/")?t:`/${t}`:""}(r.pathname).split("/").filter(Boolean);if(3!==n.length||"git"!==(null===(t=n[0])||void 0===t?void 0:t.toLowerCase()))return;const o=n[1],i=n[2];return o&&i?{owner:o,name:i}:void 0}(e)}var Sg=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},kg=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Eg=(0,h.h)("local-exec:request-context");async function xg(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{Sg(o,(0,c.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{kg(o)}}async function Cg(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 _g(e,t,r={}){const{projectDir:n,notesSessionId:o,metaAgentNotesEnabled:i,getSmartModeClassifierAutoModeEnabled:a,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:c,getSandboxEnabled:u,getSandboxSupported:d,getNetworkAllowlistInfo:h,userTerminalHint:p,artifactsFolder:f,secretRedactionEnabled:m,getComputerUseSupported:g}=r,v=`${s.platform()} ${s.release()}`,y=(0,uo.getSuggestedShell)(p),w=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),b=n,S=n?`${n}/terminals`:void 0,k=n&&!0!==i?`${n}/agent-notes/shared`:void 0,E=n&&o?`${n}/agent-notes/${o}`:void 0,x=n?`${n}/agent-transcripts`:void 0,C=!!u&&u(),_=d?.(),P=a?.();let T;if(h)try{T=await h()}catch{T=void 0}return new pg.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!==T?.hasDefaults&&{sandboxNetworkHasDefaults:T.hasDefaults},...T?.explicitEntries&&T.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:T.explicitEntries},...void 0!==g&&{computerUseSupported:g()},...void 0!==c&&{isWorkingDirHomeDir:c}})}const Pg={type:"object",properties:{},additionalProperties:!1};function Tg(e){return{tools:e.servers.flatMap((e=>e.tools)).map((e=>new rr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?nr.Value.fromJson(e.inputSchema):void 0}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function Ig(e,t){const r=e.servers.map((e=>{const r=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),n=e.tools.map((e=>new rr.E$({toolName:e.toolName,description:e.description,inputSchema:void 0!==e.inputSchema?nr.Value.fromJson(e.inputSchema):void 0})));return!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||n.some((e=>e.toolName===mp))||n.push(new rr.E$({toolName:mp,description:gp,inputSchema:nr.Value.fromJson(Pg)})),new rr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:r||void 0,tools:n})}));return new rr.U_({enabled:!0,mcpDescriptors:r})}function Rg(e){const t=e?.trim();return t||void 0}function Ag(e,t){const r=function(e){return Rg(e.serverIdentifier)}(e);if(r)return r;const n=Rg(e.serverName);return n?t.get(n)??n:void 0}function Og(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}class jg{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(Eg.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(Eg.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=>Ag(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=>Ag(e,n)===o)),status:r?.get(o)}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(Eg.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>[t,Og(await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"}))))])));return new Map(n)}(e,this.mcpLease))}}class Mg{constructor(e,t){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}return r=await this.mcpStateAccessor.getState(e),new St._W({result:{case:"success",value:new St.pv({servers:r.servers.map((e=>new St.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new rr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?nr.Value.fromJson(e.inputSchema):void 0}))),instructions:e.instructions,status:e.status})))})}});var r}}class Dg{constructor(e,t,r,n,o,i,s,a,l,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.lsExecutor=i,this.mcpStateAccessor=s,this.gitExecutor=a,this.workspacePaths=l,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:u,getSmartModeClassifierAutoModeEnabled:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,createFileWatcher:f,getSandboxEnabled:m,getSandboxSupported:g,getNetworkAllowlistInfo:v,userTerminalHint:y,getMcpFileSystemOptions:w,mcpMetaToolEnabled:b,alwaysExposeVirtualMcpAuthTool:S,artifactsFolder:k,secretRedactionEnabled:E,attributionConfigProvider:x,isAttributionDisabledByAdmin:C,getAgentSkills:_,additionalRules:P,getComputerUseSupported:T}=c;this.projectDir=u,this.isWorkingDirHomeDir=p,this.getSandboxEnabled=m,this.getSandboxSupported=g,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=d,this.devForceNextSmartModeClassifierBlockToken=h,this.userTerminalHint=y,this.getMcpFileSystemOptions=w,this.mcpMetaToolEnabled=b??!1,this.alwaysExposeVirtualMcpAuthTool=S??!1,this.artifactsFolder=k,this.secretRedactionEnabled=E,this.attributionConfigProvider=x,this.isAttributionDisabledByAdmin=C,this.getAgentSkills=_,this.additionalRules=P??[],this.getComputerUseSupported=T,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),void 0!==f&&(this.fileWatcher=f(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,Ye.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=Sg(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"getGitRepoPathForWorkspacePath"})).stdout.trim()}catch{return null}}(n.ctx,this.gitExecutor,t),i=o?await xc(n.ctx,this.gitExecutor,o):void 0,s={repoPath:o??void 0,remoteUrl:void 0!==i?Cc(i):void 0};this.cachedWorkspaces.set(t,s)}catch(e){r.error=e,r.hasError=!0}finally{kg(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,Ye.q6)(),r=Sg(e,(0,c.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId,this.globalCache=this.computeGlobalCache(r.ctx)}catch(t){e.error=t,e.hasError=!0}finally{kg(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Sg(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),i={},s=(e,t)=>{const r=performance.now();return t.finally((()=>{i[e]=Math.round(performance.now()-r)}))},[a,l,u,d]=await Promise.all([s("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),s("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),s("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),s("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),h=Math.round(performance.now()-o);return h>1e3&&Eg.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...i,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{kg(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=Sg(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let n;if(this.grepProvider.getTrackedState)try{n=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{n=void 0}let o=!0;const i=(await Promise.all(this.workspacePaths.map((async e=>{const t=this.getWorkspaceCache(e);if(void 0===t)return o=!1,void this.ensureWorkspaceCacheWarm(r.ctx,e);const i=n?.[e];if(void 0!==i)return new pg.DS({path:t.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:t.remoteUrl,isOriginBacked:bg(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(xg(e,t,r,n)),o(Cg(e,t,r,n))]);return{status:i,branchName:s}}(r.ctx,this.gitExecutor,t.repoPath,3e3);return new pg.DS({path:t.repoPath,status:s,branchName:a,remoteUrl:t.remoteUrl,isOriginBacked:bg(t.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:i,gitRepoInfoComplete:o}}catch(e){t.error=e,t.hasError=!0}finally{kg(t)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Sg(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),o=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=Sg(e,(0,c.VI)(n.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),void 0===this.globalCache){const e=this.computeGlobalCache(n.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)}))}return this.globalCache}catch(t){e.error=t,e.hasError=!0}finally{kg(e)}},s=performance.now(),a={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{a[e]=Math.round(performance.now()-r)}))},[u,d,h,{gitRepos:p,gitRepoInfoComplete:f},m,g,v,y,w]=await Promise.all([l("globalCache",i()),l("mcpState",this.mcpStateAccessor.getState(n.ctx)),l("env",_g(n.ctx,this.workspacePaths,{projectDir:o,notesSessionId:t.notesSessionId,metaAgentNotesEnabled:!1,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.artifactsFolder,secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported})),l("git",this.collectWorkspaceCaches(n.ctx)),l("conversationNotes",o&&t.notesSessionId?vg(o,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",o?yg(o):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(n.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",this.getAgentSkills?this.getAgentSkills(n.ctx):Promise.resolve([]))]),b=performance.now()-s;for(const[e,t]of Object.entries(a))n.span.setAttribute(`requestContext.timing.${e}Ms`,t);n.span.setAttribute("requestContext.timing.totalMs",Math.round(b)),b>1e3&&Eg.warn(n.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(b),...a});const S=this.mcpMetaToolEnabled?Ig(d,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool}):void 0,k=this.attributionConfigProvider?.get(),E=!y&&(k?.attribution?.attributeCommitsToAgent??!0),x=!y&&(k?.attribution?.attributePRsToAgent??!0),C=new pg.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}]:[],...Tg(d),conversationNotesListing:m,sharedNotesListing:g,customSubagents:u.customSubagents,mcpFileSystemOptions:v,mcpMetaToolOptions:S,supportsMcpAuth:!0,commitAttributionMessage:E?"enabled":void 0,prAttributionMessage:x?"enabled":void 0,agentSkills:w});return null!==u.cloudRule&&void 0!==u.cloudRule&&(C.cloudRule=u.cloudRule),C}catch(e){r.error=e,r.hasError=!0}finally{kg(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Sg(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=await this.computeCachedRequestContext(n.ctx,t);return new pg._G({result:{case:"success",value:new pg.yW({requestContext:e})}})}catch(e){return n.span.recordException(e),new pg._G({result:{case:"error",value:new pg.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{kg(r)}}}function Ng(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===kt._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var $g=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Lg{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new kt.W4({result:{case:"success",value:new kt.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:mo(e.sandboxPolicy)}):new kt.W4({result:{case:"failure",value:new kt.xC({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:mo(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=yd(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 kt.W4({result:{case:"timeout",value:new kt.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:mo(o)}):e.signal.aborted?new kt.W4({result:{case:"rejected",value:new kt.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:mo(o)}):new kt.W4({result:{case:"spawnError",value:new kt.mJ({command:t.command,workingDirectory:r,error:i instanceof Error?i.message:"Unknown error"})},sandboxPolicy:mo(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalShellExecutor.execute");const o=t.command,i=t.requestedSandboxPolicy?fo(t.requestedSandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(),a=Ng(t),l=(0,Vn.o1)(s);if(!t.parsingResult)return new kt.W4({result:{case:"spawnError",value:new kt.mJ({command:o,workingDirectory:l,error:"Parsing result is required"})}});let u;if(t.skipApproval)u=i;else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:l,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Bt(t)},i);if("block"===e.kind)return"permissionsConfig"===e.reason.type&&e.reason.isReadonly?new kt.W4({result:{case:"permissionDenied",value:new kt.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new kt.W4({result:{case:"rejected",value:new kt.pZ({command:o,workingDirectory:l,reason:vo(e.reason)})}});u=e.policy}if(ro()&&(u=lo(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{$g(r)}}}var Fg=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class Ug{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new kt.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new Fg.e({allowlisted:n})}}class Bg{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new kt.jK({status:kt.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}var zg=r("../utils/dist/workspace-paths.js"),Wg=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},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});const qg=(0,h.h)("local-exec:shell-core"),Gg="win32"===process.platform,Vg=["CURSOR_CONVERSATION_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Jg(e){return`'${e.replace(/'/g,"'\\''")}'`}function Kg(e,t){return e[t]??process.env[t]}function Zg(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}class Yg{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{Wg(r,(0,c.VI)(e.withName("ShellCoreExecutor.execute")),!1);const n=performance.now(),s=t.workingDirectory||await this.executor.getCwd(),l=(0,Vn.o1)(s,this.workspacePath);let u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(u={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,v={CURSOR_AGENT:"1"};t.conversationId&&(v.CURSOR_CONVERSATION_ID=(0,zg.sh)(t.conversationId)),this.projectDir&&(v.AGENT_TRANSCRIPTS=a.join(this.projectDir,zg.O2));const y=this.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(v,y),function(e){const t=[`builtin unset ${Vg.join(" ")} 2>/dev/null || true`];for(const r of Vg){const n=Kg(e,r);void 0!==n&&t.push(`builtin export ${r}=${Jg(n)}`)}const r=t.join("; "),n=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),o=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,n,r].filter((e=>void 0!==e&&""!==e)).join("; ")}(v);const w=function(e,t){const r=Kg(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[]}}(Kg(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=Zg(s.additionalReadonlyPaths,a):s.additionalReadwritePaths=Zg(s.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==s.type?s.additionalReadonlyPaths=Zg(s.additionalReadonlyPaths,e.path):s.additionalReadwritePaths=Zg(s.additionalReadwritePaths,e.path);return{...e,perUser:s}}(t.sandboxPolicy,v),b=(0,uo.getSandboxPolicyType)(w??uo.INSECURE_NONE_SANDBOX_POLICY);w&&(yield{type:"start",sandboxed:"workspace_readonly"===b||"workspace_readwrite"===b}),t.askpassConfig&&!Gg&&(v.SUDO_ASKPASS=t.askpassConfig.helperPath,v.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,v.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let S=0,k="";for await(const r of this.executor.execute(e,t.command,{signal:g,workingDirectory:l,env:v,sandboxPolicy:w,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,bufferOutputEvents:this.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.shellOutputBackpressureOptions?.outputLimiterOptions})){if(S=0,k="",("stdout"===r.type||"stderr"===r.type)&&(k=r.data.toString(),S=r.data.length,u))if(u.size+=S,u.lineCount+=k.split("\n").length-1,u.size>bd);else if(u.file)u.file.write(k);else if(u.buffer+=k,u.size>u.threshold){const e=a.join(this.projectDir,wd);u.path=a.join(e,`${(0,o.randomUUID)()}.txt`),await(0,Hn.mkdir)(a.dirname(u.path),{recursive:!0}),u.file=(0,i.createWriteStream)(u.path),u.file.write(u.buffer),u.buffer=""}switch(r.type){case"stdout":p||(d+S>ed?(p=!0,yield{type:"stdout_trimmed"}):(d+=S,yield{type:"stdout",data:k}));break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:uo.SHELL_OUTPUT_SUPPRESSED_NOTICE});break;case"stderr":f||(h+S>ed?(f=!0,yield{type:"stderr_trimmed"}):(h+=S,yield{type:"stderr",data:k}));break;case"exit":{const e=Math.max(0,Math.round(performance.now()-n));let t;u?.file&&(await new Promise((e=>u.file.end(e))),t=new zh.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})),yield{type:"exit",code:r.code,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}}catch(e){r.error=e,r.hasError=!0}finally{Hg(r)}}async getCwd(){return this.executor.getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Xg{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Wg(r,(0,c.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),qg.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{Hg(r)}}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Qg{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 ev=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 tv=(0,h.h)("local-exec:shell-stream");class rv{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===kt.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:kt.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:kt.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 nv{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 kt.jK({status:kt.iA.ACCEPTED,shellResult:r}):new kt.jK({status:kt.iA.NOT_FOUND})}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const n=t.command;let o=t.requestedSandboxPolicy?fo(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=Ng(t),a=(0,Vn.o1)(i),l=Date.now();if(!t.parsingResult)throw new Error("Parsing result is required");const u=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0},o);if("block"===u.kind)return"permissionsConfig"===u.reason.type?void(yield new kt.FI({event:{case:"permissionDenied",value:new kt.jn({command:n,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:u.reason.isReadonly??!1})}})):void(yield new kt.FI({event:{case:"rejected",value:new kt.pZ({command:n,workingDirectory:a,reason:vo(u.reason)})}}));if(tv.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:t.parsingResult?.executableCommands.length??0,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval)tv.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"});else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:a,timeout:s,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Bt(t)},o);if("block"===r.kind){if(tv.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 kt.FI({event:{case:"permissionDenied",value:new kt.jn({command:n,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const o=vo(r.reason);return void(yield new kt.FI({event:{case:"rejected",value:new kt.pZ({command:n,workingDirectory:a,reason:o})}}))}o=r.policy,tv.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:o.type})}if(ro()&&(o=lo(n,t.parsingResult),"insecure_none"!==o.type)){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}yield new kt.FI({event:{case:"start",value:new kt.tD({sandboxPolicy:mo(o)})}});const d=t.timeoutBehavior===kt._d.BACKGROUND,h=d&&!t.closeStdin&&void 0===t.smartModeApproval,p=new AbortController,f=d?p.signal:e.signal?AbortSignal.any([e.signal,p.signal]):p.signal,m=!0,g=o?{perRepo:o}:void 0,v=this.coreExecutor.execute(e,{command:n,workingDirectory:i,signal:f,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:g,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:h,showElapsedTime:m});let y;d||(y=setTimeout((()=>p.abort()),s));const w=d?new rv(v[Symbol.asyncIterator](),s):null;let b,S,k,E="",x=!1;const C=t.toolCallId&&w?{requestBackground:()=>{if(w.requestBackground())return k=k??this.backgroundShellManager.generateShellId(),new kt.W4({result:{case:"success",value:new kt.QR({shellId:k,pid:S,command:n,workingDirectory:a,msToWait:yd(Date.now()-l),backgroundReason:kt.Jg.USER_REQUEST,interleavedOutput:E})}})}}:void 0;t.toolCallId&&C&&this.activeForegroundExecutions.set(t.toolCallId,C);const _=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===C&&this.activeForegroundExecutions.delete(t.toolCallId)};let P;w&&e.signal&&e.signal.addEventListener("abort",(()=>{w.backgroundRequested||(p.abort(),w.abort())}),{once:!0});const T=t.hardTimeout;void 0!==T&&T>0&&(P=setTimeout((()=>{void 0!==k?this.backgroundShellManager.abort(k)||p.abort():(x=!0,p.abort(),w?.abort())}),T));const I=w?.iterate()??v;try{for await(const t of I)if("stdout"===t.type)E+=t.data,yield new kt.FI({event:{case:"stdout",value:new kt.o0({data:t.data})}});else if("stderr"===t.type)E+=t.data,yield new kt.FI({event:{case:"stderr",value:new kt.Db({data:t.data})}});else if("stdin_ready"===t.type)b=t.stdin,S=t.pid;else if("exit"===t.type){let r;t.aborted&&(r=e.signal?.aborted?kt.Lv.USER_ABORT:w?.timedOut||p.signal.aborted?kt.Lv.TIMEOUT:kt.Lv.USER_ABORT),yield new kt.FI({event:{case:"exit",value:new kt.vb({code:(t.code??0)>>>0,cwd:await this.coreExecutor.getCwd(),outputLocation:t.outputLocation,aborted:t.aborted,abortReason:r,localExecutionTimeMs:yd(t.localExecutionTimeMs)})}})}}finally{clearTimeout(y),w?.backgroundRequested||clearTimeout(P),_()}if(w?.backgroundRequested&&!x){const r=k??this.backgroundShellManager.generateShellId();k=r;const o=w.backgroundReasonValue===kt.Jg.USER_REQUEST?kt.Jg.USER_REQUEST:kt.Jg.TIMEOUT,i=o===kt.Jg.USER_REQUEST?Date.now()-l:s;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:n,workingDirectory:a,toolCallId:t.toolCallId,sandboxPolicy:g,initialOutput:E,stdin:b,pid:S,abortController:p,eventIterator:w.getHandoffIterator(),startTime:l,showElapsedTime:m,description:t.description,outputNotification:t.outputNotification}),yield new kt.FI({event:{case:"backgrounded",value:new kt.Y9({shellId:r,command:n,workingDirectory:a,pid:S,msToWait:m?i:void 0,reason:o})}})}else e.signal?.aborted&&void 0!==w?.stopReasonValue?(clearTimeout(P),yield new kt.FI({event:{case:"exit",value:new kt.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(),aborted:!0,abortReason:kt.Lv.USER_ABORT})}})):clearTimeout(P)}catch(e){r.error=e,r.hasError=!0}finally{ev(r)}}}var ov=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class iv{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new ov.M({allowlisted:r})}}var sv=r("node:constants");const av=(0,a.join)((0,s.homedir)(),".cursor","projects"),lv=(0,a.join)((0,s.homedir)(),".cursor","worktrees");function cv(e){return Cm(av,e)&&e!==av}function uv(e){return Cm(lv,e)&&e!==lv}function dv(e,t){const r=function(e){if(!Cm(av,e))return;if(e===av)return;const t=(0,a.relative)(av,e).split(a.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}var hv=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 pv=(0,h.h)("LocalWriteExecutor"),fv=async(e,t,r,n)=>{const o=setTimeout((()=>{pv.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};class mv{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:i,onWriteForAiTracking:s}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=i,this.onWriteForAiTracking=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,o=t.path,i=t.fileText,s=t.fileBytes.length>0?t.fileBytes:void 0,l=(0,Vn.o1)(o,this.workspacePath),u=dv(l,["assets","agent-tools","swarm-agents"]);if((0,Vn.fl)({targetPath:l,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Et.v3({result:{case:"error",value:new Et.QM({path:l,error:Vn.PS})}});let d,h=!1;try{(await(0,Hn.stat)(l)).size<=td?d=await fv(n,"readText before write",3e3,(()=>sc(l,t.encodingHint))):h=!0}catch{}const p=await fv(n,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(n,l,i)));if(p){const e=await fv(n,"handleBlockReason",3e3,(()=>go(p,{onNeedsApproval:async(e,r)=>{const n="fileEdit"!==r?.type||r.isNewFile,o="fileEdit"===r?.type?r.diffString:i,s="fileEdit"===r?.type?r.blockReason:void 0,a=await this.pendingDecisionProvider.requestApproval({type:rd.Write,details:{path:l,reason:e,isNewFile:n,diffString:o,before:d,after:i,blockReason:s},toolCallId:t.toolCallId});return a.approved?null:new Et.v3({result:{case:"rejected",value:new Et.en({path:l,reason:a.reason||""})}})},onUserRejected:e=>new Et.v3({result:{case:"rejected",value:new Et.en({path:l,reason:e||""})}}),onPermissionDenied:(e,t)=>new Et.v3({result:{case:"permissionDenied",value:new Et.U7({path:l,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const f=(0,a.dirname)(l);try{await fv(n,"mkdir",3e3,(()=>(0,Hn.mkdir)(f,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new Et.v3({result:{case:"permissionDenied",value:new Et.U7({path:l,directory:f,operation:"create_directory",error:"Permission denied"})}}):new Et.v3({result:{case:"error",value:new Et.QM({path:l,error:e.message})}})}let m,g;if(void 0!==s)m=s,g=0;else{const e=await fv(n,"getBufferForWrite",3e3,(()=>ac(l,i,this.workspacePath,t.encodingHint)));m=e.buffer,g=e.lines}try{await fv(n,"writeFile",3e3,(async()=>{let e;await(0,Hn.writeFile)(l,m,{flush:!0});try{e=await(0,Hn.open)((0,a.dirname)(l),sv.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new Et.v3({result:{case:"permissionDenied",value:new Et.U7({path:l,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new Et.v3({result:{case:"noSpace",value:new Et.bM({path:l})}}):new Et.v3({result:{case:"error",value:new Et.QM({path:l,error:e.message})}})}if(this.fileChangeTracker&&void 0===s&&!u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(l,d,i,e)}if(this.onWriteForAiTracking&&void 0===s&&!u){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:l,beforeContent:d,afterContent:i,metadata:e})}catch(e){pv.warn(n,"onWriteForAiTracking failed (write succeeded)",{path:l,error:e instanceof Error?e.message:String(e)})}}const v=m.byteLength;let y;if(t.returnFileContentAfterWrite)try{y=await fv(n,"readText after write",3e3,(()=>sc(l,t.encodingHint)))}catch{}return new Et.v3({result:{case:"success",value:new Et.j6({path:l,linesCreated:g,fileSize:v,...void 0!==y&&{fileContentAfterWrite:y}})}})}catch(e){r.error=e,r.hasError=!0}finally{hv(r)}}}const gv=(0,h.h)("local-exec:provider");class vv 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,a.join)(e,".cursor/sandbox.json");try{const r=(0,i.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,uo.parseSandboxPolicyJson)(n);return(0,uo.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.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig;const o=this.terminalExecutor??(0,uo.createDefaultTerminalExecutor)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let l;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,a.dirname)(e)));l=e.every((t=>t===e[0]))?e[0]:void 0}else l=t;let c=new Yg(o,t??(0,s.homedir)(),this.projectDir,e.shellOutputBackpressureOptions,e.shellExtraEnvProvider);e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Qg(c,this.askpassConfig)),this.shellManager&&(c=new Xg(c,this.shellManager));const u=e.overrideShellExecutor??new Lg(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore);this.register(xt,fm(u)),this.register(ct,fm(new wf(this.permissionsService,this.ignoreService,l??t??this.projectDir)));const d=e.overrideWriteExecutor??new mv(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:l,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking});this.register(_t,fm(d)),this.register(oe,fm(new od(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,l,e.onDeleteForAiTracking))),this.register(se,fm(new cd)),this.register(ae,new Wm);const h=this.mcpStateAccessor??new jg(this.mcpLease);this.register(le,fm(new lf(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:h})));const p=fm(e.overrideReadExecutor??new lg(this.permissionsService,l,{mcpStateAccessor:h,useStreamingRead:e.useStreamingRead}));this.register(vt,p),e.registerRedactedReadExecutor&&this.register(yt,p);const f=new hf(this.permissionsService,this.ignoreService,l);this.register(Qe,fm(f)),this.register(mt,fm(new rm(this.permissionsService,l))),this.register(ut,fm(new Rf(u))),this.register(dt,fm(new zf(this.permissionsService,d,l))),this.register(gt,fm(new im(d,l))),this.register(pt,fm(new Zf(this.permissionsService,l))),this.register(ht,fm(new Gf(this.permissionsService,l))),this.register(ft,fm(new Qf(this.permissionsService,l))),this.register(ie,fm(new Em(l,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(re,fm(new vm(e.getCanvasDiagnostics))),this.register(ot,fm(new $p(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded))),this.register(it,fm(new Lp(this.mcpLease,e.ensureMcpServersLoaded))),this.register(st,fm(new Fp(this.mcpLease,l||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(at,fm(new Mg(h,e.ensureMcpServersLoaded)));const m=fm(this.sharedRequestContextExecutor??new Dg(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,f,h,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,Vn.yn)(t,(0,s.homedir)()),createFileWatcher:this.createFileWatcher,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:e.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,artifactsFolder:e.artifactsFolder,secretRedactionEnabled:e.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor}));this.register($t,{execute:async(t,r,n)=>{const o=await m.execute(t,r,n);if("success"!==o.result.case||void 0===o.result.value.requestContext)return o;const i=o.clone();if("success"!==i.result.case)return o;const s=i.result.value.requestContext;if(void 0===s)return i;const a=await h.getState(t),l=Tg(a);if(s.tools=l.tools,s.mcpInstructions=l.mcpInstructions,s.mcpMetaToolOptions=this.mcpMetaToolEnabled?Ig(a,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool}):void 0,s.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t)),void 0!==e.getMountedAgentStores&&void 0!==s.env)try{const r=await e.getMountedAgentStores(t);s.env.mountedAgentStores=r.map((e=>e.clone()))}catch{s.env.mountedAgentStores=[],gv.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new jo(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(X,fm(this.backgroundShellExecutor));const g=new nv(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(Ct,function(e,t){const r=new qn.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 pm(a);r.set(i,l),yield*l.fork()}}}(g)),void 0!==e.agentStoreConflictDrainer&&this.register(Y,new lm(e.agentStoreConflictDrainer)),this.register(Lt,new Ug(this.permissionsService)),this.register(lt,new qm(this.permissionsService)),this.register(Kt,new iv(this.permissionsService));const v=new Bg(g);this.register(Ft,fm(v));const y=!1===e.enableWriteBackgroundShellStdin?new cm((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new cm(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(Q,fm(y)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(ne,fm(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new hg({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Nt,fm(this.recordScreenExecutor))}}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function yv(e){return e.replace(/\\/g,"/")}function wv(e,t){for(const r of t){const t=yv(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var bv;function Sv(e,t){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return bv.Plugin;const r=yv(e.fullPath);return wv(r,t.builtinDirs)?bv.Builtin:wv(r,t.userDirs)?bv.UserHome:(wv(r,t.workspaceDirs),bv.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"}(bv||(bv={}));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});const Ev=(0,$o.debuglog)("merged-agent-skills");class xv{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,c.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(Ev("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=>(Ev("getDisabledManagedSkillPaths rejected; fail-open: %s",e instanceof Error?e.message:String(e)),[])))]),s=o.flat(),l=new Set,u=[];for(const e of s){const t=lu(e.fullPath);l.has(t)||(l.add(t),u.push(e))}let d=u;i.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,i))));const h=this.getPromptSortContext;return void 0!==h?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[qc(e.userHomeDirectory).dirPath],r=Vc(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,a.join)(t,".cursor","rules"));for(const e of Gc(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,t)=>({skill:e,index:t,tier:Sv(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{kv(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()}),xv.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()}}xv.CHANGE_COALESCE_MS=1500;const Cv=(0,h.h)("skill-sync-manifest"),_v=".sync-manifest.json";async function Pv(e,t){try{const r=await(0,Hn.readFile)((0,a.join)(e,_v),"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:(Cv.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||Cv.warn(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function Tv(e,t,r){e.skills[t]={lastSyncedAt:r}}function Iv(e,t){delete e.skills[t]}var Rv=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 Av=(0,h.h)("builtin-skills-sync");function Ov(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jv(e){const t=Ia(e.content),r=Ov(t.data)?t.data:{};return Ra(`${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={...Ov(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 Mv(e,t,r){const n=(0,a.join)(t,r.id),o=(0,a.join)(n,"SKILL.md"),i=r.fileContent;try{if(await(0,Hn.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||Av.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Hn.mkdir)(n,{recursive:!0}),await(0,Hn.writeFile)(o,i,"utf-8"),!0}async function Dv(e,t){try{return(await(0,Hn.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||Av.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function Nv(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("syncBuiltinSkills")),!1).ctx,i=Date.now(),l=(0,a.join)((0,s.homedir)(),".cursor","skills-cursor");await(0,Hn.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([Pv(l,o),Dv(o,l)]),h=u.lastInventoryAt;(void 0===h||i-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,a.join)(t,e),[o,i]=await Promise.all([$v((0,a.join)(r,"SKILL.md")),"canvas"===e?$v((0,a.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));Av.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){Av.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(o,l,d,u),u.lastInventoryAt=i);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):Av.warn(o,"Skipping managed skill with unsafe id",{skillId:e.id});const f=new Set([...p.keys(),...d]);let m=0,g=0;const v=[];for(const e of f)try{const t=p.get(e),r=u.skills[e],n=r?i-r.lastSyncedAt:0,s=void 0!==r&&n>2592e5;if(t&&!1!==t.enabled)await Mv(o,l,{id:e,fileContent:jv(t)})?m++:g++,Tv(u,e,i);else if(!1===t?.enabled||s){const n=!1===t?.enabled?"enabled_false":"grace_expired";await(0,Hn.rm)((0,a.join)(l,e),{recursive:!0,force:!0}),Iv(u,e),v.push(e),Av.info(o,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?i-r.lastSyncedAt:null})}else r||Tv(u,e,i)}catch(t){Av.warn(o,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,a.join)(e,".sync-manifest.json.tmp"),n=(0,a.join)(e,_v);await(0,Hn.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,Hn.rename)(r,n)}(l,u)}catch(e){Av.warn(o,"Failed to persist sync manifest",{skillDir:l,error:String(e)})}return{synced:m,upToDate:g,removed:v}}catch(e){r.error=e,r.hasError=!0}finally{Rv(r)}var n}async function $v(e){try{return await(0,Hn.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Lv=(0,h.h)("managed-skills-sync");function Fv(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 Uv{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(...Gi(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=Fv(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var Bv=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,o,i){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=i,this.plugins=[],this._loadFailures=[],this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Fo,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{let t=[];try{t=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const r=new Set(e.plugins.map((e=>e.installPath))),n=t.filter((e=>!r.has(e.installPath)));return this.plugins=[...e.plugins,...n],this._loadFailures=e.failures,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${n.length} extension), ${e.failures.length} failures`),this.plugins})).catch((async e=>{this.pluginLogger.log("error",`Failed to load plugins: ${e}`);try{const e=await this._reloadExtensionPlugins();this.plugins=[...e]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${e}`),this.plugins=[]}return this._loadFailures=[],this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,a.resolve)(e),n=await(0,Hn.realpath)(r);if(!(await(0,Hn.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const o=s.homedir();if(n.split(a.sep).filter(Boolean).length<3||n===o||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let i=this._extensionPlugins.get(t);if(i||(i=new Map,this._extensionPlugins.set(t,i)),i.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const l=(0,a.basename)(n),c=await this._loadExtensionPluginContent(n,t);i.set(n,c),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${l} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,a.resolve)(e);let o;try{o=await(0,Hn.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,a.basename)(e),n={name:r,localPath:e,extensionId:t},o=await pl(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 n=(0,Ye.q6)().withName("LocalPluginsService.load"),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})}(e,(0,c.VI)(n),!1),performance.now()),i=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-o,{outcome:e})},s=this.getSettings(),l=(t=this.marketplaceOptions,r=this.userHomeDirectory,void 0===t?[]:(Array.isArray(t)?t:[t]).map((e=>({...e,userHomeDir:r})))),u=s.importThirdPartyPlugins,d=s.loadUserLocalPlugins??!0,h=s.loadCursorFirstParty??l.length>0;if(!u&&!h&&!d)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[]};this.pluginLogger.increment("local_plugins_service.load.start",1);const p=this.workspacePaths[0]??void 0,f=(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 Ga(this,arguments,void 0,(function*(e,t={}){var r,n,o,i,s;const l=null!==(r=t.log)&&void 0!==r?r:Fo,c=performance.now(),u=null===(n=t.loadClaude)||void 0===n||n,d=null===(o=t.loadUserLocal)||void 0===o||o,h=null!==(i=t.marketplaceSources)&&void 0!==i?i:[],p=null!==(s=t.loadCursorFirstParty)&&void 0!==s?s:h.length>0,f=[],m=[];let g;u&&f.push(gl(e,void 0,{userHomeDir:t.userHomeDir,onError:t.onError,log:l})),p&&h.length>0&&(g=Promise.all(h.map((e=>{var r,n;return function(e){return Ga(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:Fo,u=performance.now(),{client:d,userId:h,teamId:p,onCursorError:f,pruneOldVersions:m}=e,g=[],v=null!==(l=e.cacheManager)&&void 0!==l?l:new os(e.userHomeDir),y=performance.now(),w=yield d.listEnabledPlugins(h,p);c.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-y).toFixed(1)}ms (${w.plugins.length} plugins)`);const b=[];if(w.listFailures){g.push(...w.listFailures);for(const e of w.listFailures)b.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 S=new Map;for(const e of w.plugins)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`);g.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=S.get(s);if(l||(l={slug:i,pluginId:e.pluginId,versions:[]},S.set(s,l)),l.versions.push(e.version),yield v.isCached({marketplaceSlug:i,pluginId:e.pluginId,version:e.version}))a=v.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=v.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,Hn.mkdir)(t,{recursive:!0});try{yield d.installPlugin(e,t),yield v.markCacheComplete({marketplaceSlug:i,pluginId:e.pluginId,version:e.version})}catch(e){try{yield(0,Hn.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 ml(a,h,p);b.push(m);try{yield v.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));g.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:null===(i=e.marketplace)||void 0===i?void 0:i.name,errorMessage:r.message,errorType:Za(r)});const n=null===(s=e.marketplace)||void 0===s?void 0:s.name,o=void 0!==n&&"cursor-public"!==n&&n.length>0;b.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 S.values())try{yield v.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch(e){}return c.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-u).toFixed(1)}ms (${b.length} plugins loaded, ${g.length} failures)`),{plugins:b,failures:g}}))}(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 Ga(this,arguments,void 0,(function*(e={}){var t,r,n;const o=null!==(r=e.log)&&void 0!==r?r:Fo,i=performance.now(),s=null!==(n=e.userHomeDir)&&void 0!==n?n:process.env.HOME;if(!s)return o.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const l=(0,a.join)(s,".cursor","plugins","local");let c;try{c=yield(0,Hn.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,Hn.realpath)(l).catch((()=>(0,a.resolve)(l))),d=[];for(const r of c){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,a.join)(l,r.name);try{if(r.isSymbolicLink()){let e;try{e=yield(0,Hn.realpath)(n)}catch(e){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{qs(u,e)}catch(t){o.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${l}`);continue}}if(!(yield(0,Hn.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 pl(n,r.name,void 0,{configuredVariables:s}),S={source:"user-local",sourceInfo:{name:r.name,localPath:n}};d.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:S,installPath:n},void 0!==a&&{displayName:a}),void 0!==c&&{description:c}),void 0!==h&&{authorName:h}),{variablesSchema:p,skills:f,rules:m,agents:g,commands:v,mcpConfig:null!=y?y:void 0,capabilities:w,hooks:b})),o.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-i).toFixed(1)}ms`)}catch(e){o.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return o.log("info",`loadUserLocalPlugins completed in ${(performance.now()-i).toFixed(1)}ms (${d.length} plugins loaded)`),d}))}({userHomeDir:t.userHomeDir,log:l,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[v,y]=yield Promise.all([Promise.all(f),null!=g?g:Promise.resolve([])]),w=[];for(const e of y)w.push(...e.plugins),m.push(...e.failures);w.push(...v.flat());const b=new Set,S=[];for(const e of w){if(!e.installPath){S.push(e);continue}const t=yield(0,Hn.realpath)(e.installPath).catch((()=>e.installPath));b.has(t)||(b.add(t),S.push(e))}const k=new Map,E=[];for(const e of S){const t=vl(e);if(void 0!==t){const r=k.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=E.findIndex((e=>vl(e)===t&&e.loadError));-1!==r&&E.splice(r,1),k.set(t,!0),E.push(e);continue}k.set(t,n)}E.push(e)}const x=performance.now()-c;return l.log("info",`loadAllPlugins completed in ${x.toFixed(1)}ms (claude=${u}, userLocal=${d}, marketplace=${h.length} sources, total=${E.length} plugins, failures=${m.length})`),{plugins:E,failures:m}}))}(p,{userHomeDir:this.userHomeDirectory,loadClaude:u,loadUserLocal:d,loadCursorFirstParty:h&&l.length>0,marketplaceSources:l.length>0?l.map((e=>({...e,onCursorError:f}))):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 i("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-o).toFixed(1)}ms`),e}catch(e){return i("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${e}`),{plugins:[],failures:[]}}}catch(t){e.error=t,e.hasError=!0}finally{Bv(e)}var t,r}}const Wv=BigInt(0),Hv=BigInt(8),qv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Jv(e){const t=e.split(".");if(4!==t.length)return;let r=Wv;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<<Hv|BigInt(t)}return{version:4,value:r}}function Kv(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=Jv(n);if(!o)return;t.push(Number(o.value>>qv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){var t;return null!==(t=Jv(e))&&void 0!==t?t:function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Kv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<qv|BigInt(t)),Wv)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),i=Kv(n),s=Kv(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<<qv|BigInt(t)),Wv)}}(e)}function Yv(e,t){const r=Vv(e),n=Vv(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=Zv(t.slice(0,r)),o=Zv(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 Xv(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=>Yv(e,t)))}(r.hostname,t)}const Qv=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function ey(e){return e.trim().split(/\s+/).filter(Boolean)}function ty(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 ey(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 Qv.has(o)}function ry(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 ny(e,t){return e.commandName.localeCompare(t.commandName)}function oy(e){var t;return null!==(t=e.split(" ")[0])&&void 0!==t?t:e}function iy(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=ey(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(ny);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=ry(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&&ry(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(oy(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(oy(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(oy(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const s=n.filter((e=>!i.has(oy(e))));return{defaultSelectedOptionIds:[...new Set([...s,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}function sy(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function ay(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 ly(e,t){const r=(0,Vn.o1)(e,t);try{return sy(await(0,Hn.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return sy(r,r,ay(t));try{if((await(0,Hn.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Hn.readlink)(r)}catch{}return sy(r,r,{status:"danglingSymlink",symlinkTarget:e})}return sy(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){const t=e;return"ENOENT"===t.code?async function(e){let t=(0,a.dirname)(e);const r=[(0,a.basename)(e)];for(;(0,a.dirname)(t)!==t;){try{const n=await(0,Hn.realpath)(t);return sy((0,a.join)(n,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return sy(e,e,ay(r))}r.unshift((0,a.basename)(t)),t=(0,a.dirname)(t)}return sy(e,e,{status:"newFile"})}(r):sy(r,r,ay(t))}}}function cy(e){return"resolved"===e.status||"newFile"===e.status}function uy(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}var dy=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},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,h.h)("permissions-service"),fy=(0,p.Pu)("local_exec.permissions.mcp_allowlist_check.result",{description:"Result of MCP allowlist checks at user and team levels per tool call.",labelNames:["allowlist_scope","outcome"]});function my(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 gy(e){return[...new Set(e)]}function vy(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function yy(e,t){const r="win32"===process.platform||"darwin"===process.platform,n=r?e.toLowerCase():e,o=r?t.toLowerCase():t;if(n===o)return!0;const i=o.endsWith(a.sep)?o:o+a.sep;return n.startsWith(i)}function wy({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 by(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Sy(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function ky(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText&&(0,uo.isSafeHeredocStdinCommand)(e.targetText)}async function Ey({targetText:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n,pathModule:o,tempPathOptions:i}){if(""!==o.parse(e).root&&!o.isAbsolute(e))return;const s=await n(e,t);if(cy(s.resolution)){for(const e of r){const t=await n(e);if(cy(t.resolution)&&wy({basePath:t.resolvedPath,targetPath:s.resolvedPath,pathModule:o}))return"workspace-file"}return Ry(s.resolvedPath,i)?"tmp-file":void 0}}function xy(e){return gy(e.map((e=>e.trim())).filter(Boolean))}function Cy(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 _y(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Py(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new kt.r6({type:"word",value:e})));return new kt.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ty(e,t={}){return{type:e,...t}}function Iy(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1],n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Ry(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),i=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(i)}return!1}const i=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},s=i(e);return(void 0===o||!wy({basePath:i(o),targetPath:s,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>s.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>s.startsWith(e))))}function Ay(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,uo.isNetworkEnabledByPolicy)(e.networkPolicy),n=(0,uo.isNetworkEnabledByPolicy)(t.networkPolicy);if(r&&!n)return!1;const o=(0,uo.isAllowAllNetworkByPolicy)(e.networkPolicy),i=(0,uo.isAllowAllNetworkByPolicy)(t.networkPolicy);return!(o&&n&&!i)&&("workspace_readonly"===e.type&&"workspace_readwrite"===t.type||e.type===t.type)}class Oy{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&Ay(t,r);this.state=o?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Ay(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function jy(e){return e?.type??"undefined"}class My{constructor(e,t,r,n,o,i=!1,l){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=i,this.rootDirectories=Array.isArray(o)?o:[o??process.cwd()],this.perUserSandboxConfigPath=l?.perUserSandboxConfigPath??(0,a.join)((0,s.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=l?.mcpAllowlistLog}async shouldBlockRead(e,{cursorIgnoreChecked:t=!1}={}){const r=(0,Vn.o1)(e),n=await Rc(r);return null===n?{type:"unsafeResolution",message:my("Read","path",r)}:await this.ignoreService.isRepoBlocked(n)?{type:"adminBlock",source:"Team repo blocklist"}:await this.isPathExplicitlyDenied("Read",r)?{type:"permissionsConfig"}:!cv(n)&&!uv(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{dy(n,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const o=await ly(t);if(!cy(o.resolution))return{type:"unsafeResolution",message:uy(o.originalPath,o.resolution)};const i=o.resolvedPath,u=i;if(await this.ignoreService.isRepoBlocked(u))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",i))return{type:"permissionsConfig"};const d=o.originalPath.split(a.sep).pop()?.toLowerCase()??"",h=i.split(a.sep).pop()?.toLowerCase()??"";if(".cursorignore"===d||".cursorignore"===h)return{type:"permissionsConfig"};const p=cv(u),f=uv(u),m=!p&&!f&&await this.ignoreService.isCursorIgnored(u);if(p||f);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",i))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(i))return!1;const g=await this.getPermissions();if("workspace_readonly"===g.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===g.approvalMode)return!1;for(const e of this.rootDirectories){const t=await ly(e);if(!cy(t.resolution))continue;const r=t.resolvedPath;if(yy(i,r)){const e=(0,a.relative)(r,i).split(a.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const v=async()=>{let e=!1,t="";try{t=await sc(i),e=!1}catch{e=!0}let n="";if(e)n=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,jf.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 ly(e);if(!cy(t.resolution))continue;const r=t.resolvedPath;if(yy(i,r)){w=!0,y=r;break}}const b=w?void 0:function(e){if(!uv(e))return;const t=(0,a.relative)(lv,e).split(a.sep).filter(Boolean);return 0!==t.length?(0,a.join)(lv,t[0]):void 0}(i);if(!w&&void 0===b){if(function(e){return Ry(e,{platform:process.platform,env:process.env,pathModule:l,homeDirectory:(0,s.homedir)()})}(i))return!1;if(dv(i,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,s.homedir)()}${a.sep}.cursor${a.sep}`;if(i.startsWith(e)){const e=i.split(a.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const S=y??b,k=i;let E=(0,a.relative)(S,k).split(a.sep);if(E=E.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&E.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await v();return{type:"needsApproval",approvalReason:`Protected config file: ${E[E.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,uo.isHardcodedWriteProtected)(i,S)){const e=E[E.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}return await this.checkCursorFileProtection(E)||!1}catch(e){n.error=e,n.hasError=!0}finally{hy(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await Rc(t.workingDirectory);if(null===n){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:my("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(n))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const o=(await this.getPermissions()).userConfiguredPolicy,i=r??o;return"workspace_readonly"===o.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,n){const o=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory},n);if("block"===o.kind)return o;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,u=i.userConfiguredPolicy,d=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(py.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:jy(u),requestedPolicyType:jy(n),effectiveRequestedPolicyType:jy(n??u),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:zt(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return py.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:jy(u),requestedPolicyType:jy(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??u);const h=r.parsingResult.executableCommands,p=r.parsingResult.hasRedirects,f=!0===r.parsingResult.allRedirectsAreDevNull,m=r.parsingResult.parsingFailed,g=r.classifierResult,v=r.smartModeApprovalReason,y=r.smartModeApprovalRequestId,w=void 0!==g&&!g.classificationFailed&&g.commands.length>0?g:void 0,b="allowlist"===a&&i.smartAllowlistEnabled?w?.commands:void 0,S=void 0!==b,k=b?b.map(Py):h,E=void 0!==b?b.map(Cy):k.map((e=>[e.fullText.trim()].filter(Boolean))),x=void 0!==w?w.commands.map(Cy):E;if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==u.type&&(n={...n,skipStatsigDefaults:u.skipStatsigDefaults??!0}),"insecure_none"!==u.type&&(0,uo.isNetworkEnabledByPolicy)(u.networkPolicy)&&"insecure_none"!==n.type&&!(0,uo.isAllowAllNetworkByPolicy)(n.networkPolicy)){const e=u.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}}g&&py.info(e,"Smart allowlist: classifier result received",{classificationFailed:g.classificationFailed,suggestedSandboxMode:g.suggestedSandboxMode,commandCount:g.commands.length,suggestedAllowlistEntryCount:g.commands.filter((e=>e.suggestedAllowlistEntry)).length});let C=!1;const _=[],P=[];let T=[],I=[],R=[];const A=xy(i.smartAllowlistDenylist??[]);if(A.length>0){I=[];const t=x.map((e=>e[0]??""));for(let e=0;e<x.length;e++){const r=x[e];if(r&&0!==r.length&&A.some((e=>_y(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&(py.info(e,"Command blocklist: commands require approval",{count:I.length}),_.push(`In blocklist: ${I.join(", ")}`))}if(S&&g){const t=E.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));py.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:A.length});const n=E.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;e<g.commands.length;e++){if(n[e])continue;const t=g.commands[e];t&&s.push(t)}if(T=xy(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(ty(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),xy(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>T.includes(e))),T.length>0){const e=iy(T,R),t=e.length>0?e.join(", "):T.join(", ");P.push(`Not in allowlist: ${t}`)}C=o&&0===I.length,C&&py.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const O="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:u,j=k.map(((e,t)=>new Oy(e,n,O,E[t])));if((0===k.length||m&&!S)&&!c){py.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:jy(n),userConfiguredPolicyType:jy(u),isSmartAllowlistActive:S,parsingFailed:m,parserCommandCount:k.length,hasSmartModeApprovalReason:void 0!==v,hasSmartModeApprovalRequestId:void 0!==y});const o={type:rd.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:v??(m?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:v,smartModeApprovalRequestId:y}},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,j))return{kind:"block",reason:{type:"permissionsConfig"}};const M=await this.teamSettingsService.getAutoRunControls(),D={type:"insecure_none"};for(const e of j)await this.isInShellAllowlist(e)&&e.approveWithPolicy(D),d&&M&&this.isInTeamAllowlist(M,e)&&e.approveWithPolicy(D);for(const e of j)M&&this.isInTeamBlocklist(M,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of j)"rm"===e.command.name&&e.deny();const $=this.buildShellApprovalDecisionFacts({commands:j,autoRunControls:M,shouldApplyTeamShellAllowlist:d,deleteProtectionEnabled:N,softDenylistedCommands:I});if("workspace_readonly"===u.type&&"workspace_readonly"!==n.type)return py.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=zt(r.hookApprovalRequirement),F=r.hookApprovalRequirement?.reason,U=L?void 0:this.getShellAutoApprovalPolicy({approvalMode:a,isUnrestricted:c,requestedPolicy:n,facts:$,preserveRequestedPolicyForAllowlistedCommands:S}),B=void 0!==U&&$.allCommandsAllowlisted&&"insecure_none"===U.type&&"allowlistEscalated"in U&&!0===U.allowlistEscalated;if(U&&(void 0===v||B)){S&&$.allCommandsPreapproved&&!$.allCommandsAllowlisted&&py.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(U);return py.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:jy(n),userConfiguredPolicyType:jy(u),autoApprovalPolicyType:jy(U),mergedPolicyType:jy(t),isSmartAllowlistActive:S,smartModeApprovalBypassedByAllowlist:B,allCommandsRunnable:$.allCommandsRunnable,allCommandsAllowlisted:$.allCommandsAllowlisted,allCommandsPreapproved:$.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==v,commandCount:j.length}),{kind:"allow",policy:t}}const z=!(!p||f||m)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n=ly,pathModule:o=l,tempPathOptions:i={platform:process.platform,env:process.env,pathModule:o,homeDirectory:(0,s.homedir)()}}){if(!e.hasRedirects)return!0;const a=e.redirects;if(0===a.length)return!1;const c=e.executableCommands.length>1,u=vy();for(const e of a){if(ky(e))continue;const s=c?vy():u,{operator:a,targetText:l}=e,h=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=Sy(l),t=void 0===e?void 0:s.fdTargets.get(e);if("original-stdout"!==(d=t)&&"original-stderr"!==d&&"dev-null"!==d&&"workspace-file"!==d&&"tmp-file"!==d){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}for(const e of h)s.fdTargets.set(e,t);continue}if("<&"===a){const e=Sy(l),t=void 0===e?void 0:s.fdTargets.get(e);if("dev-null"!==t){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}for(const e of h)s.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of h)s.fdTargets.set(e,"dev-null");continue}if(!by(a)||void 0===l){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}const p=await Ey({targetText:l,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n,pathModule:o,tempPathOptions:i});if(!p){for(const e of h)s.fdTargets.set(e,"unsafe");return!1}for(const e of h)s.fdTargets.set(e,p)}var d;return!0}({parsingResult:r.parsingResult,workingDirectory:r.workingDirectory,rootDirectories:this.rootDirectories});let W=(S||(!p||f||z)&&!m)&&("allowlist"===a||"ask-every-time"===a)&&$.canAllowlistInPrompt;const H=[],q=void 0!==v,G=$.notInTeamAllowlist.length>0&&($.hasSecurityDenies||$.hasSoftDenies||!$.allCommandsRunnable);if(void 0!==v&&H.push(v),L&&(q||H.push(F?`Hook requested approval: ${F}`:"Hook requested approval"),W=!1),_.length>0&&(q||H.push(..._),W=!1),!q)if(S&&P.length>0)H.push(...P);else if($.unapprovedCommands.length>0){const e=iy(this.generateAllowlistPatterns($.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):$.unapprovedCommands.map((e=>e.command.fullText)).join(", ");H.push(`Not in allowlist: ${t}`)}if($.hasSecurityDenies&&(q||($.rmDeniedByDeleteProtection.length>0&&H.push("Delete protection is enabled"),$.teamBlocklistedCommands.length>0&&H.push(`In team blocklist: ${$.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),W=!1),G){const t=$.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");py.info(e,"Shell permissions: commands not in team allowlist",{commandCount:$.notInTeamAllowlist.length}),q||H.push(`Not in team allowlist: ${t}`),W=!1}const V=H.join(" • "),J=[];if(W){const e=void 0!==v?j.filter((e=>"allowlisted"!==e.state)):$.unapprovedCommands;J.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const K=S&&P.length>0,Z=K?T:J,Y=K&&R.length>0?R:void 0,X="insecure_none"!==n.type&&"insecure_none"!==u.type,Q="insecure_none"!==n.type,ee=[void 0!==v?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,_.length>0?"command_blocklist":void 0,S&&P.length>0?"smart_allowlist_miss":void 0,$.unapprovedCommands.length>0?"unapproved_commands":void 0,$.hasSecurityDenies?"security_denies":void 0,G?"team_allowlist_miss":void 0].filter((e=>void 0!==e));py.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:jy(n),userConfiguredPolicyType:jy(u),isSandboxAvailable:X,isSandboxEnabled:Q,canAllowlist:W,isSmartAllowlistActive:S,hasSmartModeApprovalReason:void 0!==v,hasSmartModeApprovalRequestId:void 0!==y,hookForcesPrompt:L,approvalReasonTypes:ee,commandCount:j.length,unapprovedCommandCount:$.unapprovedCommands.length,deniedCommandCount:$.deniedCommands.length,notInTeamAllowlistCount:$.notInTeamAllowlist.length,notAllowedCommandCount:Z.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:$.allCommandsRunnable,allCommandsAllowlisted:$.allCommandsAllowlisted,allCommandsPreapproved:$.allCommandsPreapproved,hasSecurityDenies:$.hasSecurityDenies,hasSoftDenies:$.hasSoftDenies});const te={type:rd.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:V,isSandboxAvailable:"allowlist"===a&&X,isSandboxEnabled:"allowlist"===a&&Q,canAllowlist:W,notAllowedCommands:Z,suggestedAllowlistEntries:Y,smartModeApprovalReason:v,smartModeApprovalRequestId:y}},re=await this.pendingDecisionStore.requestApproval(te);if(re.approved){const e="unrestricted"===a?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:re.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 s=r.classifierResult,a=void 0!==s&&!s.classificationFailed&&s.commands.length>0?s:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==a;if(r.parsingResult.parsingFailed&&!l)return!1;const c=r.parsingResult.executableCommands,u=l?a.commands.map(Py):c;if(0===u.length)return!1;const d=l?a.commands.map(Cy):u.map((e=>[e.fullText.trim()].filter(Boolean))),h=void 0!==a?a.commands.map(Cy):d,p={type:"insecure_none"},f=u.map(((e,t)=>new Oy(e,p,void 0,d[t])));if(await this.hasHardDeny(n,f))return!1;const m=xy(o.smartAllowlistDenylist??[]);if(m.length>0)for(const e of h)if(e&&0!==e.length&&m.some((t=>_y(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&f.some((e=>"rm"===e.command.name)))return!1;const g=await this.teamSettingsService.getAutoRunControls();if(void 0!==g&&f.some((e=>this.isInTeamBlocklist(g,e))))return!1;for(const e of f){const t=await this.isInShellAllowlist(e),r=i&&void 0!==g&&this.isInTeamAllowlist(g,e);if(!t&&!r)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,uo.isAllowAllNetworkByPolicy)(e.networkPolicy),{policy:s}=await(0,uo.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:r,perRepo:n,teamAdmin:o});return i?{...s,networkPolicy:(0,uo.networkAllowAllPolicy)()}:s}async foldPerUserFilePolicy(e){const t=await(0,uo.loadSandboxPolicyFromFileOrUndefined)(this.perUserSandboxConfigPath,(0,s.homedir)());if(!t||"insecure_none"===t.type)return e;let r=(0,uo.mergeNetworkPolicies)(t.networkPolicy,e.networkPolicy);r&&void 0!==e.networkPolicy?.default&&(r={...r,default:e.networkPolicy.default});const n=(0,uo.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,uo.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,uo.isAllowAllNetworkByPolicy)(e.networkPolicy))return e;const r={default:"deny",allow:gy(t.allowlist)};return{...e,networkPolicy:(0,uo.mergeNetworkPolicies)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,uo.loadSandboxPolicyFromFileOrUndefined)((0,a.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Ty(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict}):r:void 0}async buildTeamAdminPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return Ty(e,{networkPolicy:(0,uo.networkDisabledPolicy)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=gy(t.allowlist)),t.denylist.length>0&&(r.deny=gy(t.denylist)),Ty(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)))}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:rd.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Iy(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Iy(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)ty(n.name)||(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}matchesPathEntry(e,t,r){const n=new RegExp(`^\\s*${e}\\s*\\((.*)\\)\\s*$`),o=t.match(n);if(!o)return!1;const i=(o[1]??"").trim(),s=this.expandTilde(i);return this.matchGlob(s,r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}expandTilde(e){return"~"===e?(0,s.homedir)():e.startsWith("~/")?(0,s.homedir)()+e.slice(1):e}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}matchGlob(e,t){const r=`^${this.escapeRegExp(e.trim()).replace(/\\\*/g,".*")}$`;try{return new RegExp(r).test(t)}catch{return e.trim()===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{dy(r,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:n,toolName:o,providerIdentifier:i,args:s}=t,a=e=>{this.mcpAllowlistLog?.(e)};a(`[permissions-service] shouldBlockMcp: toolName="${o}", providerIdentifier="${i}"`);const l=await this.getPermissions(),u=await this.teamSettingsService.getMcpToolControls(),d=!0===u?.enabled;if(await this.isMcpExplicitlyDenied(e,i,o))return a(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig"};const h=t.smartModeApproval?.reason;if(void 0!==h)return"workspace_readonly"===l.userConfiguredPolicy.type&&"unrestricted"!==l.approvalMode?(a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0}):(a(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${o}", providerIdentifier="${i}"`),!(d?this.isMcpInTeamAllowlist(u,{providerIdentifier:i,toolName:o}):await this.isMcpExplicitlyAllowed(e,i,o))&&{type:"needsApproval",approvalReason:h,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:i,args:s,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:h,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(d){const t=this.isMcpInTeamAllowlist(u,{providerIdentifier:i,toolName:o});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${o}", providerIdentifier="${i}"`),!1}else{const t=await this.isMcpExplicitlyAllowed(e,i,o);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${o}", providerIdentifier="${i}"`),!1}if("workspace_readonly"===l.userConfiguredPolicy.type&&"unrestricted"!==l.approvalMode)return a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${o}", providerIdentifier="${i}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===l.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return a(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${o}", providerIdentifier="${i}"`),!1;a(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${o}", providerIdentifier="${i}"`)}return a(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${o}", providerIdentifier="${i}", approvalMode="${l.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${o}`,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:i,args:s,canAllowlist:!0}}}catch(e){r.error=e,r.hasError=!0}finally{hy(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.toLowerCase().trim(),l=r.toLowerCase().trim(),c="*"===i||this.matchGlob(i,a),u="*"===s||this.matchGlob(s,l),d=c&&u,h=`[permissions-service] ${n}: serverPattern="${i}", toolPattern="${s}", normalizedProviderIdentifier="${a}", normalizedToolName="${l}", serverMatches=${c}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){fy.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&&Yv(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 Dy=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const Ny=3e5;BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function $y({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||Xv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class Ly{constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new Dy.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new Dy.aYW({}))}}class Fy{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>Ny||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,Sd.Y)(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,Sd.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const i=$y({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?$y({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,Sd._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1}):{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=(0,Sd.FC)({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===Dy.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===Dy._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===Dy.i24.ALWAYS_DISABLED}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async getDefaultNetworkAllowlist(){const e=Date.now();return(!this.defaultAllowlistPromise||e-this.lastDefaultAllowlistFetchTime>Ny)&&(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}}}async getTeamRepos(){const e=Date.now();return(!this.teamReposPromise||e-this.lastReposFetchTime>Ny)&&(this.teamReposPromise=this.fetchTeamRepos(),this.lastReposFetchTime=e),this.teamReposPromise}async fetchTeamRepos(){return this.teamAdminSettingsProvider.getTeamRepos()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}function Uy(){return(0,a.join)(function(){const e=process.env.CURSOR_DATA_DIR;return(null==e?void 0:e.trim())?e:(0,a.join)((0,s.homedir)(),".cursor")}(),"projects")}function By(e){return(0,a.join)(Uy(),(0,zg.r_)(e))}const zy=Lo.z.any().transform(((e,t)=>{if(e instanceof Je.Gm)return e;try{return Je.Gm.fromJson(e,{ignoreUnknownFields:!1})}catch(r){return t.addIssue({code:Lo.z.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)}),e}})),Wy=Lo.z.object({type:Lo.z.literal("command"),command:Lo.z.string().min(1),padding:Lo.z.number().int().min(0).optional(),updateIntervalMs:Lo.z.number().int().positive().optional(),timeoutMs:Lo.z.number().int().positive().optional()}),Hy=Lo.z.object({allow:Lo.z.array(Lo.z.string()),deny:Lo.z.array(Lo.z.string())}),qy=Lo.z.object({vimMode:Lo.z.boolean(),defaultBehavior:Lo.z.enum(["ide","agent"]).optional()}),Gy=Lo.z.object({showLineNumbers:Lo.z.boolean().default(!1),showThinkingBlocks:Lo.z.boolean().default(!1),showStatusIndicators:Lo.z.boolean().default(!1),showStatusLineRunningTime:Lo.z.boolean().default(!1)}),Vy=Lo.z.object({enabled:Lo.z.boolean().default(!1),mode:Lo.z.enum(["access-key","team-role"]).default("access-key"),region:Lo.z.string().optional(),testModel:Lo.z.string().optional(),teamRoleArn:Lo.z.string().optional(),teamExternalId:Lo.z.string().optional()}),Jy=Lo.z.object({id:Lo.z.string(),value:Lo.z.string()}),Ky=Lo.z.object({modelId:Lo.z.string(),parameters:Lo.z.array(Jy)}),Zy=Lo.z.object({ghostMode:Lo.z.boolean(),privacyMode:Lo.z.number().optional(),updatedAt:Lo.z.number()}),Yy=Lo.z.object({backendUrl:Lo.z.string(),authCacheKey:Lo.z.string(),teamId:Lo.z.number().optional(),available:Lo.z.boolean(),updatedAt:Lo.z.number()}),Xy=Lo.z.object({agentUrl:Lo.z.string(),agentnUrl:Lo.z.string()}),Qy=Lo.z.object({backendUrl:Lo.z.string(),authCacheKey:Lo.z.string().optional(),teamId:Lo.z.number().optional(),agentUrlConfig:Xy.optional(),cliSandboxDefaultEnabled:Lo.z.boolean().optional(),serverHttp2Config:Lo.z.number().optional(),updatedAt:Lo.z.number()}),ew=Lo.z.object({email:Lo.z.string().optional(),displayName:Lo.z.string().optional(),teamId:Lo.z.number().optional(),teamName:Lo.z.string().optional(),userId:Lo.z.number().optional(),authId:Lo.z.string().optional(),organizationId:Lo.z.string().optional()}),tw=Lo.z.object({useHttp1ForAgent:Lo.z.boolean().default(!1)}),rw=Lo.z.object({mode:Lo.z.enum(["disabled","enabled"]).default("disabled"),networkAccess:Lo.z.preprocess((e=>"allowlist"===e?"user_config_with_defaults":"enabled"===e?"allow_all":e),Lo.z.enum(["user_config_only","user_config_with_defaults","allow_all"])).optional(),networkAllowlist:Lo.z.array(Lo.z.string()).default([]).optional()}),nw=Lo.z.object({attributeCommitsToAgent:Lo.z.boolean().default(!0),attributePRsToAgent:Lo.z.boolean().default(!0)}),ow=Lo.z.object({conversationId:Lo.z.string(),lastUpdatedAt:Lo.z.number()}),iw=Lo.z.object({permissions:Hy}),sw=iw.extend({version:Lo.z.number(),editor:qy,display:Gy.default({showLineNumbers:!1,showThinkingBlocks:!1,showStatusIndicators:!1,showStatusLineRunningTime:!1}),notifications:Lo.z.boolean().default(!0),hints:Lo.z.boolean().default(!0),modelSlashCommands:Lo.z.boolean().default(!0),rewind:Lo.z.boolean().default(!0),statusLine:Wy.optional(),channel:Lo.z.literal("static").or(Lo.z.literal("prod")).or(Lo.z.literal("lab")).or(Lo.z.literal("prod-stable-internal")).optional(),model:zy.optional(),bedrock:Vy.optional(),awsAuthRefresh:Lo.z.string().optional(),hasChangedDefaultModel:Lo.z.boolean().default(!1).optional(),maxMode:Lo.z.boolean().default(!1).optional(),maxModeAutoEnabled:Lo.z.boolean().optional(),modelParameters:Lo.z.record(Lo.z.string(),Lo.z.array(Jy)).optional(),selectedModel:Ky.optional(),modelSelectionHistory:Lo.z.array(Lo.z.string()).max(32).optional(),privacyCache:Zy.optional(),autoReviewAvailabilityCache:Yy.optional(),serverConfigCache:Qy.optional(),authInfo:ew.optional(),network:tw.default({useHttp1ForAgent:!1}),approvalMode:Lo.z.enum(["allowlist","unrestricted","auto-review"]).default("allowlist").optional(),autoAcceptWebSearch:Lo.z.boolean().default(!1),sandbox:rw.optional(),showSandboxIntro:Lo.z.boolean().default(!1).optional(),runEverythingSettingsPromptStreak:Lo.z.number().int().nonnegative().optional(),runEverythingSettingsPromptCooldownUntilMs:Lo.z.number().int().nonnegative().optional(),attribution:nw.optional(),webFetchDomainAllowlist:Lo.z.array(Lo.z.string()).default([]).optional(),conversationClassificationScoredConversations:Lo.z.array(ow).optional()}),aw=iw.strict().extend({});sw.merge(aw),new Set(["asb","staging"]);var lw=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class cw{constructor(e,t){this.storage=e,this.prefix=t}loadTokens(e){return lw(this,void 0,void 0,(function*(){return this.storage.loadTokens(this.prefix+e)}))}saveTokens(e,t){return lw(this,void 0,void 0,(function*(){return this.storage.saveTokens(this.prefix+e,t)}))}loadClientInformation(e){return lw(this,void 0,void 0,(function*(){return this.storage.loadClientInformation(this.prefix+e)}))}saveClientInformation(e,t){return lw(this,void 0,void 0,(function*(){return this.storage.saveClientInformation(this.prefix+e,t)}))}}class uw{constructor(e,t){this.storage=e,this.prefix=t}isServerApproved(e,t,r){return lw(this,void 0,void 0,(function*(){return this.storage.isServerApproved(this.prefix+e,t,r)}))}}class dw{constructor(e){this.loaders=e}load(e){return lw(this,arguments,void 0,(function*(e,t=!0){const r=yield Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw yield Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),i={};for(let e=0;e<o.length;e++){const t=o[e],r=this.loaders[e].prefix,n=t.getClients();for(const[e,t]of Object.entries(n)){const n=r+e;n in i||(i[n]=t)}}return new bh(i)}))}loadClient(e,t){return lw(this,arguments,void 0,(function*(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return yield n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}))}clearClient(e){var t;for(const{loader:r,prefix:n}of this.loaders){if(!e.startsWith(n))continue;const o=e.slice(n.length);null===(t=r.clearClient)||void 0===t||t.call(r,o)}}clearAllMcpCaches(){var e;for(const{loader:t}of this.loaders)null===(e=t.clearAllMcpCaches)||void 0===e||e.call(t)}}class hw{constructor(e,t,r,n,o=!1,i,l,c=a.join((0,s.homedir)(),".cursor","mcp.json")){const u=Array.isArray(e)?e:[e],d=[];for(let e=0;e<u.length;e++){const t=u[e],r=a.join(t,".cursor","mcp.json"),n=`project-${e}-${a.basename(t)}-`;d.push({path:r,prefix:n})}d.push({path:c,prefix:"user-"});const h=new Map;for(const{path:e,prefix:t}of d)h.has(e)&&"user-"!==t||h.set(e,t);const p=[];for(const[e,s]of h){const a=o?"":s,u=new cw(t,a),d=new uw(n,a),h=e===c,f=[new Od,...h?[]:[new Pd(d)],new $h(r),...l?[new _d(l)]:[]];p.push({prefix:a,loader:new Lh(e,u,f,i)})}this.loader=new dw(p)}static init(e,t,r,n=!1,o){const i=new Bh(a.join(r,"mcp-auth.json"));(function(e){return lw(this,void 0,void 0,(function*(){yield(0,Hn.rm)(a.join(e,"mcp-cache.json"),{force:!0})}))})(r).catch((()=>{}));const s=n?{isServerApproved:()=>Promise.resolve(!0)}:new Td(a.join(r,"mcp-approvals.json"),t);return new hw(t,i,e,s,!0,void 0,o)}load(e){return lw(this,arguments,void 0,(function*(e,t=!0){return this.loader.load(e,t)}))}loadClient(e,t){return lw(this,arguments,void 0,(function*(e,t,r=!1){return this.loader.loadClient(e,t,r)}))}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const pw=new pd,fw={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 Ec((0,Ye.q6)(),pw,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?By(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 mw=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const gw=(0,h.h)("ControlledConversationActionManager");class vw{get signal(){return this.abortController.signal}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.abortStarted=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,m.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortController.signal.aborted||this.abortStarted)return;const r=null==t?void 0:t.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new Je.QF({action:{case:"cancelAction",value:new Je.TT({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}submitConversationAction(e){return mw(this,void 0,void 0,(function*(){if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}yield this.clientStream.write(e)}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){var e;null===(e=this.clientStream)||void 0===e||e.close()}resetStream(){var e;null===(e=this.clientStream)||void 0===e||e.close(),this.clientStream=(0,m.Jt)(),this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new Je.QF({action:{case:"userMessageAction",value:new Je.Vt({userMessage:e})}}))}run(e,t){return mw(this,void 0,void 0,(function*(){var r,n,o,i;this.runActive=!0;try{try{for(var s,a=!0,l=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.clientStream);!(r=(s=yield l.next()).done);a=!0){i=s.value,a=!1;const r=i;try{yield t.write(r)}catch(t){gw.error(e,"Error writing conversation action",t)}}}catch(e){n={error:e}}finally{try{a||r||!(o=l.return)||(yield o.call(l))}finally{if(n)throw n.error}}}finally{this.runActive=!1}}))}dispose(){this.abortCallbacks.length=0}}let yw={warn:console.warn.bind(console),error:console.error.bind(console)};const ww=new Mo.AsyncLocalStorage;function bw(){var e;return null!==(e=ww.getStore())&&void 0!==e?e:yw}const Sw={warn(...e){bw().warn(...e)},error(...e){bw().error(...e)}};var kw=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 Ew(e){var t;if("userMessageAction"===e.action.case)return null===(t=e.action.value.userMessage)||void 0===t?void 0:t.text}function xw(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 Cw(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}const _w="cursor-plugins/local";function Pw(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===_w)return r}var Tw=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 Iw extends wh{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}dispose(){return Tw(this,void 0,void 0,(function*(){this.disposed||(this.disposed=!0,yield this.runtimeManager.closeAllClients())}))}}class Rw{constructor(e){this.storagePath=e}isServerDisabled(e){return Tw(this,void 0,void 0,(function*(){try{const t=yield(0,Hn.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 Tw(this,void 0,void 0,(function*(){yield(0,Hn.mkdir)((0,a.dirname)(this.storagePath),{recursive:!0}),yield(0,Hn.writeFile)(this.storagePath,JSON.stringify(e,null,2))}))}}class Aw{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}getDefinitions(){return Tw(this,void 0,void 0,(function*(){let e;try{e=yield this.pluginMcpService.getPluginMcpServers()}catch(e){return Sw.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&$w(r))continue;const e=Fh(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}}):Sw.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 Ow{constructor(e){this.servers=e}getDefinitions(){return Tw(this,void 0,void 0,(function*(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:Nw(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}))}}function jw(){return{getDotCursorProtection:()=>Tw(this,void 0,void 0,(function*(){return!1})),getShouldBlockMcp:()=>Tw(this,void 0,void 0,(function*(){return!1})),getDeleteFileProtection:()=>Tw(this,void 0,void 0,(function*(){return!1})),getIsHeadlessDisabled:()=>Tw(this,void 0,void 0,(function*(){return!1})),isServerBlocked:()=>Tw(this,void 0,void 0,(function*(){return!1})),getTeamRepos:()=>Tw(this,void 0,void 0,(function*(){})),getAutoRunControls:()=>Tw(this,void 0,void 0,(function*(){return{enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}})),getMcpToolControls:()=>Tw(this,void 0,void 0,(function*(){})),getNetworkAccessControls:()=>Tw(this,void 0,void 0,(function*(){return{allowlist:[],denylist:[],available:!0}})),getMcpNetworkControlsConfig:()=>Tw(this,void 0,void 0,(function*(){return{enabled:!1}})),getDefaultNetworkAllowlist:()=>Tw(this,void 0,void 0,(function*(){return{allowlist:[],available:!0}})),getSandboxingControls:()=>Tw(this,void 0,void 0,(function*(){return{sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}})),isAttributionDisabledByAdmin:()=>Tw(this,void 0,void 0,(function*(){return!1})),invalidateCache:()=>{}}}function Mw(e={}){var t,r,n;const o=null!==(t=e.teamSettingsService)&&void 0!==t?t:jw(),i=null!==(r=e.ignoreApprovals)&&void 0!==r&&r,l=null!==(n=e.importThirdPartyPlugins)&&void 0!==n&&n;return{createLease(t){return Tw(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 yh;const g=new Rw((0,a.join)(m,"mcp-disabled.json")),v=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:o,disabledStore:i,includeProjectMcp:l,includeUserMcp:c}=e;if(l&&c)return hw.init(t,r,n,o,i);if(!l&&!c)return;const u=new Bh((0,a.join)(n,"mcp-auth.json")),d=o?{isServerApproved:()=>Promise.resolve(!0)}:new Td((0,a.join)(n,"mcp-approvals.json"),r),h=[new Od,new Pd(d),new $h(t),new _d(i)],p=[];return l&&p.push({prefix:"",loader:new Lh((0,a.join)(r,".cursor","mcp.json"),u,h)}),c&&p.push({prefix:"",loader:new Lh((0,a.join)((0,s.homedir)(),".cursor","mcp.json"),u,h)}),Dw(p)}({teamSettingsService:o,projectRoot:f,projectDirectory:m,ignoreApprovals:i,disabledStore:g,includeProjectMcp:null===(n=e.includeProjectMcp)||void 0===n||n,includeUserMcp:null===(c=e.includeUserMcp)||void 0===c||c}),y=[],w=null!==(u=e.inlineMcpServers)&&void 0!==u?u:{};if(Object.keys(w).length>0){const e=new Bh((0,a.join)(m,"mcp-auth.json")),t=[new Od,new $h(o)];y.push({prefix:"",loader:new Dh(new Ow(w),e,t)})}const b=Pw(t.services.pluginBootstrapOutputs);if(b&&(null===(d=e.includePluginMcp)||void 0===d||d)){const e=new Td((0,a.join)(m,"mcp-approvals.json"),f),t=new Bh((0,a.join)(m,"mcp-auth.json")),r=[new Od];i||r.push(new Pd(e)),r.push(new $h(o),new _d(g));const n=new Uv(b.pluginsService),s=new Dh(new Aw(n,l),t,r);y.push({prefix:"",loader:s})}if(v&&y.push({prefix:"",loader:v}),0===y.length)return new yh;const S=Dw(y),k=yield S.load(null!==(h=e.initializationCtx)&&void 0!==h?h:(0,Ye.q6)(),e.cache);return new Iw(k)}))}}}function Dw(e){return 1===e.length?e[0].loader:new dw(e)}function Nw(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 $w(e){return"claude-plugin"===e.pluginSource}const Lw=["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 Fw(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,Lw)}function Uw(e){const t=(0,zg.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,zg.sh)(e.parentConversationId);return`${zg.O2}/${r}/subagents/${t}.${e.ext}`}return`${zg.O2}/${t}/${t}.${e.ext}`}function Bw(e){const t=(0,zg.sh)(e.conversationId);return`${zg.O2}/${t}.${e.ext}`}function zw(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(Uw({conversationId:e.conversationId,ext:t,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&s(Uw({conversationId:e.conversationId,ext:t,kind:"primary"})),o&&s(Bw({conversationId:e.conversationId,ext:t}));return i}var Ww;(()=>{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"}(Ww||(Ww={}));var Hw=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())}))},qw=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},Gw=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 Vw(e){switch(e){case Je.xy.AGENT:return"agent";case Je.xy.ASK:return"ask";case Je.xy.PLAN:return"plan";case Je.xy.DEBUG:return"debug";case Je.xy.TRIAGE:return"triage";case Je.xy.PROJECT:return"project";case Je.xy.MULTITASK:return"multitask";case Je.xy.CUSTOM:return"custom";case Je.xy.UNSPECIFIED:default:return"agent"}}function Jw(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 Kw(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 Zw=new TextEncoder,Yw=new TextDecoder,Xw=new class{serialize(e){const t=JSON.stringify(e,Jw);return Zw.encode(t)}deserialize(e){const t=Yw.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Kw):JSON.parse(t)}};function Qw(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 eb(e,t,r){return Hw(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=Xw.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 tb(e,t){switch(e.type){case"text":return t?rb(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 rb(e){return Fw(e)}function nb(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function ob(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?rb(e):e;return r?nb(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=nb(t?rb(e.text):e.text);return tb(Object.assign(Object.assign({},e),{text:r}),!1)}return tb(e,t)})).filter(Boolean).join("\n")}function ib(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?rb(n):n,i="assistant"===e.role?nb(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?rb(r.text):r.text,i="assistant"===e.role?nb(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 sb(e){return e.endsWith("\n")?e:`${e}\n`}function ab(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 lb(e){if("system"===e.role||Qw(e))return;const t=ib(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 cb{constructor(e,t,r,n={}){var o,i,s;this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:null===(o=n.writeText)||void 0===o||o,writeJson:null!==(i=n.writeJson)&&void 0!==i&&i,writeJsonl:null!==(s=n.writeJsonl)&&void 0!==s&&s,pathResolver:n.pathResolver,appendFile:n.appendFile}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=Uw({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}writeFromStateFull(e,t,r){return Hw(this,arguments,void 0,(function*(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const i=qw(o,(0,c.VI)(e.withName("writeFromState")),!1);try{const e=yield function(e,t,r){return Hw(this,void 0,void 0,(function*(){const n={stack:[],error:void 0,hasError:!1};try{const o=qw(n,(0,c.VI)(e.withName("hydrateSummaryArchives")),!1);let i=0;const s=(0,c.OA)(o.ctx),a=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=yield Promise.all(r.summaryArchives.map((e=>Hw(this,void 0,void 0,(function*(){i++;const r=yield t.getBlob(s,e);if(r)try{const e=Je.An.fromBinary(r);return i+=e.summarizedMessages.length,yield eb(s,t,e.summarizedMessages)}catch(e){}return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}})))));for(const e of g)a.push(...e.messages),l+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),h+=e.totalDeserializeDurationMs,p+=e.omittedOversizeBlobCount,f+=e.omittedOversizeBlobBytes,m=Math.max(m,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",i),o.span.setAttribute("hydratedBlobCount",l),o.span.setAttribute("hydratedBlobBytes",u),o.span.setAttribute("largestHydratedBlobBytes",d),o.span.setAttribute("totalDeserializeDurationMs",h),o.span.setAttribute("omittedOversizeBlobCount",p),o.span.setAttribute("omittedOversizeBlobBytes",f),o.span.setAttribute("largestOmittedOversizeBlobBytes",m);const v=qw(n,(0,c.VI)(e.withName("hydratePromptMessages")),!1),y=yield eb(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&&!Qw(e)));return a.push(...w),a}catch(e){n.error=e,n.hasError=!0}finally{Gw(n)}}))}(i.ctx,this.blobStore,t),{overviewFactory:o}=n,s=ab(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=ob(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=ib(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:Vw(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=lb(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"),sb(n)))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{Gw(o)}}))}writeFromStateIncremental(e,t,r,n){return Hw(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=ab(o),l=a.jsonlLines.length>0;if(s===n&&!l&&!o.overviewFactory)return s;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&s>=n&&(s>n||l))||o.overviewFactory)return(yield this.writeFromStateFull(e,t,r,o))?s:0;const d=qw(i,(0,c.VI)(e.withName("writeFromStateIncremental")),!1);if(s===n&&l)try{return yield u(this.resolveFilePath(r,"jsonl"),sb(a.jsonlLines.join("\n"))),s}catch(n){return console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",n),(yield this.writeFromStateFull(e,t,r,o))?s:0}try{const e=t.rootPromptMessagesJson.slice(n),o=yield eb(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=lb(e);t&&i.push(t)}if(i.push(...a.jsonlLines),i.length>0){const e=sb(i.join("\n"));yield u(this.resolveFilePath(r,"jsonl"),e)}return s}catch(n){return console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",n),(yield this.writeFromStateFull(e,t,r,o))?s:0}}catch(e){i.error=e,i.hasError=!0}finally{Gw(i)}}))}}class ub extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class db extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}function hb(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${pb}`}(t,r);throw new db(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 pb="To view or modify configured hooks, go to Cursor Settings > Hooks.",fb="Agent note: Do not suggest workarounds to the blocked tool.";function mb(e){return e.includes(fb)?e:`${e}\n\n${fb}`}function gb(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function vb(e,t){return mb(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${pb}`)}function yb(e){return function(e){return e instanceof ub}(e)||function(e){return e instanceof db}(e)}var wb=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class bb{constructor(e,t,r,n,o,i,s,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.teamHooksReadyPromise=i,this.onHookExecution=s,this.options=a,this.config=e}emitHookExecution(e){var t,r;const n=Object.assign(Object.assign({},e),{transportMode:null!==(r=e.transportMode)&&void 0!==r?r:"prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode()});try{null===(t=this.onHookExecution)||void 0===t||t.call(this,n)}catch(e){}}getCommandHookPayloadTransportMode(){var e;return"stdin"===(null===(e=this.options)||void 0===e?void 0:e.commandHookPayloadTransport)?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}writeCommandHookStdinPayload(e,t){return wb(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,Ji.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}))}updateConfig(e){this.config=e}setSessionEnvironment(e){this.sessionEnv=Object.assign(Object.assign({},this.sessionEnv),e)}clearSessionEnvironment(){this.sessionEnv=void 0}getTranscriptPathIfExists(e){return wb(this,void 0,void 0,(function*(){try{const t=(0,zg.Rv)((0,s.homedir)(),this.workspacePath),r=zw({conversationId:e,kind:"primary"}).map((e=>(0,a.join)(t,e)));for(const e of r)try{return yield(0,Hn.access)(e),e}catch(e){}return null}catch(e){return null}}))}getSubagentTranscriptPathIfExists(e){return wb(this,void 0,void 0,(function*(){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,zg.Rv)((0,s.homedir)(),this.workspacePath),n=zw({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,a.join)(e,t)));for(const e of n)try{return yield(0,Hn.access)(e),e}catch(e){}return null}catch(e){return null}}))}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks].some((t=>{const r=null==t?void 0:t.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,this.config.userHooks];for(const n of r){const r=null==n?void 0:n.hooks[e];if(r&&(t?we(r,t):r).some((e=>!0===e.failClosed)))return!0}return!1}getCwdForSource(e){var t,r,n,o;const i=this.config.configDirs;switch(e){case"enterprise":return null!==(t=null==i?void 0:i.enterprise)&&void 0!==t?t:this.workspacePath;case"team":return null!==(r=null==i?void 0:i.team)&&void 0!==r?r:this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":default:return this.workspacePath;case"user":return null!==(n=null==i?void 0:i.user)&&void 0!==n?n:this.workspacePath;case"claude-user":return null!==(o=null==i?void 0:i.claudeUser)&&void 0!==o?o:this.workspacePath}}buildHookEnvironment(e){return Object.assign(Object.assign(Object.assign(Object.assign({CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version},this.globalContext.user_email&&{CURSOR_USER_EMAIL:this.globalContext.user_email}),e&&{CURSOR_TRANSCRIPT_PATH:e}),{CLAUDE_PROJECT_DIR:this.workspacePath}),this.sessionEnv)}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=r.loop_count,o=t.loop_limit;return null!==o&&(void 0===o?n>=5:n>=o)}executeHookForStep(e,t){return wb(this,void 0,void 0,(function*(){var r,n,o,i,s,a,l,c;this.teamHooksReadyPromise&&(yield this.teamHooksReadyPromise);const u=function(e){return Oe.includes(e)}(e),d=t,h=u?null:d.conversation_id?yield this.getTranscriptPathIfExists(d.conversation_id):null;let p;if(e===ce.subagentStop){const e=t;p=e.subagent_id?yield this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const f=u?void 0:null!==(c=d.session_id)&&void 0!==c?c:d.conversation_id,m=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),void 0!==f&&{session_id:f}),{hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.globalContext.user_email}),!u&&{transcript_path:h}),e===ce.subagentStop&&{agent_transcript_path:null!=p?p:null}),g=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return t.command||void 0;case"beforeMCPExecution":case"afterMCPExecution":{const e=t;return e.tool_name?`MCP:${e.tool_name}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return t.subagent_type||void 0;case"preToolUse":case"postToolUse":case"postToolUseFailure":return t.tool_name||void 0;default:return}}(e,m),v=[],y=(e,t)=>{if(!e)return;const r=we(e,g),n=this.getCwdForSource(t);for(const e of r)Te(e)?this.promptHookClient&&v.push({type:"prompt",script:e,source:t}):("command"===(o=e).type||void 0===o.type)&&v.push({type:"command",script:e,cwd:n,source:t});var o};if(y(null===(r=this.config.enterpriseHooks)||void 0===r?void 0:r.hooks[e],"enterprise"),y(null===(n=this.config.teamHooks)||void 0===n?void 0:n.hooks[e],"team"),y(null===(o=this.config.projectHooks)||void 0===o?void 0:o.hooks[e],"project"),y(null===(i=this.config.userHooks)||void 0===i?void 0:i.hooks[e],"user"),y(null===(s=this.config.claudeProjectLocalHooks)||void 0===s?void 0:s.hooks[e],"claude-project-local"),y(null===(a=this.config.claudeProjectHooks)||void 0===a?void 0:a.hooks[e],"claude-project"),y(null===(l=this.config.claudeUserHooks)||void 0===l?void 0:l.hooks[e],"claude-user"),0!==v.length)return this.executeAllAndMerge(e,v,m)}))}executeAllAndMerge(e,t,r){return wb(this,void 0,void 0,(function*(){const n=t.map(((t,n)=>wb(this,void 0,void 0,(function*(){const{source:o,attribution:i}=t;try{return"prompt"===t.type?this.executePromptHook(e,t.script,r,o,n,i):this.executeCommandHook(e,t.script,t.cwd,r,o,n,i)}catch(r){if(!0===t.script.failClosed){const t=gb(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),i=$e(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=Ae.includes(e),o=e===ce.sessionStart,i=e===ce.workspaceOpen,s=Pe.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]=je(a[e],u):"continue"!==e||"boolean"!=typeof u?a[e]=o&&"env"===e&&"object"==typeof u&&null!==u?Me(a[e],u):u:void 0===a[e]?a[e]=u:a[e]=a[e]&&u:a[e]=je(a[e],u)}var l,c;return a}(e,i)}))}executeCommandHook(e,t,r,n,o,i,s){return wb(this,void 0,void 0,(function*(){var a,l,c,u,d,h,p,f;if(this.shouldSkipHookDueToLoopLimit(e,t,n))return{success:!1,source:o,index:i};const m=Date.now(),g=Buffer.byteLength(JSON.stringify(n),"utf8");let v;try{v=yield this.executeCommandScript({script:t,cwd:r,request:n})}catch(r){const n=r instanceof Error?r.message:String(r),a=n.toLowerCase().includes("timed out"),l=Date.now()-m,c=a?"timeout":"spawn_error";if(!0===t.failClosed){const r=gb(`Hook "${t.command}" execution failed: ${n}`),u=$e(e,r);if(u)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:a?"timeout":"blocked",latencyMs:l,payloadSizeBytes:g,errorClass:c,failClosed:!0,timedOut:a},s)),{success:!0,data:u,source:o,index:i}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:a?"timeout":"failed",latencyMs:l,payloadSizeBytes:g,errorClass:c,failClosed:!0===t.failClosed,timedOut:a},s)),{success:!1,source:o,index:i}}if(2===v.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(v.stdout,v.stderr,t.command),n=$e(e,r);return n?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:v.exitCode},s)),{success:!0,data:n,source:o,index:i}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:v.exitCode},s)),{success:!1,source:o,index:i})}if(0!==v.exitCode&&null!==v.exitCode){if(!0===t.failClosed){const r=gb(`Hook "${t.command}" failed with exit code ${v.exitCode}${v.stderr?`: ${v.stderr.trim()}`:""}`),n=$e(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"exit_nonzero",failClosed:!0,exitCode:v.exitCode},s)),{success:!0,data:n,source:o,index:i}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:v.exitCode},s)),{success:!1,source:o,index:i}}const y=v.stdout.trim();if(!y){if(!0===t.failClosed){const r=gb(`Hook "${t.command}" returned no output.`),n=$e(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"empty_stdout",failClosed:!0,exitCode:null!==(l=v.exitCode)&&void 0!==l?l:void 0},s)),{success:!0,data:n,source:o,index:i}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:null!==(c=v.exitCode)&&void 0!==c?c:void 0},s)),{success:!1,source:o,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=Le(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=Le(t.slice(e));if(void 0!==r)return r.value}}(y);if(void 0===w){const r=Ne({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(u=v.exitCode)&&void 0!==u?u:void 0},s)),{success:!0,data:r.blockResponse,source:o,index:i}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(d=v.exitCode)&&void 0!==d?d:void 0},s)),{success:!1,source:o,index:i})}const b=Re(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:null===(a=this.options)||void 0===a?void 0:a.enableClaudeNestedHookSpecificOutputCompatibility});if(b.success){const r=b.data,n="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:n?"blocked":"success",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:null!==(h=v.exitCode)&&void 0!==h?h:void 0},s)),{success:!0,data:b.data,source:o,index:i}}const S=Ne({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return S.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(p=v.exitCode)&&void 0!==p?p:void 0},s)),{success:!0,data:S.blockResponse,source:o,index:i}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(f=v.exitCode)&&void 0!==f?f:void 0},s)),{success:!1,source:o,index:i})}))}executePromptHook(e,t,r,n,o,i){return wb(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,Ye.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 De(e)?{permission:"allow"}:e===ce.beforeSubmitPrompt||e===ce.sessionStart?{continue:!0}:e===ce.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=$e(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=gb(`Prompt hook failed: ${s}`),r=$e(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 wb(this,void 0,void 0,(function*(){var t,r,n,o,i;const{script:l,cwd:c,request:u}=e,d=1e3*(null!==(i=l.timeout)&&void 0!==i?i:60),h=Date.now(),p=JSON.stringify(u);let f;const m=new AbortController,g=setTimeout((()=>{m.abort()}),d);try{const e="win32"===process.platform,i=this.getCommandHookPayloadTransportMode(),b=this.shouldUseCommandHookDirectStdinTransport();let S;if(b)S=l.command;else if("windows_temp_file"===i){f=yield(0,Hn.mkdtemp)((0,a.join)((0,s.tmpdir)(),"cursor-hooks-"));const e=(0,a.join)(f,"payload.json");yield(0,Hn.writeFile)(e,p,{encoding:"utf8",flag:"wx"}),S=function(e,t){const r=e.replace(/'/g,"''"),n=function(e){const t=e.trimStart();if(0===t.length)return e;if(t.startsWith("&"))return e;const r=t.charAt(0);return"'"===r||'"'===r?`& ${e}`:e}(t);return`$OutputEncoding = [System.Text.Encoding]::UTF8; Get-Content -LiteralPath '${r}' -Raw | & { $input | ${n} }`}(e,l.command)}else S=e?`@'\n${p.replace(/'/g,"''")}\n'@ | & ${l.command}`:`${l.command} <<'CURSOR_HOOK_EOF'\n${p}\nCURSOR_HOOK_EOF`;const k=u,E=this.buildHookEnvironment(k.transcript_path),x={};for(const[e,t]of Object.entries(E))void 0!==t&&(x[e]=t);const C=(0,Ye.q6)();let _="",P="",T=null,I=!1;try{for(var v,y=!0,w=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,o,(t=e[r](t)).done,t.value)}))}}}(this.shellExecutor.execute(C,S,{workingDirectory:c,signal:m.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:x,pipeStdin:b}));!(t=(v=yield w.next()).done);y=!0){o=v.value,y=!1;const e=o;switch(e.type){case"stdin_ready":b&&(yield this.writeCommandHookStdinPayload(e.stdin,p),I=!0);break;case"stdout":_+=e.data.toString("utf8");break;case"stderr":P+=e.data.toString("utf8");break;case"exit":T=e.code}}}catch(e){r={error:e}}finally{try{y||t||!(n=w.return)||(yield n.call(w))}finally{if(r)throw r.error}}if(b&&!I)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(g);const R=Date.now()-h;if(m.signal.aborted)throw new Error(`Hook script timed out after ${d}ms`);return{stdout:_,stderr:P,exitCode:T,duration:R}}catch(e){if(clearTimeout(g),Date.now(),m.signal.aborted)throw new Error(`Hook script timed out after ${d}ms`);throw e}finally{if(f)try{yield(0,Hn.rm)(f,{recursive:!0,force:!0})}catch(e){}}}))}}var Sb=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 kb(e){switch(null!=e?e:(0,s.platform)()){case"darwin":return a.join("/Library","Application Support","Cursor","hooks.json");case"win32":return a.join("C:\\","ProgramData","Cursor","hooks.json");default:return a.join("/etc","cursor","hooks.json")}}class Eb{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}load(){return Sb(this,arguments,void 0,(function*(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=(e,t,n,o,i,s,l)=>Sb(this,void 0,void 0,(function*(){if(e)try{if(!(yield this.fileReader.exists(e)))return;const s=yield this.fileReader.readFile(e);if(!s)return;const{config:c,error:u}=l(s);c?(r[n]=c,((e,t)=>{r.configDirs[e]=a.dirname(t)})(o,e)):u&&r.errors.push({source:t,message:`${i} at ${e}: ${u}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${s} config file: ${String(e)}`})}})),o=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise"},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team"},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user"},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project"}];for(const e of o)yield n(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,(t=>this.parseAndValidate(t,e.source)));const i=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user"},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project"},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local"}];for(const e of i)yield n(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,(t=>this.parseClaudeConfig(t,e.source)));return this.dedupeClaudeHooksAgainstCursorHooks(r),r}))}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 ue&&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=ye(r,this.logger),o=Ve(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=Ve(r);if(!n.isValid)return{error:`Invalid ${t} config: ${n.errors.join("; ")}`};const o=r;return o.hooks?{config:o}:{error:`Invalid ${t} config: missing 'hooks' property`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks];for(const e of r)if(null==e?void 0:e.hooks)for(const r of Object.keys(e.hooks))t.add(r);return t}}class xb{constructor(e){this.config=e,this.configuredSteps=Eb.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var Cb=r("node:perf_hooks");function _b(e,t){void 0!==e&&t.length>0&&e.push(...t)}class Pb 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 Tb=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function Ib({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 Pb({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new Tb.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Pe).map((e=>{if(!function(e){return e===ce.sessionStart||e===ce.beforeSubmitPrompt||e===ce.preToolUse||e===ce.postToolUse||e===ce.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 Rb=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())}))},Ab=function(e){return this instanceof Ab?(this.v=e,this):new Ab(e)};const Ob=(0,h.h)("generic-hooks");function jb(e,t,r,n){try{return Ib({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof Pb)return Ob.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const Mb=e=>Math.round(1e3*e)/1e3;function Db(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)=>Rb(this,[n,c,u,...d],void 0,(function*(n,c,u,d=!1){try{const h=yield t.executeHookForStep(ce.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));_b(s,jb(e,r,ce.postToolUseFailure,null==h?void 0:h.additional_context))}catch(t){Ob.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}})),fireSuccessAsync:(n,c)=>Rb(this,void 0,void 0,(function*(){try{const u=yield t.executeHookForStep(ce.postToolUse,Object.assign(Object.assign(Object.assign({},a),{tool_name:r,tool_input:o,tool_output:c,duration:n,tool_use_id:l}),i));_b(s,jb(e,r,ce.postToolUse,null==u?void 0:u.additional_context))}catch(t){Ob.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 Nb(e,t,r,n,o,i,s,a){return Rb(this,void 0,void 0,(function*(){var l,c;const{baseHookRequest:u,toolUseId:d,extraHookFields:h}=n;try{const a=yield r.executeHookForStep(ce.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=mb(r);try{_b(n.hookContextCollector,Ib({hookEventName:ce.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof Pb))throw t;Ob.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))),_b(n.hookContextCollector,Ib({hookEventName:ce.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,ce.preToolUse,i.toolName))&&void 0!==c&&c,u=n instanceof Pb;if(a){const e=gb(`${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}}Ob.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(yb(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 $b(e){return e.toolCallId}function Lb(e,t,r,n){return{execute(o,i,s){return Rb(this,void 0,void 0,(function*(){var a,l,c,u,d,h,p,f,m,g;const{hookContext:v,helpers:y}=Db(o,i,t,r,n,s);let w;try{w=yield Nb(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=Cb.performance.now();try{const r=yield e.execute(o,i,s),a=Mb(Cb.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(yb(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);Ob.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=Mb(Cb.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*Fb(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}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())}))};class Bb{readFile(e){return Ub(this,void 0,void 0,(function*(){try{return yield Hn.readFile(e,"utf-8")}catch(e){if("ENOENT"===(null==e?void 0:e.code))return;throw e}}))}exists(e){return Ub(this,void 0,void 0,(function*(){try{return yield Hn.access(e),!0}catch(e){return!1}}))}}class zb{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 pg.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||i)){const e=n.result.value.requestContext,t=new pg.bb(Object.assign(Object.assign(Object.assign({},e),o&&{hooksAdditionalContext:o}),i&&{hooksConfig:i}));return new pg._G({result:{case:"success",value:new pg.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 Wb(e){return!!e&&e.type!==co.vc.INSECURE_NONE&&e.type!==co.vc.UNSPECIFIED}const Hb="Shell";function qb(e){return t=this,r=arguments,o=function*({hookExecutor:e,baseHookRequest:t,command:r,cwd:n,sandbox:o}){const i=yield e.executeHookForStep(ce.beforeShellExecution,Object.assign(Object.assign({},t),{command:r,cwd:n,sandbox:o}));if("deny"===(null==i?void 0:i.permission)){const e=vb("Command execution",i.user_message);throw new ub(e)}if("ask"===(null==i?void 0:i.permission))return s=i.user_message,new kt.In({kind:kt.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 Gb={toolName:Hb,getToolCallId:$b,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 wt.Lt({result:{case:"rejected",value:new kt.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";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=Wb(t.sandboxPolicy);Ut(t,yield qb({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 Vb{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,Gb)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Jb={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new wt.nt({result:{case:"error",value:new wt.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 Kb{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,Jb)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Zb={toolName:"ComputerUse",getToolCallId:$b,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Tu.ks({result:{case:"error",value:new Tu.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 Yb{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,Zb)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Xb={toolName:"Delete",getToolCallId:$b,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new bt.Pi({result:{case:"rejected",value:new bt.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 Qb{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,Xb)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const eS={toolName:"ReadLints",getToolCallId:$b,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new gm.Ek({result:{case:"rejected",value:new gm.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 tS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,eS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const rS={toolName:"Fetch",getToolCallId:$b,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new ad.uN({result:{case:"error",value:new ad.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 nS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,rS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const oS={toolName:"Grep",getToolCallId:$b,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 fd.Ud({result:{case:"error",value:new fd.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 iS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,oS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const sS={toolName:"List",getToolCallId:$b,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 cf.fv({result:{case:"rejected",value:new cf.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 aS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,sS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var lS=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 cS=(0,h.h)("hooks-exec:mcp");function uS(e,t,r,n){try{return Ib({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof Pb)return cS.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class dS{constructor(e,t,r,n){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n}execute(e,t,r){return lS(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(ce.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{_b(h,Ib({hookEventName:ce.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof Pb))throw t;cS.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 St.iz({result:{case:"permissionDenied",value:new St.HQ({error:vb("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]=nr.Value.fromJson(n));p=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])))}catch(t){cS.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}_b(h,Ib({hookEventName:ce.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,ce.preToolUse,f))&&void 0!==l&&l,o=t instanceof Pb;if(r){const r=gb(`${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 St.iz({result:{case:"permissionDenied",value:new St.HQ({error:vb("MCP tool execution",r),isReadonly:!1})}})}cS.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(ce.beforeMCPExecution,b);if("deny"===(null==S?void 0:S.permission)){const t=vb("MCP tool execution",S.user_message);return yield this.firePostToolUseFailureAsync(e,u,f,p,t,"permission_denied",0,d,!1,h),new St.iz({result:{case:"permissionDenied",value:new St.HQ({error:t,isReadonly:!1})}})}const k=Cb.performance.now();try{const n=yield this.innerExecutor.execute(e,t,r),o=Mb(Cb.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){cS.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(ce.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 St._Z({content:{case:"text",value:new St.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 St._Z({content:{case:"text",value:new St.zN({text:String(e.text)})}})):t.push(new St._Z({content:{case:"text",value:new St.zN({text:JSON.stringify(e)})}}))}else t.push(new St._Z({content:{case:"text",value:new St.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new St.iz({result:{case:"success",value:new St.QW({content:t,isError:r})}})}catch(t){return cS.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),n}return n}catch(t){const r=Mb(Cb.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 lS(this,void 0,void 0,(function*(){try{const l=yield this.hookExecutor.executeHookForStep(ce.postToolUse,Object.assign(Object.assign({},t),{tool_name:r,tool_input:n,tool_output:o,duration:i,tool_use_id:s}));return _b(a,uS(e,r,ce.postToolUse,null==l?void 0:l.additional_context)),l}catch(t){return void cS.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 lS(this,void 0,void 0,(function*(){try{const u=yield this.hookExecutor.executeHookForStep(ce.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}));_b(c,uS(e,r,ce.postToolUseFailure,null==u?void 0:u.additional_context))}catch(t){cS.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}))}}const hS={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new St.kP({result:{case:"error",value:new St.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 pS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,hS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const fS={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 St.ZD({result:{case:"error",value:new St.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 mS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,fS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const gS={toolName:"Read",getToolCallId:$b,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Vm.sV({result:{case:"rejected",value:new Vm.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 hb((()=>o.executeHookForStep(ce.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=vb("File read",s.user_message);throw new ub(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 vS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,gS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const yS={toolName:"RecordScreen",getToolCallId:$b,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new cg.Tj({result:{case:"failure",value:new cg.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 wS{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,yS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var bS=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 SS(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const kS={toolName:Hb,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 kt.W4({result:{case:"rejected",value:new kt.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:SS(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:e=>bS(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"";Ut(t,yield qb({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:Wb(t.requestedSandboxPolicy)}))})),runPostExecutionHooks:e=>bS(void 0,void 0,void 0,(function*(){const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:i}=e,s=SS(r);yield o.executeHookForStep(ce.afterShellExecution,Object.assign(Object.assign({},n),{command:t.command,output:s,duration:i,sandbox:Wb(t.requestedSandboxPolicy)}))}))};class ES{constructor(e,t,r){this.wrappedExecutor=Lb(e,t,r,kS)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}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 CS{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 _S={toolName:Hb,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 kt.FI({event:{case:"rejected",value:new kt.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new kt.FI({event:{case:"hookContext",value:new kt.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new CS,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=>xS(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",i=Wb(t.requestedSandboxPolicy);Ut(t,yield qb({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:i}))})),runPostExecutionHooks:e=>xS(void 0,void 0,void 0,(function*(){const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:i}=e,s=Wb(t.requestedSandboxPolicy);yield n.executeHookForStep(ce.afterShellExecution,Object.assign(Object.assign({},r),{command:t.command,output:o.getOutput(),duration:i,sandbox:s}))}))};class PS{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 Ab?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}=Db(o,i,t,r,n,s),v=n.runPreExecutionHooks?e=>Rb(this,void 0,void 0,(function*(){yield n.runPreExecutionHooks(e)})):void 0,y=yield Ab(Nb(o,i,t,m,g,n,((e,t)=>n.createRejectedEvent(e,t)),v));if("rejected"===y.type){yield yield Ab(y.result);for(const e of Fb(n,m))yield yield Ab(e);return yield Ab(void 0)}const w=Cb.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 Ab(x.next())).done);E=!0){u=k.value,E=!1;const e=u;b.onEvent(e),yield yield Ab(e)}}catch(e){l={error:e}}finally{try{E||a||!(c=x.return)||(yield Ab(c.call(x)))}finally{if(l)throw l.error}}}catch(e){S=!0;const t=Mb(Cb.performance.now()-w),r=e instanceof Error?e.message:String(e);yield Ab(g.fireFailureAsync(t,r,"error"));for(const e of Fb(n,m))yield yield Ab(e);throw e}const C=Mb(Cb.performance.now()-w);if(n.runPostExecutionHooks)try{yield Ab(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){Ob.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(!S)if(b.isAborted())yield Ab(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 Ab(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 Ab(g.fireFailureAsync(C,e,"error"))}for(const e of Fb(n,m))yield yield Ab(e)}))}}}(e,t,r,_S)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var TS=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 IS{constructor(e,t,r){const n=new Map;this.wrappedExecutor=Lb(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:$b,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 Et.v3({result:{case:"error",value:new Et.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=>TS(this,void 0,void 0,(function*(){const{args:r,toolUseId:n}=e;let o,i=!1;try{(yield(0,Hn.stat)(r.path)).size>262144?i=!0:o=yield sc(r.path)}catch(e){}t.set(n,{contentBeforeWrite:o,fileTooLarge:i})})),runCleanup:e=>{t.delete(e)},runPostExecutionHooks:r=>TS(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,jf.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(ce.afterFileEdit,d);if(n.returnFileContentAfterWrite&&void 0!==h){const e=o.result.value.path;try{const t=yield sc(e),r=cc(t),n=Buffer.byteLength(t,"utf8");return new Et.v3({result:{case:"success",value:new Et.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 RS{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===Ke.symbol)return new Ze(this.hookExecutor);const r=this.innerAccessor.get(e);return e.symbol===xt.symbol?new ES(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ct.symbol?new PS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===_t.symbol?new IS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ot.symbol?new dS(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease):e.symbol===vt.symbol||e.symbol===yt.symbol?new vS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Qe.symbol?new aS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===le.symbol?new iS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===se.symbol?new nS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===oe.symbol?new Qb(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ie.symbol?new tS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===it.symbol?new pS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===st.symbol?new mS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===X.symbol?new Vb(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Q.symbol?new Kb(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ne.symbol?new Yb(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Nt.symbol?new wS(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===$t.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new zb(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===xt.symbol?yield[t,new ES(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ct.symbol?yield[t,new PS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===_t.symbol?yield[t,new IS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ot.symbol?yield[t,new dS(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease)]:t.symbol===vt.symbol||t.symbol===yt.symbol?yield[t,new vS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Qe.symbol?yield[t,new aS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===le.symbol?yield[t,new iS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===se.symbol?yield[t,new nS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===oe.symbol?yield[t,new Qb(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ie.symbol?yield[t,new tS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===it.symbol?yield[t,new pS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===st.symbol?yield[t,new mS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===X.symbol?yield[t,new Vb(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Q.symbol?yield[t,new Kb(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===ne.symbol?yield[t,new Yb(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Nt.symbol?yield[t,new wS(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===$t.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[t,new zb(r,null!==(e=this.hooksAdditionalContextPromise)&&void 0!==e?e:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease)]:yield[t,r];yield[Ke,new Ze(this.hookExecutor)]}}var AS,OS=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())}))},jS=function(e){return this instanceof jS?(this.v=e,this):new jS(e)};const MS={cursor_version:null!==(AS=process.env.AGENT_CLI_STATIC_VERSION)&&void 0!==AS?AS:"1.0.0",user_email:null};function DS(e=process.cwd()){let t=e;const r={getCwd(){return OS(this,void 0,void 0,(function*(){return t}))},clone:e=>DS(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 jS?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,uo.getPowerShellExecutable)(),args:[...He,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),h=(0,ss.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 jS(p.shift()):yield jS(new Promise((e=>{f=e})));if(void 0!==m)throw m}))}};return r}function NS(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function $S(e){return"string"==typeof e&&e.length>0?e:void 0}function LS(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function FS(e){if(Array.isArray(e)&&e.every(LS))return e.map((e=>({id:e.id,value:e.value})))}class US{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}dispose(){return OS(this,void 0,void 0,(function*(){yield this.sessionHooksRuntime.dispose()}))}}function BS(e={}){return{createHooksRuntime:t=>function(e){return OS(this,arguments,void 0,(function*(e,t={}){const r=yield new Eb(new Bb,function(e,t){var r,n,o,i,l;const c=null!==(n=null!==(r=e.projectRoot)&&void 0!==r?r:e.workingDirectory)&&void 0!==n?n:e.workspaceRoots[0],u=null===(o=t.includeProjectHooks)||void 0===o||o,d=null===(i=t.includeUserHooks)||void 0===i||i;return{enterpriseConfigPath:null===(l=t.includeEnterpriseHooks)||void 0===l||l?kb():void 0,userConfigPath:d?(0,a.join)((0,s.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:d?(0,a.join)((0,s.homedir)(),".claude","settings.json"):void 0,projectConfigPath:u&&void 0!==c?(0,a.join)(c,".cursor","hooks.json"):void 0,claudeProjectConfigPath:u&&void 0!==c?(0,a.join)(c,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:u&&void 0!==c?(0,a.join)(c,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new xb(r),o=function(e){var t,r,n;return null!==(n=null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workingDirectory)&&void 0!==r?r:e.workspaceRoots[0])&&void 0!==n?n:process.cwd()}(e),i=function(e){var t;return Object.freeze(Object.assign(Object.assign({},MS),null!==(t=e.globalContext)&&void 0!==t?t:{}))}(t);return{projectDir:e.projectRoot,workspacePath:o,hooksConfig:r,hooksConfigLease:n,globalContext:i,createSessionRuntime(){var e;const s=new bb(r,o,i,(null!==(e=t.createTerminalExecutor)&&void 0!==e?e:DS)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(a=t.useCommandHookStdinTransport,!0===a?"stdin":"legacy")});var a;return{hookExecutor:s,hooksConfigLease:n,dispose(){return OS(this,void 0,void 0,(function*(){s.clearSessionEnvironment()}))}}},dispose(){return OS(this,void 0,void 0,(function*(){}))}}}))}(t.workspaceState,e)}}var zS=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");function WS(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 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())}))};function qS(e={}){var t,r,n,o,i,a;const l=null!==(t=e.getThirdPartyExtensibilityEnabled)&&void 0!==t?t:()=>!0,c=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,u=null===(n=e.includeProjectExtensibility)||void 0===n||n,d=null===(o=e.includeUserExtensibility)||void 0===o||o,h=null===(i=e.includeManagedSkills)||void 0===i||i,p=null===(a=e.includePluginExtensibility)||void 0===a||a,f=new pd,m=(0,s.homedir)(),g=qc(m).dirPath;let v,y=!0;return{prepareLocalExtensibility(){return HS(this,void 0,void 0,(function*(){y=h&&(yield function(e){return HS(this,void 0,void 0,(function*(){if(!e)return!1;const t=(0,or.createClient)(zS.I,e),r=yield async function(e,t){try{const r=await t.getManagedSkills()??[],n=await Nv(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return Lv.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,Ye.q6)(),{getManagedSkills:()=>HS(this,void 0,void 0,(function*(){var e;return null!==(e=(yield t.getManagedSkills(new Dy.X8g({}))).skills)&&void 0!==e?e:[]}))});return"synced"===r.status}))}(e.dashboardTransport))}))},loadLocalExtensibility(t){return HS(this,void 0,void 0,(function*(){var r,n;const o=t.workspaceState,i=null!==(r=o.projectRoot)&&void 0!==r?r:o.workingDirectory;if(!i)return v=void 0,{cursorRulesService:XS(),getAgentSkills:e=>HS(this,void 0,void 0,(function*(){return[]}))};const s=(0,Ye.q6)(),a=null===(n=e.loadNestedRules)||void 0===n||n,h=function(e,t){const r=GS(t);return{getAllCursorRules(t){return HS(this,void 0,void 0,(function*(){return VS(yield e.getAllCursorRules(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(u?new hu(s,f,i,a,l,void 0):XS(),{allowedRoots:u?[i]:[],excludedRoots:[]}),w=function(e,t){const r=GS(t);return{getAllCursorRules(t){return HS(this,void 0,void 0,(function*(){return VS(yield e.getAllCursorRules(t),r)}))},getAllAgentSkills(t){return HS(this,void 0,void 0,(function*(){return VS(yield e.getAllAgentSkills(t),r)}))},reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new pu(s,u?[i]:[],m,f,a,void 0,l,Promise.resolve(),"sdk"),{allowedRoots:[...u?[i]:[],...d?[m]:[],...y?[g]:[]],excludedRoots:y?[]:[g]}),b=u?new xu(i,l):new yu,S=Pw(t.services.pluginBootstrapOutputs),k=S&&p?new mu(s,(()=>({importThirdPartyPlugins:c})),void 0,S.pluginsService):void 0,E=S&&p?new Pu((()=>({importThirdPartyPlugins:c})),S.pluginsService):void 0,x=new du([h,w,...k?[k]:[]]),C=new xv([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:u?[i]:[],userHomeDirectory:m}))),_=new _u([b,...E?[E]:[]]);return v={localRulesService:h,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:E,mergedCursorRulesService:x,mergedAgentSkillsService:C,mergedSubagentsService:_},{cursorRulesService:x,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:_}}))},disposeLocalExtensibility(){return HS(this,void 0,void 0,(function*(){if(!v)return;const e=v;v=void 0,yield function(e){return HS(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 WS(e)}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}))}(e)}))}}}function GS(e){const t=Promise.all(e.allowedRoots.map(ZS)),r=Promise.all(e.excludedRoots.map(ZS));return e=>HS(this,void 0,void 0,(function*(){const[n,o,i]=yield Promise.all([YS(e.fullPath),t,r]);return void 0!==n&&!i.some((e=>JS(n,e)))&&o.some((e=>JS(n,e)))}))}function VS(e,t){return HS(this,void 0,void 0,(function*(){const r=yield Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}))}function JS(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function KS(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}function ZS(e){return HS(this,void 0,void 0,(function*(){try{return KS(yield(0,Hn.realpath)(e))}catch(t){return KS(e)}}))}function YS(e){return HS(this,void 0,void 0,(function*(){try{return KS(yield(0,Hn.realpath)(e))}catch(e){return}}))}function XS(){return{getAllCursorRules(){return HS(this,void 0,void 0,(function*(){return[]}))},reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}var QS=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 ek(e={}){var t,r,n,o;const i=null!==(t=e.userHomeDirectory)&&void 0!==t?t:(0,s.homedir)(),l=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,c=null!==(n=e.pluginLogger)&&void 0!==n?n:{log(e,t,r){switch(e){case"warn":Sw.warn("[local-plugins-bootstrap]",t,null!=r?r:{});break;case"error":Sw.error("[local-plugins-bootstrap]",t,null!=r?r:{})}},increment(){},distribution(){},captureException(e,t){Sw.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,null!=t?t:{})}},u=tk(e.marketplaceOptions),d=void 0!==e.dashboardTransport,h=null!==(o=e.loadCursorFirstParty)&&void 0!==o?o:u||d;return{loadPluginBootstrapOutputs(t){return QS(this,void 0,void 0,(function*(){var r;const n=function(e){var t,r;return null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workspaceRoots[0])&&void 0!==r?r:e.workingDirectory}(t.workspaceState),{discoveredEntries:o,failures:s}=yield function(e){return QS(this,void 0,void 0,(function*(){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(yield jl(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}))}(n),u=null!==(r=e.marketplaceOptions)&&void 0!==r?r:e.dashboardTransport?function(e){const t=(0,a.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,or.createClient)(zS.I,e.dashboardTransport),n=_a((()=>QS(this,void 0,void 0,(function*(){try{return yield r.getEffectiveUserPlugins(new Dy.EwF({}))}catch(e){return{plugins:[]}}}))),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=_a((()=>QS(this,void 0,void 0,(function*(){var e,t;if(void 0===o)return{plugins:[]};try{const n=yield jl(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||Il(t)})).map((({key:e,entry:t})=>{const r=Ml(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=Ml(e.key);return new Dy.vwy({name:t.name,marketplaceName:t.marketplaceName})}));l=null!==(t=null===(e=(yield r.resolvePluginsByRef(new Dy.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 os(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new os(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:n,userHomeDirectory:i}):void 0,d=tk(u),p=new zv(void 0!==n?[n]:[],i,(()=>({importThirdPartyPlugins:l,loadCursorFirstParty:h})),u,c);let f=[];const m=[...s];try{f=yield p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}o.length>0&&!d&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:n,discoveredEntryCount:o.length}});const g={kind:_w,discoveredEntries:o,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,dispose(){return QS(this,void 0,void 0,(function*(){}))}};for(const e of m)Sw.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)Sw.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 tk(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}var rk=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 nk{getAllCursorRules(e){return rk(this,void 0,void 0,(function*(){return[]}))}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}class ok extends vv{constructor(e,t){super(e),this.sessionMcpLease=t}dispose(){const e=Object.create(null,{dispose:{get:()=>super.dispose}});return rk(this,void 0,void 0,(function*(){try{yield e.dispose.call(this)}finally{yield WS(this.sessionMcpLease)}}))}}function ik(e){const t=new pd;return{createResources(r){return rk(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 nk,p=null!==(a=r.workspaceServices.subagentsService)&&void 0!==a?a:new yu,f=null!==(l=r.workspaceServices.mcpLease)&&void 0!==l?l:new yh,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 sd(v,y):new id(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 vv(n):new ok(n,m)}catch(e){throw yield WS(m),e}}))}}}var sk=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 ak=["cursorRulesService","getAgentSkills","subagentsService"],lk=new WeakSet;function ck(e){("object"==typeof e&&null!==e||"function"==typeof e)&&lk.add(e)}function uk(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&lk.has(e)}function dk(e,t){const r=Object.keys(t).filter((e=>!ak.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${ak.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of ak)Object.hasOwn(t,r)&&(e[r]=t[r])}function hk(e,t,r){return sk(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&&(ck(a.cursorRulesService),ck(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&&dk(s,e)}return s}catch(t){try{yield pk(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 pk(e,t){return sk(this,void 0,void 0,(function*(){const r=null==t?void 0:t.preserveSharedContributorsFrom;let n;const o=e=>sk(this,void 0,void 0,(function*(){try{yield WS(e)}catch(e){null!=n||(n=e)}}));if(e.subagentsService===(null==r?void 0:r.subagentsService)||uk(e.subagentsService)||(yield o(e.subagentsService)),e.cursorRulesService===(null==r?void 0:r.cursorRulesService)||uk(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 sk(this,void 0,void 0,(function*(){let t;for(let r=e.length-1;r>=0;r-=1)try{yield WS(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 fk=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 mk(e){return fk(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 WS(o)}catch(e){null!=r||(r=e)}}}if(void 0!==r)throw r}))}const gk=["project","user","team","mdm","plugins"],vk=new Set([...gk,"all"]);function yk(e){if(void 0===e||0===e.length)return bk([]);for(const t of e)if(!vk.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({},bk(gk)),{all:!0})}return bk(e)}function wk(e,t){return e[t]}function bk(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 Sk=Object.freeze({}),kk=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Sk});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 xk(){return Ek(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:fw,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({},kk.metadata),e.metadata)),r=Object.assign(Object.assign(Object.assign({},kk),e),{metadata:t});return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:i});let a=yield hk(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 Ek(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 fk(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 mk(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 fk(this,void 0,void 0,(function*(){var t,r;if(!g){g=!0;try{yield mk(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 Ek(this,void 0,void 0,(function*(){l||(yield u((()=>Ek(this,void 0,void 0,(function*(){var e,t;if(l)return;const r=a,o=yield hk(n,i,s);l?yield pk(o,{disposeLocalExtensibility:d}):(a=o,yield pk(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 Ek(this,void 0,void 0,(function*(){l||(l=!0,yield u((()=>Ek(this,void 0,void 0,(function*(){var e;try{yield pk(a,{disposeLocalExtensibility:d})}finally{yield null===(e=n.lifecycle)||void 0===e?void 0:e.dispose()}})))))}))}}}))}var Ck=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class _k{requestApproval(e){return Ck(this,void 0,void 0,(function*(){return{approved:!0}}))}}class Pk{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}getPermissions(){return Ck(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 Ck(this,void 0,void 0,(function*(){}))}}class Tk{open(e,t){return Ck(this,void 0,void 0,(function*(){}))}getDiagnostics(e,t){return Ck(this,void 0,void 0,(function*(){return[]}))}}class Ik{getCodebaseReference(e,t){return Ck(this,void 0,void 0,(function*(){}))}}class Rk{constructor(e){this.inner=e}getState(e){return Ck(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 Ak{constructor(e){this.subagents=e.map((e=>new gu.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:gu.b$.DEFAULT,isBackground:!1,source:"sdk"})))}getAllSubagents(){return Ck(this,void 0,void 0,(function*(){return this.subagents}))}reload(){return Ck(this,void 0,void 0,(function*(){return this.subagents}))}}var Ok=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())}))},jk=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Mk=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 Dk=By;function Nk(e,t){return Mk(this,void 0,void 0,(function*(){const r=(0,a.dirname)(e);yield(0,Hn.mkdir)(r,{recursive:!0}),yield(0,Hn.writeFile)(e,t,"utf-8")}))}class $k{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=Dk(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=Uw({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,a.join)(this.projectDir,r)}:void 0;this.transcriptStore=new cb(this.projectDir,e.blobStore,Nk,Object.assign({writeText:!1,writeJsonl:!0},t?{pathResolver:t}:{})),this.nestedSubagentTranscriptStore=new cb(this.projectDir,e.blobStore,Nk,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=Uw({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,a.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((()=>Mk(this,void 0,void 0,(function*(){try{yield e()}catch(e){Sw.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})))),this.writeChain}writeFromState(e,t){return Mk(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>Mk(this,void 0,void 0,(function*(){yield this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=yield(0,Qt.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 Mk(this,void 0,void 0,(function*(){return this.enqueueWrite((()=>Mk(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=Uw({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,a.join)(this.projectDir,e)}return function(e,t){const r=Uw({conversationId:t,ext:"jsonl",kind:"primary"});return(0,a.join)(Dk(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var Lk=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 Fk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Uk="User aborted/interrupted manually.";class Bk{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 Vt}createOrResumeSession(e,t){return Lk(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(!Fk.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&Jt(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 Qt.We,r=(0,Qt.sh)(e),n=new Qt.pH(new Qt.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n}(n),s=new $k({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 Lk(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:Je.qL.AGENT_REQUEST,toolCallCount:0}}const i=yield this.executeSubagent(e,t,r,o);return null===(n=this.onSessionCompleted)||void 0===n||n.call(this,t,i),i}))}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}awaitBackgroundWorkers(){return Lk(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){Sw.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 Lk(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 Lk(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 Wt.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 Lk(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 Wt.Pw(Object.assign(Object.assign({},r),{runInBackground:!1})):new Wt.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 Lk(this,void 0,void 0,(function*(){var o,i,s;let a,l=0;const c=new Je.QF({action:{case:"userMessageAction",value:new Je.Vt({userMessage:new Je.RG({text:r.prompt})})}}),u=new Je.Gm({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(u.credentials=r.credentials);const d=new vw,h={sendUpdate:(e,r)=>Lk(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)=>Lk(this,void 0,void 0,(function*(){return function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return wn(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return Sn(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return xn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new jk.tz({result:{case:"rejected",value:new jk.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return kn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)}))},p={handleCheckpoint:(e,t)=>Lk(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=[[_t,(r=e.errorMessage,{execute(e,t){return Pt(this,void 0,void 0,(function*(){return new Et.v3({result:{case:"permissionDenied",value:new Et.U7({path:t.path,error:r,isReadonly:!0})}})}))}})],[oe,jt(e.errorMessage)],[ot,Mt(e.errorMessage)]];var r;return e.wrapShell&&t.push([xt,Rt(e.errorMessage)],[Ct,At(e.errorMessage)],[X,Ot(e.errorMessage)]),e.includeWriteBackgroundShellStdin&&t.push([Q,Dt(e.errorMessage)]),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):g;return yield this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,u,h,v,n.agentStore.getBlobStore(),d,p,[...this.mcpTools],{conversationGroupId:m,conversationId:t,subagentTypeName:r.subagentType||void 0,headers:this.headers,endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),yield n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:Uk}:{status:"success"}),{status:"completed",finalMessage:a,toolCallCount:l}}catch(r){const o=r instanceof Error?r.message:String(r);return Sw.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:Uk}:{status:"error",error:o}}}))}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:Uk}:{status:"error",error:t}}isAwaitBackgroundMode(e){var t;if(!Boolean(e.resumeAgentId&&!Jt(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 Lk(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 Lk(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 Lk(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 Lk(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 Lk(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 zk=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),Wk=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),Hk=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),qk=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");function Gk(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 Vk("tool-call-started",e.message.value);case"partialToolCall":return Vk("partial-tool-call",e.message.value);case"toolCallCompleted":return Vk("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=Gk(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 void 0:return null;default:return e.message,null}}function Vk(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:Qk(r)}:{}):null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"delete",args:{path:t.path}},r?{result:eE(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:tE(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:rE(r)}:{}):null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"read",args:{path:t.path}},r?{result:oE(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:iE(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:sE(r)}:{}):null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"readLints",args:{paths:t.paths}},r?{result:lE(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:cE(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:dE(r)}:{}):null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"recordScreen",args:{mode:hE(t.mode)}},r?{result:pE(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:uE(r)}:{}):null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"createPlan",args:{plan:t.plan}},r?{result:fE(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:gE(e.status)})))}},r?{result:mE(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:Jk(t)},r?{result:Yk(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"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 Jk(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:Kk(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:Zk(e.mode)}:{}),e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{})}function Kk(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function Zk(e){switch(e){case gu.FL.AGENT:return"agent";case gu.FL.PLAN:return"plan";default:return"unspecified"}}function Yk(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:Xk(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 Xk(e){switch(e){case Je.qL.AGENT_REQUEST:return"agentRequest";case Je.qL.USER_REQUEST:return"userRequest";case Je.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function Qk(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 eE(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 tE(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 rE(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]=nE(n);return{status:"success",value:Object.assign(Object.assign({},Object.keys(r).length>0?{workspaceResults:r}:{}),t.activeEditorResult?{activeEditorResult:nE(t.activeEditorResult)}:{})}}return{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}}function nE(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 oE(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 iE(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 sE(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:aE(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function aE(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(aE))&&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 lE(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:vE(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 cE(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 uE(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 dE(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 hE(e){switch(e){case cg.$u.START_RECORDING:return"START_RECORDING";case cg.$u.SAVE_RECORDING:return"SAVE_RECORDING";case cg.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function pE(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 fE(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 mE(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:gE(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 gE(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function vE(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}const yE={type:"object",properties:{},additionalProperties:!0};function wE(e){return{execute(t,r,n){return o=this,i=void 0,a=function*(){const t=r.toolName||function(e){const t=`${et}-`;return e.startsWith(t)?e.slice(t.length):e}(r.name),n=e[t];if(void 0===n)return new St.iz({result:{case:"error",value:new St.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:SE(e)?e:void 0};var t}(e),n=void 0!==r.structuredContent?nr.Struct.fromJson(r.structuredContent):void 0;return new St.iz({result:{case:"success",value:new St.QW({content:r.content.map(bE),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 St.iz({result:{case:"error",value:new St.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 bE(e){var t;return"text"===e.type?new St._Z({content:{case:"text",value:new St.zN({text:e.text})}}):new St._Z({content:{case:"image",value:new St.do({data:n.Buffer.from(e.data,"base64"),mimeType:null!==(t=e.mimeType)&&void 0!==t?t:""})}})}function SE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var kE=r("./src/agent/errors.ts"),EE=r("./src/agent/executor-common.ts"),xE=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),CE=r("./src/agent/utils/logger.ts"),_E=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};const PE={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},TE=new Map;var IE=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 RE(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof vv))throw new kE.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ot),i=wE(t);e.resources.base.register(ot,{execute(e,t,r){return IE(this,void 0,void 0,(function*(){if(function(e){return e.providerIdentifier===et}(t)){const o=yield Np(e,t,Object.assign(Object.assign({},n),{toolDef:{source:"internal"}}));return void 0!==o?o:i.execute(e,t,r)}return o.execute(e,t,r)}))}})}const AE={warn(){},error(){}},OE={log(){}};class jE{requestApproval(e){return IE(this,void 0,void 0,(function*(){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${ME(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 ME(e){switch(e.type){case rd.Shell:return"this shell command";case rd.Mcp:return"this MCP tool call";case rd.Write:return"this file edit";case rd.Delete:return"this file deletion";default:return"this operation"}}function DE(e){try{const t=(0,i.statSync)(e);return t.isFile()&&("win32"===process.platform||!!(73&t.mode))}catch(e){return!1}}function NE(e){const t=`${process.platform}-${process.arch}`,r=[`@cursor/sdk-${t}`,`@cursor/february-${t}`];if(!process.argv[1])return;let n=(0,a.dirname)((0,a.resolve)(process.argv[1]));const o=(0,a.parse)(n).root;for(;n!==o;){for(const t of r){const r=(0,a.join)(n,"node_modules",t,"bin",e);if(DE(r))return r}n=(0,a.dirname)(n)}}function $E(e){return void 0!==e&&"insecure_none"!==e.type}function LE(e,t){return IE(this,void 0,void 0,(function*(){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,Ye.q6)().with(h._O,OE);yk(r.settingSources),/:\/\/(localhost|127\.0\.0\.1)/.test(EE.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),r.apiKey&&(yield Promise.all([(0,EE.ly)(r.apiKey),(0,EE.mU)(r.apiKey)]));const l=r.workingDirectory||process.cwd(),u=(0,zg.Rv)((0,s.homedir)(),l);let d;const p="win32"===process.platform?"rg.exe":"rg",f=process.env.CURSOR_RIPGREP_PATH;d=f&&(0,a.isAbsolute)(f)?f:NE(p),d||(d=(0,uo.resolveRipgrepFromPath)()),d&&(0,uo.configureRipgrepPath)(d);let m,g=jw(),v=!1;if(r.apiKey)try{m=(0,EE.KU)(r.apiKey);const e=(0,or.createClient)(zS.I,m),t=yield function(e){let t=TE.get(e);return t||(t=function(e){return _E(this,void 0,void 0,(function*(){try{const t=yield function(e){return _E(this,void 0,void 0,(function*(){const t=yield(0,EE.dC)(e,EE.EV);if(!t)return;const r=EE.EV.endsWith("/")?EE.EV.slice(0,-1):EE.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,EE.tF)(),"x-ghost-mode":(0,EE.U)(e)},body:JSON.stringify({})});if(!n.ok)return void CE.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 PE;const r=new xE.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,EE.tF)()})})}catch(e){CE.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,EE.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 CE.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),PE}}))}(e),TE.set(e,t),t.then((r=>{r===PE&&TE.get(e)===t&&TE.delete(e)}),(()=>{TE.get(e)===t&&TE.delete(e)}))),t}(r.apiKey);v=t.checkFeatureGate("hooks_stdin_transport");const n={getDefaultNetworkAllowlist:()=>IE(this,void 0,void 0,(function*(){return t.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})}))};g=new Fy(new Ly(e),n,{isMcpAccessNetworkAllowlistEnabled:()=>t.checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:e=>t.checkFeatureGate("mcp_settings_overhaul",e)})}catch(e){CE.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const y=r.apiKey?yield(0,uo.loadSandboxPolicyFromFileOrUndefined)(`${(0,s.homedir)()}/.cursor/sandbox.json`,(0,s.homedir)()):void 0,w=void 0!==r.apiKey?yield function(e){return IE(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=$E(r)?r:!0===(null==n?void 0:n.enabled)?function(e,t={}){return Object.assign({type:e},t)}("workspace_readwrite",{networkPolicy:(0,uo.networkDisabledPolicy)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(){const e=NE("win32"===process.platform?"cursorsandbox.exe":"cursorsandbox");e&&(0,uo.configureSandboxPrereqs)({sandboxBinaryPath:e})}(),!(0,uo.isSandboxSupported)(void 0,{ctx:e.initializationCtx}))throw new kE.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,uo.resolveSandboxPolicyForWorkspace)(t,i);return{defaultSandboxPolicy:s,defaultSandboxPolicySources:i}}))}({cwd:l,perUserSandboxPolicy:y,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,b=null==w?void 0:w.defaultSandboxPolicy,S=null==w?void 0:w.defaultSandboxPolicySources,k=$E(b),E=yield function(e){return Ck(this,void 0,void 0,(function*(){var t,r,n,o,i,s,a,l,c;const{workingDirectory:u,projectDir:d}=e,h=yk(e.settingSources),p=null!==(r=e.teamSettingsService)&&void 0!==r?r:jw(),f=null!==(n=e.defaultSandboxPolicy)&&void 0!==n?n:{type:"insecure_none"},m=null!==(o=e.getSandboxSupported)&&void 0!==o?o:()=>(0,uo.isSandboxSupported)(f,{ctx:e.initializationCtx}),g=null!==(i=e.getSandboxEnabled)&&void 0!==i?i:()=>"insecure_none"!==f.type&&m(),v=new pd,y=new Ac(v,p,[u]),w=new Tk,b=new Ik,S=null===(t=e.getSmartModeClassifierAutoModeEnabled)||void 0===t?void 0:t.call(e),k=new Pk(S?"allowlist":null!==(s=e.approvalMode)&&void 0!==s?s:"unrestricted",f,p,null!==(a=e.respectAdminControls)&&void 0!==a&&a),E=e.pendingDecisionProvider,x={executeIndexedGrep:void 0},C=()=>!0,_=wk(h,"plugins"),P=null!==(l=e.importThirdPartyPlugins)&&void 0!==l&&l,T=null===(c=e.mcpMetaToolEnabled)||void 0===c||c,I=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,R=void 0!==e.customSubagents&&e.customSubagents.length>0,A=I||wk(h,"project")||wk(h,"user")||_,O=wk(h,"project")||wk(h,"user")||wk(h,"mdm"),j=wk(h,"team"),M=j&&void 0!==e.dashboardTransport,D=wk(h,"project")||wk(h,"user")||j||M||_,N=t=>xk({workingDirectory:u,adapters:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.includeMcp?{mcp:Mw({teamSettingsService:p,initializationCtx:e.initializationCtx,importThirdPartyPlugins:P,ignoreApprovals:!0,includeProjectMcp:wk(h,"project"),includeUserMcp:wk(h,"user"),includePluginMcp:_,inlineMcpServers:e.mcpServers})}:{}),_?{pluginBootstrap:ek({importThirdPartyPlugins:P,dashboardTransport:e.dashboardTransport})}:{}),O?{hooks:BS({includeProjectHooks:wk(h,"project"),includeUserHooks:wk(h,"user"),includeEnterpriseHooks:wk(h,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{}),D?{localExtensibility:qS({includeProjectExtensibility:wk(h,"project"),includeUserExtensibility:wk(h,"user"),includeManagedSkills:M,includeTeamExtensibility:j,includePluginExtensibility:_,teamSettingsService:p,getThirdPartyExtensibilityEnabled:C,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:P})}:{}),{resourceFactory:ik({ignoreService:y,grepProvider:x,workspacePaths:[u],diagnosticsProvider:w,repositoryProvider:b,projectDir:null!=d?d:u,shellManager:void 0,defaultSandboxPolicy:f,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:g,getSandboxSupported:m,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:e=>new Rk(new jg(e)),createSessionMcpLease:(t,r)=>Mw({teamSettingsService:p,initializationCtx:e.initializationCtx,importThirdPartyPlugins:!1,ignoreApprovals:!0,includeProjectMcp:!1,includeUserMcp:!1,includePluginMcp:!1,inlineMcpServers:r}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{var t;const r=null!=E?E:new _k;return{pendingDecisionStore:r,fileChangeTracker:new ud(u),permissionsService:new My(y,r,k,p,u,null!==(t=e.respectAdminControls)&&void 0!==t&&t)}}}),resourceWrappers:O?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!("object"==typeof(r=t)&&null!==r&&"hooksConfigLease"in r&&"createSessionRuntime"in r&&"function"==typeof r.createSessionRuntime&&function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources)))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new US(new RS(e.resources,n.hookExecutor,(()=>function(e,t){var r,n,o,i;const s=null!==(n=null!==(r=NS(t,$S,"conversationId","conversation_id"))&&void 0!==r?r:e.sessionId)&&void 0!==n?n:"",a=null!==(o=NS(t,$S,"generationId","generation_id"))&&void 0!==o?o:s,l=null!==(i=NS(t,$S,"model"))&&void 0!==i?i:"unknown",c=NS(t,$S,"modelId","model_id"),u=NS(t,FS,"modelParams","model_params");return Object.assign({conversation_id:s,generation_id:a,model:l},_e({modelId:c,modelParams:u}))}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[]}),R?{workspaceServicesContributors:[{contributeServices:t=>{var r;const n=new Ak(null!==(r=e.customSubagents)&&void 0!==r?r:[]),o=t.services.subagentsService;return{subagentsService:void 0===o?n:new _u([n,o])}}}]}:{})});if(!A)return N({includeMcp:!1});try{return yield N({includeMcp:!0})}catch(e){return Sw.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:u,projectDir:d,enablePlugins:_,importThirdPartyPlugins:P}),N({includeMcp:!1})}}))}({workingDirectory:l,projectDir:u,teamSettingsService:g,initializationCtx:i,dashboardTransport:m,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:b,defaultSandboxPolicySources:S,approvalMode:k?"allowlist":void 0,pendingDecisionProvider:k||!0===r.autoReview?new jE:void 0,getNetworkAllowlistInfo:k?()=>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,uo.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,uo.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}}(g,(0,s.homedir)(),l):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:v});let x,C;return{run:(e,t,i)=>IE(this,void 0,void 0,(function*(){return function(e,t){return ww.run(e,t)}(AE,(()=>IE(this,void 0,void 0,(function*(){var s,a,u,d;const p=(0,c.VI)((0,Ye.q6)().withName("sdk.run").with(h._O,OE)),[f,m]=p.ctx.withCancel(),g=null!==(s=t.sessionId)&&void 0!==s?s:(0,o.randomUUID)(),v=t.mcpServersOverride,y=void 0===(w=t.customTools)?[]:Object.entries(w).map((([e,t])=>{var r,n;return{clientKey:et,providerIdentifier:et,toolName:e,name:`${et}-${e}`,description:null!==(r=t.description)&&void 0!==r?r:"",inputSchema:null!==(n=t.inputSchema)&&void 0!==n?n:yE,source:"internal"}}));var w;let b;b=yield E.createSessionRuntime({sessionId:g,mcpServersOverride:v,extraMcpTools:y});const S=new Map;try{const s=b.resources.wrapped;RE(b,t.customTools);const c=null!==(a=t.blobStore)&&void 0!==a?a:new Qt.ve;let h=null!==(u=t.initialState)&&void 0!==u?u:new Je.Y9({});const p=void 0!==t.model?new Je.G4({modelId:t.model.id,parameters:(null!==(d=t.model.params)&&void 0!==d?d:[]).map((e=>new Je.SR({id:e.id,value:e.value})))}):void 0,w=Array.isArray(e.images)?e.images.map((e=>{const t=(0,o.randomUUID)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),i=(0,EE.v8)(r);return new Hk.d(Object.assign(Object.assign({uuid:t},i?{mimeType:i}:{}),{dataOrBlobId:{case:"data",value:r}}))})):[],k=w.length>0?new Hk.xv({selectedImages:w}):void 0,_=function(e){switch(e){case"agent":return Je.xy.AGENT;case"plan":return Je.xy.PLAN;default:return}}(t.mode),P=new Je.QF({action:{case:"userMessageAction",value:new Je.Vt({userMessage:new Je.RG(Object.assign({text:e.text,selectedContext:k},void 0!==_?{mode:_}:{}))})}}),T={sendUpdate:(e,t)=>IE(this,void 0,void 0,(function*(){const e=Gk(t,g);null!==e&&(yield i.sendUpdate(e))})),query:(e,t)=>IE(this,void 0,void 0,(function*(){return function(e){var t;switch(e.query.case){case"webSearchRequestQuery":return yn(e.id);case"webFetchRequestQuery":return bn(e.id);case"switchModeRequestQuery":return En(e.id);case"askQuestionInteractionQuery":return kn(e.id,new jk.tz({result:{case:"rejected",value:new jk.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return Cn(e.id,new hn.bK({result:{case:"success",value:new hn.Jo},planUri:""}));case"setupVmEnvironmentArgs":return _n(e.id,new qk.r$({result:{case:"success",value:new qk.JH}}));case"replaceEnvArgs":return Pn(e.id,new Wk.dV({result:{case:"failure",value:new Wk.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return Tn(e.id,new On.HL({result:{case:"error",value:new On.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return In(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Rn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return An(e.id,null===(t=e.query.value.args)||void 0===t?void 0:t.description);case void 0:throw new kE.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new kE.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)}))};if(x!==t.apiKey||!C){yield Promise.all([(0,EE.ly)(t.apiKey),(0,EE.mU)(t.apiKey)]);const e=(0,EE.KU)(t.apiKey),r=Un((0,or.createClient)(zk.N,e),{injectTraceHeaders:!0});C=new un(r),x=t.apiKey}const I=(0,EE.Vh)(C,(()=>{const e=(0,EE.KU)(t.apiKey),r=Un((0,or.createClient)(zk.N,e),{injectTraceHeaders:!0}),n=new un(r);return C=n,x=t.apiKey,n})),R=new Bk({agentClient:I,getResources:e=>IE(this,[e],void 0,(function*({agentId:e}){let r=S.get(e);return r||(r=yield E.createSessionRuntime({sessionId:e,mcpServersOverride:v,extraMcpTools:y}),RE(r,t.customTools),r.resources.base.register(Gt,A),S.set(e,r)),r.resources.wrapped})),mcpTools:y,workspacePath:l,parentConversationId:g,onSessionReleased:e=>{const t=S.get(e);t&&(t.dispose(),S.delete(e))}}),A=qt(R);b.resources.base.register(Gt,A);const O=E.services.hooksRuntime,j=O?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(ce.sessionStart)||t.hooksConfigLease.hasHookForStep(ce.sessionEnd)||t.hooksConfigLease.hasHookForStep(ce.stop)||t.hooksConfigLease.hasHookForStep(ce.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{onSessionStart(e){return Ok(this,void 0,void 0,(function*(){if(o=e,n.hasHooksForStep(ce.sessionStart))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},_e(e)),{is_background_agent:!1}),r=yield n.executeHookForStep(ce.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){Sw.warn("[hooks-adapter] sessionStart hook failed:",e)}}))},onSessionEnd(e,t){return Ok(this,void 0,void 0,(function*(){var r,i,s;if(n.hasHooksForStep(ce.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?_e(o):{}),{reason:e,duration_ms:t,is_background_agent:!1,final_status:e});yield n.executeHookForStep(ce.sessionEnd,a)}catch(e){Sw.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()}))},onBeforeSubmitPrompt(e){return Ok(this,void 0,void 0,(function*(){var t;if(n.hasHooksForStep(ce.beforeSubmitPrompt))try{const r=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},_e(e)),{prompt:null!==(t=e.promptText)&&void 0!==t?t:"",attachments:[]});yield n.executeHookForStep(ce.beforeSubmitPrompt,r)}catch(e){Sw.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}}))},onTurnCompleted(e){return Ok(this,void 0,void 0,(function*(){if(!n.hasHooksForStep(ce.stop))return;const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},_e(e)),{status:"completed",loop_count:e.loopCount}),r=yield n.executeHookForStep(ce.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 Ok(this,void 0,void 0,(function*(){if(n.hasHooksForStep(ce.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},_e(e)),{status:"error",loop_count:e.loopCount});yield n.executeHookForStep(ce.stop,t)}catch(e){Sw.warn("[hooks-adapter] onTurnError stop hook failed:",e)}}))},onTurnAborted(e){return Ok(this,void 0,void 0,(function*(){if(n.hasHooksForStep(ce.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},_e(e)),{status:"aborted",loop_count:e.loopCount});yield n.executeHookForStep(ce.stop,t)}catch(e){Sw.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}}))},dispose(){return Ok(this,void 0,void 0,(function*(){yield r.dispose()}))}}}({workspaceRuntime:O,sessionState:b.state,metadata:b.metadata}):void 0,M=new $k({workspacePath:l,conversationId:g,blobStore:c}),D=function(e,t,r){const{hooks:n}=r,[o,i]=e.withCancel(),s=new vw;let a=r.initialState;const l={handleCheckpoint(e,t){return kw(this,void 0,void 0,(function*(){var e;a=t,yield null===(e=r.onCheckpoint)||void 0===e?void 0:e.call(r,t)}))},getLatestCheckpoint:()=>a};let c="completed";const u=Date.now(),d=(()=>kw(this,void 0,void 0,(function*(){var e,i,u,d,h,p,f,m,g;const v=xw(r,0,Ew(t));try{const t=yield null===(e=null==n?void 0:n.onSessionStart)||void 0===e?void 0:e.call(n,v);if(null==t?void 0:t.blocked)throw c="error",new Error(null!==(f=t.blockedReason)&&void 0!==f?f:"Session blocked by sessionStart hook")}catch(e){if("completed"!==c)throw e;Sw.warn("[agent-session-runner] sessionStart hook failed:",e)}let y=t,w=0;for(;y;){const e=xw(r,w,Ew(y));try{yield null===(i=null==n?void 0:n.onBeforeSubmitPrompt)||void 0===i?void 0:i.call(n,e)}catch(e){Sw.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}const t=0===w?r.preFetchedBlobs:void 0;try{yield r.agentClient.run(o,a,y,void 0,r.interactionListener,r.resources,r.blobStore,s,l,null!==(m=r.mcpTools)&&void 0!==m?m:[],Object.assign(Object.assign(Object.assign({conversationId:r.conversationId},r.runOptions),{subagentModelOverrides:null!==(g=null===(u=r.runOptions)||void 0===u?void 0:u.subagentModelOverrides)&&void 0!==g?g:[]}),void 0!==t?{preFetchedBlobs:t}:{}))}catch(t){throw c=Cw(t)?"aborted":"error",null==(b="aborted"===c?null===(d=null==n?void 0:n.onTurnAborted)||void 0===d?void 0:d.call(n,e):null===(h=null==n?void 0:n.onTurnError)||void 0===h?void 0:h.call(n,e))||b.catch((e=>{Sw.warn("[agent-session-runner] fire-and-forget hook failed:",e)})),t}let f;try{f=yield null===(p=null==n?void 0:n.onTurnCompleted)||void 0===p?void 0:p.call(n,e)}catch(e){throw c="error",e}const v="string"==typeof f?f.trim():"";0!==v.length?(w+=1,s.resetStream(),S=v,y=new Je.QF({action:{case:"userMessageAction",value:new Je.Vt({userMessage:new Je.RG({text:S})})}})):y=void 0}var b,S})))().finally((()=>kw(this,void 0,void 0,(function*(){var e,t;const r=Date.now()-u;try{yield null===(e=null==n?void 0:n.onSessionEnd)||void 0===e?void 0:e.call(n,c,r)}catch(e){Sw.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{yield null===(t=null==n?void 0:n.dispose)||void 0===t?void 0:t.call(n)}catch(e){Sw.warn("[agent-session-runner] hooks dispose failed:",e)}}))));return{done:d,abort(){i()}}}(f,P,Object.assign(Object.assign({agentClient:I,interactionListener:T,resources:s,blobStore:c,initialState:h,conversationId:g,mcpTools:y,runOptions:{generationUUID:t.requestId,requestedModel:p,enableAgentRetries:!1!==r.enableAgentRetries}},t.preFetchedBlobs&&t.preFetchedBlobs.length>0?{preFetchedBlobs:t.preFetchedBlobs}:{}),{hooks:j,onCheckpoint(e){return IE(this,void 0,void 0,(function*(){var r;h=e,M.writeFromState(f,e),yield null===(r=t.onCheckpoint)||void 0===r?void 0:r.call(t,e)}))}})),N=D.done.finally((()=>IE(this,void 0,void 0,(function*(){try{yield R.awaitBackgroundWorkers()}finally{yield M.waitForPendingWrites().catch((()=>{}));for(const e of S.values())try{yield e.dispose()}catch(e){CE.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}S.clear(),yield b.dispose()}})))).catch((e=>{throw e}));return{abort(){D.abort(),m()},done:N}}catch(e){for(const e of S.values())try{yield e.dispose()}catch(e){}throw S.clear(),yield b.dispose(),e}}))))})),reload(){return IE(this,void 0,void 0,(function*(){yield E.reload()}))},dispose(){return IE(this,void 0,void 0,(function*(){yield E.dispose()}))}}}))}},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){r.r(t),r.d(t,{buildMcpSandboxPolicy:()=>n.Ic});var n=r("../mcp-core/dist/index.js")},"../mcp-core/dist/index.js"(e,t,r){r.d(t,{B1:()=>q,c8:()=>Me,E_:()=>De,Ic:()=>Re,O3:()=>Q,tB:()=>Z,ME:()=>M,Fm:()=>je,jI:()=>_e,VD:()=>ue,X5:()=>le,$H:()=>L,Y:()=>B,PK:()=>Ne,FC:()=>W,_N:()=>$,q2:()=>J});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=A(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=A(e),n=A(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=A(e);return t.length>0&&t.length<=253&&f.test(t)}function S(e){const t=A(e);return v.test(t)||function(e){const t=A(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=A(e);return"*"===t||!!m.test(t)||(t.includes("/")?function(e){const t=A(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){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=`${A(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}function _(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function P(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function T(e,t){return function(e,t,r){const n=I(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("*")&&A(i)===A(s)&&(_(a=o.pathname,l=n.pathname)||_(P(a),P(l)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:_(e,t)}(o.search,n.search,r));var i,s,a,l}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function I(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=O(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!A(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(A(r.hostname)!==A(o))return}return r}}function R(e,t){if(_(e,t))return!0;const r=O(t);return!!r&&u(r.hostname,e)}function A(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function O(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 j(e){return(null!=(t=e.mcpNetworkAllowlist)?t:[]).flatMap((e=>{const t=C(e);return void 0===t?[]:[t]}));var t}function M(e,t){var r,n;if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!I(e))return{allowed:!1,message:null!==(r=t.blockMessage)&&void 0!==r?r:d};const o=j(t);return o.length>0&&o.some((t=>function(e,t){const r=I(t);if(!r)return!1;if(!e.includes("://"))return u(A(r.hostname),e);if(T(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&&T(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:null!==(n=t.blockMessage)&&void 0!==n?n:d}}function D(e){const t=null==e?void 0:e.trim();return t&&t.length>0?t:void 0}function N(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 $({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=D(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=D(e.command),n=D(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&_(r,t.command),i=void 0===n||void 0!==t.url&&R(n,t.url);return o&&i}(e,t)))}(s,t),c=N(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||N(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!==D(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!==D(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 L(e){if(!0===(null==e?void 0:e.enabled)&&"no_sandbox"!==e.mcpNetworkMode)return e}function F(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function U(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function B(e,t,r){var n;if(void 0===t)return!0;if(!0===t.disableAll)return!1;const o=null!==(n=t.allowedMcpServers)&&void 0!==n?n:[];return 0===o.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){var n;const o=null!==(n=null==r?void 0:r.matchesServerUrlPattern)&&void 0!==n?n:R;return t.some((t=>{const r=F(t.command),n=U(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&_(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:R;return(null!=t?t:[]).some((t=>{const r=F(t.command),n=U(t.serverUrl);if(void 0===r&&void 0===n)return!1;const i=void 0===r||void 0!==e.command&&_(r,e.command),s=void 0===n||void 0!==e.url&&o(n,e.url);return i&&s}))}(e,t.deniedMcpServers,r)}function z(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 W({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?[...z(t),...o]:[...o],[...new Set(i)];var i}var H=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 q{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}get(e){return H(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=(()=>H(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 G(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function V(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 J(e,t){return V(e,t)}var K=r("crypto");function Z(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 Y(e){if(e)return(0,K.createHash)("sha256").update(e).digest("hex").slice(0,12)}function X(e){if(e&&0!==e.length)return Y(JSON.stringify([...e].sort()))}function Q(e){var t,r;return{clientIdHash:Y(null==e?void 0:e.client_id),clientSecretHash:Y(null==e?void 0:e.client_secret),redirectUrisHash:X(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 ee(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 te(e,t){for(const r of t)if("string"==typeof ee(e,r.split(".")))return ee(e,r.split("."))}const re="[REDACTED]",ne=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function oe(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${re}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${re}`)}function ie(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function se(e,t){return ie(oe(e),null==t?void 0:t.maxLength)}function ae(e){if("string"==typeof e)return ie(oe(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")||ne.test(t)}(e)?re:"string"==typeof t?oe(t):t));if(!t)return;return ie(t)}catch(e){return}}function le(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?se(a):void 0,c=te(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:te(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=ee(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=ae(null!==(i=null!==(o=null!==(n=ee(e,["response","body"]))&&void 0!==n?n:ee(e,["body"]))&&void 0!==o?o:ee(e,["data"]))&&void 0!==i?i:ee(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 G({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 ce={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 ue(e){var t,r,n,o,i,s,a,l,c,u;const d=null!==(c=e.message)&&void 0!==c?c:ce[e.event],h={event:e.event,cursorMcp:{oauth:G(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 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())}))};const he=4096;function pe(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function fe(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function me(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function ge(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function ve(e,t){var r,n,o,i,s;if(null==e)return{kind:"none",bytes:0,contentLength:ge(t.get("content-length"))};if("string"==typeof e){const n=(new TextEncoder).encode(e).length;return{kind:"text",bytes:n,contentLength:null!==(r=ge(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=ge(t.get("content-length")))&&void 0!==n?n:o}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:null!==(o=ge(t.get("content-length")))&&void 0!==o?o:e.size}:e instanceof ArrayBuffer?{kind:"binary",bytes:e.byteLength,contentLength:null!==(i=ge(t.get("content-length")))&&void 0!==i?i:e.byteLength}:ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:null!==(s=ge(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:ge(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:ge(t.get("content-length"))}}function ye(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 we(e){var t,r,n,o;const{input:i,init:s}=e,a=V(fe(i)),l=function(e,t){const r=new Headers(pe(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=me(l),u=l.get("content-type"),d=Y(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:pe(i)?i.method:void 0)&&void 0!==o?o:"GET").toUpperCase(),url:a,headers:{names:c,count:c.length},contentType:u,body:ve(null==s?void 0:s.body,l),sessionIdHash:null!=d?d:null,authorizationScheme:p}}function be(e,t){var r,n,o,i,s;const a=me(e.headers),l=ge(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=Y(null!==(r=e.headers.get("mcp-session-id"))&&void 0!==r?r:void 0))&&void 0!==n?n:null,wwwAuthenticateHash:null!==(i=Y(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 Se(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 ke(e,t){return de(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 Ee(e){return de(this,void 0,void 0,(function*(){if(!function(e,t){var r,n;const o=we({input:e,init:t});if(void 0!==ye(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 ke(e.response,he);if(void 0!==t)try{return ae(JSON.parse(t))}catch(e){return se(t,{maxLength:he})}}))}function xe(e){return de(this,void 0,void 0,(function*(){const t=yield function(e,t){return de(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 ke(t,he);if(void 0===i)return;return function(e){if("/mcp"!==(t=V(fe(e.input)).path)&&!0!==(null==t?void 0:t.endsWith("/mcp")))return se(e.rawText,{maxLength:he});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?se(r.message,{maxLength:he}):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 Ee({input:e.input,response:e.response,init:e.init}):void 0}}))}function Ce(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 _e(e){const{fetch:t,logger:r,metadata:n,logSuccessfulExchanges:o=!0}=e;return(e,i)=>de(this,void 0,void 0,(function*(){const s=Date.now();try{const a=yield t(e,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:c}=a.ok?{}:yield xe({input:e,init:i,response:a});return!o&&a.ok||Ce((()=>{!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=we({input:t,init:r}),c=ye(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:be(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 xe({input:e,init:i,response:o}):{};throw Ce((()=>{!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=le(o),d=we({input:r,init:n}),h=ye(d.contentType,null==n?void 0:n.body),p=void 0!==a?be(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:Se(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 Pe=["0.0.0.0/0","::/0"];function Te(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 Ie(e){const t=Te(e.mcpNetworkAllowlist),r=Te(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:[...Pe]},r.entries.length>0?{deny:r.entries}:{});if("allowlist"===n||t.hasConfiguredEntries){const e=function(e){return e.entries.includes("*")?[...Pe]: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:[...Pe]},r.entries.length>0?{deny:r.entries}:{})}function Re(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:Ie(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 Ae=["0.0.0.0/0","::/0"];function Oe(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 je(e){const t=!0===e.enabled,r=Oe(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...Ae];const t=Oe(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...Ae]:t.entries;if(!function(e){var t;return(null!==(t=e.mcpNetworkAllowlist)&&void 0!==t?t:[]).some((e=>e.trim().length>0))}(e))return[...Ae];const r=j(e);return r.includes("*")?[...Ae]:r}(e):[],i=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:i})}class Me extends Error{constructor(e,t){super(`MCP server "${e}" requires sandboxing because MCP Network Controls are enabled, but the sandbox is not supported on this platform or system. The server was not started.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}function De(e,t){void 0!==t&&t.length>0&&e.searchParams.set("scope",t.join(" "))}function Ne(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!(null==n?void 0:n[1]))return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){var t;if(!(e instanceof Error))return!1;const r=e,n=null===(t=e.cause)||void 0===t?void 0:t.code;return"ECONNREFUSED"===r.code||"ECONNREFUSED"===n||e.message.includes("ECONNREFUSED")}(e)}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]),new Set([429,502,503,504]),new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]),Error},"../shell-exec/dist/index.js"(e,t,r){r.r(t),r.d(t,{BashState:()=>ct,INSECURE_NONE_SANDBOX_POLICY:()=>tr,KnownShellExecutor:()=>Te,NaiveTerminalExecutor:()=>gt,OutputSuppressionController:()=>Bt,PowerShellState:()=>ft,SHELL_OUTPUT_SUPPRESSED_NOTICE:()=>Ut,SandboxUnsupportedError:()=>ke,ZshState:()=>kt,configureRipgrepPath:()=>v,configureSandboxPrereqs:()=>xe,createDefaultTerminalExecutor:()=>er,createIgnoreMapping:()=>Kt,createNaiveTerminalExecutor:()=>vt,getLastSandboxFailureReason:()=>Se,getPowerShellExecutable:()=>pt,getRipgrepBinaryPath:()=>S,getSandboxPolicyType:()=>Ue,getShellExecutablePath:()=>Zt,getSuggestedShell:()=>Qt,isAllowAllNetworkByPolicy:()=>te,isHardcodedWriteProtected:()=>Y,isNetworkEnabledByPolicy:()=>ee,isRipgrepConfigured:()=>k,isSafeHeredocStdinCommand:()=>Wt,isSandboxSupported:()=>Pe,loadSandboxPolicyFromFileOrUndefined:()=>Vt,mergeNetworkPolicies:()=>Je,mergePathsIntersection:()=>ze,mergePathsUnion:()=>We,networkAllowAllPolicy:()=>ne,networkDisabledPolicy:()=>re,parseSandboxPolicyJson:()=>Gt,resolvePolicyPaths:()=>Jt,resolveRipgrepFromPath:()=>g,resolveSandboxPolicyForWorkspace:()=>Ye,spawnInSandbox:()=>Ce,spawnWithSignal:()=>Re,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 T;function I(){const e=(0,n.join)((0,h.tmpdir)(),"cursor-sandbox-cache",(T||(T=(0,P.randomBytes)(16).toString("hex")),T));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"),j=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class M 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,M)}}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 M(`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,j.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new M(`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,j.L5)({count:e,delay:(e,r)=>{if(e instanceof M&&0!==e.exitCode)return(0,O.timer)(t);throw e}}))}return r.split?i:i.pipe((0,j.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 M){const n=new M(`${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 M){const t=new M(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(D(e,t,Object.assign(Object.assign({},null!=r?r:{}),{split:!1})));var n}var $=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const L=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".ssh"}];function F(e){const t=L.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function U(e){const t=L.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}L.filter((e=>"git"===e.type)).map((e=>e.pattern)),L.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const B=[];let z=null,W=null;let H=null;const q=new Map;const G="win32"===process.platform||"darwin"===process.platform;function V(e){if(!e.endsWith(n.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function J(e){return e.endsWith(n.sep)?e:e+n.sep}function K(e,t){const r=V(t);if(G){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(J(n))}return e===r||e.startsWith(J(r))}function Z(e,t){const r=V(e);return G?(0,n.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,n.relative)(r,t).replace(/\\/g,"/")}async function Y(e,t){if(K(e,t)){const r=Z(t,e);if((null===z&&(z=$({ignoreCase:!0}),z.add(L.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),z).ignores(r))return!0}const{isWorktree:r,gitDirParent:o}=await async function(e){const t=q.get(e);if(t)return t;const r=await(0,d.stat)((0,n.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return q.set(e,t),t}const o=await async function(e){try{const t=await N("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,n.dirname)((0,n.resolve)(e,t.trim()))}catch{return null}}(e),i={isWorktree:!0,gitDirParent:o??e};return q.set(e,i),i}(t);if(K(e,o)){const t=Z(o,e);if((null===W&&(W=$({ignoreCase:!0}),W.add(L.filter((e=>"git"===e.type)).map((e=>e.pattern)))),W).ignores(t))return!0}if(r&&K(e,t)&&".git"===Z(t,e))return!0;for(const t of function(){if(null!==H)return H;const e=h.homedir(),t=[];for(const r of L)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,n.join)(e,r.pattern))}return H=t,t}())if(K(e,t))return!0;return!1}const X=new WeakMap;function Q(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}function ee(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function te(e){return void 0!==e&&"allow"===e.default}function re(){return{version:1,default:"deny"}}function ne(){return{version:1,default:"allow"}}const oe="darwin"===process.platform,ie="linux"===process.platform,se=(0,R.h)("shell-exec:sandbox");function ae(e){const t=P.randomBytes(8).toString("hex"),r=n.join(h.tmpdir(),`sandbox-policy-${t}`);return o.writeFileSync(r,e,{encoding:"utf-8",mode:384}),r}let le;function ce(){return le}function ue(e){"linux"===process.platform&&Object.assign(e,b(e))}let de=null,he=null,pe=null,fe=null;function me(e){if(null!==de)return!!de;try{const t=ce();return se.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(de=o.existsSync(t),de?se.info(e,`[checkBinaryAvailable] Binary path exists: ${de}`):(he=new Error(`Sandbox binary not found at ${t}`),se.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!de):(he=new Error("Sandbox binary path was not configured"),de=!1,se.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return he=t,de=!1,se.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function ge(e){if(null!==fe)return fe;const t=e??(0,A.q6)();if(se.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!me(t)){const e=he?.message||"Binary check failed";return pe=e,se.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),fe=!1,fe}if("win32"===process.platform)return pe="Windows sandbox helper only provides network proxy, not filesystem isolation",se.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),fe=!1,fe;if("darwin"===process.platform)return pe=null,se.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),fe=!0,fe;try{const e=process.cwd(),r={sandbox:{type:"workspace_readwrite",cwd:e,additionalReadwritePaths:[],networkAccess:!1,disableTmpWrite:!1,ignoreMapping:void 0}},n=String(ce());se.info(t,`[isSandboxHelperSupported] Running preflight with binary: ${n}`),se.info(t,`[isSandboxHelperSupported] CWD: ${e}`);const o={...process.env};ue(o);const i=ae(JSON.stringify(r));return(0,E.execFileSync)(n,["--policy",i,"--preflight-only","--","/bin/true"],{stdio:["ignore","ignore","pipe"],timeout:15e3,env:o,shell:!1}),pe=null,se.info(t,"[isSandboxHelperSupported] Preflight succeeded, sandbox supported!"),fe=!0,fe}catch(e){const r=e,n=r.stderr?.toString?.()||"";return se.error(t,`[isSandboxHelperSupported] Preflight failed: ${r.message}`),se.error(t,`[isSandboxHelperSupported] Exit status: ${r?.status}`),n&&se.error(t,`[isSandboxHelperSupported] Stderr: ${n}`),"number"==typeof r?.status&&2===r.status?(pe=`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${n||"none"}`,fe=!1,fe):(pe=`Linux preflight failed: ${r.message||"unknown error"}. Exit status: ${r?.status}. stderr: ${n||"none"}`,fe=!1,fe)}}function ve(e,t=[],r={},i){const s=(0,A.q6)();if(r.env=x(r.env),!me(s))throw new Error(`Sandbox binary not available: ${he?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===i.type)return(0,E.spawn)(e,t,r);if("workspace_readwrite"===i.type||"workspace_readonly"===i.type)return function(e,t,r,i){if("workspace_readwrite"!==i.type&&"workspace_readonly"!==i.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=i.sandboxWorkspaceRoot??s;let l,c=e,u=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",u=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",u=["-c",`${e} ${t.join(" ")}`])),i.ignoreMapping&&(l=ye(i.ignoreMapping));const d=function(e,t,r){const i=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,o.existsSync)(r)&&(0,o.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},s=function(e){let t=n.resolve(e);for(;;){try{const e=n.join(t,".git");if(o.existsSync(e))return!0}catch{}const e=n.dirname(t);if(e===t)return!1;t=e}}(r),a=!ie||s?t??{}:{},l={...i};for(const[e,t]of Object.entries(a))l[e]?l[e]=[...l[e],...t]:l[e]=t;if(0!==Object.keys(l).length)return ye(l)}(i.additionalReadonlyPaths,i.writeProtectionMapping,a),h=ee(i.networkPolicy),p="workspace_readonly"===i.type?{type:"workspace_readonly",cwd:a,readBoundary:i.readBoundary??"system",additionalReadPaths:i.additionalReadPaths||[],additionalReadonlyPaths:d,networkAccess:h,ignoreMapping:l}:{type:"workspace_readwrite",cwd:a,readBoundary:i.readBoundary??"system",additionalReadPaths:i.additionalReadPaths||[],additionalReadwritePaths:i.additionalReadwritePaths||[],additionalReadonlyPaths:d,networkAccess:h,disableTmpWrite:i.disableTmpWrite||!1,ignoreMapping:l},f=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!ee(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(i),m={sandbox:p};void 0!==f&&(m.networkPolicy=f),!1===i.networkPolicyStrict&&(m.networkPolicyStrict=!1);const g=["--policy",ae(JSON.stringify(m)),"--",c,...u],v={..."linux"===process.platform?_(process.env):process.env,..."linux"===process.platform&&r.env?_(r.env):r.env,CURSOR_SANDBOX:"native"};ue(v);const y={cwd:r.cwd||s,env:v,stdio:r.stdio||["pipe","pipe","pipe"]};try{const e=new Date,t=(0,E.spawn)(String(ce()),g,y);return oe&&t.pid&&function(e,t){X.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${e}`)}}(e,t,r,i);throw new Error(`Unsupported sandbox policy: ${String(i)}`)}function ye(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?we(t):t;o[e]=r;const n=be(e);n!==e&&(o[n]=r)}return o}function we(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function be(e){try{return(0,o.realpathSync)(e)}catch{return e}}function Se(){return pe}class ke extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Ee="darwin"===process.platform;function xe(e){!function(e){S();const{sandboxBinaryPath:t}=e;le||(le=t)}(e)}function Ce(e,t=[],r={},n){if(r.env=x(r.env),n.enableSharedBuildCache&&(r={...r,env:{...x(process.env),...I(),...r.env}}),"insecure_none"!==n.type){if(ge())return ve(e,t,r,n);const o=Se();throw new ke(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r){return(0,E.spawn)(e,t,r)}(e,t,r)}function _e(e){return Ee?async function(e){const t=X.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,i=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,E.execFile)("/usr/bin/log",i,((t,n,i)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),a=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const i=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(i){const[,e,s,l,c,u,d]=i,h=Number(s);a.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:l.toLowerCase(),decisionCode:Number(c),operation:u,target:d,duplicateCount:1,raw:n,relationship:Q(h,r,o)});continue}const s=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(s){const e=Number(s[1]),i=s[2],l=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(i);if(l){const[,i,s,c,u,d,h]=l,p=Number(s);a.push({timestamp:t.timestamp,processName:i.trim(),pid:p,decision:c.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Q(p,r,o)})}else a.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}a.push({timestamp:t.timestamp,raw:n})}catch{}e(a)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Pe(e,t){if(Ee)try{(0,o.accessSync)("/usr/bin/sandbox-exec",o.constants.X_OK)}catch{return!1}return ge(t?.ctx)}var Te;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Te||(Te={}));const Ie={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Re(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=Ce(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 Ae(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function Oe(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}const je="__CURSOR_BASH_STATE_START__",Me="__CURSOR_BASH_STATE_END__",De=50,Ne=262144;class $e{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??De,this.maxBufferedBytes=t?.maxBufferedBytes??Ne}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 Le(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 $e(e.writable,e.outputLimiterOptions);let r;const n=Promise.all([Fe(e.stdout,"stdout",t),Fe(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 Fe(e,t,r){if(e)for await(const n of e)await r.push(t,n)}function Ue(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Be(...e){return e.some((e=>!0===e))}function ze(...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=Ve(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(Ve);let r=new Set(t[0].map(Ve));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(Ve));r=new Set([...r].filter((e=>n.has(e))))}return[...r]}function We(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(Ve(e));return[...t]}const He=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]<t[e]?r:e))}}}({defaultValue:"system",rank:{workspace:0,custom:1,system:2}}),qe=(...e)=>ze(...e);function Ge(e,t){if("custom"===e)return t??[]}function Ve(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Je(...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 Ke(...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 Ze(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ye(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"===Ue(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:Ke(i?.writeProtectionMapping,U(e))}}}}if(i)return Xe(t,{workspaceDir:e,gitDirParent:r})}return Xe(t,{workspaceDir:e})}function Xe(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 tt(e,t);switch(r){case"workspace_readwrite":return tt(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Qe(e,t),o={policy:et({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:Be(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:Ze(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:Be(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:Ze(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 Qe(e,t){const r=t?.debug,{perUser:o,perRepo:i,teamAdmin:s}=e,a=t?.workspaceDir??process.cwd(),l=function(e){const t=function(){if(0!==B.length)return{version:1,deny:[...B]}}(),r=h.homedir(),o=[];for(const e of L)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":o.push(e.pattern);break;case"home":r.length>0&&o.push((0,n.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${t}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:o,writeProtectionMapping:F(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(a),c={},u=[o,i,s],d=["perUser","perRepo","teamAdmin","hardcoded"],p=(e,t)=>{r&&(c[e]=d[t]??"unknown")},f=Be(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=Be(o?.networkPolicyStrict,i?.networkPolicyStrict,s?.networkPolicyStrict,l.networkPolicyStrict);l.networkPolicyStrict&&p("networkPolicyStrict",3);const g=function(...e){return He.merge(...e)}(o?.readBoundary,i?.readBoundary,s?.readBoundary),v=function(...e){return qe(...e)}(Ge(o?.readBoundary,o?.additionalReadPaths),Ge(i?.readBoundary,i?.additionalReadPaths),Ge(s?.readBoundary,s?.additionalReadPaths)),y="custom"===g?v:void 0,w=We(o?.additionalReadonlyPaths,i?.additionalReadonlyPaths,s?.additionalReadonlyPaths,l.additionalReadonlyPaths),b=w.length>0?w:void 0;let S=Je(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=Ze(o?.debugOutputDir,i?.debugOutputDir,s?.debugOutputDir),_=Be(o?.captureDenies,i?.captureDenies,s?.captureDenies),P=Ze(o?.enableSharedBuildCache,i?.enableSharedBuildCache,s?.enableSharedBuildCache),T=Ke(o?.ignoreMapping,i?.ignoreMapping,s?.ignoreMapping,l.ignoreMapping),I=function(e){const t=L.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??a);return{disableTmpWrite:f||void 0,networkPolicyStrict:m,readBoundary:g,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:E,debugOutputDir:C,captureDenies:_||void 0,enableSharedBuildCache:P,ignoreMapping:T,writeProtectionMapping:Ke(o?.writeProtectionMapping,i?.writeProtectionMapping,s?.writeProtectionMapping,l.writeProtectionMapping,I),fieldSources:c}}function et(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function tt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,i=t?.debug,s=Qe(e,t),a=We(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),l={policy:et({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 rt="win32"===process.platform;function nt(e){return!rt&&!!e?.SUDO_ASKPASS}function ot(e){return nt(e)?"alias sudo='sudo -A'; ":""}function it(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 at(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 lt(e){if("win32"!==process.platform)return e;const t=n.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===n.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}class ct{cwd;state;userTerminalHint;useFileStateTransport;constructor(e,t,r,n=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n}async getCwd(){return this.cwd}clone(e){return new ct(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport)}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,p.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,a=(0,f.Jt)(),l=r?.workingDirectory??this.cwd,c={...process.env,...Ie,...r?.env};let u='builtin eval "$1"';s||(u+=" < /dev/null");const m=ot(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=lt(y),t=lt(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=at(this.userTerminalHint);if(!S)throw new Error("Can't find Bash");const k=r?.sandboxWorkspaceRoot??l,E=(await Ye(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 T;try{T=Re(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}T.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:T.stdin??void 0,pid:T.pid})}catch(e){}}));const I=Le({stdout:T.stdout,stderr:T.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});T.on("error",(async e=>{await P(),a.throw(e)}));let R=null,A=null,O=!1;const j=async e=>{if(!O){if(O=!0,A&&(clearTimeout(A),A=null),(0,p.HF)(i.ctx,"exit"),e)try{await I.waitForOutput()}catch(e){return await P(),void a.throw(e instanceof Error?e:new Error(String(e)))}if(await I.flush(),!r?.signal?.aborted){await _();const e=`${je}\n`,t=`${Me}\n`;if(C.startsWith(e)&&C.endsWith(t)){let t=C.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=Ae(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(x.captureDenies)try{const e=await _e(T);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()}};T.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.`),j(!1)}),n))})),T.on("close",(async()=>{await j(!0)}));const M=T.stdio[3],D=T.stdio[4];g||(M?.write(this.state),M?.end(),D?.on("data",(e=>{C+=e.toString()}))),yield*a}catch(e){o.error=e,o.hasError=!0}finally{st(o)}}}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});class dt{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new dt((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const 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{ut(n)}}}var ht=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 pt(){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 ft{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new ft(e??this.cwd,this.state)}async*execute(e,t,r){const 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,...Ie,...r?.env},u=nt(c)?it(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=pt(),S="win32"===process.platform,k=r?.sandboxWorkspaceRoot??a,E=(await Ye(k,r?.sandboxPolicy)).policy,x=Re(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=Le({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}=Ae(e);this.state=r,this.cwd=t.trim(),await(0,d.rm)(g).catch((()=>{}))}catch(e){}await(0,d.rm)(y).catch((()=>{}))};let T=null,I=null,R=!1;const A=async e=>{if(!R){if(R=!0,I&&(clearTimeout(I),I=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:T,data:"",aborted:r?.signal?.aborted??!1}),await _(),l.close()}catch(e){l.close()}}};x.on("exit",((e,t)=>{T=e;const n=r?.closeTimeout??5e3;n>0&&(I=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{ht(o)}}}var mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var i=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(i).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class gt{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new gt(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,...Ie,...r?.env},l=nt(a)?it(t):t,c=r?.workingDirectory??this.cwd,u=r?.sandboxWorkspaceRoot??c,d=(await Ye(u,r?.sandboxPolicy)).policy,h="insecure_none"!==d.type?{...d,sandboxWorkspaceRoot:u}:d,m=Re(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=Le({stdout:m.stdout,stderr:m.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});m.on("error",(e=>{i.throw(e)})),m.on("exit",(async e=>{if((0,p.HF)(o.ctx,"exit"),await g.flush(),h.captureDenies)try{const e=await _e(m);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:e,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}})),yield*i}catch(e){n.error=e,n.hasError=!0}finally{mt(n)}}}function vt(e){const t="win32"===process.platform,r=e?.shell??(t?pt():void 0),n=process.cwd();return new gt(n,{...e,shell:r})}const yt="__CURSOR_ZSH_STATE_START__",wt="__CURSOR_ZSH_STATE_END__";var bt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 St(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class kt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new kt(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,...Ie,...r?.env};let c='builtin eval "$1"';i||(c+=" < /dev/null");const u=["-c",`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; ${ot(l)}${c}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],d=r?.sandboxWorkspaceRoot??a,h=(await Ye(d,r?.sandboxPolicy)).policy,m="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:d}:h,g=Re(St(),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=Le({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=`${yt}\n`,t=`${wt}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=Ae(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(m.captureDenies)try{const e=await _e(g);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:w,data:"",aborted:r?.signal?.aborted??!1}),s.close()}catch(e){s.close()}}};g.on("exit",((e,t)=>{w=e;const n=r?.closeTimeout??5e3;n>0&&(b=setTimeout((()=>{S||(console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Killing detached process group.`),function(e,t){if(e)try{process.kill(-e,t)}catch{return}}(g.pid,"SIGKILL"),k(!1))}),n))})),g.on("close",(async()=>{await k(!0)}));const E=g.stdio[3],x=g.stdio[4];E?.write(this.state),E?.end(),x?.on("data",(e=>{v+=e.toString()})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{bt(n)}}}const Et="__CURSOR_ZSH_STATE_LIGHT_VALID__",xt='#!/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 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});function _t(){const e=process.env.SHELL;return e?.includes("zsh")?e:u("zsh",[]).cmd}class Pt{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Pt(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,...Ie,...r?.env};let c='builtin eval "$1"';i||(c+=" < /dev/null");const u=ot(l),d=["-c",`snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; ${xt} 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 Ye(h,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,v=Re(_t(),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=Le({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=`${Et}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=Ae(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await _e(v);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:b,data:"",aborted:r?.signal?.aborted??!1}),s.close()}catch(e){s.close()}}};v.on("exit",((e,t)=>{b=e;const n=r?.closeTimeout??5e3;n>0&&(S=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),E(!1)}),n))})),v.on("close",(async()=>{await E(!0)}));const x=v.stdio[3],C=v.stdio[4];x?.write(this.state),x?.end(),C?.on("data",(e=>{y+=e.toString()})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Ct(n)}}}var Tt,It,Rt=r("node:perf_hooks");!function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}(Tt||(Tt={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(It||(It={}));const At={eventLoopDelayP95Ms:0,eventLoopUtilization:0};let Ot,jt=0;class Mt{eventLoopMonitor;sampleTimer;lastEventLoopUtilization=Rt.performance.eventLoopUtilization();latestSnapshot=At;constructor(){this.eventLoopMonitor=(0,Rt.monitorEventLoopDelay)({resolution:It.EventLoopResolutionMs}),this.lastEventLoopUtilization=Rt.performance.eventLoopUtilization(),this.eventLoopMonitor.enable(),this.sample(),this.sampleTimer=setInterval((()=>{this.sample()}),It.SampleIntervalMs),this.sampleTimer.unref?.()}dispose(){void 0!==this.sampleTimer&&(clearInterval(this.sampleTimer),this.sampleTimer=void 0,this.eventLoopMonitor.disable(),this.latestSnapshot=At,this.lastEventLoopUtilization=Rt.performance.eventLoopUtilization())}isUnderPressure(){return this.latestSnapshot.eventLoopDelayP95Ms>=Tt.EventLoopDelayP95Ms||this.latestSnapshot.eventLoopUtilization>=Tt.EventLoopUtilization}formatSuppressionSection(){const e=this.latestSnapshot,t=[`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms (threshold ${Tt.EventLoopDelayP95Ms}ms)`,`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% (threshold ${(100*Tt.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>=Tt.EventLoopDelayP95Ms&&t.push(`event loop delay p95 ${e.eventLoopDelayP95Ms.toFixed(1)}ms >= ${Tt.EventLoopDelayP95Ms}ms`),e.eventLoopUtilization>=Tt.EventLoopUtilization&&t.push(`event loop utilization ${(100*e.eventLoopUtilization).toFixed(1)}% >= ${(100*Tt.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-It.EventLoopResolutionMs)}computeEventLoopUtilization(){const e=Rt.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 Dt=6e4,Nt=65536,$t=2097152,Lt=262144,Ft=1e3,Ut="\n[This shell is producing too much output to stream. The command will still run.]\n";class Bt{bucketChars;bucketStarts;totalChars=0;outputSuppressed=!1;noticeSent=!1;windowMs;minimumThresholdCharsPerSecond;thresholdCharsPerSecondWithoutPressure;minChars;eventLoopPressureTracker;disposed=!1;constructor(e){this.windowMs=e?.windowMs??Dt,this.minimumThresholdCharsPerSecond=e?.minimumThresholdCharsPerSecond??Nt,this.thresholdCharsPerSecondWithoutPressure=e?.thresholdCharsPerSecondWithoutPressure??$t,this.minChars=e?.minChars??Lt;const t=Math.ceil(this.windowMs/Ft)+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===Ot&&(Ot=new Mt);const e=Ot;let t=!1;return{isUnderPressure:()=>e.isUnderPressure(),formatSuppressionSection:()=>e.formatSuppressionSection(),dispose:()=>{t||(t=!0,jt--,0===jt&&void 0!==Ot&&(Ot.dispose(),Ot=void 0))}}}()),this.eventLoopPressureTracker}recordChars(e,t){if(this.prune(t),e<=0)return;const r=Math.floor(t/Ft)*Ft,n=Math.floor(r/Ft)%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(Ft,Math.min(this.windowMs,e-r+Ft));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)}}const zt=new Set(["cat","grep"]);function Wt(e){return zt.has(e)}var Ht=r("../utils/dist/path-utils.js");function qt(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 Gt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:qt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}async function Vt(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=Gt(n);return t&&(i=Jt(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 Jt(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ht.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ht.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ht.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}function Kt(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 Zt(e){switch(e){case Te.Zsh:case Te.ZshLight:return u("zsh",[]).cmd;case Te.Bash:return u("bash",[]).cmd;case Te.PowerShell:return pt();default:return process.env.SHELL||"/bin/sh"}}function Yt(e){try{return u(e,[]).cmd!==e}catch(e){return!1}}function Xt(){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 Qt(e){if(e===Te.ZshLight)return Te.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?Xt():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")?Te.Zsh:t.includes("bash")&&i?Te.Bash:t.includes("pwsh")||t.includes("powershell")?Te.PowerShell:n?Te.Bash:r&&(Yt("pwsh")||Yt("powershell"))?Te.PowerShell:Yt("zsh")?Te.Zsh:Yt("bash")&&i?Te.Bash:Yt("pwsh")||Yt("powershell")?Te.PowerShell:Te.Naive}function er(e){let t=e;if(!e?.userTerminalHint){const r=Xt();r&&(t={...e,userTerminalHint:r})}switch(Qt(t?.userTerminalHint??"")){case Te.Zsh:return new dt((()=>async function(e){const t={...process.env,...Ie,...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=Re(St(),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=Oe(i,r),a=`${yt}\n`,l=`${wt}\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}=Ae(c);return new kt(u,d)}(t)));case Te.Bash:return new dt((()=>async function(e){const t={...process.env,...Ie,...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=at(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const i=Re(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=Oe(s,r),l=`${je}\n`,c=`${Me}\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}=Ae(u),p="win32"===process.platform,f="win32"===process.platform?process.cwd():d;return new ct(f,h,e?.userTerminalHint,p)}(t)));case Te.PowerShell:return new dt((()=>async function(){return new ft(process.cwd(),"")}()));case Te.ZshLight:return new dt((()=>async function(e){const t={...process.env,...Ie,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`${xt} builtin printf '${r}\\n'; dump_zsh_state_light`],o=Re(_t(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let i="";o.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const s=Oe(i,r),a=`${Et}\n`,l=s.startsWith(a)?s.slice(a.length):s,{cwd:c,rest:u}=Ae(l);return new Pt(c,u)}(t)));default:return vt(t)}}process.platform;const tr={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){r.d(t,{q:()=>he});var n,o,i,s,a,l,c,u,d,h,p,f,m,g,v,y,w,b,S,k,E,x,C,_,P,T,I,R,A,O,j,M,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,T,"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),T.set(this,void 0),I.set(this,void 0),R.set(this,void 0),A.set(this,void 0),O.set(this,void 0),M.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,I,!!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",j).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,T=new WeakMap,I=new WeakMap,R=new WeakMap,A=new WeakMap,O=new WeakMap,M=new WeakMap,D=new WeakMap,N=new WeakMap,$=new WeakMap,F=new WeakMap,U=new WeakMap,B=new WeakMap,s=new WeakSet,j=function(){const e=new ue(te(this,a,"f")),t=new ue(te(this,a,"f"));ee(this,T,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,M,(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,T,"f")&&te(this,P,"f")){const e=te(this,T,"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,T,"f")&&te(this,P,"f")){i.ttl=te(this,T,"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:M=this.sizeCalculation,status:$}=r;let{noUpdateTTL:L=this.noUpdateTTL}=r;const z=te(this,B,"f").call(this,e,t,r.size||0,M);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,I,"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,I,"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,T,"f")||te(this,s,"m",j).call(this),te(this,T,"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,M,"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,M,"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,M,"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,I,"f")||te(this,A,"f"))&&(te(this,I,"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,I,"f")||te(this,A,"f"))&&(te(this,I,"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,I,"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,T,"f")&&te(this,P,"f")&&(te(this,T,"f").fill(0),te(this,P,"f").fill(0)),te(this,_,"f")&&te(this,_,"f").fill(0),ee(this,k,0,"f"),ee(this,E,0,"f"),te(this,x,"f").length=0,ee(this,g,0,"f"),ee(this,m,0,"f"),te(this,A,"f")&&te(this,C,"f")){const e=te(this,C,"f");let t;for(;t=null==e?void 0:e.shift();)null===(n=te(this,d,"f"))||void 0===n||n.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){r.d(t,{DN:()=>l,PS:()=>h,ZU:()=>c,fl:()=>p,o1:()=>a,oL:()=>d,yn:()=>s});var n=r("node:fs/promises"),o=r("node:os"),i=r("node:path");function s(e,t){return void 0!==e&&("win32"===process.platform?(0,i.normalize)(e).toLowerCase()===(0,i.normalize)(t).toLowerCase():e===t)}function a(e,t){const r=function(e){return e.replace(/^~(?=$|\/|\\)/,(0,o.homedir)())}(e);return t&&!(0,i.isAbsolute)(r)?(0,i.resolve)(t,r):(0,i.resolve)(r)}function l(e,t){return r=this,o=void 0,l=function*(){const r=a(e,t);let o=r;for(;;)try{const e=yield(0,n.realpath)(o);return(0,i.resolve)(e,(0,i.relative)(o,r))}catch(e){if("ENOENT"!==e.code)return null;const t=(0,i.dirname)(o);if(t===o)return r;o=t}},new((s=void 0)||(s=Promise))((function(e,t){function n(e){try{a(l.next(e))}catch(e){t(e)}}function i(e){try{a(l.throw(e))}catch(e){t(e)}}function a(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(n,i)}a((l=l.apply(r,o||[])).next())}));var r,o,s,l}function c({basePath:e,targetPath:t}){const r=(0,i.resolve)(e),n=(0,i.resolve)(e,t);return r===(0,i.parse)(r).root?(0,i.parse)(n).root===r&&(n===r||n.length>r.length):n===r||n.startsWith(r+i.sep)}function u(e,t){for(const r of t)if(c({basePath:r,targetPath:e}))return!0;return!1}function d(e){return e.replace(/\\/g,"/")}const h="You cannot search other worktrees for this repository, stay within your workspace paths.";function p(e){const{targetPath:t,workspacePaths:r,mainWorktreePath:n}=e;if(void 0===t)return!1;if(0===r.length)return!1;if(!r.every((e=>function(e){return d(e).includes(".cursor/worktrees")}(e))))return!1;if(u(t,r))return!1;const o=(0,i.isAbsolute)(t)?[(0,i.resolve)(t)]:r.map((e=>(0,i.resolve)(e,t))),s=r.map((e=>function(e){var t;const r=d(e),n=r.indexOf("/.cursor/worktrees/");if(-1===n)return;const o=r.slice(n+19).split("/");if(o.length<2)return;const i=null!==(t=o[0])&&void 0!==t?t:"";return 0!==i.length?r.slice(0,n+19+i.length):void 0}(e))).filter((e=>void 0!==e));return!!(s.length>0&&o.some((e=>u(e,s))))||!(void 0===n||!o.some((e=>u(e,[n]))))}},"../utils/dist/writable-iterable.js"(e,t,r){r.d(t,{F8:()=>i,Jt:()=>s,W2:()=>o});var n=function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))};class o extends Error{constructor(e){super(e),this.name="WriteIterableClosedError"}}class i{constructor(e,t){this.writable=e,this.map=t,this.closed=!1}write(e){return n(this,void 0,void 0,(function*(){if(this.closed)throw new o("WritableIterable is closed");const t=this.map(e);yield this.writable.write(t)}))}close(){this.closed||(this.closed=!0)}}function s(){const e=[],t=[];let r,i=!1,s=()=>{},a=()=>{};const l=()=>{const e=new Promise(((e,t)=>{s=e,a=t}));return e.catch((()=>{})),e};let c=l();function u(t,r){for(;e.length>0;){const n=e.shift();r?n.reject(r):n.resolve(t)}}function d(e){t.length=0,a(e),c=Promise.reject(e),c.catch((()=>{}))}return{write(s){return n(this,void 0,void 0,(function*(){if(i)throw null!=r?r:new o("WritableIterable is closed");const n=e.shift();if(n){if(n.resolve({done:!1,value:s}),e.length>0)return}else t.push(s);const a=t.length+1;for(let e=0;e<a;e++)yield c}))},throw(e){i||(i=!0,r=e,d(e),u({done:!0,value:void 0},e))},close(){i||(i=!0,t.length=0,s(),c=Promise.reject(new o("WritableIterable is closed")),c.catch((()=>{})),u({done:!0,value:void 0}))},[Symbol.asyncIterator]:()=>({next(){s(),c=l();const n=t.shift();return void 0!==n?Promise.resolve({done:!1,value:n}):i?r?Promise.reject(r):Promise.resolve({done:!0,value:void 0}):new Promise(((t,r)=>{e.push({resolve:t,reject:r})}))},throw:e=>(i=!0,r=e,t.length=0,d(e),u({done:!0,value:void 0},e),Promise.resolve({done:!0,value:void 0})),return:()=>(i=!0,t.length=0,s(),c=Promise.reject(new Error("Iterator was closed")),c.catch((()=>{})),u({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))})}}}};