bb-app 0.0.1-alpha.2 → 0.0.1-alpha.3

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 (80) hide show
  1. package/README.md +19 -12
  2. package/app/dist/assets/{angular-html-DClx6Hnj.js → angular-html-B66mJRBQ.js} +1 -1
  3. package/app/dist/assets/{angular-ts-CUKRwFOm.js → angular-ts-Db7jGnqJ.js} +1 -1
  4. package/app/dist/assets/{apl-B7MowzF1.js → apl-DMgeEg7r.js} +1 -1
  5. package/app/dist/assets/{astro-kQqKtr82.js → astro-i1F4D3VM.js} +1 -1
  6. package/app/dist/assets/{blade-CZEQ7tr7.js → blade-CiWt8USs.js} +1 -1
  7. package/app/dist/assets/{c-Cg180MhC.js → c-BHq08H9G.js} +1 -1
  8. package/app/dist/assets/{cobol-DTf96kYw.js → cobol-D_JmDLld.js} +1 -1
  9. package/app/dist/assets/{coffee-DJB_eRir.js → coffee-umIHDekw.js} +1 -1
  10. package/app/dist/assets/{cpp-C3Al1j95.js → cpp-D94npP6r.js} +1 -1
  11. package/app/dist/assets/{crystal-BCXunLWO.js → crystal-8YBmtXaf.js} +1 -1
  12. package/app/dist/assets/{css-DbsJv0Bu.js → css-BFM8U_dh.js} +1 -1
  13. package/app/dist/assets/{edge-CDXvE_z_.js → edge-DZng818P.js} +1 -1
  14. package/app/dist/assets/{elixir-CAqAh8f8.js → elixir-oG24WxNL.js} +1 -1
  15. package/app/dist/assets/{elm-DYNYI3a5.js → elm-BQn9SMXX.js} +1 -1
  16. package/app/dist/assets/{erb-KrO8ur1w.js → erb-Cq0klEZI.js} +1 -1
  17. package/app/dist/assets/{git-rebase-D1si-UnU.js → git-rebase-DR5b4anZ.js} +1 -1
  18. package/app/dist/assets/{glimmer-js-Cgu1QvMU.js → glimmer-js-BDd0xnyC.js} +1 -1
  19. package/app/dist/assets/{glimmer-ts-BSMQWRJ8.js → glimmer-ts-CWNbj8-E.js} +1 -1
  20. package/app/dist/assets/{glsl-D03y45UT.js → glsl-B2PbL7Xo.js} +1 -1
  21. package/app/dist/assets/{graphql-dFRK1xTI.js → graphql-B7GBakJc.js} +1 -1
  22. package/app/dist/assets/{hack-CF9sLUCE.js → hack-DOVnHknU.js} +1 -1
  23. package/app/dist/assets/{haml-BRHtglN7.js → haml-Bb8YVHgL.js} +1 -1
  24. package/app/dist/assets/{handlebars-CkgQvZOQ.js → handlebars-D0mwNWC9.js} +1 -1
  25. package/app/dist/assets/{html-DMuvKP38.js → html-5tM-GssK.js} +1 -1
  26. package/app/dist/assets/{html-derivative-ci8SRFSR.js → html-derivative-Cn9-LWpS.js} +1 -1
  27. package/app/dist/assets/{http-Btn-RJv_.js → http-DSc9SnjM.js} +1 -1
  28. package/app/dist/assets/{hurl-CrXWYN81.js → hurl-C6ZqBePl.js} +1 -1
  29. package/app/dist/assets/{index-DOa6Yy5e.js → index-M3g3Gg6J.js} +114 -113
  30. package/app/dist/assets/{java-W2AvQV6W.js → java-DVVviYm-.js} +1 -1
  31. package/app/dist/assets/{javascript-DnaGKFzQ.js → javascript-DdCIxHkN.js} +1 -1
  32. package/app/dist/assets/{jinja-BXZN0Ggb.js → jinja-DHPhjOzH.js} +1 -1
  33. package/app/dist/assets/{jison-CGysTQta.js → jison-By1Hu-Dz.js} +1 -1
  34. package/app/dist/assets/{json-Lcm-9SoS.js → json-CrdbxEK1.js} +1 -1
  35. package/app/dist/assets/{jsx-BhweTQ4-.js → jsx-BrcNxjjW.js} +1 -1
  36. package/app/dist/assets/{julia-tOQdXZGN.js → julia-DmT_hZuo.js} +1 -1
  37. package/app/dist/assets/{just-BybfKTud.js → just-zec1wO4o.js} +1 -1
  38. package/app/dist/assets/{latex-BTktLAHm.js → latex-DEL8AM-S.js} +1 -1
  39. package/app/dist/assets/{liquid-DS3BL2AV.js → liquid-CakfIUn9.js} +1 -1
  40. package/app/dist/assets/{lua-BQJykTls.js → lua-CuS4yijJ.js} +1 -1
  41. package/app/dist/assets/{marko-C0Pm5GOY.js → marko-BkQRYrVE.js} +1 -1
  42. package/app/dist/assets/{mdc-egpUIawL.js → mdc-CPdw2KJD.js} +1 -1
  43. package/app/dist/assets/{nginx-B-t-4wGD.js → nginx-CuAYQPPK.js} +1 -1
  44. package/app/dist/assets/{nim-bNYDi-6w.js → nim-D1z45KKR.js} +1 -1
  45. package/app/dist/assets/{perl-Usm20V_J.js → perl-B8x_3S10.js} +1 -1
  46. package/app/dist/assets/{php-D-RCwU7T.js → php-D6nsPaWE.js} +1 -1
  47. package/app/dist/assets/{pug-D2COKgXR.js → pug-Dw4uD-ga.js} +1 -1
  48. package/app/dist/assets/{qml-InbhWeHr.js → qml-ChhLw5P-.js} +1 -1
  49. package/app/dist/assets/{r-BZWn2CKh.js → r-D06WP9cb.js} +1 -1
  50. package/app/dist/assets/{razor-D0FQf5mc.js → razor-D5asdsXb.js} +1 -1
  51. package/app/dist/assets/{regexp-BUOlAQRT.js → regexp-r_PMV4rl.js} +1 -1
  52. package/app/dist/assets/{rst-Bt7yusps.js → rst-CzgcFWde.js} +1 -1
  53. package/app/dist/assets/{ruby-efHfUKUm.js → ruby-Tab10fjZ.js} +1 -1
  54. package/app/dist/assets/{sas-ajwKIvw5.js → sas-BnhJR4wu.js} +1 -1
  55. package/app/dist/assets/{scss-Di2DthwS.js → scss-BBmEnVnb.js} +1 -1
  56. package/app/dist/assets/{shellscript-Bx-PMe9C.js → shellscript-X9fEW9dZ.js} +1 -1
  57. package/app/dist/assets/{shellsession-DjGfaagt.js → shellsession-B9vaRCQF.js} +1 -1
  58. package/app/dist/assets/{soy-D-tQALBO.js → soy-CvIAn83B.js} +1 -1
  59. package/app/dist/assets/{sql-B84C0Irl.js → sql-B6ER5sIr.js} +1 -1
  60. package/app/dist/assets/{stata-BgVwk2Ek.js → stata-DjmIaxGQ.js} +1 -1
  61. package/app/dist/assets/{surrealql-PemmT4Gt.js → surrealql-DCN0BLbL.js} +1 -1
  62. package/app/dist/assets/{svelte-ZX6XP5QA.js → svelte-GOEpr8Ie.js} +1 -1
  63. package/app/dist/assets/{templ-CW8mGVda.js → templ-JztkjpQy.js} +1 -1
  64. package/app/dist/assets/{tex-muNTdjS3.js → tex-CWi57Gg0.js} +1 -1
  65. package/app/dist/assets/{ts-tags-DVLAyxCb.js → ts-tags-wyKOPTXK.js} +1 -1
  66. package/app/dist/assets/{tsx-DZAo0jhh.js → tsx-DBYRxMLM.js} +1 -1
  67. package/app/dist/assets/{twig-BFWuL7fj.js → twig-BFpPa9u6.js} +1 -1
  68. package/app/dist/assets/{typescript-CHgdx0m4.js → typescript-LnuLHd3v.js} +1 -1
  69. package/app/dist/assets/{vue-7sUk4JNj.js → vue-CfS6pKCD.js} +1 -1
  70. package/app/dist/assets/{vue-html-DRCYO1X7.js → vue-html-CPERjiBI.js} +1 -1
  71. package/app/dist/assets/{vue-vine-C7DDCuDM.js → vue-vine-uBWCpWZh.js} +1 -1
  72. package/app/dist/assets/{xml-NijZAt93.js → xml-BbGNa1vt.js} +1 -1
  73. package/app/dist/assets/{xsl-BeN4kJ7C.js → xsl-CaMpt9fu.js} +1 -1
  74. package/app/dist/assets/{yaml-Cqf9nNxQ.js → yaml-CbWnKJNt.js} +1 -1
  75. package/app/dist/index.html +1 -1
  76. package/host-daemon/dist/bb +29 -28
  77. package/host-daemon/dist/bb-claude-code-bridge.mjs +1 -1
  78. package/host-daemon/dist/daemon-bundle.mjs +248 -248
  79. package/package.json +1 -1
  80. package/server/dist/index.js +47 -3
@@ -135,6 +135,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
135
135
  `+" ".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
136
136
  `+" ".repeat(t))}},rT;(function(e){e.DEFAULT={allowTrailingComma:!1}})(rT||(rT={}));var nT;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(nT||(nT={}));var iT;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(iT||(iT={}));var oT;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(oT||(oT={}));function HH(e){return e.startsWith("\uFEFF")?e.slice(1):e}var Sn=k1.homedir(),NS=k1.tmpdir(),{env:Qi}=qy,KH=e=>{let t=st.join(Sn,"Library");return{data:st.join(t,"Application Support",e),config:st.join(t,"Preferences",e),cache:st.join(t,"Caches",e),log:st.join(t,"Logs",e),temp:st.join(NS,e)}},YH=e=>{let t=Qi.APPDATA||st.join(Sn,"AppData","Roaming"),n=Qi.LOCALAPPDATA||st.join(Sn,"AppData","Local");return{data:st.join(n,e,"Data"),config:st.join(t,e,"Config"),cache:st.join(n,e,"Cache"),log:st.join(n,e,"Log"),temp:st.join(NS,e)}},XH=e=>{let t=st.basename(Sn);return{data:st.join(Qi.XDG_DATA_HOME||st.join(Sn,".local","share"),e),config:st.join(Qi.XDG_CONFIG_HOME||st.join(Sn,".config"),e),cache:st.join(Qi.XDG_CACHE_HOME||st.join(Sn,".cache"),e),log:st.join(Qi.XDG_STATE_HOME||st.join(Sn,".local","state"),e),temp:st.join(NS,t,e)}};function JH(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),qy.platform==="darwin"?KH(e):qy.platform==="win32"?YH(e):XH(e)}var Qte=JH("claude-cli");function QH(){return process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC?"essential-traffic":process.env.DISABLE_TELEMETRY||Bt(process.env.DO_NOT_TRACK)?"no-telemetry":"default"}function eK(){return QH()==="essential-traffic"}var tK=100,qv=[];function rK(e){qv.length>=tK&&qv.shift(),qv.push(e)}var nK=[],aT=null,ere=Pt(()=>process.argv.includes("--hard-fail"));function od(e){let t=wd(e);try{if(Bt(process.env.CLAUDE_CODE_USE_BEDROCK)||Bt(process.env.CLAUDE_CODE_USE_VERTEX)||Bt(process.env.CLAUDE_CODE_USE_FOUNDRY)||Bt(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||Bt(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||eK())return;let n={error:t.stack||t.message,timestamp:new Date().toISOString()};if(rK(n),aT===null){nK.push({type:"error",error:t});return}aT.logError(t)}catch{}}var Bi=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,x1=new Set,Fy=typeof process=="object"&&process?process:{},I1=(e,t,n,i)=>{typeof Fy.emitWarning=="function"?Fy.emitWarning(e,t,n,i):console.error(`[${n}] ${t}: ${e}`)},ad=globalThis.AbortController,sT=globalThis.AbortSignal;if(typeof ad>"u"){sT=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},ad=class{constructor(){t()}signal=new sT;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let e=Fy.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,I1("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))}}var iK=e=>!x1.has(e);var yn=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),T1=e=>yn(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?no:null:null,no=class extends Array{constructor(t){super(t),this.fill(0)}},Vy=class e{heap;length;static#l=!1;static create(t){let n=T1(t);if(!n)return[];e.#l=!0;let i=new e(t,n);return e.#l=!1,i}constructor(t,n){if(!e.#l)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Gy=class e{#l;#d;#h;#g;#j;#z;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#v;#n;#r;#e;#u;#p;#s;#o;#y;#a;#b;#_;#f;#S;#T;#c;static unsafeExposeInternals(t){return{starts:t.#_,ttls:t.#f,sizes:t.#b,keyMap:t.#n,keyList:t.#r,valList:t.#e,next:t.#u,prev:t.#p,get head(){return t.#s},get tail(){return t.#o},free:t.#y,isBackgroundFetch:n=>t.#t(n),backgroundFetch:(n,i,r,o)=>t.#U(n,i,r,o),moveToTail:n=>t.#O(n),indexes:n=>t.#w(n),rindexes:n=>t.#k(n),isStale:n=>t.#m(n)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#v}get size(){return this.#i}get fetchMethod(){return this.#j}get memoMethod(){return this.#z}get dispose(){return this.#h}get disposeAfter(){return this.#g}constructor(t){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:a,updateAgeOnHas:s,allowStale:l,dispose:c,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:h,maxSize:m=0,maxEntrySize:_=0,sizeCalculation:S,fetchMethod:w,memoMethod:g,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:k,ignoreFetchAbort:x}=t;if(n!==0&&!yn(n))throw TypeError("max option must be a nonnegative integer");let T=n?T1(n):Array;if(!T)throw Error("invalid max value: "+n);if(this.#l=n,this.#d=m,this.maxEntrySize=_||this.#d,this.sizeCalculation=S,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(g!==void 0&&typeof g!="function")throw TypeError("memoMethod must be a function if defined");if(this.#z=g,w!==void 0&&typeof w!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#j=w,this.#T=!!w,this.#n=new Map,this.#r=Array(n).fill(void 0),this.#e=Array(n).fill(void 0),this.#u=new T(n),this.#p=new T(n),this.#s=0,this.#o=0,this.#y=Vy.create(n),this.#i=0,this.#v=0,typeof c=="function"&&(this.#h=c),typeof d=="function"?(this.#g=d,this.#a=[]):(this.#g=void 0,this.#a=void 0),this.#S=!!this.#h,this.#c=!!this.#g,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!h,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!x,this.maxEntrySize!==0){if(this.#d!==0&&!yn(this.#d))throw TypeError("maxSize must be a positive integer if specified");if(!yn(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#Z()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!s,this.ttlResolution=yn(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!yn(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#R()}if(this.#l===0&&this.ttl===0&&this.#d===0)throw TypeError("At least one of max, maxSize, or ttl is required");!this.ttlAutopurge&&!this.#l&&!this.#d&&iK("LRU_CACHE_UNBOUNDED")&&(x1.add("LRU_CACHE_UNBOUNDED"),I1("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",e))}getRemainingTTL(t){return this.#n.has(t)?1/0:0}#R(){let t=new no(this.#l),n=new no(this.#l);this.#f=t,this.#_=n,this.#A=(o,a,s=Bi.now())=>{if(n[o]=a!==0?s:0,t[o]=a,a!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#m(o)&&this.#x(this.#r[o],"expire")},a+1);l.unref&&l.unref()}},this.#P=o=>{n[o]=t[o]!==0?Bi.now():0},this.#I=(o,a)=>{if(t[a]){let s=t[a],l=n[a];if(!s||!l)return;o.ttl=s,o.start=l,o.now=i||r();let c=o.now-l;o.remainingTTL=s-c}};let i=0,r=()=>{let o=Bi.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#n.get(o);if(a===void 0)return 0;let s=t[a],l=n[a];if(!s||!l)return 1/0;let c=(i||r())-l;return s-c},this.#m=o=>{let a=n[o],s=t[o];return!!s&&!!a&&(i||r())-a>s}}#P=()=>{};#I=()=>{};#A=()=>{};#m=()=>!1;#Z(){let t=new no(this.#l);this.#v=0,this.#b=t,this.#E=n=>{this.#v-=t[n],t[n]=0},this.#D=(n,i,r,o)=>{if(this.#t(i))return 0;if(!yn(r))if(o){if(typeof o!="function")throw TypeError("sizeCalculation must be a function");if(r=o(i,n),!yn(r))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return r},this.#C=(n,i,r)=>{if(t[n]=i,this.#d){let o=this.#d-t[n];for(;this.#v>o;)this.#N(!0)}this.#v+=t[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#v)}}#E=t=>{};#C=(t,n,i)=>{};#D=(t,n,i,r)=>{if(i||r)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#w({allowStale:t=this.allowStale}={}){if(this.#i)for(let n=this.#o;!(!this.#$(n)||((t||!this.#m(n))&&(yield n),n===this.#s));)n=this.#p[n]}*#k({allowStale:t=this.allowStale}={}){if(this.#i)for(let n=this.#s;!(!this.#$(n)||((t||!this.#m(n))&&(yield n),n===this.#o));)n=this.#u[n]}#$(t){return t!==void 0&&this.#n.get(this.#r[t])===t}*entries(){for(let t of this.#w())this.#e[t]!==void 0&&this.#r[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#r[t],this.#e[t]])}*rentries(){for(let t of this.#k())this.#e[t]!==void 0&&this.#r[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#r[t],this.#e[t]])}*keys(){for(let t of this.#w()){let n=this.#r[t];n!==void 0&&!this.#t(this.#e[t])&&(yield n)}}*rkeys(){for(let t of this.#k()){let n=this.#r[t];n!==void 0&&!this.#t(this.#e[t])&&(yield n)}}*values(){for(let t of this.#w())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#k())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,n={}){for(let i of this.#w()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&t(o,this.#r[i],this))return this.get(this.#r[i],n)}}forEach(t,n=this){for(let i of this.#w()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&t.call(n,o,this.#r[i],this)}}rforEach(t,n=this){for(let i of this.#k()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&t.call(n,o,this.#r[i],this)}}purgeStale(){let t=!1;for(let n of this.#k({allowStale:!0}))this.#m(n)&&(this.#x(this.#r[n],"expire"),t=!0);return t}info(t){let n=this.#n.get(t);if(n===void 0)return;let i=this.#e[n],r=this.#t(i)?i.__staleWhileFetching:i;if(r===void 0)return;let o={value:r};if(this.#f&&this.#_){let a=this.#f[n],s=this.#_[n];if(a&&s){let l=a-(Bi.now()-s);o.ttl=l,o.start=Date.now()}}return this.#b&&(o.size=this.#b[n]),o}dump(){let t=[];for(let n of this.#w({allowStale:!0})){let i=this.#r[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let a={value:o};if(this.#f&&this.#_){a.ttl=this.#f[n];let s=Bi.now()-this.#_[n];a.start=Math.floor(Date.now()-s)}this.#b&&(a.size=this.#b[n]),t.unshift([i,a])}return t}load(t){this.clear();for(let[n,i]of t){if(i.start){let r=Date.now()-i.start;i.start=Bi.now()-r}this.set(n,i.value,i)}}set(t,n,i={}){if(n===void 0)return this.delete(t),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:l}=i,{noUpdateTTL:c=this.noUpdateTTL}=i,d=this.#D(t,n,i.size||0,s);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#x(t,"set"),this;let f=this.#i===0?void 0:this.#n.get(t);if(f===void 0)f=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#N(!1):this.#i,this.#r[f]=t,this.#e[f]=n,this.#n.set(t,f),this.#u[this.#o]=f,this.#p[f]=this.#o,this.#o=f,this.#i++,this.#C(f,d,l),l&&(l.set="add"),c=!1;else{this.#O(f);let h=this.#e[f];if(n!==h){if(this.#T&&this.#t(h)){h.__abortController.abort(Error("replaced"));let{__staleWhileFetching:m}=h;m!==void 0&&!a&&(this.#S&&this.#h?.(m,t,"set"),this.#c&&this.#a?.push([m,t,"set"]))}else a||(this.#S&&this.#h?.(h,t,"set"),this.#c&&this.#a?.push([h,t,"set"]));if(this.#E(f),this.#C(f,d,l),this.#e[f]=n,l){l.set="replace";let m=h&&this.#t(h)?h.__staleWhileFetching:h;m!==void 0&&(l.oldValue=m)}}else l&&(l.set="update")}if(r!==0&&!this.#f&&this.#R(),this.#f&&(c||this.#A(f,r,o),l&&this.#I(l,f)),!a&&this.#c&&this.#a){let h=this.#a,m;for(;m=h?.shift();)this.#g?.(...m)}return this}pop(){try{for(;this.#i;){let t=this.#e[this.#s];if(this.#N(!0),this.#t(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#c&&this.#a){let t=this.#a,n;for(;n=t?.shift();)this.#g?.(...n)}}}#N(t){let n=this.#s,i=this.#r[n],r=this.#e[n];return this.#T&&this.#t(r)?r.__abortController.abort(Error("evicted")):(this.#S||this.#c)&&(this.#S&&this.#h?.(r,i,"evict"),this.#c&&this.#a?.push([r,i,"evict"])),this.#E(n),t&&(this.#r[n]=void 0,this.#e[n]=void 0,this.#y.push(n)),this.#i===1?(this.#s=this.#o=0,this.#y.length=0):this.#s=this.#u[n],this.#n.delete(i),this.#i--,n}has(t,n={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=n,o=this.#n.get(t);if(o!==void 0){let a=this.#e[o];if(this.#t(a)&&a.__staleWhileFetching===void 0)return!1;if(this.#m(o))r&&(r.has="stale",this.#I(r,o));else return i&&this.#P(o),r&&(r.has="hit",this.#I(r,o)),!0}else r&&(r.has="miss");return!1}peek(t,n={}){let{allowStale:i=this.allowStale}=n,r=this.#n.get(t);if(r===void 0||!i&&this.#m(r))return;let o=this.#e[r];return this.#t(o)?o.__staleWhileFetching:o}#U(t,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let a=new ad,{signal:s}=i;s?.addEventListener("abort",()=>a.abort(s.reason),{signal:a.signal});let l={signal:a.signal,options:i,context:r},c=(S,w=!1)=>{let{aborted:g}=a.signal,b=i.ignoreFetchAbort&&S!==void 0;if(i.status&&(g&&!w?(i.status.fetchAborted=!0,i.status.fetchError=a.signal.reason,b&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),g&&!b&&!w)return f(a.signal.reason);let y=m;return this.#e[n]===m&&(S===void 0?y.__staleWhileFetching?this.#e[n]=y.__staleWhileFetching:this.#x(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,S,l.options))),S},d=S=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=S),f(S)),f=S=>{let{aborted:w}=a.signal,g=w&&i.allowStaleOnFetchAbort,b=g||i.allowStaleOnFetchRejection,y=b||i.noDeleteOnFetchRejection,v=m;if(this.#e[n]===m&&(!y||v.__staleWhileFetching===void 0?this.#x(t,"fetch"):g||(this.#e[n]=v.__staleWhileFetching)),b)return i.status&&v.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),v.__staleWhileFetching;if(v.__returned===v)throw S},h=(S,w)=>{let g=this.#j?.(t,o,l);g&&g instanceof Promise&&g.then(b=>S(b===void 0?void 0:b),w),a.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(S(void 0),i.allowStaleOnFetchAbort&&(S=b=>c(b,!0)))})};i.status&&(i.status.fetchDispatched=!0);let m=new Promise(h).then(c,d),_=Object.assign(m,{__abortController:a,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(t,_,{...l.options,status:void 0}),n=this.#n.get(t)):this.#e[n]=_,_}#t(t){if(!this.#T)return!1;let n=t;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof ad}async fetch(t,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:_=this.allowStaleOnFetchAbort,context:S,forceRefresh:w=!1,status:g,signal:b}=n;if(!this.#T)return g&&(g.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:g});let y={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:a,noDisposeOnSet:s,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:_,ignoreFetchAbort:m,status:g,signal:b},v=this.#n.get(t);if(v===void 0){g&&(g.fetch="miss");let k=this.#U(t,v,y,S);return k.__returned=k}else{let k=this.#e[v];if(this.#t(k)){let U=i&&k.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",U&&(g.returnedStale=!0)),U?k.__staleWhileFetching:k.__returned=k}let x=this.#m(v);if(!w&&!x)return g&&(g.fetch="hit"),this.#O(v),r&&this.#P(v),g&&this.#I(g,v),k;let T=this.#U(t,v,y,S),E=T.__staleWhileFetching!==void 0&&i;return g&&(g.fetch=x?"stale":"refresh",E&&x&&(g.returnedStale=!0)),E?T.__staleWhileFetching:T.__returned=T}}async forceFetch(t,n={}){let i=await this.fetch(t,n);if(i===void 0)throw Error("fetch() returned undefined");return i}memo(t,n={}){let i=this.#z;if(!i)throw Error("no memoMethod provided to constructor");let{context:r,forceRefresh:o,...a}=n,s=this.get(t,a);if(!o&&s!==void 0)return s;let l=i(t,s,{options:a,context:r});return this.set(t,l,a),l}get(t,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:a}=n,s=this.#n.get(t);if(s!==void 0){let l=this.#e[s],c=this.#t(l);return a&&this.#I(a,s),this.#m(s)?(a&&(a.get="stale"),c?(a&&i&&l.__staleWhileFetching!==void 0&&(a.returnedStale=!0),i?l.__staleWhileFetching:void 0):(o||this.#x(t,"expire"),a&&i&&(a.returnedStale=!0),i?l:void 0)):(a&&(a.get="hit"),c?l.__staleWhileFetching:(this.#O(s),r&&this.#P(s),l))}else a&&(a.get="miss")}#M(t,n){this.#p[n]=t,this.#u[t]=n}#O(t){t!==this.#o&&(t===this.#s?this.#s=this.#u[t]:this.#M(this.#p[t],this.#u[t]),this.#M(this.#o,t),this.#o=t)}delete(t){return this.#x(t,"delete")}#x(t,n){let i=!1;if(this.#i!==0){let r=this.#n.get(t);if(r!==void 0)if(i=!0,this.#i===1)this.#L(n);else{this.#E(r);let o=this.#e[r];if(this.#t(o)?o.__abortController.abort(Error("deleted")):(this.#S||this.#c)&&(this.#S&&this.#h?.(o,t,n),this.#c&&this.#a?.push([o,t,n])),this.#n.delete(t),this.#r[r]=void 0,this.#e[r]=void 0,r===this.#o)this.#o=this.#p[r];else if(r===this.#s)this.#s=this.#u[r];else{let a=this.#p[r];this.#u[a]=this.#u[r];let s=this.#u[r];this.#p[s]=this.#p[r]}this.#i--,this.#y.push(r)}}if(this.#c&&this.#a?.length){let r=this.#a,o;for(;o=r?.shift();)this.#g?.(...o)}return i}clear(){return this.#L("delete")}#L(t){for(let n of this.#k({allowStale:!0})){let i=this.#e[n];if(this.#t(i))i.__abortController.abort(Error("deleted"));else{let r=this.#r[n];this.#S&&this.#h?.(i,r,t),this.#c&&this.#a?.push([i,r,t])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#_&&(this.#f.fill(0),this.#_.fill(0)),this.#b&&this.#b.fill(0),this.#s=0,this.#o=0,this.#y.length=0,this.#v=0,this.#i=0,this.#c&&this.#a){let n=this.#a,i;for(;i=n?.shift();)this.#g?.(...i)}}};function oK(e,t,n=100){let i=new Gy({max:n}),r=(...o)=>{let a=t(...o),s=i.get(a);if(s!==void 0)return s;let l=e(...o);return i.set(a,l),l};return r.cache={clear:()=>i.clear(),size:()=>i.size,delete:o=>i.delete(o),get:o=>i.peek(o),has:o=>i.has(o)},r}var aK=8192;function P1(e,t){try{return{ok:!0,value:JSON.parse(HH(e))}}catch(n){return t&&od(n),{ok:!1}}}var lT=oK(P1,e=>e,50),tre=Object.assign(function(e,t=!0){if(!e)return null;let n=e.length>aK?P1(e,t):lT(e,t);return n.ok?n.value:null},{cache:lT.cache}),O1=Pt(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){try{let e=Xa().readFileSync("/proc/version",{encoding:"utf8"});if(e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl"))return"wsl"}catch(e){od(e)}return"linux"}return"unknown"}catch(e){return od(e),"unknown"}}),are=Pt(()=>{if(process.platform==="linux")try{let e=Xa().readFileSync("/proc/version",{encoding:"utf8"}),t=e.match(/WSL(\d+)/i);return t&&t[1]?t[1]:e.toLowerCase().includes("microsoft")?"1":void 0}catch(e){od(e);return}}),sre=Pt(async()=>{if(process.platform!=="linux")return;let e={linuxKernel:E1()};try{let t=await lK("/etc/os-release","utf8");for(let n of t.split(`
137
137
  `)){let i=n.match(/^(ID|VERSION_ID)=(.*)$/);if(i&&i[1]&&i[2]){let r=i[2].replace(/^"|"$/g,"");i[1]==="ID"?e.linuxDistroId=r:e.linuxDistroVersion=r}}}catch{}return e}),lre=Pt(()=>{if(process.platform!=="darwin")return;let e=E1().match(/^(\d+)\./);if(!(!e||!e[1]))return parseInt(e[1],10)-9}),uK=Pt(function(){switch(O1()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),ure=Pt(function(){return sK(uK(),"managed-settings.d")}),cK=re(()=>p.object({allowedDomains:p.array(p.string()).optional(),deniedDomains:p.array(p.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:p.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:p.array(p.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:p.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:p.boolean().optional(),allowMachLookup:p.array(p.string().refine(e=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:p.number().optional(),socksProxyPort:p.number().optional(),tlsTerminate:p.object({caCertPath:p.string().min(1).optional(),caKeyPath:p.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session.")}).optional()),dK=re(()=>p.object({allowWrite:p.array(p.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:p.array(p.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:p.array(p.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:p.array(p.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:p.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),pK=re(()=>p.object({enabled:p.boolean().optional(),failIfUnavailable:p.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:p.boolean().optional(),allowUnsandboxedCommands:p.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:cK(),filesystem:dK(),ignoreViolations:p.record(p.string(),p.array(p.string())).optional(),enableWeakerNestedSandbox:p.boolean().optional(),enableWeakerNetworkIsolation:p.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. **Reduces security** \u2014 opens a potential data exfiltration vector through the trustd service. Default: false"),excludedCommands:p.array(p.string()).optional(),ripgrep:p.object({command:p.string(),args:p.array(p.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:p.preprocess(e=>typeof e=="string"&&uT(e)?e:void 0,p.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:p.preprocess(e=>typeof e=="string"&&uT(e)?e:void 0,p.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough()),fK=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],mK=["normal","vim"],hK=["auto","tmux","in-process"],gK=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],vK=["auto",...gK],dre=O1()==="macos"?"\u23FA":"\u25CF",US=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],yK=[...US,"bubble"],bK=yK,pre=re(()=>Kz.enum(bK)),fre=re(()=>Kz.enum(US)),_K=["bash","powershell"],La=re(()=>p.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));function SK(){let e=p.object({type:p.literal("command").describe("Shell command hook type"),command:p.string().describe("Shell command to execute"),args:p.array(p.string()).optional().describe("Argument list for exec form. When present, `command` is resolved as an executable and spawned directly with these arguments \u2014 no shell. Path placeholders like ${CLAUDE_PLUGIN_ROOT} are substituted per-element as plain strings, so paths with quotes, $, or backticks never reach a shell parser. When absent, `command` runs through a shell (bash on POSIX, PowerShell on Windows without Git Bash)."),if:La(),shell:p.enum(_K).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:p.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:p.string().optional().describe("Custom status message to display in spinner while hook runs"),once:p.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:p.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:p.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:p.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:p.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),t=p.object({type:p.literal("prompt").describe("LLM prompt hook type"),prompt:p.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:La(),timeout:p.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:p.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-4-6"). If not specified, uses the default small fast model.'),continueOnBlock:p.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:p.string().optional().describe("Custom status message to display in spinner while hook runs"),once:p.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=p.object({type:p.literal("mcp_tool").describe("MCP tool hook type"),server:p.string().describe("Name of an already-configured MCP server to invoke"),tool:p.string().describe("Name of the tool on that server to call"),input:p.record(p.string(),p.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:La(),timeout:p.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:p.string().optional().describe("Custom status message to display in spinner while hook runs"),once:p.boolean().optional().describe("If true, hook runs once and is removed after execution")}),i=p.object({type:p.literal("http").describe("HTTP hook type"),url:p.string().url().describe("URL to POST the hook input JSON to"),if:La(),timeout:p.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:p.record(p.string(),p.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:p.array(p.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:p.string().optional().describe("Custom status message to display in spinner while hook runs"),once:p.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=p.object({type:p.literal("agent").describe("Agentic verifier hook type"),prompt:p.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:La(),timeout:p.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:p.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:p.string().optional().describe("Custom status message to display in spinner while hook runs"),once:p.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:i,AgentHookSchema:r,McpToolHookSchema:n}}var wK=re(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:i,McpToolHookSchema:r}=SK();return p.discriminatedUnion("type",[e,t,n,i,r])}),kK=re(()=>p.object({matcher:p.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:p.array(wK()).describe("List of hooks to execute when the matcher matches")})),sd=re(()=>p.partialRecord(p.enum(WT),p.array(kK()))),mre=re(()=>p.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),hre=re(()=>p.enum(["stdio","sse","sse-ide","http","ws","sdk"])),xK=re(()=>p.object({type:p.literal("stdio").optional(),command:p.string().min(1,"Command cannot be empty"),args:p.array(p.string()).default([]),env:p.record(p.string(),p.string()).optional(),alwaysLoad:p.boolean().optional()})),IK=re(()=>p.boolean()),j1=re(()=>p.object({clientId:p.string().optional(),callbackPort:p.number().int().positive().optional(),authServerMetadataUrl:p.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:p.string().min(1).optional(),xaa:IK().optional()})),TK=re(()=>p.object({type:p.literal("sse"),url:p.string(),headers:p.record(p.string(),p.string()).optional(),headersHelper:p.string().optional(),oauth:j1().optional(),alwaysLoad:p.boolean().optional()})),PK=re(()=>p.object({type:p.literal("sse-ide"),url:p.string(),ideName:p.string(),ideRunningInWindows:p.boolean().optional(),alwaysLoad:p.boolean().optional()})),EK=re(()=>p.object({type:p.literal("ws-ide"),url:p.string(),ideName:p.string(),authToken:p.string().optional(),ideRunningInWindows:p.boolean().optional(),alwaysLoad:p.boolean().optional()})),OK=re(()=>p.object({type:p.enum(["http","streamable-http"]).transform(()=>"http"),url:p.string(),headers:p.record(p.string(),p.string()).optional(),headersHelper:p.string().optional(),oauth:j1().optional(),alwaysLoad:p.boolean().optional()})),jK=re(()=>p.object({type:p.literal("ws"),url:p.string(),headers:p.record(p.string(),p.string()).optional(),headersHelper:p.string().optional(),alwaysLoad:p.boolean().optional()})),zK=re(()=>p.object({type:p.literal("sdk"),name:p.string(),alwaysLoad:p.boolean().optional()})),CK=re(()=>p.enum(["allow","ask","blocked"])),NK=re(()=>p.object({type:p.literal("claudeai-proxy"),url:p.string(),id:p.string(),alwaysLoad:p.boolean().optional(),toolPermissions:p.record(p.string(),CK()).optional()})),By=re(()=>p.union([xK(),TK(),PK(),EK(),OK(),jK(),zK(),NK()])),gre=re(()=>p.object({mcpServers:p.record(p.string(),By())})),z1=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins"]),UK=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,RK=/[^\u0020-\u007E]/;function AK(e){return z1.has(e.toLowerCase())?!1:RK.test(e)?!0:UK.test(e)}var Or=re(()=>p.string().startsWith("./")),ii=re(()=>Or().endsWith(".json")),cT=re(()=>p.union([Or().refine(e=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),p.string().url().refine(e=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),Hy=re(()=>Or().endsWith(".md")),Ky=re(()=>p.union([Hy(),Or()])),C1=re(()=>p.string().min(1,"Marketplace must have a name").refine(e=>!e.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine(e=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine(e=>!AK(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine(e=>e.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine(e=>e.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine(e=>e.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),RS=re(()=>p.object({name:p.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:p.string().optional().describe("Contact email for support or feedback"),url:p.string().optional().describe("Website, GitHub profile, or organization URL")})),DK=re(()=>p.object({$schema:p.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:p.string().min(1,"Plugin name cannot be empty").refine(e=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),version:p.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:p.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:RS().optional().describe("Information about the plugin creator or maintainer"),homepage:p.string().url().optional().describe("Plugin homepage or documentation URL"),repository:p.string().optional().describe("Source code repository URL"),license:p.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:p.array(p.string()).optional().describe("Tags for plugin discovery and categorization"),dependencies:p.array(aY()).optional().describe(`Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin's own marketplace.`)})),vre=re(()=>p.object({description:p.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:p.lazy(()=>sd()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),$K=re(()=>p.object({hooks:p.union([ii().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),p.lazy(()=>sd()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),p.array(p.union([ii().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),p.lazy(()=>sd()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),MK=re(()=>p.object({source:Ky().optional().describe("Path to command markdown file, relative to plugin root"),content:p.string().optional().describe("Inline markdown content for the command"),description:p.string().optional().describe("Command description override"),argumentHint:p.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:p.string().optional().describe("Default model for this command"),allowedTools:p.array(p.string()).optional().describe("Tools allowed when command runs")}).refine(e=>e.source&&!e.content||!e.source&&e.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),LK=re(()=>p.object({commands:p.union([Ky().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded \u2014 list its files here if you want both."),p.array(Ky().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of command file or skill directory paths. When set, the commands/ directory is not auto-loaded."),p.record(p.string(),MK()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" \u2192 "/plugin:about")')])})),ZK=re(()=>p.object({agents:p.union([Hy().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded \u2014 list its files here if you want both."),p.array(Hy().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of agent file paths. When set, the agents/ directory is not auto-loaded.")])})),WK=re(()=>p.object({skills:p.union([Or().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory."),p.array(Or().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory.")).describe("List of skill directory paths, loaded in addition to the skills/ directory.")])})),qK=re(()=>p.object({outputStyles:p.union([Or().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded \u2014 list its files here if you want both."),p.array(Or().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of output-style directory or file paths. When set, the output-styles/ directory is not auto-loaded.")])})),N1=re(()=>p.object({themes:p.union([Or().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded \u2014 list its files here if you want both."),p.array(Or().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of theme directory or file paths. When set, the themes/ directory is not auto-loaded.")])})),FK=re(()=>p.object({})),dT=re(()=>p.string().min(1)),VK=re(()=>p.string().min(2).refine(e=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),GK=re(()=>p.object({mcpServers:p.union([ii().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),cT().describe("Path or URL to MCPB file containing MCP server configuration"),p.record(p.string(),By()).describe("MCP server configurations keyed by server name"),p.array(p.union([ii().describe("Path to MCP servers configuration file"),cT().describe("Path or URL to MCPB file"),p.record(p.string(),By()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),U1=re(()=>p.object({type:p.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:p.string().describe("Human-readable label shown in the config dialog"),description:p.string().describe("Help text shown beneath the field in the config dialog"),required:p.boolean().optional().describe("If true, validation fails when this field is empty"),default:p.union([p.string(),p.number(),p.boolean(),p.array(p.string())]).optional().describe("Default value used when the user provides nothing"),multiple:p.boolean().optional().describe("For string type: allow an array of strings"),sensitive:p.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:p.number().optional().describe("Minimum value (number type only)"),max:p.number().optional().describe("Maximum value (number type only)")}).strict()),BK=re(()=>p.object({userConfig:p.record(p.string().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) \u2014 they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),U1()).optional().describe("User-configurable values this plugin needs. Prompted at enable time. Non-sensitive values saved to settings.json; sensitive values to secure storage. Available as ${user_config.KEY} in MCP/LSP server config, hook commands, and (non-sensitive only) skill/agent content. Keep sensitive value counts small.")})),HK=re(()=>p.object({channels:p.array(p.object({server:p.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:p.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:p.record(p.string(),U1()).optional().describe("Fields to prompt the user for when enabling this plugin in assistant mode. Saved values are substituted into ${user_config.KEY} references in the mcpServers env.")}).strict()).describe("Channels this plugin provides. Each entry declares an MCP server as a message channel and optionally specifies user configuration to prompt for at enable time.")})),pT=re(()=>p.strictObject({command:p.string().min(1).refine(e=>!(e.includes(" ")&&!e.startsWith("/")),{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:p.array(dT()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:p.record(VK(),dT()).refine(e=>Object.keys(e).length>0,{message:"extensionToLanguage must have at least one mapping"}).describe("Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping."),transport:p.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:p.record(p.string(),p.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:p.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:p.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:p.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:p.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:p.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:p.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:p.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up")})),KK=re(()=>p.strictObject({name:p.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:p.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd \u2014 prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:p.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:p.union([p.literal("always"),p.string().startsWith("on-skill-invoke:").refine(e=>e.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),YK=re(()=>p.array(KK()).refine(e=>new Set(e.map(t=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),R1=re(()=>p.object({monitors:p.union([ii().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),YK()]).describe("Background watch scripts the host arms as persistent Monitor tasks (unsandboxed, same trust tier as hooks) so plugins need not instruct the model to arm them. When omitted, monitors/monitors.json at the plugin root is loaded if present.")})),XK=re(()=>p.object({lspServers:p.union([ii().describe("Path to .lsp.json configuration file relative to plugin root"),p.record(p.string(),pT()).describe("LSP server configurations keyed by server name"),p.array(p.union([ii().describe("Path to LSP configuration file"),p.record(p.string(),pT()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),A1=re(()=>p.string().refine(e=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine(e=>{let t=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,n=/^[a-z0-9][a-z0-9-._]*$/;return t.test(e)||n.test(e)},"Invalid npm package name format")),JK=re(()=>p.object({settings:p.record(p.string(),p.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),QK=re(()=>p.object({experimental:p.preprocess(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,p.object({...N1().partial().shape,...R1().partial().shape}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),eY=re(()=>p.object({...DK().shape,...$K().partial().shape,...LK().partial().shape,...ZK().partial().shape,...WK().partial().shape,...qK().partial().shape,...N1().partial().shape,...FK().shape,...HK().partial().shape,...GK().partial().shape,...XK().partial().shape,...R1().partial().shape,...JK().partial().shape,...BK().partial().shape,...QK().partial().shape})),ld=re(()=>p.discriminatedUnion("source",[p.object({source:p.literal("url"),url:p.string().url().describe("Direct URL to marketplace.json file"),headers:p.record(p.string(),p.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),p.object({source:p.literal("github"),repo:p.string().describe("GitHub repository in owner/repo format"),ref:p.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:p.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:p.array(p.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.')}),p.object({source:p.literal("git"),url:p.string().describe("Full git repository URL"),ref:p.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:p.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:p.array(p.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.')}),p.object({source:p.literal("npm"),package:A1().describe("NPM package containing marketplace.json")}),p.object({source:p.literal("file"),path:p.string().describe("Local file path to marketplace.json")}),p.object({source:p.literal("directory"),path:p.string().describe("Local directory containing .claude-plugin/marketplace.json")}),p.object({source:p.literal("hostPattern"),hostPattern:p.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against "github.com". For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),p.object({source:p.literal("pathPattern"),pathPattern:p.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),p.object({source:p.literal("settings"),name:C1().refine(e=>!z1.has(e.toLowerCase()),{message:"Reserved official marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation as PluginMarketplaceSchema plus reserved-name rejection \u2014 validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:p.array(tY()).describe("Plugin entries declared inline in settings.json"),owner:RS().optional()}).describe("Inline marketplace manifest defined directly in settings.json. The reconciler writes a synthetic marketplace.json to the cache; diffMarketplaces detects edits via isEqual on the stored source (the plugins array is inside this object, so edits surface as sourceChanged).")])),Fv=re(()=>p.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),D1=re(()=>p.union([Or().describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),p.object({source:p.literal("npm"),package:A1().or(p.string().refine(e=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(e)||!e.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:p.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:p.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),p.object({source:p.literal("url"),url:p.string().describe("Full git repository URL (https:// or git@)"),ref:p.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Fv().optional().describe("Specific commit SHA to use")}),p.object({source:p.literal("github"),repo:p.string().describe("GitHub repository in owner/repo format"),ref:p.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Fv().optional().describe("Specific commit SHA to use")}),p.object({source:p.literal("git-subdir"),url:p.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:p.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:p.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Fv().optional().describe("Specific commit SHA to use")}).describe("Plugin located in a subdirectory of a larger repository (monorepo). Only the specified subdirectory is materialized; the rest of the repo is not downloaded."),p.object({source:p.literal("unsupported")}).describe('Placeholder for source types this Claude Code version does not recognize. Never authored by hand \u2014 PluginMarketplaceSchema rewrites unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with a clear "update Claude Code" message.')])),tY=re(()=>p.object({name:p.string().min(1,"Plugin name cannot be empty").refine(e=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:D1().describe("Where to fetch the plugin from. Must be a remote source \u2014 relative paths have no marketplace repository to resolve against."),description:p.string().optional(),version:p.string().optional(),strict:p.boolean().optional()}).refine(e=>typeof e.source!="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine(e=>typeof e.source=="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."})),rY=re(()=>eY().partial().extend({name:p.string().min(1,"Plugin name cannot be empty").refine(e=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:D1().describe("Where to fetch the plugin from"),category:p.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:p.array(p.string()).optional().describe("Tags for searchability and discovery"),strict:p.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest.")})),nY=re(()=>p.object({name:p.string().min(1).refine(e=>!e.includes(" "))}));function iY(e){let t=rY();return e.flatMap((n,i)=>{let r=t.safeParse(n);if(r.success)return[r.data];let o=nY().safeParse(n).data?.name,a=r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ");return o?(St(`Stubbing unparseable marketplace plugin entry (${o}): ${a}`,{level:"warn"}),[{name:o,source:{source:"unsupported"},strict:!0}]):(St(`Dropping unparseable marketplace plugin entry (index ${i}): ${a}`,{level:"warn"}),[])})}var yre=re(()=>p.object({$schema:p.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:C1(),version:p.string().optional().describe("Marketplace manifest version"),description:p.string().optional().describe("Human-readable description of this marketplace"),owner:RS().describe("Marketplace maintainer or curator information"),plugins:p.array(p.unknown()).transform(iY).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:p.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:p.object({pluginRoot:p.string().optional().describe("Base path for relative plugin sources"),version:p.string().optional().describe("Marketplace version"),description:p.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:p.array(p.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies \u2014 no transitive trust.")})),$1=re(()=>p.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),oY=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,aY=re(()=>p.union([p.string().regex(oY,"Dependency must be a plugin name, optionally qualified with @marketplace").transform(e=>e.replace(/@\^[^@]*$/,"")),p.object({name:p.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:p.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform(e=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),sY=re(()=>p.object({version:p.string().describe("Currently installed version"),installedAt:p.string().describe("ISO 8601 timestamp of installation"),lastUpdated:p.string().optional().describe("ISO 8601 timestamp of last update"),installPath:p.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:p.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:p.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:p.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),lY=re(()=>p.object({version:p.literal(1).describe("Schema version 1"),plugins:p.record($1(),sY()).describe("Map of plugin IDs to their installation metadata")})),uY=re(()=>p.enum(["managed","user","project","local"])),cY=re(()=>p.object({scope:uY().describe("Installation scope"),projectPath:p.string().optional().describe("Project path (required for project/local scopes)"),installPath:p.string().describe("Absolute path to the versioned plugin directory"),version:p.string().optional().describe("Currently installed version"),installedAt:p.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:p.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:p.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:p.string().optional().describe("Tag-derived semver this install resolved to"),auto:p.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),dY=re(()=>p.object({version:p.literal(2).describe("Schema version 2"),plugins:p.record($1(),p.array(cY())).describe("Map of plugin IDs to arrays of installation entries")})),bre=re(()=>p.union([lY(),dY()])),pY=re(()=>p.object({source:ld().describe("Where to fetch the marketplace from"),installLocation:p.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:p.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:p.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),_re=re(()=>p.record(p.string(),pY()));var fY="https://json.schemastore.org/claude-code-settings.json",mY=["autoMode","deepLink","voice","assistant","briefView"],Xu={},Hd={autoMode:{buildGate:()=>!1,shape:()=>Xu,permissionsShape:()=>Xu,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:p.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>Xu},assistant:{buildGate:()=>!1,shape:()=>Xu},briefView:{buildGate:()=>!0,shape:()=>({defaultView:p.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})}};function M1(){return mY.filter(e=>Hd[e].buildGate())}function hY(e){let t={};for(let n of e)t={...t,...Hd[n].shape()};return t}function gY(e){let t={};for(let n of e)t={...t,...Hd[n].permissionsShape?.()};return t}function vY(e){let t=[];for(let n of e)t.push(...Hd[n].permissionModes?.()??[]);return t}function yY(e){let t=e.split("__"),[n,i,...r]=t;if(n!=="mcp"||!i)return null;let o=r.length>0?r.join("__"):void 0;return{serverName:i,toolName:o}}var fT={Task:"Agent",KillShell:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage"};function Hi(e){return Object.hasOwn(fT,e)?fT[e]:e}var L1="workspace",Sre=`mcp__${L1}__bash`,wre=`mcp__${L1}__web_fetch`;function bY(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function _Y(e){let t=SY(e,"(");if(t===-1)return{toolName:Hi(e)};let n=wY(e,")");if(n===-1||n<=t)return{toolName:Hi(e)};if(n!==e.length-1)return{toolName:Hi(e)};let i=e.substring(0,t),r=e.substring(t+1,n);if(!i)return{toolName:Hi(e)};if(r===""||r==="*")return{toolName:Hi(i)};let o=bY(r);return{toolName:Hi(i),ruleContent:o}}function SY(e,t){for(let n=0;n<e.length;n++)if(e[n]===t){let i=0,r=n-1;for(;r>=0&&e[r]==="\\";)i++,r--;if(i%2===0)return n}return-1}function wY(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){let i=0,r=n-1;for(;r>=0&&e[r]==="\\";)i++,r--;if(i%2===0)return n}return-1}var ud={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit"],bashPrefixTools:["Bash"],customValidation:{WebSearch:e=>e.includes("*")||e.includes("?")?{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]}:{valid:!0},WebFetch:e=>e.includes("://")||e.startsWith("http")?{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]}:e.startsWith("domain:")?{valid:!0}:{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]}}};function kY(e){return ud.filePatternTools.includes(e)}function xY(e){return ud.bashPrefixTools.includes(e)}function IY(e){return Object.hasOwn(ud.customValidation,e)?ud.customValidation[e]:void 0}function Z1(e,t){let n=0,i=t-1;for(;i>=0&&e[i]==="\\";)n++,i--;return n%2!==0}function Vv(e,t){let n=0;for(let i=0;i<e.length;i++)e[i]===t&&!Z1(e,i)&&n++;return n}function TY(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"&&!Z1(e,t))return!0;return!1}function PY(e){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let t=Vv(e,"("),n=Vv(e,")");if(t!==n)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(TY(e)){let a=e.substring(0,e.indexOf("("));return a?{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}:{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"}}let i=_Y(e),r=yY(i.toolName);if(r)return i.ruleContent!==void 0||Vv(e,"(")>0?{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${i.toolName}" without parentheses, or use "mcp__${r.serverName}__*" for all tools`,examples:[`mcp__${r.serverName}`,`mcp__${r.serverName}__*`,r.toolName&&r.toolName!=="*"?`mcp__${r.serverName}__${r.toolName}`:void 0].filter(Boolean)}:{valid:!0};if(!i.toolName||i.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(!i.toolName.includes("_")&&i.toolName[0]!==i.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${fW(String(i.toolName))}"`};let o=IY(i.toolName);if(o&&i.ruleContent!==void 0){let a=o(i.ruleContent);if(!a.valid)return a}if(xY(i.toolName)&&i.ruleContent!==void 0){let a=i.ruleContent;if(a.includes(":*")&&!a.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(a===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(kY(i.toolName)&&i.ruleContent!==void 0){let a=i.ruleContent;if(a.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${i.toolName}(*.ts) - matches .ts files`,`${i.toolName}(src/**) - matches all files in src`,`${i.toolName}(**/*.test.ts) - matches test files`]};if(a.includes("*")&&!a.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!a.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${i.toolName}(*.js) - all .js files`,`${i.toolName}(src/*) - all files directly in src`,`${i.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}var Gv=re(()=>p.string().superRefine((e,t)=>{let n=PY(e);if(!n.valid){let i=n.error;n.suggestion&&(i+=`. ${n.suggestion}`),n.examples&&n.examples.length>0&&(i+=`. Examples: ${n.examples.join(", ")}`),t.addIssue({code:p.ZodIssueCode.custom,message:i,params:{received:e}})}})),EY=re(()=>p.record(p.string(),p.coerce.string()));function W1(e){return p.object({allow:p.array(Gv()).optional().describe("List of permission rules for allowed operations"),deny:p.array(Gv()).optional().describe("List of permission rules for denied operations"),ask:p.array(Gv()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:p.enum([...US,...vY(e)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:p.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...gY(e),additionalDirectories:p.array(p.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var kre=re(()=>W1(M1())),OY=re(()=>p.object({source:ld().describe("Where to fetch the marketplace from"),installLocation:p.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:p.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),jY=re(()=>p.object({serverName:p.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:p.array(p.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:p.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(e=>BP([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),zY=re(()=>p.object({serverName:p.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:p.array(p.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:p.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(e=>BP([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),CY=re(()=>p.object({path:p.string().describe("Absolute path to the helper executable"),timeoutMs:p.number().int().min(1e3).optional(),refreshIntervalMs:p.union([p.literal(0),p.number().int().min(6e4)]).optional()})),mT=["skills","agents","hooks","mcp"];function NY(e){return p.object({$schema:p.literal(fY).optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:p.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:p.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:p.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:p.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:p.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:CY().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...Bt(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:p.object({issuer:p.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:p.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:p.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:p.object({type:p.literal("command"),command:p.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:p.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:p.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:p.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:p.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:p.boolean().optional().describe("When set to true in either admin-only Windows source \u2014 the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json \u2014 WSL reads managed settings from the full Windows policy chain (HKLM, C:/Program Files/ClaudeCode via DrvFs, HKCU) in addition to /etc/claude-code. Windows sources take priority. The flag is also required in HKCU itself for HKCU policy to apply on WSL (double opt-in: admin enables the chain, user confirms HKCU). On native Windows the flag has no effect."),env:EY().optional().describe("Environment variables to set for Claude Code sessions"),attribution:p.object({commit:p.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:p.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:p.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:p.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:W1(e).optional().describe("Tool usage permissions configuration"),model:p.string().optional().describe("Override the default model used by Claude Code"),availableModels:p.array(p.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:p.record(p.string(),p.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:p.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:p.array(p.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:p.array(p.string()).optional().describe("List of rejected MCP servers from .mcp.json"),skillOverrides:p.record(p.string(),p.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),allowedMcpServers:p.array(jY()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:p.array(zY()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:sd().optional().describe("Custom commands to run before/after tool executions"),worktree:p.object({symlinkDirectories:p.array(p.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:p.array(p.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). Dramatically faster in large monorepos \u2014 only the listed paths are written to disk."),baseRef:p.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:p.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:p.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:p.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableSkillShellExecution:p.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:p.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:p.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:p.array(p.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:p.array(p.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:p.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:p.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:p.preprocess(t=>Array.isArray(t)?t.filter(n=>mT.includes(n)):t,p.union([p.boolean(),p.array(p.enum(mT))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. Composes with strictKnownMarketplaces for end-to-end admin control \u2014 plugins gated by marketplace allowlist, everything else blocked here.'),statusLine:p.object({type:p.literal("command"),command:p.string(),padding:p.number().optional(),refreshInterval:p.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:p.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:p.string().optional().describe('URL template for PR links in the footer badge and inline messages. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),subagentStatusLine:p.object({type:p.literal("command"),command:p.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:p.record(p.string(),p.union([p.array(p.string()),p.boolean(),p.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json \u2014 setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:p.record(p.string(),OY()).check(t=>{for(let[n,i]of Object.entries(t.value))i.source.source==="settings"&&i.source.name!==n&&t.issues.push({code:"custom",input:i.source.name,path:[n,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${n}" but source.name "${i.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:p.array(ld()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. Note: this is a policy gate only \u2014 it does NOT register marketplaces. To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:p.array(ld()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),forceLoginMethod:p.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),parentSettingsBehavior:p.enum(["first-wins","merge"]).optional().describe(`Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" (default): parent is dropped \u2014 admin tiers are the only policy source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:p.union([p.string(),p.array(p.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:p.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:p.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:p.string().optional().describe("Controls the output style for assistant responses"),viewMode:p.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:p.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:p.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:pK().optional(),feedbackSurveyRate:p.number().min(0).max(1).optional().describe("Probability (0\u20131) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:p.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:p.object({mode:p.enum(["append","replace"]),verbs:p.array(p.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:p.object({excludeDefault:p.boolean().optional(),tips:p.array(p.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:p.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:p.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:p.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:p.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),autoCompactWindow:p.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:p.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:p.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:p.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:p.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:p.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:p.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:p.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:p.array(p.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:p.record(p.string(),p.object({mcpServers:p.record(p.string(),p.record(p.string(),p.union([p.string(),p.number(),p.boolean(),p.array(p.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:p.record(p.string(),p.union([p.string(),p.number(),p.boolean(),p.array(p.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:p.object({defaultEnvironmentId:p.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:p.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:p.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:p.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:p.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),voice:p.object({enabled:p.boolean().optional(),mode:p.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:p.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:p.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:p.array(p.object({marketplace:p.string(),plugin:p.string()})).optional().describe("Managed-org allowlist of channel plugins. When set, replaces the default Anthropic allowlist \u2014 admins decide which plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:p.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:p.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),autoMemoryEnabled:p.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:p.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:p.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:p.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:p.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),disableAutoMode:p.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:p.array(p.object({id:p.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:p.string().describe("Display name for the SSH connection"),sshHost:p.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:p.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:p.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:p.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:p.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:p.array(p.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:p.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:p.union([p.enum(vK),p.string().startsWith("custom:").transform(t=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:p.enum(mK).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:p.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:p.enum(fK).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:p.boolean().optional().describe("Automatically compact conversation when context fills"),autoScrollEnabled:p.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),fileCheckpointingEnabled:p.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:p.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:p.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:p.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:p.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:p.enum(hK).optional().catch(void 0).describe("How spawned teammates execute (tmux, in-process, auto)"),remoteControlAtStartup:p.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:p.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:p.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:p.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:p.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:p.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...hY(e)}).passthrough()}var UY=re(()=>NY(M1()));var xre=re(()=>UY().strict());var Ire=new Set(WT);var Tre=Object.freeze({settings:{},errors:[]});function RY(e,t,n){(n!==void 0&&!yd(e[t],n)||n===void 0&&!(t in e))&&vb(e,t,n)}var Yy=RY;function AY(e){return function(t,n,i){for(var r=-1,o=Object(t),a=i(t),s=a.length;s--;){var l=a[e?s:++r];if(n(o[l],l,o)===!1)break}return t}}var DY=AY,$Y=DY(),MY=$Y;function LY(e){return Co(e)&&_b(e)}var ZY=LY,WY="[object Object]",qY=Function.prototype,FY=Object.prototype,q1=qY.toString,VY=FY.hasOwnProperty,GY=q1.call(Object);function BY(e){if(!Co(e)||xs(e)!=WY)return!1;var t=NP(e);if(t===null)return!0;var n=VY.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&q1.call(n)==GY}var HY=BY;function KY(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var Xy=KY;function YY(e){return jL(e,jP(e))}var XY=YY;function JY(e,t,n,i,r,o,a){var s=Xy(e,n),l=Xy(t,n),c=a.get(l);if(c){Yy(e,n,c);return}var d=o?o(s,l,n+"",e,t,a):void 0,f=d===void 0;if(f){var h=In(l),m=!h&&yb(l),_=!h&&!m&&EP(l);d=l,h||m||_?In(s)?d=s:ZY(s)?d=GZ(s):m?(f=!1,d=CP(l,!0)):_?(f=!1,d=e2(l,!0)):d=[]:HY(l)||os(l)?(d=s,os(s)?d=XY(s):(!Jr(s)||ob(s))&&(d=i2(l))):f=!1}f&&(a.set(l,d),r(d,l,i,o,a),a.delete(l)),Yy(e,n,d)}var QY=JY;function F1(e,t,n,i,r){e!==t&&MY(t,function(o,a){if(r||(r=new kL),Jr(o))QY(e,t,a,n,F1,i,r);else{var s=i?i(Xy(e,a),o,a+"",e,t,r):void 0;s===void 0&&(s=o),Yy(e,a,s)}},jP)}var e3=F1;function t3(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}var r3=t3,hT=Math.max;function n3(e,t,n){return t=hT(t===void 0?e.length-1:t,0),function(){for(var i=arguments,r=-1,o=hT(i.length-t,0),a=Array(o);++r<o;)a[r]=i[t+r];r=-1;for(var s=Array(t+1);++r<t;)s[r]=i[r];return s[t]=n(a),r3(e,this,s)}}var V1=n3;function i3(e){return function(){return e}}var o3=i3,a3=Ac?function(e,t){return Ac(e,"toString",{configurable:!0,enumerable:!1,value:o3(t),writable:!0})}:RP,s3=a3,l3=800,u3=16,c3=Date.now;function d3(e){var t=0,n=0;return function(){var i=c3(),r=u3-(i-n);if(n=i,r>0){if(++t>=l3)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var p3=d3,f3=p3(s3),G1=f3;function m3(e,t){return G1(V1(e,t,RP),e+"")}var h3=m3;function g3(e,t,n){if(!Jr(n))return!1;var i=typeof t;return(i=="number"?_b(n)&&xd(t,n.length):i=="string"&&t in n)?yd(n[t],e):!1}var v3=g3;function y3(e){return h3(function(t,n){var i=-1,r=n.length,o=r>1?n[r-1]:void 0,a=r>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(r--,o):void 0,a&&v3(n[0],n[1],a)&&(o=r<3?void 0:o,r=1),t=Object(t);++i<r;){var s=n[i];s&&e(t,s,i,o)}return t})}var b3=y3,Pre=b3(function(e,t,n,i){e3(e,t,n,i)});function _3(e,t,n,i){if(!Jr(e))return e;t=Id(t,e);for(var r=-1,o=t.length,a=o-1,s=e;s!=null&&++r<o;){var l=wb(t[r]),c=n;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(r!=a){var d=s[l];c=i?i(d,l,s):void 0,c===void 0&&(c=Jr(d)?d:xd(t[r+1])?[]:{})}xP(s,l,c),s=s[l]}return e}var S3=_3;function w3(e,t,n){for(var i=-1,r=t.length,o={};++i<r;){var a=t[i],s=E2(e,a);n(s,a)&&S3(o,Id(a,e),s)}return o}var k3=w3;function x3(e,t){return k3(e,t,function(n,i){return U2(e,i)})}var I3=x3,gT=xn?xn.isConcatSpreadable:void 0;function T3(e){return In(e)||os(e)||!!(gT&&e&&e[gT])}var P3=T3;function B1(e,t,n,i,r){var o=-1,a=e.length;for(n||(n=P3),r||(r=[]);++o<a;){var s=e[o];t>0&&n(s)?t>1?B1(s,t-1,n,i,r):HZ(r,s):i||(r[r.length]=s)}return r}var E3=B1;function O3(e){var t=e==null?0:e.length;return t?E3(e,1):[]}var j3=O3;function z3(e){return G1(V1(e,void 0,j3),e+"")}var C3=z3,Ere=C3(function(e,t){return e==null?{}:I3(e,t)});async function N3(e,t){try{await c$(e,t)}catch(n){if(!kd(n))throw n}}async function U3(e,t){if(!e)return;let n=e;try{let i=xb(e);i?.claudeAiOauth?.refreshToken&&(delete i.claudeAiOauth.refreshToken,n=At(i))}catch{}await DT(t,n,{mode:384})}function R3(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=uq(lq);return new Promise(t=>{s$("security",["find-generic-password","-a",dq(),"-w","-s",e],{encoding:"utf-8",timeout:5e3},(n,i)=>t(n?void 0:i.trim()||void 0))})}async function A3(e,t,n,i,r=6e4){if(!GW(t))return;let o=Y1(n),a=await Ha(e.load({projectKey:o,sessionId:t}),r,`SessionStore.load() timed out after ${r}ms for session ${t}`);if(!a||a.length===0)return;let s=Ir(m$(),`claude-resume-${l$()}`);try{let l=Ir(s,"projects",o);await kv(l,{recursive:!0});let c=Ir(l,`${t}.jsonl`);await _I(c,a);let d=i?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=d??Ir(Hv(),".claude"),h;try{h=await d$(Ir(f,".credentials.json"),"utf-8")}catch(m){if(!kd(m))throw m}if(!d&&!(i??process.env).ANTHROPIC_API_KEY&&!(i??process.env).CLAUDE_CODE_OAUTH_TOKEN&&(h=await R3()??h),await U3(h,Ir(s,".credentials.json")),await N3(Ir(d??Hv(),".claude.json"),Ir(s,".claude.json")),e.listSubkeys){let m=Ir(l,t),_=await Ha(e.listSubkeys({projectKey:o,sessionId:t}),r,`SessionStore.listSubkeys() timed out after ${r}ms for session ${t}`);for(let S of _){let w=ic(m,S+".jsonl");if(!S||$T(S)||S.split(/[\\/]/).includes("..")||!w.startsWith(m+MT)){St(`[SessionStore] skipping unsafe subpath from listSubkeys: ${S}`,{level:"warn"});continue}let g=await Ha(e.load({projectKey:o,sessionId:t,subpath:S}),r,`SessionStore.load() timed out after ${r}ms for session ${t} subpath ${S}`);if(!g||g.length===0)continue;let b=[],y=[];for(let v of g)L3(v)?b.push(v):y.push(v);if(y.length>0&&(await kv(yx(w),{recursive:!0}),await _I(w,y)),b.length>0){let v=b.at(-1),k=ic(m,S+".meta.json");await kv(yx(k),{recursive:!0});let{type:x,...T}=v;await DT(k,At(T),{mode:384})}}}return s}catch(l){throw await H1(s),l}}function vT(e,t,n,i){let{systemPrompt:r,settings:o,managedSettings:a,settingSources:s,sandbox:l,...c}=e??{},d,f,h;r===void 0?d="":typeof r=="string"||Array.isArray(r)?d=r:r.type==="preset"&&(f=r.append,h=r.excludeDynamicSections);let m=c.pathToClaudeCodeExecutable;if(!m){let Qt=g$(import.meta.url),ur=f$(Qt),Un=RW(pi=>ur.resolve(pi));if(Un)m=Un;else try{m=ur.resolve("./cli.js")}catch{throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`)}}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.140";let{abortController:_=LT(),additionalDirectories:S=[],agent:w,agents:g,allowedTools:b=[],betas:y,canUseTool:v,continue:k,cwd:x,debug:T,debugFile:E,disallowedTools:U=[],tools:q,env:L,executable:V=qT()?"bun":"node",executableArgs:ne=[],extraArgs:ae={},fallbackModel:Ie,enableFileCheckpointing:He,toolConfig:de,forkSession:kt,hooks:Ae,includeHookEvents:Q,includePartialMessages:j,forwardSubagentText:W,onElicitation:A,persistSession:I,sessionStore:P,sessionStoreFlush:M,thinking:pe,effort:he,maxThinkingTokens:De,maxTurns:$e,maxBudgetUsd:at,taskBudget:C,mcpServers:R,model:F,outputFormat:te,permissionMode:ge="default",allowDangerouslySkipPermissions:Oe=!1,permissionPromptToolName:ht,plugins:Jt,getOAuthToken:xt,workload:It,resume:mt,resumeSessionAt:rn,sessionId:Zt,skills:di,stderr:Nn,strictMcpConfig:$o}=c;if(P&&I===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");if(P&&k&&!mt&&!P.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(P&&He)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");P&&c.spawnClaudeCodeProcess&&St("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});let Mo=te?.type==="json_schema"?te.schema:void 0,Wt=L?{...L}:{...process.env};Wt.CLAUDE_CODE_ENTRYPOINT||(Wt.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),He&&(Wt.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),xt&&(Wt.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1"),de?.askUserQuestion?.previewFormat&&(Wt.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=de.askUserQuestion.previewFormat);let Lo={};if(yI.propagation.inject(yI.context.active(),Lo),"traceparent"in Lo)for(let Qt of["TRACEPARENT","TRACESTATE"])Qt in(L??{})||delete Wt[Qt];for(let[Qt,ur]of Object.entries(Lo)){let Un=Qt.toUpperCase();Un in(L??{})||(Wt[Un]=ur)}let _w={},Sw=new Map;if(R)for(let[Qt,ur]of Object.entries(R))ur.type==="sdk"&&ur.instance?Sw.set(Qt,ur.instance):_w[Qt]=ur;let Zo;if(pe)switch(pe.type){case"adaptive":Zo={type:"adaptive",display:pe.display};break;case"enabled":Zo={type:"enabled",budgetTokens:pe.budgetTokens,display:pe.display};break;case"disabled":Zo={type:"disabled"};break}else De!==void 0&&(Zo=De===0?{type:"disabled"}:{type:"enabled",budgetTokens:De});n&&(Wt.CLAUDE_CONFIG_DIR=n);let ww=new my({abortController:_,additionalDirectories:S,agent:w,betas:y,cwd:x,debug:T,debugFile:E,executable:V,executableArgs:ne,extraArgs:It?{...ae,workload:It}:ae,pathToClaudeCodeExecutable:m,env:Wt,forkSession:kt,stderr:Nn,thinkingConfig:Zo,effort:he,maxTurns:$e,maxBudgetUsd:at,taskBudget:C,model:F,fallbackModel:Ie,jsonSchema:Mo,permissionMode:ge,allowDangerouslySkipPermissions:Oe,permissionPromptToolName:ht,continueConversation:P?void 0:k,resume:mt,resumeSessionAt:rn,sessionId:Zt,settings:typeof o=="object"?At(o):o,managedSettings:a?At(a):void 0,settingSources:s,skills:di,allowedTools:b,disallowedTools:U,tools:q,mcpServers:_w,strictMcpConfig:$o,canUseTool:!!v,hooks:!!Ae,includeHookEvents:Q,includePartialMessages:j,persistSession:I,sessionMirror:!!P,plugins:Jt,sandbox:l,spawnClaudeCodeProcess:c.spawnClaudeCodeProcess,deferSpawn:i}),CU={systemPrompt:d,appendSystemPrompt:f,planModeInstructions:c.planModeInstructions,appendSubagentSystemPrompt:c.appendSubagentSystemPrompt,excludeDynamicSections:h,agents:g,title:c.title,skills:di,webSearchIsolationExemptMcpServers:c.webSearchIsolationExemptMcpServers,promptSuggestions:c.promptSuggestions,agentProgressSummaries:c.agentProgressSummaries,forwardSubagentText:W},wp=new vy(ww,t,v,Ae,_,Sw,Mo,CU,A,xt);if(P){let Qt=()=>Ir(Wt.CLAUDE_CONFIG_DIR??Ir(Hv(),".claude"),"projects"),ur=M==="eager",Un=new yy(async(pi,kp)=>{let Wo=bT(pi,Qt());Wo?await P.append(Wo,kp):St(`[SessionStore] dropping mirror frame: filePath ${pi} is not under ${Qt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(pi,kp)=>{let Wo=bT(pi,Qt());Wo&&wp.reportMirrorError(Wo,kp.message)},ur?0:VP,ur?0:GP);wp.setTranscriptMirrorBatcher(Un)}return{queryInstance:wp,transport:ww,abortController:_,processEnv:Wt}}function yT(e,t,n,i){typeof n=="string"?t.write(At({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
138
- `):e.streamInput(n).catch(r=>i.abort(r))}var D3=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function H1(e){for(let t=0;;t++)try{return await p$(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!D3.has(to(n)??""))return;await ZT((t+1)*100)}}function $3(e,t){e.waitForExit().catch(()=>{}).finally(()=>H1(t))}function K1({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore){let{queryInstance:o,transport:a,abortController:s,processEnv:l}=vT({...t},typeof e=="string",void 0,!0),c=ic(t.cwd??"."),d=t.sessionStore,f=t.loadTimeoutMs??6e4,h=t.resume;return(async()=>{if(h||(h=(await Ha(d.listSessions(Y1(c)),f,`SessionStore.listSessions() timed out after ${f}ms`)).slice().sort((m,_)=>_.mtime-m.mtime)[0]?.sessionId),!!h)return A3(d,h,c,t.env,t.loadTimeoutMs)})().then(m=>{m&&(a.updateResume(h),a.updateEnv({CLAUDE_CONFIG_DIR:m}),l.CLAUDE_CONFIG_DIR=m,o.addCleanupCallback(()=>$3(a,m))),o.isClosed()||a.spawn()}).catch(m=>{let _=wd(m);a.spawnAbort(_),o.setError(_)}),yT(o,a,e,s),o}let{queryInstance:n,transport:i,abortController:r}=vT(t,typeof e=="string");return yT(n,i,e,r),n}function M3(e){let t=ic(e??"."),n;try{n=u$(t)}catch{n=t}return n.normalize("NFC")}function Y1(e){return HW(M3(e))}function L3(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function bT(e,t){let n=h$(t,e),i=n.split(MT);if(i[0]===".."||$T(n)||i.length<2)return null;let r=i[0],o=i[1];if(i.length===2&&o.endsWith(".jsonl"))return{projectKey:r,sessionId:o.replace(/\.jsonl$/,"")};if(i.length>=4){let a=i.slice(2),s=a.length-1;return a[s]=a.at(-1).replace(/\.jsonl$/,""),{projectKey:r,sessionId:o,subpath:a.join("/")}}return null}var Kd=class{constructor(t,n,i){this.options=t;this.onMessage=n;this.onDone=i;this.completion=new Promise(r=>{this.complete=r})}options;onMessage;onDone;query;sessionId;inputResolve=null;inputQueue=[];inputDone=!1;abortController=new AbortController;isProcessing=!1;completion;complete=null;getSessionId(){return this.sessionId}getIsProcessing(){return this.isProcessing}start(t){t?this.sessionId=t:this.options.sessionId&&(this.sessionId=this.options.sessionId);let n={abortController:this.abortController,cwd:this.options.cwd,systemPrompt:this.options.systemPrompt,permissionMode:this.options.permissionMode??"default",includePartialMessages:!0,settingSources:["user","project","local"],persistSession:!0,env:this.options.env??process.env,...this.options.mcpServers?{mcpServers:this.options.mcpServers}:{},...this.options.allowedTools?{allowedTools:this.options.allowedTools}:{},...this.options.disallowedTools?{disallowedTools:this.options.disallowedTools}:{},...this.options.tools?{tools:this.options.tools}:{},...this.options.canUseTool?{canUseTool:this.options.canUseTool}:{},...this.options.sandbox?{sandbox:this.options.sandbox}:{},...this.options.hooks?{hooks:this.options.hooks}:{},...this.options.permissionMode==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},...t?{resume:t}:{},...!t&&this.options.sessionId?{sessionId:this.options.sessionId}:{},...this.options.model?{model:this.options.model}:{},...this.options.additionalDirectories?{additionalDirectories:[...this.options.additionalDirectories]}:{},...this.options.effort?{effort:this.options.effort}:{},...this.options.pathToClaudeCodeExecutable?{pathToClaudeCodeExecutable:this.options.pathToClaudeCodeExecutable}:{},...this.options.thinking?{thinking:this.options.thinking}:{}};this.query=K1({prompt:this.createInputIterable(),options:n}),this.consumeStream()}pushInput(t){let n={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:this.sessionId??""};if(!this.inputDone){if(this.inputResolve){let i=this.inputResolve;this.inputResolve=null,i({value:n,done:!1});return}this.inputQueue.push(n)}}stop(){this.inputDone=!0,this.resolveInputDone(),this.abortController.abort(),this.query?.close(),this.query=void 0,this.isProcessing=!1}async closeGracefully(t){if(this.inputDone=!0,this.resolveInputDone(),!this.query)return;let n;try{await Promise.race([this.completion,new Promise((i,r)=>{n=setTimeout(()=>{r(new Error(`Claude SDK session did not close within ${t}ms`))},t)})])}catch{this.stop()}finally{n&&clearTimeout(n)}}createInputIterable(){let t=this;return{[Symbol.asyncIterator](){return{async next(){if(t.inputQueue.length>0){let n=t.inputQueue.shift();return n?{value:n,done:!1}:{value:void 0,done:!0}}return t.inputDone?{value:void 0,done:!0}:new Promise(n=>{t.inputResolve=n})},async return(){return t.inputDone=!0,t.resolveInputDone(),{value:void 0,done:!0}}}}}}resolveInputDone(){if(!this.inputResolve)return;let t=this.inputResolve;this.inputResolve=null,t({value:void 0,done:!0})}async consumeStream(){let t=this.query;if(t)try{for await(let n of t)this.captureSessionId(n),this.trackProcessingState(n),this.onMessage(n);this.isProcessing=!1,this.onDone()}catch(n){this.isProcessing=!1,this.onDone(n)}finally{this.query=void 0,this.complete&&(this.complete(),this.complete=null)}}captureSessionId(t){let{session_id:n}=t,i=n?.trim()??"";i.length>0&&(this.sessionId=i)}trackProcessingState(t){(t.type==="assistant"||t.type==="stream_event")&&(this.isProcessing=!0),t.type==="result"&&(this.isProcessing=!1)}};var Rre=u.object({command:u.string().optional(),cwd:u.string().optional()}).passthrough(),Z3=u.object({type:u.literal("text"),text:u.string()}),W3=u.object({content:u.array(u.unknown())}).passthrough();var As={reasoningEffort:"low",description:"Low reasoning effort"},Yd={reasoningEffort:"medium",description:"Medium reasoning effort"},Xd={reasoningEffort:"high",description:"High reasoning effort"},X1={reasoningEffort:"xhigh",description:"Extra high reasoning effort"},qre=u.string().regex(/^[A-Z_][A-Z0-9_]*$/i);var J1=[As,Yd,Xd,X1],tp=[As,Yd,Xd],rp=[As,Yd,Xd],tC=[As],Jd="claude-opus-4-7",Qd="claude-opus-4-6",ep="claude-sonnet-4-6",Q1="claude-haiku-4-5";function Ro(e){return`${e}[1m]`}var q3=[{id:Ro(Jd),model:Ro(Jd),displayName:"Opus 4.7 (1M)",description:"Opus 4.7 with 1M context for complex long coding sessions",supportedReasoningEfforts:J1,defaultReasoningEffort:"medium"},{id:Jd,model:Jd,displayName:"Opus 4.7",description:"Opus 4.7 for complex coding tasks",supportedReasoningEfforts:J1,defaultReasoningEffort:"medium"},{id:Ro(Qd),model:Ro(Qd),displayName:"Opus 4.6 (1M)",description:"Opus 4.6 with 1M context for complex long coding sessions",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:Qd,model:Qd,displayName:"Opus 4.6",description:"Opus 4.6 for complex coding tasks",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:Ro(ep),model:Ro(ep),displayName:"Sonnet 4.6 (1M)",description:"Sonnet 4.6 with 1M context for long coding sessions",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:ep,model:ep,displayName:"Sonnet 4.6",description:"Sonnet 4.6 for everyday coding tasks",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:Q1,model:Q1,displayName:"Haiku 4.5",description:"Haiku 4.5 for quick answers",supportedReasoningEfforts:tC,defaultReasoningEffort:"low"}],F3=[{id:"opus[1m]",model:"opus[1m]",displayName:"Opus Alias (1M, Legacy)",description:"Legacy moving Opus 1M alias retained for existing selections",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:"opus",model:"opus",displayName:"Opus Alias (Legacy)",description:"Legacy moving Opus alias retained for existing selections",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:"sonnet[1m]",model:"sonnet[1m]",displayName:"Sonnet Alias (1M, Legacy)",description:"Legacy moving Sonnet 1M alias retained for existing selections",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:"sonnet",model:"sonnet",displayName:"Sonnet Alias (Legacy)",description:"Legacy moving Sonnet alias retained for existing selections",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:"haiku",model:"haiku",displayName:"Haiku Alias (Legacy)",description:"Legacy moving Haiku alias retained for existing selections",supportedReasoningEfforts:tC,defaultReasoningEffort:"low"}];function V3(e){return e.map(t=>({...t}))}function eC(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,supportedReasoningEfforts:V3(e.supportedReasoningEfforts),defaultReasoningEffort:e.defaultReasoningEffort,isDefault:!1}}function G3(e){return e.map((t,n)=>n===0?{...t,isDefault:!0}:t)}function rC(){return{models:G3(q3.map(eC)),selectedOnlyModels:F3.map(eC)}}async function nC(){return rC()}var np=["low","medium","high","xhigh"],Lr=u.enum(np),li=u.enum(["fast","default"]),ip=["append","replace"],B3=u.enum(ip),iC=["full","workspace-write","readonly"],On=u.enum(iC),op=["ask","deny"],AS=u.enum(op),jn=u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("image"),url:u.string().url()}),u.object({type:u.literal("localImage"),path:u.string()}),u.object({type:u.literal("localFile"),path:u.string(),name:u.string().optional(),sizeBytes:u.number().int().nonnegative().optional(),mimeType:u.string().optional()})]),DS=u.enum(["client/thread/start","client/turn/requested","client/turn/start"]),oC=u.object({model:u.string().optional(),serviceTier:li.optional(),reasoningLevel:Lr.optional(),permissionMode:On.optional(),source:DS.optional(),seq:u.number().int().optional()}),Ds=oC.extend({model:u.string().min(1),serviceTier:li,reasoningLevel:Lr,permissionMode:On,source:DS}),aC=u.discriminatedUnion("permissionMode",[u.object({permissionMode:u.literal("full"),permissionEscalation:u.null()}),u.object({permissionMode:u.literal("workspace-write"),permissionEscalation:AS}),u.object({permissionMode:u.literal("readonly"),permissionEscalation:AS})]),H3=u.object({model:u.string().min(1),serviceTier:li,reasoningLevel:Lr}),K3=H3.and(aC),Y3=u.object({providerId:u.string().min(1),model:u.string().min(1),serviceTier:li,reasoningLevel:Lr,permissionMode:On});var X3=u.object({askUserQuestion:u.boolean(),terminals:u.boolean()});var sC=500,lC=200,ap=64*1024,uC=Math.ceil(ap/3)*4,J3=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,cC=["starting","running","disconnected","exited"],Q3=u.enum(cC),dC=["user","process-exit","daemon-disconnect","environment-destroyed","thread-archived","thread-deleted","open-timeout"],e5=u.enum(dC);function pC(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return e.length/4*3-t}var t5=u.number().int().positive().max(sC),r5=u.number().int().positive().max(lC),n5=u.string().min(1).max(uC).regex(J3).refine(e=>pC(e)<=ap,{message:`Terminal data must decode to ${ap} bytes or less`});var fC=["project","thread"],i5=u.enum(fC),o5=u.object({id:u.string().min(1),createdAt:u.number(),input:u.array(jn).min(1)});var Ls=u.enum(["pending","resolving","resolved","interrupted","expired"]),hC=u.discriminatedUnion("type",[u.object({type:u.literal("read"),command:u.string(),name:u.string(),path:u.string()}),u.object({type:u.literal("listFiles"),command:u.string(),path:u.string().nullable()}),u.object({type:u.literal("search"),command:u.string(),query:u.string().nullable(),path:u.string().nullable()}),u.object({type:u.literal("unknown"),command:u.string()})]),LS=u.object({enabled:u.boolean().nullable()}),ZS=u.object({read:u.array(u.string()),write:u.array(u.string())}),a5=u.enum(["none","read_only","read_write"]),s5=u.enum(["none","read_only","read_write"]),l5=u.union([u.literal("none"),u.literal("all"),u.object({kind:u.literal("bundle_ids"),bundleIds:u.array(u.string())})]),gC=u.object({preferences:a5,automations:l5,launchServices:u.boolean(),accessibility:u.boolean(),calendar:u.boolean(),reminders:u.boolean(),contacts:s5}),u5=u.object({network:LS.nullable(),fileSystem:ZS.nullable(),macos:gC.nullable()}),Zs=u.object({network:LS.nullable(),fileSystem:ZS.nullable()}).strict(),mC=Zs,vC=u.enum(["allow_once","allow_for_session","deny"]),c5=u.string().min(1),yC=u.object({kind:u.literal("command"),itemId:u.string().min(1),command:u.string().min(1),cwd:u.string().nullable(),actions:u.array(hC),sessionGrant:Zs.nullable()}),bC=u.object({kind:u.literal("file_change"),itemId:u.string().min(1),writeScope:c5.nullable(),sessionGrant:Zs.nullable()}),sp=u.object({kind:u.literal("permission_grant"),itemId:u.string().min(1),toolName:u.string().nullable(),permissions:Zs}),_C=u.discriminatedUnion("kind",[yC,bC,sp]),SC=u.object({kind:u.literal("approval"),subject:_C,reason:u.string().nullable(),availableDecisions:u.array(vC).min(1)}),$s=4,Ms=4,$S=4,MS=4096,d5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question ids cannot be blank"}),p5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question prompts cannot be blank"}),f5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question short labels cannot be blank"}),m5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question option values cannot be blank"}),h5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question option labels cannot be blank"}),g5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question option descriptions cannot be blank"}),v5=u.string().min(1).max(MS,`User question free text cannot exceed ${MS} characters`).refine(e=>e.trim().length>0,{message:"User question free text cannot be blank"}),wC=u.object({value:m5,label:h5,description:g5.optional()}),kC=u.object({id:d5,prompt:p5,shortLabel:f5.optional(),multiSelect:u.boolean(),options:u.array(wC).max(Ms,`User questions cannot include more than ${Ms} options`).optional(),allowFreeText:u.boolean()}).superRefine((e,t)=>{let n=new Set;e.options?.forEach((i,r)=>{if(n.has(i.value)){t.addIssue({code:u.ZodIssueCode.custom,message:"User question option values must be unique",path:["options",r,"value"]});return}n.add(i.value)})}).refine(e=>e.allowFreeText||(e.options?.length??0)>0,{message:"User questions must allow free text or provide at least one option",path:["options"]}),lp=u.object({kind:u.literal("user_question"),questions:u.array(kC).min(1).max($s,`User questions cannot include more than ${$s} questions`)}).superRefine((e,t)=>{let n=new Set;e.questions.forEach((i,r)=>{if(n.has(i.id)){t.addIssue({code:u.ZodIssueCode.custom,message:"User question ids must be unique",path:["questions",r,"id"]});return}n.add(i.id)})}),WS=u.discriminatedUnion("kind",[SC,lp]);var xC="Invalid discriminator value. Expected 'allow_once' | 'allow_for_session' | 'deny'",up=u.discriminatedUnion("decision",[u.object({decision:u.literal("allow_once"),grantedPermissions:mC.nullable()}),u.object({decision:u.literal("allow_for_session"),grantedPermissions:mC.nullable()}),u.object({decision:u.literal("deny")})],xC),IC=u.object({selected:u.array(u.string().min(1)).max($S,`User question selected choices cannot exceed ${$S}`),freeText:v5.optional()}),cp=u.object({kind:u.literal("user_answer"),answers:u.record(u.string().min(1),IC)}),TC=u.union([up,cp],xC);var y5=u.object({threadId:u.string().min(1),turnId:u.string().min(1),providerId:u.string().min(1),providerThreadId:u.string().min(1),providerRequestId:u.string().min(1),payload:WS}),b5=u.object({id:u.string().min(1),threadId:u.string().min(1),turnId:u.string().min(1),providerId:u.string().min(1),providerThreadId:u.string().min(1),providerRequestId:u.string().min(1),status:Ls,payload:WS,resolution:TC.nullable(),statusReason:u.string().nullable(),createdAt:u.number().int().nonnegative(),resolvedAt:u.number().int().nonnegative().nullable()});var PC=u.object({reasoningEffort:Lr,description:u.string()}),_5=u.object({id:u.string(),model:u.string(),displayName:u.string(),description:u.string(),supportedReasoningEfforts:u.array(PC),defaultReasoningEffort:Lr,isDefault:u.boolean()}),EC=u.object({supportsArchive:u.boolean(),supportsRename:u.boolean(),supportsServiceTier:u.boolean(),supportsUserQuestion:u.boolean(),supportedPermissionModes:u.array(On).min(1)}),S5=u.object({id:u.string(),displayName:u.string(),capabilities:EC,available:u.boolean()}),OC=u.discriminatedUnion("type",[u.object({type:u.literal("inputText"),text:u.string()}),u.object({type:u.literal("inputImage"),imageUrl:u.string()})]),w5=u.object({requestId:u.union([u.string().min(1),u.number()]),threadId:u.string().min(1),providerThreadId:u.string().min(1),turnId:u.string().min(1),callId:u.string().min(1),tool:u.string().min(1),arguments:u.unknown().optional()}),k5=u.object({contentItems:u.array(OC),success:u.boolean()}),x5=u.object({text:u.string().trim().min(1).optional(),message:u.string().trim().min(1).optional()}).refine(e=>e.text!==void 0||e.message!==void 0,"message_user requires text").transform(e=>({text:e.text??e.message??""})),I5=u.object({name:u.string(),description:u.string(),inputSchema:u.unknown()});var jC=["provisioning","ready","error","destroying","destroyed"],zC=u.enum(jC),T5=["safe"],CC=u.enum(T5),NC=["unmanaged","managed-worktree"],UC=u.enum(NC),RC=["managed-worktree","unmanaged-worktree","other"],qS=u.enum(RC);var P5=u.object({path:u.string().min(1),isGitRepo:u.boolean(),isWorktree:u.boolean(),branchName:u.string().nullable(),defaultBranch:u.string().nullable()}),E5=u.object({id:u.string(),projectId:u.string(),hostId:u.string(),path:u.string().nullable(),managed:u.boolean(),isGitRepo:u.boolean(),isWorktree:u.boolean(),workspaceProvisionType:UC,branchName:u.string().nullable(),baseBranch:u.string().nullable(),defaultBranch:u.string().nullable(),mergeBaseBranch:u.string().nullable(),cleanupRequestedAt:u.number().nullable(),cleanupMode:CC.nullable(),status:zC,createdAt:u.number(),updatedAt:u.number()});var O5=u.string().regex(/^hdevt_[23456789abcdefghijkmnpqrstuvwxyz]{20}$/u),Ao=u.string().regex(/^creq_[23456789abcdefghijkmnpqrstuvwxyz]{10}$/u);var zn=u.lazy(()=>u.union([u.string(),u.number(),u.boolean(),u.null(),u.array(zn),u.record(u.string(),zn)]));var dp=["client/thread/start","client/turn/requested","client/turn/start","system/error","system/manager/user_message","system/thread/interrupted","system/operation","system/permissionGrant/lifecycle","system/userQuestion/lifecycle","system/thread-provisioning"],j5=u.enum(dp),AC=["user","agent","system"],FS=u.enum(AC),VS=["thread-created","boot-created-thread","tell-after-provisioning-failure","tell-after-missing-environment-attachment","resume-missing-provider-thread"],z5=u.enum(VS),DC=[...VS,"boot-active-resume","resume-existing-provider-session"],C5=u.enum(DC),$C=Ds,pp=u.discriminatedUnion("kind",[u.object({kind:u.literal("thread-start")}),u.object({kind:u.literal("new-turn")}),u.object({kind:u.literal("auto"),expectedTurnId:u.string().nullable()}),u.object({kind:u.literal("steer"),expectedTurnId:u.string().nullable()})]),fp=u.object({direction:u.literal("outbound"),source:u.enum(["spawn","tell"]),initiator:FS.optional(),request:u.object({method:u.enum(["thread/start","turn/start"]),params:u.record(u.string(),u.unknown())})}),Ws=u.object({direction:u.literal("outbound"),requestId:Ao,source:u.enum(["spawn","tell"]),initiator:FS.optional(),input:u.array(jn),target:pp,request:u.object({method:u.enum(["thread/start","turn/start"]),params:u.record(u.string(),u.unknown())}),execution:$C}),GS=u.object({code:u.string().optional(),message:u.string(),detail:u.string().optional(),reconnectAttempt:u.number().int().positive().optional(),reconnectTotal:u.number().int().positive().optional()}).superRefine((e,t)=>{let n=e.reconnectAttempt!==void 0,i=e.reconnectTotal!==void 0;if(n!==i){t.addIssue({code:u.ZodIssueCode.custom,message:"system/error reconnectAttempt and reconnectTotal must be provided together"});return}e.reconnectAttempt!==void 0&&e.reconnectTotal!==void 0&&e.reconnectAttempt>e.reconnectTotal&&t.addIssue({code:u.ZodIssueCode.custom,message:"system/error reconnectAttempt cannot be greater than reconnectTotal"})}),MC=["assign","release","transfer"],LC=u.enum(MC),N5=u.object({action:LC,nextParentThreadId:u.string().nullable(),nextParentThreadTitle:u.string().nullable(),previousParentThreadId:u.string().nullable(),previousParentThreadTitle:u.string().nullable()}),BS=u.object({operation:u.string(),status:u.string(),message:u.string(),operationId:u.string(),metadata:u.record(u.string(),zn).optional()}),HS=u.object({interactionId:u.string(),providerId:u.string(),providerRequestId:u.string(),status:Ls,resolution:up.nullable().default(null),statusReason:u.string().nullable().default(null),subject:sp}),KS=u.object({interactionId:u.string(),providerId:u.string(),providerRequestId:u.string(),status:Ls,resolution:cp.nullable().default(null),statusReason:u.string().nullable().default(null),payload:lp}),ZC=["manual-stop","host-daemon-restarted"],WC=u.enum(ZC),YS=u.object({reason:WC}),qC=u.object({type:u.enum(["step","output"]),key:u.string(),text:u.string(),startedAt:u.number().optional(),status:u.enum(["started","completed","failed"]).optional(),metadata:u.record(u.string(),u.unknown()).optional()}),FC=["active","completed","failed"],VC=u.enum(FC),XS=u.object({provisioningId:u.string(),status:VC,environmentId:u.string(),entries:u.array(qC)}),JS=u.object({text:u.string(),toolCallId:u.string().optional(),turnId:u.string().optional()}),U5=u.object({turnId:u.string().optional(),input:u.array(jn).optional()});var GC=["thread","turn"],R5=u.enum(GC),ui=u.discriminatedUnion("kind",[u.object({kind:u.literal("thread")}),u.object({kind:u.literal("turn"),turnId:u.string().min(1)})]),BC=["thread","turn","thread-or-turn"],A5=u.enum(BC),HC={"thread/started":{policy:"thread",rationale:"Thread lifecycle event; it creates the thread timeline itself."},"thread/identity":{policy:"thread",rationale:"Thread metadata event; it identifies the provider thread outside turn chronology."},"turn/started":{policy:"turn"},"turn/completed":{policy:"turn"},"turn/input/accepted":{policy:"turn"},"thread/name/updated":{policy:"thread",rationale:"Thread metadata event; names are not part of a specific turn transcript."},"thread/compacted":{policy:"turn"},"item/started":{policy:"turn"},"item/completed":{policy:"turn"},"item/agentMessage/delta":{policy:"turn"},"item/commandExecution/outputDelta":{policy:"turn"},"item/fileChange/outputDelta":{policy:"turn"},"item/reasoning/summaryTextDelta":{policy:"turn"},"item/reasoning/textDelta":{policy:"turn"},"item/plan/delta":{policy:"turn"},"item/mcpToolCall/progress":{policy:"turn"},"item/toolCall/progress":{policy:"turn"},"thread/tokenUsage/updated":{policy:"turn"},"thread/contextWindowUsage/updated":{policy:"turn"},"turn/plan/updated":{policy:"turn"},"turn/diff/updated":{policy:"turn"},"provider/error":{policy:"thread-or-turn",rationale:"Provider diagnostics use thread scope for provider setup/session failures; in-turn failures use turn scope."},"provider/warning":{policy:"thread-or-turn",rationale:"Provider warnings use thread scope for config, deprecation, or global notices; turn-specific warnings use turn scope."},"provider/unhandled":{policy:"thread-or-turn",rationale:"Unhandled provider events use thread scope only when no active turn context exists; in-turn unknown events use turn scope."},"client/thread/start":{policy:"thread",rationale:"Outbound client lifecycle event; it requests thread creation before any turn exists."},"client/turn/requested":{policy:"thread",rationale:"Outbound client lifecycle event; it records the request before provider turn acceptance."},"client/turn/start":{policy:"thread",rationale:"Outbound client lifecycle event; it records the start request before provider turn acceptance."},"system/error":{policy:"thread-or-turn",rationale:"System errors use thread scope for app, daemon, or session failures outside a turn; turn failures use turn scope."},"system/manager/user_message":{policy:"thread-or-turn",rationale:"Manager messages can be thread-scoped for general manager updates or turn-scoped for in-turn updates."},"system/thread/interrupted":{policy:"thread",rationale:"Thread stop lifecycle event; it represents user interruption of the whole running thread."},"system/operation":{policy:"thread",rationale:"Thread-management operation event; ownership and lifecycle operations are not turn transcript content."},"system/permissionGrant/lifecycle":{policy:"turn"},"system/userQuestion/lifecycle":{policy:"turn"},"system/thread-provisioning":{policy:"thread",rationale:"Workspace provisioning lifecycle event; environment setup belongs to the thread, not a turn."}};function QS(){return Object.entries(HC).map(([e,t])=>({type:e,definition:t}))}function ew(e){return QS().filter(t=>t.definition.policy===e).map(t=>t.type)}function D5(){let e={};for(let t of QS())e[t.type]=t.definition.policy;return e}function M5(){let e={};for(let t of QS())t.definition.rationale&&(e[t.type]=t.definition.rationale);return e}var L5=ew("turn"),Z5=ew("thread"),W5=ew("thread-or-turn"),KC=D5(),q5=M5();function tw(e){let t=KC[e.type];return t==="thread-or-turn"?{valid:!0}:t!==e.scope.kind?{valid:!1,message:`${e.type} requires ${t} scope but received ${e.scope.kind} scope`}:{valid:!0}}var hp=u.enum(["pending","completed","failed","interrupted"]),YC=u.enum(["waiting_for_approval","denied"]).nullable(),JC=u.enum(["completed","failed","interrupted"]),QC=u.enum(["add","delete","update"]),eN=u.object({path:u.string(),kind:QC,movePath:u.string().optional(),diff:u.string().optional()}),tN=u.enum(["pending","active","completed","failed"]),rN=u.object({step:u.string(),status:tN.optional()}),nN=u.object({type:u.literal("webSearch"),id:u.string(),queries:u.array(u.string()).min(1),resultText:u.string().nullable(),parentToolCallId:u.string().optional()}),iN=u.object({type:u.literal("webFetch"),id:u.string(),url:u.string(),prompt:u.string().nullable(),pattern:u.string().nullable(),resultText:u.string().nullable(),parentToolCallId:u.string().optional()}),gp=u.object({originalLength:u.number(),retainedHeadLength:u.number(),retainedTailLength:u.number(),truncatedAt:u.number()}),rw=u.object({aggregatedOutput:gp.optional(),result:gp.optional(),resultText:gp.optional()}),oN=u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("image"),url:u.string()}),u.object({type:u.literal("localImage"),path:u.string()}),u.object({type:u.literal("localFile"),path:u.string()})]),nw=u.object({totalTokens:u.number(),inputTokens:u.number(),cachedInputTokens:u.number(),outputTokens:u.number(),reasoningOutputTokens:u.number()}),aN=u.object({usedTokens:u.number().nullable(),modelContextWindow:u.number().nullable(),estimated:u.boolean()}),sN=u.object({total:nw,last:nw,modelContextWindow:u.number().nullable()}),lN=u.enum(["deprecation","config","general"]),uN=u.object({jsonrpc:u.literal("2.0"),id:u.union([u.string(),u.number()]).optional(),method:u.string(),params:zn.optional()}),F5=u.object({type:u.literal("provider/unhandled"),threadId:u.string(),providerThreadId:u.string(),providerId:u.string(),rawType:u.string(),rawEvent:uN,parentToolCallId:u.string().optional()}),V5=u.object({type:u.literal("item/toolCall/progress"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),message:u.string().optional(),parentToolCallId:u.string().optional()}),iw=u.discriminatedUnion("type",[u.object({type:u.literal("userMessage"),id:u.string(),content:u.array(oN),clientRequestId:Ao.optional(),parentToolCallId:u.string().optional()}).strict(),u.object({type:u.literal("agentMessage"),id:u.string(),text:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("commandExecution"),id:u.string(),command:u.string(),cwd:u.string(),status:hp,approvalStatus:YC,aggregatedOutput:u.string().optional(),exitCode:u.number().optional(),durationMs:u.number().optional(),truncation:rw.optional(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("fileChange"),id:u.string(),changes:u.array(eN),status:hp,approvalStatus:YC,parentToolCallId:u.string().optional()}),nN,iN,u.object({type:u.literal("toolCall"),id:u.string(),server:u.string().optional(),tool:u.string(),arguments:u.record(u.string(),u.unknown()).optional(),status:hp,result:u.unknown().optional(),error:u.string().optional(),durationMs:u.number().optional(),truncation:rw.optional(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("reasoning"),id:u.string(),summary:u.array(u.string()),content:u.array(u.string()),parentToolCallId:u.string().optional()}),u.object({type:u.literal("plan"),id:u.string(),text:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("contextCompaction"),id:u.string(),parentToolCallId:u.string().optional()})]),cN=u.discriminatedUnion("type",[u.object({type:u.literal("thread/started"),threadId:u.string()}),u.object({type:u.literal("thread/identity"),threadId:u.string(),providerThreadId:u.string()}),u.object({type:u.literal("turn/started"),threadId:u.string(),providerThreadId:u.string()}),u.object({type:u.literal("turn/completed"),threadId:u.string(),providerThreadId:u.string().nullable(),status:JC,error:u.object({message:u.string()}).optional()}),u.object({type:u.literal("turn/input/accepted"),threadId:u.string(),providerThreadId:u.string(),clientRequestId:Ao,scope:ui}).strict(),u.object({type:u.literal("thread/name/updated"),threadId:u.string(),providerThreadId:u.string(),threadName:u.string()}),u.object({type:u.literal("thread/compacted"),threadId:u.string(),providerThreadId:u.string()}),u.object({type:u.literal("item/started"),threadId:u.string(),providerThreadId:u.string(),item:iw}),u.object({type:u.literal("item/completed"),threadId:u.string(),providerThreadId:u.string(),item:iw}),u.object({type:u.literal("item/agentMessage/delta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/commandExecution/outputDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),reset:u.boolean().optional(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/fileChange/outputDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/reasoning/summaryTextDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/reasoning/textDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/plan/delta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/mcpToolCall/progress"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),message:u.string().optional(),parentToolCallId:u.string().optional()}),V5,u.object({type:u.literal("thread/tokenUsage/updated"),threadId:u.string(),providerThreadId:u.string(),tokenUsage:sN}),u.object({type:u.literal("thread/contextWindowUsage/updated"),threadId:u.string(),providerThreadId:u.string(),contextWindowUsage:aN}),u.object({type:u.literal("turn/plan/updated"),threadId:u.string(),providerThreadId:u.string(),plan:u.array(rN),explanation:u.string().optional()}),u.object({type:u.literal("turn/diff/updated"),threadId:u.string(),providerThreadId:u.string(),diff:u.string().optional()}),u.object({type:u.literal("provider/error"),threadId:u.string(),providerThreadId:u.string(),message:u.string(),detail:u.string().optional(),willRetry:u.boolean().optional()}),u.object({type:u.literal("provider/warning"),threadId:u.string(),providerThreadId:u.string(),category:lN,summary:u.string().optional(),details:u.string().optional()}),F5]),dN=u.object({scope:ui}),pN=cN.and(dN),ow=cN.options.map(e=>e.shape.type.value),B5=new Set(ow),H5=u.string().refine(e=>B5.has(e),"Invalid provider event type"),K5=u.union([u.object({type:u.literal("client/thread/start"),threadId:u.string()}).merge(fp),u.object({type:u.literal("client/turn/requested"),threadId:u.string()}).merge(Ws),u.object({type:u.literal("client/turn/start"),threadId:u.string()}).merge(fp),u.object({type:u.literal("system/error"),threadId:u.string()}).merge(GS),u.object({type:u.literal("system/manager/user_message"),threadId:u.string()}).merge(JS),u.object({type:u.literal("system/thread/interrupted"),threadId:u.string()}).merge(YS),u.object({type:u.literal("system/operation"),threadId:u.string()}).merge(BS),u.object({type:u.literal("system/permissionGrant/lifecycle"),threadId:u.string()}).merge(HS),u.object({type:u.literal("system/userQuestion/lifecycle"),threadId:u.string()}).merge(KS),u.object({type:u.literal("system/thread-provisioning"),threadId:u.string()}).merge(XS)]),fN=K5.and(dN),XC=u.record(u.string(),u.unknown()),mp=["clientRequest","Sequence"].join(""),Y5=u.unknown().superRefine((e,t)=>{let n=XC.safeParse(e);if(!n.success)return;Object.hasOwn(n.data,mp)&&t.addIssue({code:u.ZodIssueCode.custom,message:"legacy request sequence field is no longer accepted",path:[mp]});let i=XC.safeParse(n.data.item);i.success&&i.data.type==="userMessage"&&Object.hasOwn(i.data,mp)&&t.addIssue({code:u.ZodIssueCode.custom,message:"legacy user-message request sequence field is no longer accepted",path:["item",mp]})}),vp=Y5.pipe(u.union([pN,fN]).superRefine((e,t)=>{let n=tw({type:e.type,scope:e.scope});if(!n.valid){t.addIssue({code:u.ZodIssueCode.custom,message:n.message??"Invalid thread event scope",path:["scope"]});return}})),mN=[...ow,...dp],X5=new Set(mN),aw=u.string().refine(e=>X5.has(e),"Invalid thread event type");var hN=["requested","queued","completed","failed","cancelled"],J5=u.enum(hN);var gN=["provision","reprovision","destroy"],Q5=u.enum(gN),vN=["provision","start","stop"],e8=u.enum(vN),yN=["metadata-pending","environment-pending","environment-attached","environment-provisioning","workspace-ready"],t8=u.enum(yN),bN=["delete"],r8=u.enum(bN);var n8=u.object({id:u.string(),name:u.string(),createdAt:u.number(),updatedAt:u.number()}),_N=["local_path"],i8=u.enum(_N),o8=u.object({id:u.string(),projectId:u.string(),isDefault:u.boolean(),createdAt:u.number(),updatedAt:u.number()}),a8=o8.extend({type:u.literal("local_path"),hostId:u.string(),path:u.string()});var SN=["persistent"],wN=u.enum(SN),kN=["connected","disconnected"],xN=u.enum(kN),s8=u.object({id:u.string(),name:u.string(),type:wN,status:xN,lastSeenAt:u.number().nullable(),createdAt:u.number(),updatedAt:u.number()});var qs=["created","provisioning","idle","active","error"],yp=u.enum(qs);var IN=[...qs,"host-reconnecting","waiting-for-host"],TN=u.enum(IN),PN=u.object({displayStatus:TN,hostReconnectGraceExpiresAt:u.number().nullable()}),EN=["standard","manager"],ON=u.enum(EN),jN=["clean","untracked","dirty_uncommitted","committed_unmerged","dirty_and_committed_unmerged"],zN=u.enum(jN),CN=u.enum(["M","A","D","R","C","U","??","?"]),NN=u.object({path:u.string(),status:CN,insertions:u.number().nullable(),deletions:u.number().nullable()}),UN=u.object({sha:u.string(),shortSha:u.string(),subject:u.string(),authorName:u.string(),authoredAt:u.number()}),sw=u.object({insertions:u.number(),deletions:u.number(),files:u.array(NN)}),RN=sw.extend({hasUncommittedChanges:u.boolean(),state:zN}),AN=u.object({currentBranch:u.string().nullable(),defaultBranch:u.string()}),DN=sw.extend({mergeBaseBranch:u.string(),baseRef:u.string().nullable(),aheadCount:u.number(),behindCount:u.number(),hasCommittedUnmergedChanges:u.boolean(),commits:u.array(UN)}),l8=u.object({workingTree:RN,branch:AN,mergeBase:DN.nullable()}),u8=u.object({id:u.string(),content:u.array(jn).min(1),model:u.string().min(1),reasoningLevel:Lr,permissionMode:On,serviceTier:li,createdAt:u.number(),updatedAt:u.number()}),$N=u.object({id:u.string(),projectId:u.string(),environmentId:u.string().nullable(),automationId:u.string().nullable(),providerId:u.string(),type:ON,title:u.string().nullable(),titleFallback:u.string().nullable(),status:yp,parentThreadId:u.string().nullable(),archivedAt:u.number().nullable(),stopRequestedAt:u.number().nullable(),deletedAt:u.number().nullable(),lastReadAt:u.number().nullable(),latestAttentionAt:u.number(),createdAt:u.number(),updatedAt:u.number()}),MN=$N.extend({runtime:PN}),c8=MN.extend({hasPendingInteraction:u.boolean(),environmentHostId:u.string().nullable(),environmentBranchName:u.string().nullable(),environmentWorkspaceDisplayKind:qS});var d8=u.discriminatedUnion("type",[u.object({type:u.literal("uncommitted")}),u.object({type:u.literal("branch_committed"),mergeBaseBranch:u.string().min(1)}),u.object({type:u.literal("all"),mergeBaseBranch:u.string().min(1)}),u.object({type:u.literal("commit"),sha:u.string().regex(/^[0-9a-f]{4,40}$/iu)})]),p8=u.object({diff:u.string(),truncated:u.boolean(),shortstat:u.string(),files:u.string(),mergeBaseRef:u.string().nullable()});var f8=u.object({id:u.string(),scope:ui,threadId:u.string(),seq:u.number(),type:aw,data:u.record(u.string(),u.unknown()),createdAt:u.number()}),m8=new Set(["client/turn/requested"]),h8={kind:"new-turn"},g8=Ws.extend({target:pp.default(h8),execution:Ds});function v8(e){return g8.parse(e.data)}function y8(e){let{scope:t,threadId:n,type:i,...r}=e;return r}function b8(e){let{scope:t,turnId:n,...i}=e;return i}function LN(e){let t=ui.safeParse(e.scope);if(!t.success)throw new Error("Stored thread event is missing valid scope");let n=t.data,i=m8.has(e.type)?v8(e):e.data;return vp.parse({...b8(i),...e.providerThreadId!=null?{providerThreadId:e.providerThreadId}:{},scope:n,threadId:e.threadId,type:e.type})}function ZN(e){let{event:t,...n}=e;return{...n,type:t.type,data:y8(t)}}function _8(e){return ZN({id:e.id,scope:e.scope,threadId:e.threadId,seq:e.seq,createdAt:e.createdAt,event:LN({type:e.type,data:e.data,threadId:e.threadId,scope:e.scope})})}var S8=f8.transform(e=>_8(e));var w8=u.object({id:u.string(),text:u.string(),startedAt:u.number(),updatedAt:u.number()});var WN=u.enum(["pending","in_progress","completed"]),qN=u.object({id:u.string(),text:u.string(),status:WN}),k8=u.object({sourceSeq:u.number().int().nonnegative(),updatedAt:u.number(),items:u.array(qN)});var FN=["thread","project","environment","host","system"],lw=u.enum(FN);var VN=u.object({type:u.literal("subscribe"),entity:lw,id:u.string().optional()}),GN=u.object({type:u.literal("unsubscribe"),entity:lw,id:u.string().optional()}),x8=u.discriminatedUnion("type",[VN,GN]);var HN="item/permissions/requestApproval",KN="AskUserQuestion",YN="item/userQuestion/request",uw=u.enum(["default","acceptEdits","bypassPermissions","plan","dontAsk"]);var I8=u.object({toolName:u.string(),ruleContent:u.string().optional()}),cw=u.discriminatedUnion("type",[u.object({type:u.literal("addRules"),rules:u.array(I8).min(1),behavior:u.literal("allow"),destination:u.literal("session")}),u.object({type:u.literal("addDirectories"),directories:u.array(u.string()).min(1),destination:u.literal("session")})]),T8=u.object({enabled:u.boolean().nullable()}),P8=u.object({read:u.array(u.string()),write:u.array(u.string())}),E8=u.object({network:T8.nullable().optional(),fileSystem:P8.nullable().optional()}).transform(e=>({network:e.network??null,fileSystem:e.fileSystem??null})),O8=new Map([["Read","read"],["Grep","read"],["Glob","read"],["LS","read"],["Edit","write"],["Write","write"],["NotebookEdit","write"],["Bash","read_write"]]),j8=new Set(["WebFetch","WebSearch"]);function z8(e){return O8.get(e)??null}function C8(e){return(e??[]).flatMap(t=>t.type==="addDirectories"?t.directories:[])}function dw(e){let t=(e.suggestions??[]).some(s=>s.type==="addRules"),n=[...C8(e.suggestions),...e.blockedPath===void 0?[]:[e.blockedPath]],i=[...new Set(n)],r=z8(e.toolName),o=i.length===0?null:(()=>{switch(r){case"read":return{read:i,write:[]};case"write":return{read:[],write:i};case"read_write":case null:return{read:i,write:i}}})();return{network:j8.has(e.toolName)||t?{enabled:!0}:null,fileSystem:o}}function XN(e){return e.blockedPath!==void 0||e.decisionReason!==void 0||(e.suggestions?.length??0)>0}var Woe=u.object({threadId:u.string(),providerThreadId:u.string(),turnId:u.string().min(1).nullable(),itemId:u.string(),toolName:u.string(),input:u.record(u.string(),u.unknown()),reason:u.string().nullable(),permissions:E8}),N8=u.object({label:u.string().min(1),description:u.string().min(1),preview:u.string().optional()}),U8=u.object({question:u.string().min(1),header:u.string().min(1),options:u.array(N8).min(2).max(Ms),multiSelect:u.boolean()}),pw=u.array(U8).min(1).max($s).superRefine((e,t)=>{let n=new Set;e.forEach((i,r)=>{if(n.has(i.question)){t.addIssue({code:u.ZodIssueCode.custom,message:"Claude user-question prompts must be unique",path:[r,"question"]});return}n.add(i.question)})}),JN=u.object({questions:pw}),qoe=u.object({threadId:u.string(),providerThreadId:u.string(),turnId:u.string().min(1).nullable(),itemId:u.string(),questions:pw}),R8=u.object({preview:u.string().optional(),notes:u.string().optional()}),A8=u.object({questions:pw,answers:u.record(u.string().min(1),u.string().min(1)),annotations:u.record(u.string().min(1),R8).optional()}),BN=u.enum(["user_temporary","user_permanent","user_reject"]),D8=u.discriminatedUnion("behavior",[u.object({kind:u.literal("permission_request"),behavior:u.literal("allow"),updatedPermissions:u.array(cw).optional(),decisionClassification:BN.optional()}),u.object({kind:u.literal("permission_request"),behavior:u.literal("deny"),message:u.string(),interrupt:u.boolean().optional(),decisionClassification:BN.optional()})]),$8=u.object({kind:u.literal("user_question"),behavior:u.literal("allow"),updatedInput:A8}),QN=u.union([D8,$8]);var eU=u.enum(ip),tU=u.enum(op).nullable(),rU=u.enum(np),nU=u.array(u.string()).optional(),iU=u.object({name:u.string(),description:u.string(),inputSchema:u.unknown()}),M8=u.discriminatedUnion("method",[u.object({method:u.literal("initialize"),params:u.object({clientInfo:u.object({name:u.string(),version:u.string()})})}),u.object({method:u.literal("model/list"),params:u.object({})}),u.object({method:u.literal("thread/start"),params:u.object({threadId:u.string(),cwd:u.string(),baseInstructions:u.string(),additionalWorkspaceWriteRoots:nU,permissionMode:uw,permissionEscalation:tU,config:u.record(u.string(),u.unknown()).optional(),model:u.string().optional(),reasoningLevel:rU.optional(),instructionMode:eU,dynamicTools:u.array(iU).optional()})}),u.object({method:u.literal("thread/resume"),params:u.object({threadId:u.string(),cwd:u.string(),providerThreadId:u.string().nullable(),baseInstructions:u.string().optional(),additionalWorkspaceWriteRoots:nU,permissionMode:uw,permissionEscalation:tU,config:u.record(u.string(),u.unknown()).optional(),model:u.string().optional(),reasoningLevel:rU.optional(),instructionMode:eU,dynamicTools:u.array(iU).optional()})}),u.object({method:u.literal("turn/start"),params:u.object({threadId:u.string(),providerThreadId:u.string().nullable(),input:u.array(u.unknown()),model:u.string().optional(),config:u.record(u.string(),u.unknown()).optional()})}),u.object({method:u.literal("turn/steer"),params:u.object({threadId:u.string(),providerThreadId:u.string().nullable(),expectedTurnId:u.string(),input:u.array(u.unknown())})}),u.object({method:u.literal("thread/stop"),params:u.object({threadId:u.string()})})]);function oU(e){let t=fx.safeParse(e);if(!t.success)return null;let n=M8.safeParse({method:t.data.method,params:t.data.params??{}});return n.success?{...n.data,jsonrpc:"2.0",id:t.data.id}:null}import{accessSync as fU,constants as mU}from"node:fs";import{delimiter as gX,join as vX}from"node:path";var L8=new Set(["--no-optional-locks","--no-pager"]),Z8=new Set(["--ahead-behind","--branch","--ignored","--long","--no-ahead-behind","--porcelain","--porcelain=v1","--porcelain=v2","--short","-b","-s","-u","-uno"]),W8=new Set(["--","--cached","--check","--color","--compact-summary","--find-copies","--find-renames","--histogram","--ignore-all-space","--ignore-blank-lines","--ignore-space-at-eol","--ignore-space-change","--minimal","--name-only","--name-status","--no-color","--no-ext-diff","--no-textconv","--numstat","--patch","--patience","--shortstat","--stat","--summary","--word-diff","-M","-U0","-U1","-U2","-U3","-w"]),q8=new Set(["--","--color","--decorate","--format=full","--format=fuller","--format=medium","--format=oneline","--name-only","--name-status","--no-color","--no-ext-diff","--no-patch","--no-textconv","--numstat","--oneline","--patch","--shortstat","--stat","--summary","-1"]),F8=new Set(["--all","--fork-point","--independent","--is-ancestor","--octopus"]),V8=new Set(["--","--all","--color","--decorate","--format=full","--format=fuller","--format=medium","--format=oneline","--graph","--max-count=1","--name-only","--name-status","--no-color","--no-ext-diff","--no-textconv","--oneline","--shortstat","--stat","-1"]),G8=new Set(["--all","--current","--no-color","--remotes","--show-current","-a","-r"]),B8=new Set(["--contains","--merged","--no-contains","--no-merged"]),H8=new Set(["--","--cached","--deleted","--modified","--others","--stage","--unmerged","--with-tree","-d","-m","-o","-s","-u"]),K8=new Set(["--abbrev-ref","--absolute-git-dir","--git-common-dir","--git-dir","--is-inside-work-tree","--show-prefix","--show-toplevel","--short","--verify"]),Y8=new Set(["--","--break","--cached","--count","--files-with-matches","--heading","--ignore-case","--line-number","--name-only","--no-color","--untracked","-I","-c","-i","-l","-n"]),X8=new Set(["--","--abbrev","--date","--line-porcelain","--porcelain","--root","-L","-w"]),J8=/^[A-Za-z0-9_./:@%+=,-]+$/u,aU=/^-[1-9][0-9]*$/u,Q8=/^-U[0-9]+$/u,eX=/^--max-count=[1-9][0-9]*$/u,tX=/^--untracked-files=(all|normal|no)$/u,sU=/^--format=[A-Za-z0-9_./:@%+=,-]+$/u,lU=/^--abbrev=[0-9]+$/u,rX=/^--date=[A-Za-z0-9_./:@%+=,-]+$/u,nX=/^-L[0-9]+(,[0-9]+)?$/u,iX=["--no-ext-diff","--no-textconv"],oX=new Set(["diff","show","log"]),aX=u.object({command:u.string()}).passthrough();function sX(e){return e===".."||e.startsWith("../")||e.includes("/../")}function cU(e){return e.startsWith("/")||/^[A-Za-z]:\//u.test(e)}function lX(e){let t=e.trim().split(/\s+/u).filter(Boolean);if(t.length===0)return null;for(let n of t)if(!J8.test(n)||sX(n))return null;return t}function uX(e){return e==="--"||!e.startsWith("-")&&!cU(e)}function uU(e){return!e.startsWith("-")&&!cU(e)}function tn(e,t,n){for(let i of e)if(!uX(i)&&!t.has(i)&&!n?.(i))return!1;return!0}function cX(e){let t=0,n=!1;for(;t<e.length;){let i=e[t];if(!i)return!1;if(G8.has(i)){t+=1;continue}if(i==="--list"){n=!0,t+=1;continue}if(B8.has(i)){t+=1;let r=e[t];r&&uU(r)&&(t+=1);continue}if(n&&uU(i)){t+=1;continue}return!1}return!0}function dU(e){let t=1;for(;t<e.length;){let n=e[t];if(!n||!L8.has(n))break;t+=1}return t}function dX(e){if(e[0]!=="git")return!1;let t=dU(e),n=e[t];if(!n)return!1;let i=e.slice(t+1);switch(n){case"status":return tn(i,Z8,r=>tX.test(r));case"diff":return tn(i,W8,r=>Q8.test(r));case"show":return tn(i,q8,r=>aU.test(r)||sU.test(r));case"merge-base":return tn(i,F8);case"log":return tn(i,V8,r=>aU.test(r)||eX.test(r)||sU.test(r));case"branch":return cX(i);case"ls-files":return tn(i,H8);case"rev-parse":return tn(i,K8,r=>lU.test(r));case"grep":return tn(i,Y8);case"blame":return tn(i,X8,r=>lU.test(r)||rX.test(r)||nX.test(r));default:return!1}}function pX(e){let t=lX(e);return t?t[0]==="pwd"&&(t.length===1||t.length===2&&(t[1]==="-L"||t[1]==="-P"))?{needsNoOptionalGitLocks:!1,tokens:t}:dX(t)?{needsNoOptionalGitLocks:!t.includes("--no-optional-locks"),tokens:t}:null:null}function bp(e){let t=aX.safeParse(e);if(!t.success)return null;let n=pX(t.data.command);return n?{...t.data,command:fX(n)}:null}function fX(e){let t=e.needsNoOptionalGitLocks?mX(e.tokens):[...e.tokens];return hX(t).join(" ")}function mX(e){return[e[0],"--no-optional-locks",...e.slice(1)]}function hX(e){if(e[0]!=="git")return[...e];let t=dU(e),n=e[t];if(!n||!oX.has(n))return[...e];let i=e.slice(t+1),r=i.indexOf("--"),o=r===-1?i:i.slice(0,r),a=iX.filter(s=>!o.includes(s));return a.length===0?[...e]:[...e.slice(0,t+1),...a,...e.slice(t+1)]}var yX=new Set(["Agent","Glob","Grep","LS","Read","TodoRead"]),bX="Bash",_X={type:"adaptive",display:"summarized"},pU="BB_CLAUDE_CODE_EXECUTABLE";function fw(){return"bb readonly mode allows reading and analysis only. Continue with a read-only answer; do not modify files, run mutating shell commands, use network, or use mutating tools."}function hU(){return"bb workspace-write mode allows work inside the current workspace only. Stay inside the workspace or explain why extra access is needed."}function SX(e){if(e.permissionMode!=="default"&&e.permissionMode!=="dontAsk")return;let t=e.permissionEscalation==="deny"?"deny":"ask",n=t==="deny"?fw():"bb readonly mode requires approval before using tools that can modify state, run commands, access network, or perform non-read actions.";return{PreToolUse:[{hooks:[async i=>{if(i.hook_event_name!=="PreToolUse"||yX.has(i.tool_name))return{continue:!0};if(i.tool_name===bX){let r=bp(i.tool_input);if(r)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:r}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:n}}}]}]}}function wX(e){if(e.permissionMode!=="acceptEdits")return;let t=e.additionalWorkspaceWriteRoots??[];return{enabled:!0,autoAllowBashIfSandboxed:!0,allowUnsandboxedCommands:e.permissionEscalation==="ask",...t.length>0?{filesystem:{allowWrite:[...t]}}:{}}}function kX(e){if(!e.pathEnv)return null;for(let t of e.pathEnv.split(gX)){if(!t)continue;let n=vX(t,e.executableName);try{return fU(n,mU.X_OK),n}catch{continue}}return null}function xX(e){let n=e.env[pU]?.trim();if(n&&n.length>0)try{return fU(n,mU.X_OK),n}catch{throw new Error(`${pU} must point to an executable Claude CLI path: ${n}`)}return kX({executableName:"claude",pathEnv:e.env.PATH})}function _p(e,t){let n=e.instructionMode==="replace"?e.baseInstructions??"You are a helpful coding assistant.":{type:"preset",preset:"claude_code",...e.baseInstructions&&e.baseInstructions.length>0?{append:e.baseInstructions}:{}},i=e.model,r=wX(e),o=SX(e),a=e.permissionMode==="acceptEdits"?e.additionalWorkspaceWriteRoots??[]:[],s=xX({env:t});return{cwd:e.cwd,systemPrompt:n,model:i,env:t,permissionMode:e.permissionMode,...e.reasoningLevel?{effort:e.reasoningLevel}:{},...e.reasoningLevel?{thinking:_X}:{},...s?{pathToClaudeCodeExecutable:s}:{},...r?{sandbox:r}:{},...o?{hooks:o}:{},...a.length>0?{additionalDirectories:[...a]}:{}}}var Fs="bb-bridge";function mw(e,t){let n=e.map(i=>S1(i.name,i.description,IX(i.inputSchema),async r=>{let o=await t(i.name,r);return{content:[{type:"text",text:o.content}],...o.isError?{isError:!0}:{}}}));return w1({name:Fs,version:"1.0.0",tools:n})}function hw(e){return e.map(t=>`mcp__${Fs}__${t.name}`)}function IX(e){if(!e||typeof e!="object"||!("properties"in e))return{};let t=e;if(!t.properties)return{};let n={};for(let[i,r]of Object.entries(t.properties))switch(r?.type){case"string":n[i]=u.string().optional();break;case"number":case"integer":n[i]=u.number().optional();break;case"boolean":n[i]=u.boolean().optional();break;default:n[i]=u.unknown().optional();break}return n}var EX=u.object({type:u.literal("text"),text:u.string()}),OX=u.object({result:u.string()}).passthrough(),wt=new Map,gw=new Map,vU=0,Do=0,jX=4e3;function yU(e){return xU(e)}function zX(e,t){let n=yU(e),i=yU(t);if(n===i)return!0;let r=n.endsWith("/")?n:`${n}/`;return i.startsWith(r)}function bU(e,t){return t.every(n=>e.some(i=>zX(i,n)))}function CX(e,t){if(t===null)return!0;if(e===null)return!1;let n=[...e.read,...e.write];return bU(n,t.read)&&bU(e.write,t.write)}function NX(e,t){return t?.enabled===!0?e?.enabled===!0:!0}function UX(e){return e.grant.toolName!==null&&e.grant.toolName!==e.toolName?!1:NX(e.grant.permissions.network,e.permissions.network)&&CX(e.grant.permissions.fileSystem,e.permissions.fileSystem)}function RX(e){return e.grants.some(t=>UX({grant:t,permissions:e.permissions,toolName:e.toolName}))}function AX(e){return e.kind==="permission_request"&&e.behavior==="allow"&&(e.decisionClassification==="user_permanent"||e.updatedPermissions!==void 0)}function Cn(e){process.stdout.write(JSON.stringify(e)+`
138
+ `):e.streamInput(n).catch(r=>i.abort(r))}var D3=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function H1(e){for(let t=0;;t++)try{return await p$(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!D3.has(to(n)??""))return;await ZT((t+1)*100)}}function $3(e,t){e.waitForExit().catch(()=>{}).finally(()=>H1(t))}function K1({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore){let{queryInstance:o,transport:a,abortController:s,processEnv:l}=vT({...t},typeof e=="string",void 0,!0),c=ic(t.cwd??"."),d=t.sessionStore,f=t.loadTimeoutMs??6e4,h=t.resume;return(async()=>{if(h||(h=(await Ha(d.listSessions(Y1(c)),f,`SessionStore.listSessions() timed out after ${f}ms`)).slice().sort((m,_)=>_.mtime-m.mtime)[0]?.sessionId),!!h)return A3(d,h,c,t.env,t.loadTimeoutMs)})().then(m=>{m&&(a.updateResume(h),a.updateEnv({CLAUDE_CONFIG_DIR:m}),l.CLAUDE_CONFIG_DIR=m,o.addCleanupCallback(()=>$3(a,m))),o.isClosed()||a.spawn()}).catch(m=>{let _=wd(m);a.spawnAbort(_),o.setError(_)}),yT(o,a,e,s),o}let{queryInstance:n,transport:i,abortController:r}=vT(t,typeof e=="string");return yT(n,i,e,r),n}function M3(e){let t=ic(e??"."),n;try{n=u$(t)}catch{n=t}return n.normalize("NFC")}function Y1(e){return HW(M3(e))}function L3(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function bT(e,t){let n=h$(t,e),i=n.split(MT);if(i[0]===".."||$T(n)||i.length<2)return null;let r=i[0],o=i[1];if(i.length===2&&o.endsWith(".jsonl"))return{projectKey:r,sessionId:o.replace(/\.jsonl$/,"")};if(i.length>=4){let a=i.slice(2),s=a.length-1;return a[s]=a.at(-1).replace(/\.jsonl$/,""),{projectKey:r,sessionId:o,subpath:a.join("/")}}return null}var Kd=class{constructor(t,n,i){this.options=t;this.onMessage=n;this.onDone=i;this.completion=new Promise(r=>{this.complete=r})}options;onMessage;onDone;query;sessionId;inputResolve=null;inputQueue=[];inputDone=!1;abortController=new AbortController;isProcessing=!1;completion;complete=null;getSessionId(){return this.sessionId}getIsProcessing(){return this.isProcessing}start(t){t?this.sessionId=t:this.options.sessionId&&(this.sessionId=this.options.sessionId);let n={abortController:this.abortController,cwd:this.options.cwd,systemPrompt:this.options.systemPrompt,permissionMode:this.options.permissionMode??"default",includePartialMessages:!0,settingSources:["user","project","local"],persistSession:!0,env:this.options.env??process.env,...this.options.mcpServers?{mcpServers:this.options.mcpServers}:{},...this.options.allowedTools?{allowedTools:this.options.allowedTools}:{},...this.options.disallowedTools?{disallowedTools:this.options.disallowedTools}:{},...this.options.tools?{tools:this.options.tools}:{},...this.options.canUseTool?{canUseTool:this.options.canUseTool}:{},...this.options.sandbox?{sandbox:this.options.sandbox}:{},...this.options.hooks?{hooks:this.options.hooks}:{},...this.options.permissionMode==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},...t?{resume:t}:{},...!t&&this.options.sessionId?{sessionId:this.options.sessionId}:{},...this.options.model?{model:this.options.model}:{},...this.options.additionalDirectories?{additionalDirectories:[...this.options.additionalDirectories]}:{},...this.options.effort?{effort:this.options.effort}:{},...this.options.pathToClaudeCodeExecutable?{pathToClaudeCodeExecutable:this.options.pathToClaudeCodeExecutable}:{},...this.options.thinking?{thinking:this.options.thinking}:{}};this.query=K1({prompt:this.createInputIterable(),options:n}),this.consumeStream()}pushInput(t){let n={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:this.sessionId??""};if(!this.inputDone){if(this.inputResolve){let i=this.inputResolve;this.inputResolve=null,i({value:n,done:!1});return}this.inputQueue.push(n)}}stop(){this.inputDone=!0,this.resolveInputDone(),this.abortController.abort(),this.query?.close(),this.query=void 0,this.isProcessing=!1}async closeGracefully(t){if(this.inputDone=!0,this.resolveInputDone(),!this.query)return;let n;try{await Promise.race([this.completion,new Promise((i,r)=>{n=setTimeout(()=>{r(new Error(`Claude SDK session did not close within ${t}ms`))},t)})])}catch{this.stop()}finally{n&&clearTimeout(n)}}createInputIterable(){let t=this;return{[Symbol.asyncIterator](){return{async next(){if(t.inputQueue.length>0){let n=t.inputQueue.shift();return n?{value:n,done:!1}:{value:void 0,done:!0}}return t.inputDone?{value:void 0,done:!0}:new Promise(n=>{t.inputResolve=n})},async return(){return t.inputDone=!0,t.resolveInputDone(),{value:void 0,done:!0}}}}}}resolveInputDone(){if(!this.inputResolve)return;let t=this.inputResolve;this.inputResolve=null,t({value:void 0,done:!0})}async consumeStream(){let t=this.query;if(t)try{for await(let n of t)this.captureSessionId(n),this.trackProcessingState(n),this.onMessage(n);this.isProcessing=!1,this.onDone()}catch(n){this.isProcessing=!1,this.onDone(n)}finally{this.query=void 0,this.complete&&(this.complete(),this.complete=null)}}captureSessionId(t){let{session_id:n}=t,i=n?.trim()??"";i.length>0&&(this.sessionId=i)}trackProcessingState(t){(t.type==="assistant"||t.type==="stream_event")&&(this.isProcessing=!0),t.type==="result"&&(this.isProcessing=!1)}};var Rre=u.object({command:u.string().optional(),cwd:u.string().optional()}).passthrough(),Z3=u.object({type:u.literal("text"),text:u.string()}),W3=u.object({content:u.array(u.unknown())}).passthrough();var As={reasoningEffort:"low",description:"Low reasoning effort"},Yd={reasoningEffort:"medium",description:"Medium reasoning effort"},Xd={reasoningEffort:"high",description:"High reasoning effort"},X1={reasoningEffort:"xhigh",description:"Extra high reasoning effort"},qre=u.string().regex(/^[A-Z_][A-Z0-9_]*$/i);var J1=[As,Yd,Xd,X1],tp=[As,Yd,Xd],rp=[As,Yd,Xd],tC=[As],Jd="claude-opus-4-7",Qd="claude-opus-4-6",ep="claude-sonnet-4-6",Q1="claude-haiku-4-5";function Ro(e){return`${e}[1m]`}var q3=[{id:Ro(Jd),model:Ro(Jd),displayName:"Opus 4.7 (1M)",description:"Opus 4.7 with 1M context for complex long coding sessions",supportedReasoningEfforts:J1,defaultReasoningEffort:"medium"},{id:Jd,model:Jd,displayName:"Opus 4.7",description:"Opus 4.7 for complex coding tasks",supportedReasoningEfforts:J1,defaultReasoningEffort:"medium"},{id:Ro(Qd),model:Ro(Qd),displayName:"Opus 4.6 (1M)",description:"Opus 4.6 with 1M context for complex long coding sessions",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:Qd,model:Qd,displayName:"Opus 4.6",description:"Opus 4.6 for complex coding tasks",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:Ro(ep),model:Ro(ep),displayName:"Sonnet 4.6 (1M)",description:"Sonnet 4.6 with 1M context for long coding sessions",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:ep,model:ep,displayName:"Sonnet 4.6",description:"Sonnet 4.6 for everyday coding tasks",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:Q1,model:Q1,displayName:"Haiku 4.5",description:"Haiku 4.5 for quick answers",supportedReasoningEfforts:tC,defaultReasoningEffort:"low"}],F3=[{id:"opus[1m]",model:"opus[1m]",displayName:"Opus Alias (1M, Legacy)",description:"Legacy moving Opus 1M alias retained for existing selections",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:"opus",model:"opus",displayName:"Opus Alias (Legacy)",description:"Legacy moving Opus alias retained for existing selections",supportedReasoningEfforts:tp,defaultReasoningEffort:"medium"},{id:"sonnet[1m]",model:"sonnet[1m]",displayName:"Sonnet Alias (1M, Legacy)",description:"Legacy moving Sonnet 1M alias retained for existing selections",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:"sonnet",model:"sonnet",displayName:"Sonnet Alias (Legacy)",description:"Legacy moving Sonnet alias retained for existing selections",supportedReasoningEfforts:rp,defaultReasoningEffort:"medium"},{id:"haiku",model:"haiku",displayName:"Haiku Alias (Legacy)",description:"Legacy moving Haiku alias retained for existing selections",supportedReasoningEfforts:tC,defaultReasoningEffort:"low"}];function V3(e){return e.map(t=>({...t}))}function eC(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,supportedReasoningEfforts:V3(e.supportedReasoningEfforts),defaultReasoningEffort:e.defaultReasoningEffort,isDefault:!1}}function G3(e){return e.map((t,n)=>n===0?{...t,isDefault:!0}:t)}function rC(){return{models:G3(q3.map(eC)),selectedOnlyModels:F3.map(eC)}}async function nC(){return rC()}var np=["low","medium","high","xhigh"],Lr=u.enum(np),li=u.enum(["fast","default"]),ip=["append","replace"],B3=u.enum(ip),iC=["full","workspace-write","readonly"],On=u.enum(iC),op=["ask","deny"],AS=u.enum(op),jn=u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("image"),url:u.string().url()}),u.object({type:u.literal("localImage"),path:u.string()}),u.object({type:u.literal("localFile"),path:u.string(),name:u.string().optional(),sizeBytes:u.number().int().nonnegative().optional(),mimeType:u.string().optional()})]),DS=u.enum(["client/thread/start","client/turn/requested","client/turn/start"]),oC=u.object({model:u.string().optional(),serviceTier:li.optional(),reasoningLevel:Lr.optional(),permissionMode:On.optional(),source:DS.optional(),seq:u.number().int().optional()}),Ds=oC.extend({model:u.string().min(1),serviceTier:li,reasoningLevel:Lr,permissionMode:On,source:DS}),aC=u.discriminatedUnion("permissionMode",[u.object({permissionMode:u.literal("full"),permissionEscalation:u.null()}),u.object({permissionMode:u.literal("workspace-write"),permissionEscalation:AS}),u.object({permissionMode:u.literal("readonly"),permissionEscalation:AS})]),H3=u.object({model:u.string().min(1),serviceTier:li,reasoningLevel:Lr}),K3=H3.and(aC),Y3=u.object({providerId:u.string().min(1),model:u.string().min(1),serviceTier:li,reasoningLevel:Lr,permissionMode:On});var X3=u.object({askUserQuestion:u.boolean(),terminals:u.boolean()});var sC=500,lC=200,ap=64*1024,uC=Math.ceil(ap/3)*4,J3=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,cC=["starting","running","disconnected","exited"],Q3=u.enum(cC),dC=["user","process-exit","daemon-disconnect","environment-destroyed","thread-archived","thread-deleted","open-timeout"],e5=u.enum(dC);function pC(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return e.length/4*3-t}var t5=u.number().int().positive().max(sC),r5=u.number().int().positive().max(lC),n5=u.string().min(1).max(uC).regex(J3).refine(e=>pC(e)<=ap,{message:`Terminal data must decode to ${ap} bytes or less`});var fC=["project","thread"],i5=u.enum(fC),o5=u.object({id:u.string().min(1),createdAt:u.number(),input:u.array(jn).min(1)});var Ls=u.enum(["pending","resolving","resolved","interrupted","expired"]),hC=u.discriminatedUnion("type",[u.object({type:u.literal("read"),command:u.string(),name:u.string(),path:u.string()}),u.object({type:u.literal("listFiles"),command:u.string(),path:u.string().nullable()}),u.object({type:u.literal("search"),command:u.string(),query:u.string().nullable(),path:u.string().nullable()}),u.object({type:u.literal("unknown"),command:u.string()})]),LS=u.object({enabled:u.boolean().nullable()}),ZS=u.object({read:u.array(u.string()),write:u.array(u.string())}),a5=u.enum(["none","read_only","read_write"]),s5=u.enum(["none","read_only","read_write"]),l5=u.union([u.literal("none"),u.literal("all"),u.object({kind:u.literal("bundle_ids"),bundleIds:u.array(u.string())})]),gC=u.object({preferences:a5,automations:l5,launchServices:u.boolean(),accessibility:u.boolean(),calendar:u.boolean(),reminders:u.boolean(),contacts:s5}),u5=u.object({network:LS.nullable(),fileSystem:ZS.nullable(),macos:gC.nullable()}),Zs=u.object({network:LS.nullable(),fileSystem:ZS.nullable()}).strict(),mC=Zs,vC=u.enum(["allow_once","allow_for_session","deny"]),c5=u.string().min(1),yC=u.object({kind:u.literal("command"),itemId:u.string().min(1),command:u.string().min(1),cwd:u.string().nullable(),actions:u.array(hC),sessionGrant:Zs.nullable()}),bC=u.object({kind:u.literal("file_change"),itemId:u.string().min(1),writeScope:c5.nullable(),sessionGrant:Zs.nullable()}),sp=u.object({kind:u.literal("permission_grant"),itemId:u.string().min(1),toolName:u.string().nullable(),permissions:Zs}),_C=u.discriminatedUnion("kind",[yC,bC,sp]),SC=u.object({kind:u.literal("approval"),subject:_C,reason:u.string().nullable(),availableDecisions:u.array(vC).min(1)}),$s=4,Ms=4,$S=4,MS=4096,d5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question ids cannot be blank"}),p5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question prompts cannot be blank"}),f5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question short labels cannot be blank"}),m5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question option values cannot be blank"}),h5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question option labels cannot be blank"}),g5=u.string().min(1).refine(e=>e.trim().length>0,{message:"User question option descriptions cannot be blank"}),v5=u.string().min(1).max(MS,`User question free text cannot exceed ${MS} characters`).refine(e=>e.trim().length>0,{message:"User question free text cannot be blank"}),wC=u.object({value:m5,label:h5,description:g5.optional()}),kC=u.object({id:d5,prompt:p5,shortLabel:f5.optional(),multiSelect:u.boolean(),options:u.array(wC).max(Ms,`User questions cannot include more than ${Ms} options`).optional(),allowFreeText:u.boolean()}).superRefine((e,t)=>{let n=new Set;e.options?.forEach((i,r)=>{if(n.has(i.value)){t.addIssue({code:u.ZodIssueCode.custom,message:"User question option values must be unique",path:["options",r,"value"]});return}n.add(i.value)})}).refine(e=>e.allowFreeText||(e.options?.length??0)>0,{message:"User questions must allow free text or provide at least one option",path:["options"]}),lp=u.object({kind:u.literal("user_question"),questions:u.array(kC).min(1).max($s,`User questions cannot include more than ${$s} questions`)}).superRefine((e,t)=>{let n=new Set;e.questions.forEach((i,r)=>{if(n.has(i.id)){t.addIssue({code:u.ZodIssueCode.custom,message:"User question ids must be unique",path:["questions",r,"id"]});return}n.add(i.id)})}),WS=u.discriminatedUnion("kind",[SC,lp]);var xC="Invalid discriminator value. Expected 'allow_once' | 'allow_for_session' | 'deny'",up=u.discriminatedUnion("decision",[u.object({decision:u.literal("allow_once"),grantedPermissions:mC.nullable()}),u.object({decision:u.literal("allow_for_session"),grantedPermissions:mC.nullable()}),u.object({decision:u.literal("deny")})],xC),IC=u.object({selected:u.array(u.string().min(1)).max($S,`User question selected choices cannot exceed ${$S}`),freeText:v5.optional()}),cp=u.object({kind:u.literal("user_answer"),answers:u.record(u.string().min(1),IC)}),TC=u.union([up,cp],xC);var y5=u.object({threadId:u.string().min(1),turnId:u.string().min(1),providerId:u.string().min(1),providerThreadId:u.string().min(1),providerRequestId:u.string().min(1),payload:WS}),b5=u.object({id:u.string().min(1),threadId:u.string().min(1),turnId:u.string().min(1),providerId:u.string().min(1),providerThreadId:u.string().min(1),providerRequestId:u.string().min(1),status:Ls,payload:WS,resolution:TC.nullable(),statusReason:u.string().nullable(),createdAt:u.number().int().nonnegative(),resolvedAt:u.number().int().nonnegative().nullable()});var PC=u.object({reasoningEffort:Lr,description:u.string()}),_5=u.object({id:u.string(),model:u.string(),displayName:u.string(),description:u.string(),supportedReasoningEfforts:u.array(PC),defaultReasoningEffort:Lr,isDefault:u.boolean()}),EC=u.object({supportsArchive:u.boolean(),supportsRename:u.boolean(),supportsServiceTier:u.boolean(),supportsUserQuestion:u.boolean(),supportedPermissionModes:u.array(On).min(1)}),S5=u.object({id:u.string(),displayName:u.string(),capabilities:EC,available:u.boolean()}),OC=u.discriminatedUnion("type",[u.object({type:u.literal("inputText"),text:u.string()}),u.object({type:u.literal("inputImage"),imageUrl:u.string()})]),w5=u.object({requestId:u.union([u.string().min(1),u.number()]),threadId:u.string().min(1),providerThreadId:u.string().min(1),turnId:u.string().min(1),callId:u.string().min(1),tool:u.string().min(1),arguments:u.unknown().optional()}),k5=u.object({contentItems:u.array(OC),success:u.boolean()}),x5=u.object({text:u.string().trim().min(1).optional(),message:u.string().trim().min(1).optional()}).refine(e=>e.text!==void 0||e.message!==void 0,"message_user requires text").transform(e=>({text:e.text??e.message??""})),I5=u.object({name:u.string(),description:u.string(),inputSchema:u.unknown()});var jC=["provisioning","ready","error","destroying","destroyed"],zC=u.enum(jC),T5=["safe"],CC=u.enum(T5),NC=["unmanaged","managed-worktree"],UC=u.enum(NC),RC=["managed-worktree","unmanaged-worktree","other"],qS=u.enum(RC);var P5=u.object({path:u.string().min(1),isGitRepo:u.boolean(),isWorktree:u.boolean(),branchName:u.string().nullable(),defaultBranch:u.string().nullable()}),E5=u.object({id:u.string(),projectId:u.string(),hostId:u.string(),path:u.string().nullable(),managed:u.boolean(),isGitRepo:u.boolean(),isWorktree:u.boolean(),workspaceProvisionType:UC,branchName:u.string().nullable(),baseBranch:u.string().nullable(),defaultBranch:u.string().nullable(),mergeBaseBranch:u.string().nullable(),cleanupRequestedAt:u.number().nullable(),cleanupMode:CC.nullable(),status:zC,createdAt:u.number(),updatedAt:u.number()});var O5=u.string().regex(/^hdevt_[23456789abcdefghijkmnpqrstuvwxyz]{20}$/u),Ao=u.string().regex(/^creq_[23456789abcdefghijkmnpqrstuvwxyz]{10}$/u);var zn=u.lazy(()=>u.union([u.string(),u.number(),u.boolean(),u.null(),u.array(zn),u.record(u.string(),zn)]));var dp=["client/thread/start","client/turn/requested","client/turn/start","system/error","system/manager/user_message","system/thread/interrupted","system/operation","system/permissionGrant/lifecycle","system/userQuestion/lifecycle","system/thread-provisioning"],j5=u.enum(dp),AC=["user","agent","system"],FS=u.enum(AC),VS=["thread-created","boot-created-thread","tell-after-provisioning-failure","tell-after-missing-environment-attachment","resume-missing-provider-thread"],z5=u.enum(VS),DC=[...VS,"boot-active-resume","resume-existing-provider-session"],C5=u.enum(DC),$C=Ds,pp=u.discriminatedUnion("kind",[u.object({kind:u.literal("thread-start")}),u.object({kind:u.literal("new-turn")}),u.object({kind:u.literal("auto"),expectedTurnId:u.string().nullable()}),u.object({kind:u.literal("steer"),expectedTurnId:u.string().nullable()})]),fp=u.object({direction:u.literal("outbound"),source:u.enum(["spawn","tell"]),initiator:FS.optional(),request:u.object({method:u.enum(["thread/start","turn/start"]),params:u.record(u.string(),u.unknown())})}),Ws=u.object({direction:u.literal("outbound"),requestId:Ao,source:u.enum(["spawn","tell"]),initiator:FS.optional(),input:u.array(jn),target:pp,request:u.object({method:u.enum(["thread/start","turn/start"]),params:u.record(u.string(),u.unknown())}),execution:$C}),GS=u.object({code:u.string().optional(),message:u.string(),detail:u.string().optional(),reconnectAttempt:u.number().int().positive().optional(),reconnectTotal:u.number().int().positive().optional()}).superRefine((e,t)=>{let n=e.reconnectAttempt!==void 0,i=e.reconnectTotal!==void 0;if(n!==i){t.addIssue({code:u.ZodIssueCode.custom,message:"system/error reconnectAttempt and reconnectTotal must be provided together"});return}e.reconnectAttempt!==void 0&&e.reconnectTotal!==void 0&&e.reconnectAttempt>e.reconnectTotal&&t.addIssue({code:u.ZodIssueCode.custom,message:"system/error reconnectAttempt cannot be greater than reconnectTotal"})}),MC=["assign","release","transfer"],LC=u.enum(MC),N5=u.object({action:LC,nextParentThreadId:u.string().nullable(),nextParentThreadTitle:u.string().nullable(),previousParentThreadId:u.string().nullable(),previousParentThreadTitle:u.string().nullable()}),BS=u.object({operation:u.string(),status:u.string(),message:u.string(),operationId:u.string(),metadata:u.record(u.string(),zn).optional()}),HS=u.object({interactionId:u.string(),providerId:u.string(),providerRequestId:u.string(),status:Ls,resolution:up.nullable().default(null),statusReason:u.string().nullable().default(null),subject:sp}),KS=u.object({interactionId:u.string(),providerId:u.string(),providerRequestId:u.string(),status:Ls,resolution:cp.nullable().default(null),statusReason:u.string().nullable().default(null),payload:lp}),ZC=["manual-stop","host-daemon-restarted"],WC=u.enum(ZC),YS=u.object({reason:WC}),qC=u.object({type:u.enum(["step","output"]),key:u.string(),text:u.string(),startedAt:u.number().optional(),status:u.enum(["started","completed","failed"]).optional(),metadata:u.record(u.string(),u.unknown()).optional()}),FC=["active","completed","failed"],VC=u.enum(FC),XS=u.object({provisioningId:u.string(),status:VC,environmentId:u.string(),entries:u.array(qC)}),JS=u.object({text:u.string(),toolCallId:u.string().optional(),turnId:u.string().optional()}),U5=u.object({turnId:u.string().optional(),input:u.array(jn).optional()});var GC=["thread","turn"],R5=u.enum(GC),ui=u.discriminatedUnion("kind",[u.object({kind:u.literal("thread")}),u.object({kind:u.literal("turn"),turnId:u.string().min(1)})]),BC=["thread","turn","thread-or-turn"],A5=u.enum(BC),HC={"thread/started":{policy:"thread",rationale:"Thread lifecycle event; it creates the thread timeline itself."},"thread/identity":{policy:"thread",rationale:"Thread metadata event; it identifies the provider thread outside turn chronology."},"turn/started":{policy:"turn"},"turn/completed":{policy:"turn"},"turn/input/accepted":{policy:"turn"},"thread/name/updated":{policy:"thread",rationale:"Thread metadata event; names are not part of a specific turn transcript."},"thread/compacted":{policy:"turn"},"item/started":{policy:"turn"},"item/completed":{policy:"turn"},"item/agentMessage/delta":{policy:"turn"},"item/commandExecution/outputDelta":{policy:"turn"},"item/fileChange/outputDelta":{policy:"turn"},"item/reasoning/summaryTextDelta":{policy:"turn"},"item/reasoning/textDelta":{policy:"turn"},"item/plan/delta":{policy:"turn"},"item/mcpToolCall/progress":{policy:"turn"},"item/toolCall/progress":{policy:"turn"},"thread/tokenUsage/updated":{policy:"turn"},"thread/contextWindowUsage/updated":{policy:"turn"},"turn/plan/updated":{policy:"turn"},"turn/diff/updated":{policy:"turn"},"provider/error":{policy:"thread-or-turn",rationale:"Provider diagnostics use thread scope for provider setup/session failures; in-turn failures use turn scope."},"provider/warning":{policy:"thread-or-turn",rationale:"Provider warnings use thread scope for config, deprecation, or global notices; turn-specific warnings use turn scope."},"provider/unhandled":{policy:"thread-or-turn",rationale:"Unhandled provider events use thread scope only when no active turn context exists; in-turn unknown events use turn scope."},"client/thread/start":{policy:"thread",rationale:"Outbound client lifecycle event; it requests thread creation before any turn exists."},"client/turn/requested":{policy:"thread",rationale:"Outbound client lifecycle event; it records the request before provider turn acceptance."},"client/turn/start":{policy:"thread",rationale:"Outbound client lifecycle event; it records the start request before provider turn acceptance."},"system/error":{policy:"thread-or-turn",rationale:"System errors use thread scope for app, daemon, or session failures outside a turn; turn failures use turn scope."},"system/manager/user_message":{policy:"thread-or-turn",rationale:"Manager messages can be thread-scoped for general manager updates or turn-scoped for in-turn updates."},"system/thread/interrupted":{policy:"thread",rationale:"Thread stop lifecycle event; it represents user interruption of the whole running thread."},"system/operation":{policy:"thread",rationale:"Thread-management operation event; ownership and lifecycle operations are not turn transcript content."},"system/permissionGrant/lifecycle":{policy:"turn"},"system/userQuestion/lifecycle":{policy:"turn"},"system/thread-provisioning":{policy:"thread",rationale:"Workspace provisioning lifecycle event; environment setup belongs to the thread, not a turn."}};function QS(){return Object.entries(HC).map(([e,t])=>({type:e,definition:t}))}function ew(e){return QS().filter(t=>t.definition.policy===e).map(t=>t.type)}function D5(){let e={};for(let t of QS())e[t.type]=t.definition.policy;return e}function M5(){let e={};for(let t of QS())t.definition.rationale&&(e[t.type]=t.definition.rationale);return e}var L5=ew("turn"),Z5=ew("thread"),W5=ew("thread-or-turn"),KC=D5(),q5=M5();function tw(e){let t=KC[e.type];return t==="thread-or-turn"?{valid:!0}:t!==e.scope.kind?{valid:!1,message:`${e.type} requires ${t} scope but received ${e.scope.kind} scope`}:{valid:!0}}var hp=u.enum(["pending","completed","failed","interrupted"]),YC=u.enum(["waiting_for_approval","denied"]).nullable(),JC=u.enum(["completed","failed","interrupted"]),QC=u.enum(["add","delete","update"]),eN=u.object({path:u.string(),kind:QC,movePath:u.string().optional(),diff:u.string().optional()}),tN=u.enum(["pending","active","completed","failed"]),rN=u.object({step:u.string(),status:tN.optional()}),nN=u.object({type:u.literal("webSearch"),id:u.string(),queries:u.array(u.string()).min(1),resultText:u.string().nullable(),parentToolCallId:u.string().optional()}),iN=u.object({type:u.literal("webFetch"),id:u.string(),url:u.string(),prompt:u.string().nullable(),pattern:u.string().nullable(),resultText:u.string().nullable(),parentToolCallId:u.string().optional()}),gp=u.object({originalLength:u.number(),retainedHeadLength:u.number(),retainedTailLength:u.number(),truncatedAt:u.number()}),rw=u.object({aggregatedOutput:gp.optional(),result:gp.optional(),resultText:gp.optional()}),oN=u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("image"),url:u.string()}),u.object({type:u.literal("localImage"),path:u.string()}),u.object({type:u.literal("localFile"),path:u.string()})]),nw=u.object({totalTokens:u.number(),inputTokens:u.number(),cachedInputTokens:u.number(),outputTokens:u.number(),reasoningOutputTokens:u.number()}),aN=u.object({usedTokens:u.number().nullable(),modelContextWindow:u.number().nullable(),estimated:u.boolean()}),sN=u.object({total:nw,last:nw,modelContextWindow:u.number().nullable()}),lN=u.enum(["deprecation","config","general"]),uN=u.object({jsonrpc:u.literal("2.0"),id:u.union([u.string(),u.number()]).optional(),method:u.string(),params:zn.optional()}),F5=u.object({type:u.literal("provider/unhandled"),threadId:u.string(),providerThreadId:u.string(),providerId:u.string(),rawType:u.string(),rawEvent:uN,parentToolCallId:u.string().optional()}),V5=u.object({type:u.literal("item/toolCall/progress"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),message:u.string().optional(),parentToolCallId:u.string().optional()}),iw=u.discriminatedUnion("type",[u.object({type:u.literal("userMessage"),id:u.string(),content:u.array(oN),clientRequestId:Ao.optional(),parentToolCallId:u.string().optional()}).strict(),u.object({type:u.literal("agentMessage"),id:u.string(),text:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("commandExecution"),id:u.string(),command:u.string(),cwd:u.string(),status:hp,approvalStatus:YC,aggregatedOutput:u.string().optional(),exitCode:u.number().optional(),durationMs:u.number().optional(),truncation:rw.optional(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("fileChange"),id:u.string(),changes:u.array(eN),status:hp,approvalStatus:YC,parentToolCallId:u.string().optional()}),nN,iN,u.object({type:u.literal("toolCall"),id:u.string(),server:u.string().optional(),tool:u.string(),arguments:u.record(u.string(),u.unknown()).optional(),status:hp,result:u.unknown().optional(),error:u.string().optional(),durationMs:u.number().optional(),truncation:rw.optional(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("reasoning"),id:u.string(),summary:u.array(u.string()),content:u.array(u.string()),parentToolCallId:u.string().optional()}),u.object({type:u.literal("plan"),id:u.string(),text:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("contextCompaction"),id:u.string(),parentToolCallId:u.string().optional()})]),cN=u.discriminatedUnion("type",[u.object({type:u.literal("thread/started"),threadId:u.string()}),u.object({type:u.literal("thread/identity"),threadId:u.string(),providerThreadId:u.string()}),u.object({type:u.literal("turn/started"),threadId:u.string(),providerThreadId:u.string()}),u.object({type:u.literal("turn/completed"),threadId:u.string(),providerThreadId:u.string().nullable(),status:JC,error:u.object({message:u.string()}).optional()}),u.object({type:u.literal("turn/input/accepted"),threadId:u.string(),providerThreadId:u.string(),clientRequestId:Ao,scope:ui}).strict(),u.object({type:u.literal("thread/name/updated"),threadId:u.string(),providerThreadId:u.string(),threadName:u.string()}),u.object({type:u.literal("thread/compacted"),threadId:u.string(),providerThreadId:u.string()}),u.object({type:u.literal("item/started"),threadId:u.string(),providerThreadId:u.string(),item:iw}),u.object({type:u.literal("item/completed"),threadId:u.string(),providerThreadId:u.string(),item:iw}),u.object({type:u.literal("item/agentMessage/delta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/commandExecution/outputDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),reset:u.boolean().optional(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/fileChange/outputDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/reasoning/summaryTextDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/reasoning/textDelta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/plan/delta"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),delta:u.string(),parentToolCallId:u.string().optional()}),u.object({type:u.literal("item/mcpToolCall/progress"),threadId:u.string(),providerThreadId:u.string(),itemId:u.string(),message:u.string().optional(),parentToolCallId:u.string().optional()}),V5,u.object({type:u.literal("thread/tokenUsage/updated"),threadId:u.string(),providerThreadId:u.string(),tokenUsage:sN}),u.object({type:u.literal("thread/contextWindowUsage/updated"),threadId:u.string(),providerThreadId:u.string(),contextWindowUsage:aN}),u.object({type:u.literal("turn/plan/updated"),threadId:u.string(),providerThreadId:u.string(),plan:u.array(rN),explanation:u.string().optional()}),u.object({type:u.literal("turn/diff/updated"),threadId:u.string(),providerThreadId:u.string(),diff:u.string().optional()}),u.object({type:u.literal("provider/error"),threadId:u.string(),providerThreadId:u.string(),message:u.string(),detail:u.string().optional(),willRetry:u.boolean().optional()}),u.object({type:u.literal("provider/warning"),threadId:u.string(),providerThreadId:u.string(),category:lN,summary:u.string().optional(),details:u.string().optional()}),F5]),dN=u.object({scope:ui}),pN=cN.and(dN),ow=cN.options.map(e=>e.shape.type.value),B5=new Set(ow),H5=u.string().refine(e=>B5.has(e),"Invalid provider event type"),K5=u.union([u.object({type:u.literal("client/thread/start"),threadId:u.string()}).merge(fp),u.object({type:u.literal("client/turn/requested"),threadId:u.string()}).merge(Ws),u.object({type:u.literal("client/turn/start"),threadId:u.string()}).merge(fp),u.object({type:u.literal("system/error"),threadId:u.string()}).merge(GS),u.object({type:u.literal("system/manager/user_message"),threadId:u.string()}).merge(JS),u.object({type:u.literal("system/thread/interrupted"),threadId:u.string()}).merge(YS),u.object({type:u.literal("system/operation"),threadId:u.string()}).merge(BS),u.object({type:u.literal("system/permissionGrant/lifecycle"),threadId:u.string()}).merge(HS),u.object({type:u.literal("system/userQuestion/lifecycle"),threadId:u.string()}).merge(KS),u.object({type:u.literal("system/thread-provisioning"),threadId:u.string()}).merge(XS)]),fN=K5.and(dN),XC=u.record(u.string(),u.unknown()),mp=["clientRequest","Sequence"].join(""),Y5=u.unknown().superRefine((e,t)=>{let n=XC.safeParse(e);if(!n.success)return;Object.hasOwn(n.data,mp)&&t.addIssue({code:u.ZodIssueCode.custom,message:"legacy request sequence field is no longer accepted",path:[mp]});let i=XC.safeParse(n.data.item);i.success&&i.data.type==="userMessage"&&Object.hasOwn(i.data,mp)&&t.addIssue({code:u.ZodIssueCode.custom,message:"legacy user-message request sequence field is no longer accepted",path:["item",mp]})}),vp=Y5.pipe(u.union([pN,fN]).superRefine((e,t)=>{let n=tw({type:e.type,scope:e.scope});if(!n.valid){t.addIssue({code:u.ZodIssueCode.custom,message:n.message??"Invalid thread event scope",path:["scope"]});return}})),mN=[...ow,...dp],X5=new Set(mN),aw=u.string().refine(e=>X5.has(e),"Invalid thread event type");var hN=["requested","queued","completed","failed","cancelled"],J5=u.enum(hN);var gN=["provision","reprovision","destroy"],Q5=u.enum(gN),vN=["provision","start","stop"],e8=u.enum(vN),yN=["metadata-pending","environment-pending","environment-attached","environment-provisioning","workspace-ready"],t8=u.enum(yN),bN=["delete"],r8=u.enum(bN);var n8=u.object({id:u.string(),name:u.string(),createdAt:u.number(),updatedAt:u.number()}),_N=["local_path"],i8=u.enum(_N),o8=u.object({id:u.string(),projectId:u.string(),isDefault:u.boolean(),createdAt:u.number(),updatedAt:u.number()}),a8=o8.extend({type:u.literal("local_path"),hostId:u.string(),path:u.string()});var SN=["persistent"],wN=u.enum(SN),kN=["connected","disconnected"],xN=u.enum(kN),s8=u.object({id:u.string(),name:u.string(),type:wN,status:xN,lastSeenAt:u.number().nullable(),createdAt:u.number(),updatedAt:u.number()});var qs=["created","provisioning","idle","active","error"],yp=u.enum(qs);var IN=[...qs,"host-reconnecting","waiting-for-host"],TN=u.enum(IN),PN=u.object({displayStatus:TN,hostReconnectGraceExpiresAt:u.number().nullable()}),EN=["standard","manager"],ON=u.enum(EN),jN=["clean","untracked","dirty_uncommitted","committed_unmerged","dirty_and_committed_unmerged"],zN=u.enum(jN),CN=u.enum(["M","A","D","R","C","U","??","?"]),NN=u.object({path:u.string(),status:CN,insertions:u.number().nullable(),deletions:u.number().nullable()}),UN=u.object({sha:u.string(),shortSha:u.string(),subject:u.string(),authorName:u.string(),authoredAt:u.number()}),sw=u.object({insertions:u.number(),deletions:u.number(),files:u.array(NN)}),RN=sw.extend({hasUncommittedChanges:u.boolean(),state:zN}),AN=u.object({currentBranch:u.string().nullable(),defaultBranch:u.string()}),DN=sw.extend({mergeBaseBranch:u.string(),baseRef:u.string().nullable(),aheadCount:u.number(),behindCount:u.number(),hasCommittedUnmergedChanges:u.boolean(),commits:u.array(UN)}),l8=u.object({workingTree:RN,branch:AN,mergeBase:DN.nullable()}),u8=u.object({id:u.string(),content:u.array(jn).min(1),model:u.string().min(1),reasoningLevel:Lr,permissionMode:On,serviceTier:li,createdAt:u.number(),updatedAt:u.number()}),$N=u.object({id:u.string(),projectId:u.string(),environmentId:u.string().nullable(),automationId:u.string().nullable(),providerId:u.string(),type:ON,title:u.string().nullable(),titleFallback:u.string().nullable(),status:yp,parentThreadId:u.string().nullable(),archivedAt:u.number().nullable(),stopRequestedAt:u.number().nullable(),deletedAt:u.number().nullable(),lastReadAt:u.number().nullable(),latestAttentionAt:u.number(),createdAt:u.number(),updatedAt:u.number()}),MN=$N.extend({runtime:PN}),c8=MN.extend({hasPendingInteraction:u.boolean(),environmentHostId:u.string().nullable(),environmentBranchName:u.string().nullable(),environmentWorkspaceDisplayKind:qS});var d8=u.discriminatedUnion("type",[u.object({type:u.literal("uncommitted")}),u.object({type:u.literal("branch_committed"),mergeBaseBranch:u.string().min(1)}),u.object({type:u.literal("all"),mergeBaseBranch:u.string().min(1)}),u.object({type:u.literal("commit"),sha:u.string().regex(/^[0-9a-f]{4,40}$/iu)})]),p8=u.object({diff:u.string(),truncated:u.boolean(),shortstat:u.string(),files:u.string(),mergeBaseRef:u.string().nullable()});var f8=u.object({id:u.string(),scope:ui,threadId:u.string(),seq:u.number(),type:aw,data:u.record(u.string(),u.unknown()),createdAt:u.number()}),m8=new Set(["client/turn/requested"]),h8={kind:"new-turn"},g8=Ws.extend({target:pp.default(h8),execution:Ds});function v8(e){return g8.parse(e.data)}function y8(e){let{scope:t,threadId:n,type:i,...r}=e;return r}function b8(e){let{scope:t,turnId:n,...i}=e;return i}function LN(e){let t=ui.safeParse(e.scope);if(!t.success)throw new Error("Stored thread event is missing valid scope");let n=t.data,i=m8.has(e.type)?v8(e):e.data;return vp.parse({...b8(i),...e.providerThreadId!=null?{providerThreadId:e.providerThreadId}:{},scope:n,threadId:e.threadId,type:e.type})}function ZN(e){let{event:t,...n}=e;return{...n,type:t.type,data:y8(t)}}function _8(e){return ZN({id:e.id,scope:e.scope,threadId:e.threadId,seq:e.seq,createdAt:e.createdAt,event:LN({type:e.type,data:e.data,threadId:e.threadId,scope:e.scope})})}var S8=f8.transform(e=>_8(e));var w8=u.object({id:u.string(),text:u.string(),startedAt:u.number(),updatedAt:u.number()});var WN=u.enum(["pending","in_progress","completed"]),qN=u.object({id:u.string(),text:u.string(),status:WN}),k8=u.object({sourceSeq:u.number().int().nonnegative(),updatedAt:u.number(),items:u.array(qN)});var FN=["thread","project","environment","host","system"],lw=u.enum(FN);var VN=u.object({type:u.literal("subscribe"),entity:lw,id:u.string().optional()}),GN=u.object({type:u.literal("unsubscribe"),entity:lw,id:u.string().optional()}),x8=u.discriminatedUnion("type",[VN,GN]);var HN="item/permissions/requestApproval",KN="AskUserQuestion",YN="item/userQuestion/request",uw=u.enum(["default","acceptEdits","bypassPermissions","plan","dontAsk"]);var I8=u.object({toolName:u.string(),ruleContent:u.string().optional()}),cw=u.discriminatedUnion("type",[u.object({type:u.literal("addRules"),rules:u.array(I8).min(1),behavior:u.literal("allow"),destination:u.literal("session")}),u.object({type:u.literal("addDirectories"),directories:u.array(u.string()).min(1),destination:u.literal("session")})]),T8=u.object({enabled:u.boolean().nullable()}),P8=u.object({read:u.array(u.string()),write:u.array(u.string())}),E8=u.object({network:T8.nullable().optional(),fileSystem:P8.nullable().optional()}).transform(e=>({network:e.network??null,fileSystem:e.fileSystem??null})),O8=new Map([["Read","read"],["Grep","read"],["Glob","read"],["LS","read"],["Edit","write"],["Write","write"],["NotebookEdit","write"],["Bash","read_write"]]),j8=new Set(["WebFetch","WebSearch"]);function z8(e){return O8.get(e)??null}function C8(e){return(e??[]).flatMap(t=>t.type==="addDirectories"?t.directories:[])}function dw(e){let t=(e.suggestions??[]).some(s=>s.type==="addRules"),n=[...C8(e.suggestions),...e.blockedPath===void 0?[]:[e.blockedPath]],i=[...new Set(n)],r=z8(e.toolName),o=i.length===0?null:(()=>{switch(r){case"read":return{read:i,write:[]};case"write":return{read:[],write:i};case"read_write":case null:return{read:i,write:i}}})();return{network:j8.has(e.toolName)||t?{enabled:!0}:null,fileSystem:o}}function XN(e){return e.blockedPath!==void 0||e.decisionReason!==void 0||(e.suggestions?.length??0)>0}var Woe=u.object({threadId:u.string(),providerThreadId:u.string(),turnId:u.string().min(1).nullable(),itemId:u.string(),toolName:u.string(),input:u.record(u.string(),u.unknown()),reason:u.string().nullable(),permissions:E8}),N8=u.object({label:u.string().min(1),description:u.string().min(1),preview:u.string().optional()}),U8=u.object({question:u.string().min(1),header:u.string().min(1),options:u.array(N8).min(2).max(Ms),multiSelect:u.boolean()}),pw=u.array(U8).min(1).max($s).superRefine((e,t)=>{let n=new Set;e.forEach((i,r)=>{if(n.has(i.question)){t.addIssue({code:u.ZodIssueCode.custom,message:"Claude user-question prompts must be unique",path:[r,"question"]});return}n.add(i.question)})}),JN=u.object({questions:pw}),qoe=u.object({threadId:u.string(),providerThreadId:u.string(),turnId:u.string().min(1).nullable(),itemId:u.string(),questions:pw}),R8=u.object({preview:u.string().optional(),notes:u.string().optional()}),A8=u.object({questions:pw,answers:u.record(u.string().min(1),u.string().min(1)),annotations:u.record(u.string().min(1),R8).optional()}),BN=u.enum(["user_temporary","user_permanent","user_reject"]),D8=u.discriminatedUnion("behavior",[u.object({kind:u.literal("permission_request"),behavior:u.literal("allow"),updatedPermissions:u.array(cw).optional(),decisionClassification:BN.optional()}),u.object({kind:u.literal("permission_request"),behavior:u.literal("deny"),message:u.string(),interrupt:u.boolean().optional(),decisionClassification:BN.optional()})]),$8=u.object({kind:u.literal("user_question"),behavior:u.literal("allow"),updatedInput:A8}),QN=u.union([D8,$8]);var eU=u.enum(ip),tU=u.enum(op).nullable(),rU=u.enum(np),nU=u.array(u.string()).optional(),iU=u.object({name:u.string(),description:u.string(),inputSchema:u.unknown()}),M8=u.discriminatedUnion("method",[u.object({method:u.literal("initialize"),params:u.object({clientInfo:u.object({name:u.string(),version:u.string()})})}),u.object({method:u.literal("model/list"),params:u.object({})}),u.object({method:u.literal("thread/start"),params:u.object({threadId:u.string(),cwd:u.string(),baseInstructions:u.string(),additionalWorkspaceWriteRoots:nU,permissionMode:uw,permissionEscalation:tU,config:u.record(u.string(),u.unknown()).optional(),model:u.string().optional(),reasoningLevel:rU.optional(),instructionMode:eU,dynamicTools:u.array(iU).optional(),disallowedTools:u.array(u.string()).optional()})}),u.object({method:u.literal("thread/resume"),params:u.object({threadId:u.string(),cwd:u.string(),providerThreadId:u.string().nullable(),baseInstructions:u.string().optional(),additionalWorkspaceWriteRoots:nU,permissionMode:uw,permissionEscalation:tU,config:u.record(u.string(),u.unknown()).optional(),model:u.string().optional(),reasoningLevel:rU.optional(),instructionMode:eU,dynamicTools:u.array(iU).optional(),disallowedTools:u.array(u.string()).optional()})}),u.object({method:u.literal("turn/start"),params:u.object({threadId:u.string(),providerThreadId:u.string().nullable(),input:u.array(u.unknown()),model:u.string().optional(),config:u.record(u.string(),u.unknown()).optional()})}),u.object({method:u.literal("turn/steer"),params:u.object({threadId:u.string(),providerThreadId:u.string().nullable(),expectedTurnId:u.string(),input:u.array(u.unknown())})}),u.object({method:u.literal("thread/stop"),params:u.object({threadId:u.string()})})]);function oU(e){let t=fx.safeParse(e);if(!t.success)return null;let n=M8.safeParse({method:t.data.method,params:t.data.params??{}});return n.success?{...n.data,jsonrpc:"2.0",id:t.data.id}:null}import{accessSync as fU,constants as mU}from"node:fs";import{delimiter as gX,join as vX}from"node:path";var L8=new Set(["--no-optional-locks","--no-pager"]),Z8=new Set(["--ahead-behind","--branch","--ignored","--long","--no-ahead-behind","--porcelain","--porcelain=v1","--porcelain=v2","--short","-b","-s","-u","-uno"]),W8=new Set(["--","--cached","--check","--color","--compact-summary","--find-copies","--find-renames","--histogram","--ignore-all-space","--ignore-blank-lines","--ignore-space-at-eol","--ignore-space-change","--minimal","--name-only","--name-status","--no-color","--no-ext-diff","--no-textconv","--numstat","--patch","--patience","--shortstat","--stat","--summary","--word-diff","-M","-U0","-U1","-U2","-U3","-w"]),q8=new Set(["--","--color","--decorate","--format=full","--format=fuller","--format=medium","--format=oneline","--name-only","--name-status","--no-color","--no-ext-diff","--no-patch","--no-textconv","--numstat","--oneline","--patch","--shortstat","--stat","--summary","-1"]),F8=new Set(["--all","--fork-point","--independent","--is-ancestor","--octopus"]),V8=new Set(["--","--all","--color","--decorate","--format=full","--format=fuller","--format=medium","--format=oneline","--graph","--max-count=1","--name-only","--name-status","--no-color","--no-ext-diff","--no-textconv","--oneline","--shortstat","--stat","-1"]),G8=new Set(["--all","--current","--no-color","--remotes","--show-current","-a","-r"]),B8=new Set(["--contains","--merged","--no-contains","--no-merged"]),H8=new Set(["--","--cached","--deleted","--modified","--others","--stage","--unmerged","--with-tree","-d","-m","-o","-s","-u"]),K8=new Set(["--abbrev-ref","--absolute-git-dir","--git-common-dir","--git-dir","--is-inside-work-tree","--show-prefix","--show-toplevel","--short","--verify"]),Y8=new Set(["--","--break","--cached","--count","--files-with-matches","--heading","--ignore-case","--line-number","--name-only","--no-color","--untracked","-I","-c","-i","-l","-n"]),X8=new Set(["--","--abbrev","--date","--line-porcelain","--porcelain","--root","-L","-w"]),J8=/^[A-Za-z0-9_./:@%+=,-]+$/u,aU=/^-[1-9][0-9]*$/u,Q8=/^-U[0-9]+$/u,eX=/^--max-count=[1-9][0-9]*$/u,tX=/^--untracked-files=(all|normal|no)$/u,sU=/^--format=[A-Za-z0-9_./:@%+=,-]+$/u,lU=/^--abbrev=[0-9]+$/u,rX=/^--date=[A-Za-z0-9_./:@%+=,-]+$/u,nX=/^-L[0-9]+(,[0-9]+)?$/u,iX=["--no-ext-diff","--no-textconv"],oX=new Set(["diff","show","log"]),aX=u.object({command:u.string()}).passthrough();function sX(e){return e===".."||e.startsWith("../")||e.includes("/../")}function cU(e){return e.startsWith("/")||/^[A-Za-z]:\//u.test(e)}function lX(e){let t=e.trim().split(/\s+/u).filter(Boolean);if(t.length===0)return null;for(let n of t)if(!J8.test(n)||sX(n))return null;return t}function uX(e){return e==="--"||!e.startsWith("-")&&!cU(e)}function uU(e){return!e.startsWith("-")&&!cU(e)}function tn(e,t,n){for(let i of e)if(!uX(i)&&!t.has(i)&&!n?.(i))return!1;return!0}function cX(e){let t=0,n=!1;for(;t<e.length;){let i=e[t];if(!i)return!1;if(G8.has(i)){t+=1;continue}if(i==="--list"){n=!0,t+=1;continue}if(B8.has(i)){t+=1;let r=e[t];r&&uU(r)&&(t+=1);continue}if(n&&uU(i)){t+=1;continue}return!1}return!0}function dU(e){let t=1;for(;t<e.length;){let n=e[t];if(!n||!L8.has(n))break;t+=1}return t}function dX(e){if(e[0]!=="git")return!1;let t=dU(e),n=e[t];if(!n)return!1;let i=e.slice(t+1);switch(n){case"status":return tn(i,Z8,r=>tX.test(r));case"diff":return tn(i,W8,r=>Q8.test(r));case"show":return tn(i,q8,r=>aU.test(r)||sU.test(r));case"merge-base":return tn(i,F8);case"log":return tn(i,V8,r=>aU.test(r)||eX.test(r)||sU.test(r));case"branch":return cX(i);case"ls-files":return tn(i,H8);case"rev-parse":return tn(i,K8,r=>lU.test(r));case"grep":return tn(i,Y8);case"blame":return tn(i,X8,r=>lU.test(r)||rX.test(r)||nX.test(r));default:return!1}}function pX(e){let t=lX(e);return t?t[0]==="pwd"&&(t.length===1||t.length===2&&(t[1]==="-L"||t[1]==="-P"))?{needsNoOptionalGitLocks:!1,tokens:t}:dX(t)?{needsNoOptionalGitLocks:!t.includes("--no-optional-locks"),tokens:t}:null:null}function bp(e){let t=aX.safeParse(e);if(!t.success)return null;let n=pX(t.data.command);return n?{...t.data,command:fX(n)}:null}function fX(e){let t=e.needsNoOptionalGitLocks?mX(e.tokens):[...e.tokens];return hX(t).join(" ")}function mX(e){return[e[0],"--no-optional-locks",...e.slice(1)]}function hX(e){if(e[0]!=="git")return[...e];let t=dU(e),n=e[t];if(!n||!oX.has(n))return[...e];let i=e.slice(t+1),r=i.indexOf("--"),o=r===-1?i:i.slice(0,r),a=iX.filter(s=>!o.includes(s));return a.length===0?[...e]:[...e.slice(0,t+1),...a,...e.slice(t+1)]}var yX=new Set(["Agent","Glob","Grep","LS","Read","TodoRead"]),bX="Bash",_X={type:"adaptive",display:"summarized"},pU="BB_CLAUDE_CODE_EXECUTABLE";function fw(){return"bb readonly mode allows reading and analysis only. Continue with a read-only answer; do not modify files, run mutating shell commands, use network, or use mutating tools."}function hU(){return"bb workspace-write mode allows work inside the current workspace only. Stay inside the workspace or explain why extra access is needed."}function SX(e){if(e.permissionMode!=="default"&&e.permissionMode!=="dontAsk")return;let t=e.permissionEscalation==="deny"?"deny":"ask",n=t==="deny"?fw():"bb readonly mode requires approval before using tools that can modify state, run commands, access network, or perform non-read actions.";return{PreToolUse:[{hooks:[async i=>{if(i.hook_event_name!=="PreToolUse"||yX.has(i.tool_name))return{continue:!0};if(i.tool_name===bX){let r=bp(i.tool_input);if(r)return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:r}}}return{continue:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:n}}}]}]}}function wX(e){if(e.permissionMode!=="acceptEdits")return;let t=e.additionalWorkspaceWriteRoots??[];return{enabled:!0,autoAllowBashIfSandboxed:!0,allowUnsandboxedCommands:e.permissionEscalation==="ask",...t.length>0?{filesystem:{allowWrite:[...t]}}:{}}}function kX(e){if(!e.pathEnv)return null;for(let t of e.pathEnv.split(gX)){if(!t)continue;let n=vX(t,e.executableName);try{return fU(n,mU.X_OK),n}catch{continue}}return null}function xX(e){let n=e.env[pU]?.trim();if(n&&n.length>0)try{return fU(n,mU.X_OK),n}catch{throw new Error(`${pU} must point to an executable Claude CLI path: ${n}`)}return kX({executableName:"claude",pathEnv:e.env.PATH})}function _p(e,t){let n=e.instructionMode==="replace"?e.baseInstructions??"You are a helpful coding assistant.":{type:"preset",preset:"claude_code",...e.baseInstructions&&e.baseInstructions.length>0?{append:e.baseInstructions}:{}},i=e.model,r=wX(e),o=SX(e),a=e.permissionMode==="acceptEdits"?e.additionalWorkspaceWriteRoots??[]:[],s=xX({env:t});return{cwd:e.cwd,systemPrompt:n,model:i,env:t,permissionMode:e.permissionMode,...e.reasoningLevel?{effort:e.reasoningLevel}:{},...e.reasoningLevel?{thinking:_X}:{},...s?{pathToClaudeCodeExecutable:s}:{},...r?{sandbox:r}:{},...o?{hooks:o}:{},...a.length>0?{additionalDirectories:[...a]}:{},...e.disallowedTools&&e.disallowedTools.length>0?{disallowedTools:[...e.disallowedTools]}:{}}}var Fs="bb-bridge";function mw(e,t){let n=e.map(i=>S1(i.name,i.description,IX(i.inputSchema),async r=>{let o=await t(i.name,r);return{content:[{type:"text",text:o.content}],...o.isError?{isError:!0}:{}}}));return w1({name:Fs,version:"1.0.0",tools:n})}function hw(e){return e.map(t=>`mcp__${Fs}__${t.name}`)}function IX(e){if(!e||typeof e!="object"||!("properties"in e))return{};let t=e;if(!t.properties)return{};let n={};for(let[i,r]of Object.entries(t.properties))switch(r?.type){case"string":n[i]=u.string().optional();break;case"number":case"integer":n[i]=u.number().optional();break;case"boolean":n[i]=u.boolean().optional();break;default:n[i]=u.unknown().optional();break}return n}var EX=u.object({type:u.literal("text"),text:u.string()}),OX=u.object({result:u.string()}).passthrough(),wt=new Map,gw=new Map,vU=0,Do=0,jX=4e3;function yU(e){return xU(e)}function zX(e,t){let n=yU(e),i=yU(t);if(n===i)return!0;let r=n.endsWith("/")?n:`${n}/`;return i.startsWith(r)}function bU(e,t){return t.every(n=>e.some(i=>zX(i,n)))}function CX(e,t){if(t===null)return!0;if(e===null)return!1;let n=[...e.read,...e.write];return bU(n,t.read)&&bU(e.write,t.write)}function NX(e,t){return t?.enabled===!0?e?.enabled===!0:!0}function UX(e){return e.grant.toolName!==null&&e.grant.toolName!==e.toolName?!1:NX(e.grant.permissions.network,e.permissions.network)&&CX(e.grant.permissions.fileSystem,e.permissions.fileSystem)}function RX(e){return e.grants.some(t=>UX({grant:t,permissions:e.permissions,toolName:e.toolName}))}function AX(e){return e.kind==="permission_request"&&e.behavior==="allow"&&(e.decisionClassification==="user_permanent"||e.updatedPermissions!==void 0)}function Cn(e){process.stdout.write(JSON.stringify(e)+`
139
139
  `)}function ci(e,t){Cn({jsonrpc:"2.0",id:e,result:t})}function Vs(e,t,n){Cn({jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function DX(e,t){Cn({jsonrpc:"2.0",method:"sdk/message",params:{threadId:e,message:t}})}function yw(e,t){Cn({jsonrpc:"2.0",method:"thread/identity",params:{threadId:e,providerThreadId:t}})}function $X(){return vU+=1,vU}function bw(e){let t=$X();return{session:new Kd(e.sessionOptions,VX({sessionSerial:t,threadIdRef:e.threadIdRef}),GX({sessionSerial:t,threadIdRef:e.threadIdRef})),sessionOptions:e.sessionOptions,sessionSerial:t,closing:!1,pendingToolCalls:new Map,pendingInteractiveRequests:new Map,permissionEscalation:e.permissionEscalation,permissionMode:e.permissionMode,...e.providerThreadId?{providerThreadId:e.providerThreadId}:{},resumeRecovery:e.resumeRecovery,sessionPermissionGrants:[...e.sessionPermissionGrants??[]],threadIdRef:e.threadIdRef}}function MX(e){let t=OX.safeParse(e);return t.success?t.data.result:null}function LX(e){if(e.subtype!=="error_during_execution")return null;let t=Array.isArray(e.errors)&&e.errors.length===1?e.errors[0]:null,n=!Array.isArray(e.errors)||e.errors.length===0?MX(e):null;return t??n}function ZX(e){let t=`No conversation found with session ID: ${e.attemptedProviderThreadId}`,{message:n}=e;return n.type!=="result"||n.is_error!==!0||LX(n)!==t?null:t}function WX(e){let t=kU(),n={...e.threadSession.sessionOptions,sessionId:t},i=[...e.threadSession.resumeRecovery?.acceptedInputTexts??[]],r=bw({permissionEscalation:e.threadSession.permissionEscalation,permissionMode:e.threadSession.permissionMode,providerThreadId:t,resumeRecovery:null,sessionOptions:n,sessionPermissionGrants:e.threadSession.sessionPermissionGrants,threadIdRef:e.threadSession.threadIdRef});qX({acceptedInputTexts:i,providerThreadId:t,replacementSession:r,threadId:e.threadId,threadSession:e.threadSession})}function qX(e){e.threadSession.closing=!0,PU(e.threadSession,"Thread session replaced after stale Claude resume"),e.threadSession.session.stop(),wt.set(e.threadId,e.replacementSession),e.replacementSession.session.start(),yw(e.threadId,e.providerThreadId);for(let t of e.acceptedInputTexts)e.replacementSession.session.pushInput(t)}function FX(e){let{resumeRecovery:t}=e.threadSession;return!t||t.retryAttempted?"forward":ZX({attemptedProviderThreadId:t.attemptedProviderThreadId,message:e.message})?(t.retryAttempted=!0,WX({threadId:e.threadId,threadSession:e.threadSession}),"suppress"):(e.message.type==="result"&&(e.threadSession.resumeRecovery=null),"forward")}function IU(e){let t=wt.get(e.threadId);if(!(!t||t.closing||t.sessionSerial!==e.sessionSerial))return t}function VX(e){return t=>{let n=IU({sessionSerial:e.sessionSerial,threadId:e.threadIdRef.current});if(!n||FX({message:t,threadId:e.threadIdRef.current,threadSession:n})==="suppress")return;let r=t.session_id?.trim()??"";r.length>0&&n.providerThreadId!==r&&(n.providerThreadId=r,yw(e.threadIdRef.current,r)),DX(e.threadIdRef.current,t)}}function GX(e){return t=>{if(!t||!IU({sessionSerial:e.sessionSerial,threadId:e.threadIdRef.current}))return;let i=t instanceof Error?t.message:String(t);Cn({jsonrpc:"2.0",method:"error",params:{threadId:e.threadIdRef.current,message:i}})}}function TU(e){return(t,n)=>new Promise(i=>{let r=wt.get(e.current);if(!r||r.closing){i({content:"Thread session not found",isError:!0});return}Do+=1;let o=Do;r.pendingToolCalls.set(o,{resolve:i}),Cn({jsonrpc:"2.0",id:o,method:"item/tool/call",params:{threadId:e.current,providerThreadId:r.providerThreadId??e.current,turnId:null,callId:`call-${o}`,tool:t,arguments:n}})})}function _U(e){for(let t of wt.values())if(t.pendingToolCalls.has(e))return t}function SU(e){for(let t of wt.values())if(t.pendingInteractiveRequests.has(e))return t}function BX(e,t){for(let[n,i]of e.pendingInteractiveRequests)e.pendingInteractiveRequests.delete(n),i.resolve({behavior:"deny",interrupt:!0,message:t,toolUseID:i.itemId})}function HX(e,t){for(let[n,i]of e.pendingToolCalls)e.pendingToolCalls.delete(n),i.resolve({content:t,isError:!0})}function PU(e,t){HX(e,t),BX(e,t)}async function Sp(e){let t=gw.get(e.threadId);if(t){await t;return}let n=wt.get(e.threadId);if(!n)return;n.closing=!0,PU(n,e.message);let i=(async()=>{if(e.graceful){await n.session.closeGracefully(jX);return}n.session.stop()})().finally(()=>{wt.get(e.threadId)===n&&wt.delete(e.threadId),gw.delete(e.threadId)});gw.set(e.threadId,i),await i}async function KX(e){await Promise.all(Array.from(wt.keys()).map(t=>Sp({graceful:!0,message:e,threadId:t})))}function EU(e){let t={};if(e){for(let[n,i]of Object.entries(e))if(n.startsWith("shell_environment_policy.set.")&&typeof i=="string"){let r=n.slice(29);t[r]=i}}return t}function OU(e){return{...process.env,...e,CLAUDE_AGENT_SDK_CLIENT_APP:"bb/1.0.0"}}function YX(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let i=cw.safeParse(n);return i.success?[i.data]:[]});return t.length>0?t:void 0}function XX(e){return{threadId:e.threadId,providerThreadId:e.providerThreadId,turnId:null,itemId:e.toolUseId,toolName:e.toolName,input:e.input,reason:e.decisionReason??null,permissions:dw({toolName:e.toolName,blockedPath:e.blockedPath,suggestions:e.suggestions})}}function JX(e){return{threadId:e.threadId,providerThreadId:e.providerThreadId,turnId:null,itemId:e.toolUseId,questions:e.input.questions}}function QX(e,t){switch(e.kind){case"permission_request":return t.kind!=="permission_request"?{behavior:"deny",message:"Interactive response kind mismatch",toolUseID:e.itemId}:t.behavior==="deny"?{behavior:"deny",message:t.message,...t.interrupt===void 0?{}:{interrupt:t.interrupt},...t.decisionClassification===void 0?{}:{decisionClassification:t.decisionClassification},toolUseID:e.itemId}:{behavior:"allow",updatedInput:e.originalInput,...t.updatedPermissions===void 0?{}:{updatedPermissions:t.updatedPermissions},...t.decisionClassification===void 0?{}:{decisionClassification:t.decisionClassification},toolUseID:e.itemId};case"user_question":return t.kind!=="user_question"?{behavior:"deny",message:"Interactive response kind mismatch",toolUseID:e.itemId}:{behavior:"allow",updatedInput:t.updatedInput,toolUseID:e.itemId}}}function e7(e){return t=>new Promise(n=>{let i=wt.get(e.current);if(!i){n({behavior:"deny",message:"Thread session not found",toolUseID:t.toolUseId});return}let r;try{r=XX(t)}catch(l){n({behavior:"deny",message:l instanceof Error?l.message:String(l),toolUseID:t.toolUseId});return}Do+=1;let o=Do,a=l=>{t.signal.removeEventListener("abort",s),n(l)},s=()=>{i.pendingInteractiveRequests.delete(o)&&a({behavior:"deny",message:"Interactive request cancelled",toolUseID:t.toolUseId})};t.signal.addEventListener("abort",s,{once:!0}),i.pendingInteractiveRequests.set(o,{itemId:t.toolUseId,kind:"permission_request",originalInput:t.input,permissions:r.permissions,resolve:a,toolName:t.toolName}),Cn({jsonrpc:"2.0",id:o,method:HN,params:r})})}function t7(e){return t=>new Promise(n=>{let i=wt.get(e.current);if(!i){n({behavior:"deny",message:"Thread session not found",toolUseID:t.toolUseId});return}let r=JX(t);Do+=1;let o=Do,a=l=>{t.signal.removeEventListener("abort",s),n(l)},s=()=>{i.pendingInteractiveRequests.delete(o)&&a({behavior:"deny",message:"User question request cancelled",toolUseID:t.toolUseId})};t.signal.addEventListener("abort",s,{once:!0}),i.pendingInteractiveRequests.set(o,{itemId:t.toolUseId,kind:"user_question",resolve:a}),Cn({jsonrpc:"2.0",id:o,method:YN,params:r})})}function jU(e){let t=e7(e),n=t7(e);return async(i,r,o)=>{let a=wt.get(e.current);if(!a)return{behavior:"deny",message:"Thread session not found",toolUseID:o.toolUseID};if(i===KN){let f=JN.safeParse(r);return f.success?n({threadId:e.current,providerThreadId:a.providerThreadId??e.current,toolUseId:o.toolUseID,input:f.data,signal:o.signal}):{behavior:"deny",message:"Invalid AskUserQuestion input",toolUseID:o.toolUseID}}let s=YX(o.suggestions),l={toolName:i,blockedPath:o.blockedPath,decisionReason:o.decisionReason,suggestions:s},c=dw(l);if(RX({grants:a.sessionPermissionGrants,permissions:c,toolName:i}))return{behavior:"allow",updatedInput:r,toolUseID:o.toolUseID,decisionClassification:"user_permanent"};if(i==="Bash"&&(a.permissionMode==="default"||a.permissionMode==="dontAsk")){let f=bp(r);if(f)return{behavior:"allow",updatedInput:f,toolUseID:o.toolUseID}}if(!(XN(l)||(o.suggestions?.length??0)>0))return{behavior:"allow",updatedInput:r,toolUseID:o.toolUseID};if(a.permissionMode==="bypassPermissions")return{behavior:"allow",updatedInput:r,toolUseID:o.toolUseID};if(gx(a)||a.permissionMode==="dontAsk"){let f=a.permissionMode==="acceptEdits"?hU():fw();return{behavior:"deny",message:o.decisionReason??f,toolUseID:o.toolUseID}}return t({threadId:e.current,providerThreadId:a.providerThreadId??e.current,toolName:i,toolUseId:o.toolUseID,input:r,decisionReason:o.decisionReason,blockedPath:o.blockedPath,suggestions:s,signal:o.signal})}}async function r7(e){switch(e.method){case"initialize":ci(e.id,{ok:!0});break;case"model/list":ci(e.id,await nC());break;case"thread/start":await n7(e.id,e.params);break;case"thread/resume":await i7(e.id,e.params);break;case"turn/start":o7(e.id,e.params);break;case"turn/steer":a7(e.id,e.params);break;case"thread/stop":ci(e.id,await s7(e.params));break}}async function n7(e,t){let n={current:t.threadId};wt.get(n.current)&&await Sp({graceful:!1,message:"Thread session replaced while awaiting permission approval",threadId:n.current});let r=EU(t.config),o=OU(r),a=_p(t,o),s=kU();if(a.sessionId=s,a.canUseTool=jU(n),t.dynamicTools&&t.dynamicTools.length>0){let c=mw(t.dynamicTools,TU(n));a.mcpServers={[Fs]:c},a.allowedTools=hw(t.dynamicTools)}let l=bw({permissionEscalation:t.permissionEscalation,permissionMode:t.permissionMode,providerThreadId:s,resumeRecovery:null,sessionOptions:a,sessionPermissionGrants:[],threadIdRef:n});wt.set(n.current,l),l.session.start(),ci(e,{threadId:n.current,providerThreadId:s}),yw(n.current,s)}async function i7(e,t){let n=t.threadId,i=t.providerThreadId??void 0;wt.get(n)&&await Sp({graceful:!1,message:"Thread session replaced while awaiting permission approval",threadId:n});let o=EU(t.config),a=OU(o),s={current:n},l=_p(t,a);if(l.canUseTool=jU(s),t.dynamicTools&&t.dynamicTools.length>0){let d=mw(t.dynamicTools,TU(s));l.mcpServers={[Fs]:d},l.allowedTools=hw(t.dynamicTools)}let c=bw({permissionEscalation:t.permissionEscalation,permissionMode:t.permissionMode,...i?{providerThreadId:i}:{},resumeRecovery:i?{acceptedInputTexts:[],attemptedProviderThreadId:i,retryAttempted:!1}:null,sessionOptions:l,sessionPermissionGrants:[],threadIdRef:s});wt.set(n,c),c.session.start(i),ci(e,{threadId:n,providerThreadId:i??null})}function o7(e,t){let n=wt.get(t.threadId);if(!n||n.closing){Vs(e,-32e3,"No active session");return}let i=zU(t.input);if(!i){Vs(e,-32602,"Missing input text");return}n.resumeRecovery?.acceptedInputTexts.push(i),n.session.pushInput(i),ci(e,{threadId:t.threadId})}function a7(e,t){let n=wt.get(t.threadId);if(!n||n.closing){Vs(e,-32e3,"No active session");return}let i=zU(t.input);if(!i){Vs(e,-32602,"Missing input text");return}n.resumeRecovery?.acceptedInputTexts.push(i),n.session.pushInput(i),ci(e,{threadId:t.threadId})}async function s7(e){return await Sp({graceful:!0,message:"Thread stopped while awaiting permission approval",threadId:e.threadId}),{ok:!0}}function zU(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let i=EX.safeParse(n);i.success&&t.push(i.data.text)}return t.length>0?t.join(`
140
140
  `):void 0}function l7(e){let t=e.trim();if(!t)return;let n;try{n=JSON.parse(t)}catch{return}let i=mx(n);if(i&&_U(i.id)){let o=_U(i.id),a=o.pendingToolCalls.get(i.id);o.pendingToolCalls.delete(i.id),"error"in i?a.resolve({content:i.error.message??"Tool call failed",isError:!0}):a.resolve(hx(i.result));return}if(i&&SU(i.id)){let o=SU(i.id),a=o.pendingInteractiveRequests.get(i.id);if(o.pendingInteractiveRequests.delete(i.id),"error"in i){a.resolve({behavior:"deny",message:i.error.message??"Interactive request failed",toolUseID:a.itemId});return}let s=QN.safeParse(i.result);if(!s.success){a.resolve({behavior:"deny",message:"Invalid interactive response payload",toolUseID:a.itemId});return}let l=s.data;a.kind==="permission_request"&&AX(l)&&o.sessionPermissionGrants.push({permissions:a.permissions,toolName:a.toolName}),a.resolve(QX(a,l));return}let r=oU(n);r&&r7(r).catch(o=>{let a=o instanceof Error?o.message:String(o);Vs(r.id,-32e3,a)})}var wU=!1;function vw(e){wU||(wU=!0,KX(e).finally(()=>{process.exit(0)}))}function u7(){let e=process.argv[1];if(e===void 0)return!1;try{return gU(PX(import.meta.url))===gU(xU(e))}catch{return!1}}if(u7()){process.once("SIGTERM",()=>{vw("Bridge shutting down while awaiting permission approval")}),process.once("SIGINT",()=>{vw("Bridge interrupted while awaiting permission approval")});let e=TX({input:process.stdin,terminal:!1});e.on("line",l7),e.on("close",()=>{vw("Bridge closed while awaiting permission approval")})}export{_p as buildSessionOptions,l7 as handleLine};