@anthropic-ai/claude-agent-sdk 0.3.229 → 0.3.231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
3
3
 
4
- // Version: 0.3.229
4
+ // Version: 0.3.231
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -148,7 +148,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
148
148
  `+" ".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
149
149
  `+" ".repeat(t))},"\t":{"\n":Array(200).fill(0).map((e,t)=>`
150
150
  `+"\t".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+"\t".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
151
- `+"\t".repeat(t))}};var F6;(function(e){e.DEFAULT={allowTrailingComma:!1}})(F6||(F6={}));var j6;(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"})(j6||(j6={}));var $6;(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"})($6||($6={}));var B6;(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"})(B6||(B6={}));var ql=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,K6=new Set,lR=typeof process==="object"&&!!process?process:{},q6=(e,t,n,r)=>{typeof lR.emitWarning==="function"?lR.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},xy=globalThis.AbortController,H6=globalThis.AbortSignal;if(typeof xy>"u"){H6=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},xy=class{constructor(){t()}signal=new H6;abort(r){if(this.signal.aborted)return;this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}};let e=lR.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{if(!e)return;e=!1,q6("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 R$e=(e)=>!K6.has(e),gEt=Symbol("type"),ti=(e)=>e&&e===Math.floor(e)&&e>0&&isFinite(e),G6=(e)=>!ti(e)?null:e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Rf:null;class Rf extends Array{constructor(e){super(e);this.fill(0)}}class Gl{heap;length;static#e=!1;static create(e){let t=G6(e);if(!t)return[];Gl.#e=!0;let n=new Gl(e,t);return Gl.#e=!1,n}constructor(e,t){if(!Gl.#e)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class Ey{#e;#t;#n;#r;#o;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#s;#l;#u;#i;#c;#p;#h;#d;#f;#_;#m;#b;#S;#y;#E;#T;#x;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#y,sizes:e.#b,keyMap:e.#u,keyList:e.#i,valList:e.#c,next:e.#p,prev:e.#h,get head(){return e.#d},get tail(){return e.#f},free:e.#_,isBackgroundFetch:(t)=>e.#g(t),backgroundFetch:(t,n,r,o)=>e.#M(t,n,r,o),moveToTail:(t)=>e.#I(t),indexes:(t)=>e.#k(t),rindexes:(t)=>e.#C(t),isStale:(t)=>e.#w(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#l}get size(){return this.#s}get fetchMethod(){return this.#o}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:i,allowStale:a,dispose:c,disposeAfter:l,noDisposeOnSet:u,noUpdateTTL:p,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:x,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:k,ignoreFetchAbort:R}=e;if(t!==0&&!ti(t))throw TypeError("max option must be a nonnegative integer");let V=t?G6(t):Array;if(!V)throw Error("invalid max value: "+t);if(this.#e=t,this.#t=f,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!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(y!==void 0&&typeof y!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#a=y,g!==void 0&&typeof g!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#o=g,this.#T=!!g,this.#u=new Map,this.#i=Array(t).fill(void 0),this.#c=Array(t).fill(void 0),this.#p=new V(t),this.#h=new V(t),this.#d=0,this.#f=0,this.#_=Gl.create(t),this.#s=0,this.#l=0,typeof c==="function")this.#n=c;if(typeof l==="function")this.#r=l,this.#m=[];else this.#r=void 0,this.#m=void 0;if(this.#E=!!this.#n,this.#x=!!this.#r,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!R,this.maxEntrySize!==0){if(this.#t!==0){if(!ti(this.#t))throw TypeError("maxSize must be a positive integer if specified")}if(!ti(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!x,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!i,this.ttlResolution=ti(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!ti(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#O()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){if(R$e("LRU_CACHE_UNBOUNDED"))K6.add("LRU_CACHE_UNBOUNDED"),q6("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",Ey)}}getRemainingTTL(e){return this.#u.has(e)?1/0:0}#O(){let e=new Rf(this.#e),t=new Rf(this.#e);this.#y=e,this.#S=t,this.#N=(o,s,i=ql.now())=>{if(t[o]=s!==0?i:0,e[o]=s,s!==0&&this.ttlAutopurge){let a=setTimeout(()=>{if(this.#w(o))this.#R(this.#i[o],"expire")},s+1);if(a.unref)a.unref()}},this.#A=(o)=>{t[o]=e[o]!==0?ql.now():0},this.#v=(o,s)=>{if(e[s]){let i=e[s],a=t[s];if(!i||!a)return;o.ttl=i,o.start=a,o.now=n||r();let c=o.now-a;o.remainingTTL=i-c}};let n=0,r=()=>{let o=ql.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);if(s.unref)s.unref()}return o};this.getRemainingTTL=(o)=>{let s=this.#u.get(o);if(s===void 0)return 0;let i=e[s],a=t[s];if(!i||!a)return 1/0;let c=(n||r())-a;return i-c},this.#w=(o)=>{let s=t[o],i=e[o];return!!i&&!!s&&(n||r())-s>i}}#A=()=>{};#v=()=>{};#N=()=>{};#w=()=>!1;#$(){let e=new Rf(this.#e);this.#l=0,this.#b=e,this.#P=(t)=>{this.#l-=e[t],e[t]=0},this.#U=(t,n,r,o)=>{if(this.#g(n))return 0;if(!ti(r))if(o){if(typeof o!=="function")throw TypeError("sizeCalculation must be a function");if(r=o(n,t),!ti(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.#D=(t,n,r)=>{if(e[t]=n,this.#t){let o=this.#t-e[t];while(this.#l>o)this.#L(!0)}if(this.#l+=e[t],r)r.entrySize=n,r.totalCalculatedSize=this.#l}}#P=(e)=>{};#D=(e,t,n)=>{};#U=(e,t,n,r)=>{if(n||r)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:e=this.allowStale}={}){if(this.#s)for(let t=this.#f;;){if(!this.#z(t))break;if(e||!this.#w(t))yield t;if(t===this.#d)break;else t=this.#h[t]}}*#C({allowStale:e=this.allowStale}={}){if(this.#s)for(let t=this.#d;;){if(!this.#z(t))break;if(e||!this.#w(t))yield t;if(t===this.#f)break;else t=this.#p[t]}}#z(e){return e!==void 0&&this.#u.get(this.#i[e])===e}*entries(){for(let e of this.#k())if(this.#c[e]!==void 0&&this.#i[e]!==void 0&&!this.#g(this.#c[e]))yield[this.#i[e],this.#c[e]]}*rentries(){for(let e of this.#C())if(this.#c[e]!==void 0&&this.#i[e]!==void 0&&!this.#g(this.#c[e]))yield[this.#i[e],this.#c[e]]}*keys(){for(let e of this.#k()){let t=this.#i[e];if(t!==void 0&&!this.#g(this.#c[e]))yield t}}*rkeys(){for(let e of this.#C()){let t=this.#i[e];if(t!==void 0&&!this.#g(this.#c[e]))yield t}}*values(){for(let e of this.#k())if(this.#c[e]!==void 0&&!this.#g(this.#c[e]))yield this.#c[e]}*rvalues(){for(let e of this.#C())if(this.#c[e]!==void 0&&!this.#g(this.#c[e]))yield this.#c[e]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#k()){let r=this.#c[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;if(e(o,this.#i[n],this))return this.get(this.#i[n],t)}}forEach(e,t=this){for(let n of this.#k()){let r=this.#c[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#i[n],this)}}rforEach(e,t=this){for(let n of this.#C()){let r=this.#c[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#i[n],this)}}purgeStale(){let e=!1;for(let t of this.#C({allowStale:!0}))if(this.#w(t))this.#R(this.#i[t],"expire"),e=!0;return e}info(e){let t=this.#u.get(e);if(t===void 0)return;let n=this.#c[t],r=this.#g(n)?n.__staleWhileFetching:n;if(r===void 0)return;let o={value:r};if(this.#y&&this.#S){let s=this.#y[t],i=this.#S[t];if(s&&i){let a=s-(ql.now()-i);o.ttl=a,o.start=Date.now()}}if(this.#b)o.size=this.#b[t];return o}dump(){let e=[];for(let t of this.#k({allowStale:!0})){let n=this.#i[t],r=this.#c[t],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#y&&this.#S){s.ttl=this.#y[t];let i=ql.now()-this.#S[t];s.start=Math.floor(Date.now()-i)}if(this.#b)s.size=this.#b[t];e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let r=Date.now()-n.start;n.start=ql.now()-r}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:i=this.sizeCalculation,status:a}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#U(e,t,n.size||0,i);if(this.maxEntrySize&&l>this.maxEntrySize){if(a)a.set="miss",a.maxEntrySizeExceeded=!0;return this.#R(e,"set"),this}let u=this.#s===0?void 0:this.#u.get(e);if(u===void 0){if(u=this.#s===0?this.#f:this.#_.length!==0?this.#_.pop():this.#s===this.#e?this.#L(!1):this.#s,this.#i[u]=e,this.#c[u]=t,this.#u.set(e,u),this.#p[this.#f]=u,this.#h[u]=this.#f,this.#f=u,this.#s++,this.#D(u,l,a),a)a.set="add";c=!1}else{this.#I(u);let p=this.#c[u];if(t!==p){if(this.#T&&this.#g(p)){p.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=p;if(f!==void 0&&!s){if(this.#E)this.#n?.(f,e,"set");if(this.#x)this.#m?.push([f,e,"set"])}}else if(!s){if(this.#E)this.#n?.(p,e,"set");if(this.#x)this.#m?.push([p,e,"set"])}if(this.#P(u),this.#D(u,l,a),this.#c[u]=t,a){a.set="replace";let f=p&&this.#g(p)?p.__staleWhileFetching:p;if(f!==void 0)a.oldValue=f}}else if(a)a.set="update"}if(r!==0&&!this.#y)this.#O();if(this.#y){if(!c)this.#N(u,r,o);if(a)this.#v(a,u)}if(!s&&this.#x&&this.#m){let p=this.#m,f;while(f=p?.shift())this.#r?.(...f)}return this}pop(){try{while(this.#s){let e=this.#c[this.#d];if(this.#L(!0),this.#g(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#x&&this.#m){let e=this.#m,t;while(t=e?.shift())this.#r?.(...t)}}}#L(e){let t=this.#d,n=this.#i[t],r=this.#c[t];if(this.#T&&this.#g(r))r.__abortController.abort(Error("evicted"));else if(this.#E||this.#x){if(this.#E)this.#n?.(r,n,"evict");if(this.#x)this.#m?.push([r,n,"evict"])}if(this.#P(t),e)this.#i[t]=void 0,this.#c[t]=void 0,this.#_.push(t);if(this.#s===1)this.#d=this.#f=0,this.#_.length=0;else this.#d=this.#p[t];return this.#u.delete(n),this.#s--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,o=this.#u.get(e);if(o!==void 0){let s=this.#c[o];if(this.#g(s)&&s.__staleWhileFetching===void 0)return!1;if(!this.#w(o)){if(n)this.#A(o);if(r)r.has="hit",this.#v(r,o);return!0}else if(r)r.has="stale",this.#v(r,o)}else if(r)r.has="miss";return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#u.get(e);if(r===void 0||!n&&this.#w(r))return;let o=this.#c[r];return this.#g(o)?o.__staleWhileFetching:o}#M(e,t,n,r){let o=t===void 0?void 0:this.#c[t];if(this.#g(o))return o;let s=new xy,{signal:i}=n;i?.addEventListener("abort",()=>s.abort(i.reason),{signal:s.signal});let a={signal:s.signal,options:n,context:r},c=(h,g=!1)=>{let{aborted:y}=s.signal,b=n.ignoreFetchAbort&&h!==void 0;if(n.status)if(y&&!g){if(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,b)n.status.fetchAbortIgnored=!0}else n.status.fetchResolved=!0;if(y&&!b&&!g)return u(s.signal.reason);let x=f;if(this.#c[t]===f)if(h===void 0)if(x.__staleWhileFetching)this.#c[t]=x.__staleWhileFetching;else this.#R(e,"fetch");else{if(n.status)n.status.fetchUpdated=!0;this.set(e,h,a.options)}return h},l=(h)=>{if(n.status)n.status.fetchRejected=!0,n.status.fetchError=h;return u(h)},u=(h)=>{let{aborted:g}=s.signal,y=g&&n.allowStaleOnFetchAbort,b=y||n.allowStaleOnFetchRejection,x=b||n.noDeleteOnFetchRejection,E=f;if(this.#c[t]===f){if(!x||E.__staleWhileFetching===void 0)this.#R(e,"fetch");else if(!y)this.#c[t]=E.__staleWhileFetching}if(b){if(n.status&&E.__staleWhileFetching!==void 0)n.status.returnedStale=!0;return E.__staleWhileFetching}else if(E.__returned===E)throw h},p=(h,g)=>{let y=this.#o?.(e,o,a);if(y&&y instanceof Promise)y.then((b)=>h(b===void 0?void 0:b),g);s.signal.addEventListener("abort",()=>{if(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort){if(h(void 0),n.allowStaleOnFetchAbort)h=(b)=>c(b,!0)}})};if(n.status)n.status.fetchDispatched=!0;let f=new Promise(p).then(c,l),m=Object.assign(f,{__abortController:s,__staleWhileFetching:o,__returned:void 0});if(t===void 0)this.set(e,m,{...a.options,status:void 0}),t=this.#u.get(e);else this.#c[t]=m;return m}#g(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof xy}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:i=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:y,signal:b}=t;if(!this.#T){if(y)y.fetch="get";return this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:y})}let x={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:i,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:y,signal:b},E=this.#u.get(e);if(E===void 0){if(y)y.fetch="miss";let k=this.#M(e,E,x,h);return k.__returned=k}else{let k=this.#c[E];if(this.#g(k)){let X=n&&k.__staleWhileFetching!==void 0;if(y){if(y.fetch="inflight",X)y.returnedStale=!0}return X?k.__staleWhileFetching:k.__returned=k}let R=this.#w(E);if(!g&&!R){if(y)y.fetch="hit";if(this.#I(E),r)this.#A(E);if(y)this.#v(y,E);return k}let V=this.#M(e,E,x,h),Q=V.__staleWhileFetching!==void 0&&n;if(y){if(y.fetch=R?"stale":"refresh",Q&&R)y.returnedStale=!0}return Q?V.__staleWhileFetching:V.__returned=V}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#a;if(!n)throw Error("no memoMethod provided to constructor");let{context:r,forceRefresh:o,...s}=t,i=this.get(e,s);if(!o&&i!==void 0)return i;let a=n(e,i,{options:s,context:r});return this.set(e,a,s),a}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=t,i=this.#u.get(e);if(i!==void 0){let a=this.#c[i],c=this.#g(a);if(s)this.#v(s,i);if(this.#w(i)){if(s)s.get="stale";if(!c){if(!o)this.#R(e,"expire");if(s&&n)s.returnedStale=!0;return n?a:void 0}else{if(s&&n&&a.__staleWhileFetching!==void 0)s.returnedStale=!0;return n?a.__staleWhileFetching:void 0}}else{if(s)s.get="hit";if(c)return a.__staleWhileFetching;if(this.#I(i),r)this.#A(i);return a}}else if(s)s.get="miss"}#F(e,t){this.#h[t]=e,this.#p[e]=t}#I(e){if(e!==this.#f){if(e===this.#d)this.#d=this.#p[e];else this.#F(this.#h[e],this.#p[e]);this.#F(this.#f,e),this.#f=e}}delete(e){return this.#R(e,"delete")}#R(e,t){let n=!1;if(this.#s!==0){let r=this.#u.get(e);if(r!==void 0)if(n=!0,this.#s===1)this.#j(t);else{this.#P(r);let o=this.#c[r];if(this.#g(o))o.__abortController.abort(Error("deleted"));else if(this.#E||this.#x){if(this.#E)this.#n?.(o,e,t);if(this.#x)this.#m?.push([o,e,t])}if(this.#u.delete(e),this.#i[r]=void 0,this.#c[r]=void 0,r===this.#f)this.#f=this.#h[r];else if(r===this.#d)this.#d=this.#p[r];else{let s=this.#h[r];this.#p[s]=this.#p[r];let i=this.#p[r];this.#h[i]=this.#h[r]}this.#s--,this.#_.push(r)}}if(this.#x&&this.#m?.length){let r=this.#m,o;while(o=r?.shift())this.#r?.(...o)}return n}clear(){return this.#j("delete")}#j(e){for(let t of this.#C({allowStale:!0})){let n=this.#c[t];if(this.#g(n))n.__abortController.abort(Error("deleted"));else{let r=this.#i[t];if(this.#E)this.#n?.(n,r,e);if(this.#x)this.#m?.push([n,r,e])}}if(this.#u.clear(),this.#c.fill(void 0),this.#i.fill(void 0),this.#y&&this.#S)this.#y.fill(0),this.#S.fill(0);if(this.#b)this.#b.fill(0);if(this.#d=0,this.#f=0,this.#_.length=0,this.#l=0,this.#s=0,this.#x&&this.#m){let t=this.#m,n;while(n=t?.shift())this.#r?.(...n)}}}function W6(e,t,n=100){let r=new Ey({max:n}),o=(...s)=>{let i=t(...s),a=r.get(i);if(a!==void 0)return a;let c=e(...s);return r.set(i,c),c};return o.cache={clear:()=>r.clear(),size:()=>r.size,delete:(s)=>r.delete(s),get:(s)=>r.peek(s),has:(s)=>r.has(s)},o}var O$e=8192;function Z6(e,t){try{return{ok:!0,value:JSON.parse(ml(e))}}catch(n){if(t)tg($L(n,`safeParseJSON: invalid JSON (${n instanceof Error?n.constructor.name:typeof n}, ${e.length} bytes)`));return{ok:!1}}}class Y6{cached=W6(Z6,(e)=>e,50);cache=this.cached.cache;parse(e,t){return this.cached(e,t)}}var V6=new Y6;var Wl=Object.assign(function(t,n=!0){if(!t)return null;let r=t.length>O$e?Z6(t,n):V6.parse(t,n);return r.ok?r.value:null},{cache:V6.cache});import{join as P$e}from"path";class J6{managedFilePath=void 0;dropInDir=void 0;getManagedFilePath(){return this.managedFilePath??=D$e(),this.managedFilePath}getDropInDir(){return this.dropInDir??=P$e(pa(),"managed-settings.d"),this.dropInDir}clearDropInDir(){this.dropInDir=void 0}reset(){this.managedFilePath=void 0,this.dropInDir=void 0}}var I$e=new J6;function pa(){return I$e.getManagedFilePath()}function D$e(){switch(Bo()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}var L$e=function(){try{var e=An(Object,"defineProperty");return e({},"",{}),e}catch(t){}}(),Vl=L$e;function M$e(e,t,n){if(t=="__proto__"&&Vl)Vl(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0});else e[t]=n}var Zl=M$e;function N$e(e,t,n){if(n!==void 0&&!co(e[t],n)||n===void 0&&!(t in e))Zl(e,t,n)}var Of=N$e;function U$e(e){return function(t,n,r){var o=-1,s=Object(t),i=r(t),a=i.length;while(a--){var c=i[e?a:++o];if(n(s[c],c,s)===!1)break}return t}}var X6=U$e;var z$e=X6(),Q6=z$e;var wy={};Ht(wy,{default:()=>uR});var r3=typeof wy=="object"&&wy&&!wy.nodeType&&wy,e3=r3&&typeof vy=="object"&&vy&&!vy.nodeType&&vy,F$e=e3&&e3.exports===r3,t3=F$e?Pt.Buffer:void 0,n3=t3?t3.allocUnsafe:void 0;function j$e(e,t){if(t)return e.slice();var n=e.length,r=n3?n3(n):new e.constructor(n);return e.copy(r),r}var uR=j$e;function $$e(e){var t=new e.constructor(e.byteLength);return new Oc(t).set(new Oc(e)),t}var o3=$$e;function B$e(e,t){var n=t?o3(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}var s3=B$e;function H$e(e,t){var n=-1,r=e.length;t||(t=Array(r));while(++n<r)t[n]=e[n];return t}var i3=H$e;var a3=Object.create,K$e=function(){function e(){}return function(t){if(!Nt(t))return{};if(a3)return a3(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}(),c3=K$e;var q$e=Bh(Object.getPrototypeOf,Object),Yl=q$e;function G$e(e){return typeof e.constructor=="function"&&!Lc(e)?c3(Yl(e)):{}}var l3=G$e;function W$e(e){return Sn(e)&&Os(e)}var u3=W$e;var V$e="[object Object]",Z$e=Function.prototype,Y$e=Object.prototype,d3=Z$e.toString,J$e=Y$e.hasOwnProperty,X$e=d3.call(Object);function Q$e(e){if(!Sn(e)||Yn(e)!=V$e)return!1;var t=Yl(e);if(t===null)return!0;var n=J$e.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&d3.call(n)==X$e}var p3=Q$e;function e1e(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var Pf=e1e;var t1e=Object.prototype,n1e=t1e.hasOwnProperty;function r1e(e,t,n){var r=e[t];if(!(n1e.call(e,t)&&co(r,n))||n===void 0&&!(t in e))Zl(e,t,n)}var Ty=r1e;function o1e(e,t,n,r){var o=!n;n||(n={});var s=-1,i=t.length;while(++s<i){var a=t[s],c=r?r(n[a],e[a],a,n,e):void 0;if(c===void 0)c=e[a];if(o)Zl(n,a,c);else Ty(n,a,c)}return n}var f3=o1e;function s1e(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var m3=s1e;var i1e=Object.prototype,a1e=i1e.hasOwnProperty;function c1e(e){if(!Nt(e))return m3(e);var t=Lc(e),n=[];for(var r in e)if(!(r=="constructor"&&(t||!a1e.call(e,r))))n.push(r);return n}var h3=c1e;function l1e(e){return Os(e)?$h(e,!0):h3(e)}var Jl=l1e;function u1e(e){return f3(e,Jl(e))}var g3=u1e;function d1e(e,t,n,r,o,s,i){var a=Pf(e,n),c=Pf(t,n),l=i.get(c);if(l){Of(e,n,l);return}var u=s?s(a,c,n+"",e,t,i):void 0,p=u===void 0;if(p){var f=Tt(c),m=!f&&Cs(c),h=!f&&!m&&Dc(c);if(u=c,f||m||h)if(Tt(a))u=a;else if(u3(a))u=i3(a);else if(m)p=!1,u=uR(c,!0);else if(h)p=!1,u=s3(c,!0);else u=[];else if(p3(c)||$o(c)){if(u=a,$o(a))u=g3(a);else if(!Nt(a)||Aa(a))u=l3(c)}else p=!1}if(p)i.set(c,u),o(u,c,r,s,i),i.delete(c);Of(e,n,u)}var _3=d1e;function y3(e,t,n,r,o){if(e===t)return;Q6(t,function(s,i){if(o||(o=new ks),Nt(s))_3(e,t,i,n,y3,r,o);else{var a=r?r(Pf(e,i),s,i+"",e,t,o):void 0;if(a===void 0)a=s;Of(e,i,a)}},Jl)}var b3=y3;function p1e(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 S3=p1e;var x3=Math.max;function f1e(e,t,n){return t=x3(t===void 0?e.length-1:t,0),function(){var r=arguments,o=-1,s=x3(r.length-t,0),i=Array(s);while(++o<s)i[o]=r[t+o];o=-1;var a=Array(t+1);while(++o<t)a[o]=r[o];return a[t]=n(i),S3(e,this,a)}}var Ay=f1e;function m1e(e){return function(){return e}}var E3=m1e;var h1e=!Vl?Fc:function(e,t){return Vl(e,"toString",{configurable:!0,enumerable:!1,value:E3(t),writable:!0})},v3=h1e;var g1e=800,_1e=16,y1e=Date.now;function b1e(e){var t=0,n=0;return function(){var r=y1e(),o=_1e-(r-n);if(n=r,o>0){if(++t>=g1e)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var w3=b1e;var S1e=w3(v3),ky=S1e;function x1e(e,t){return ky(Ay(e,t,Fc),e+"")}var T3=x1e;function E1e(e,t,n){if(!Nt(n))return!1;var r=typeof t;if(r=="number"?Os(n)&&Rs(t,n.length):r=="string"&&(t in n))return co(n[t],e);return!1}var A3=E1e;function v1e(e){return T3(function(t,n){var r=-1,o=n.length,s=o>1?n[o-1]:void 0,i=o>2?n[2]:void 0;if(s=e.length>3&&typeof s=="function"?(o--,s):void 0,i&&A3(n[0],n[1],i))s=o<3?void 0:s,o=1;t=Object(t);while(++r<o){var a=n[r];if(a)e(t,a,r,s)}return t})}var k3=v1e;var w1e=k3(function(e,t,n,r){b3(e,t,n,r)}),io=w1e;function T1e(e,t,n,r){if(!Nt(e))return e;t=Ps(t,e);var o=-1,s=t.length,i=s-1,a=e;while(a!=null&&++o<s){var c=xo(t[o]),l=n;if(c==="__proto__"||c==="constructor"||c==="prototype")return e;if(o!=i){var u=a[c];if(l=r?r(u,c,a):void 0,l===void 0)l=Nt(u)?u:Rs(t[o+1])?[]:{}}Ty(a,c,l),a=a[c]}return e}var C3=T1e;function A1e(e,t,n){var r=-1,o=t.length,s={};while(++r<o){var i=t[r],a=zc(e,i);if(n(a,i))C3(s,Ps(i,e),a)}return s}var Cy=A1e;function k1e(e,t){return Cy(e,t,function(n,r){return Xh(e,r)})}var R3=k1e;var O3=gn?gn.isConcatSpreadable:void 0;function C1e(e){return Tt(e)||$o(e)||!!(O3&&e&&e[O3])}var P3=C1e;function I3(e,t,n,r,o){var s=-1,i=e.length;n||(n=P3),o||(o=[]);while(++s<i){var a=e[s];if(t>0&&n(a))if(t>1)I3(a,t-1,n,r,o);else Pc(o,a);else if(!r)o[o.length]=a}return o}var D3=I3;function R1e(e){var t=e==null?0:e.length;return t?D3(e,1):[]}var L3=R1e;function O1e(e){return ky(Ay(e,void 0,L3),e+"")}var M3=O1e;var P1e=M3(function(e,t){return e==null?{}:R3(e,t)}),Ry=P1e;import{homedir as jHe}from"os";import{dirname as $He,join as ao,resolve as Or}from"path";var I1e="Expected a function";function D1e(e){if(typeof e!="function")throw TypeError(I1e);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}var N3=D1e;var L1e=Object.getOwnPropertySymbols,M1e=!L1e?Lh:function(e){var t=[];while(e)Pc(t,Mh(e)),e=Yl(e);return t},U3=M1e;function N1e(e){return Dh(e,Jl,U3)}var z3=N1e;function U1e(e,t){if(e==null)return{};var n=Jh(z3(e),function(r){return[r]});return t=jc(t),Cy(e,n,function(r,o){return t(r,o[0])})}var F3=U1e;function z1e(e,t){return F3(e,N3(jc(t)))}var j3=z1e;import{join as H1e}from"path";var dR=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","ANTHROPIC_GOOGLE_CLOUD_PROJECT","ANTHROPIC_GOOGLE_CLOUD_LOCATION","ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID","CLOUD_ML_REGION"],$3=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE"];var B3="OTEL_EXPORTER_OTLP_",H3=["OTEL_LOG_RAW_API_BODIES","OTEL_LOG_USER_PROMPTS","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_TOOL_DETAILS","OTEL_LOGS_EXPORTER","ENABLE_BETA_TRACING_DETAILED","BETA_TRACING_ENDPOINT","ANT_OTEL_LOGS_EXPORTER"],K3=[B3,`ANT_${B3}`],q3={apiKeyHelper:["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],awsAuthRefresh:[...$3,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],awsCredentialExport:[...$3,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],gcpAuthRefresh:["CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL"]},F1e=["CLAUDE_CODE_MEMORY_API_BASE_URL","CLAUDE_CODE_MEMORY_API_TOKEN"];var pR=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_TOKEN","CLAUDE_CODE_ARTIFACT_ASSET_BASE_URL","CLAUDE_CODE_ARTIFACT_LIVE_BASE_URL","CLAUDE_CODE_ARTIFACT_VIEWER_BASE_URL",...F1e];var fR=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_AWS_API_KEY"],j1e=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],mR=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_3P_PROBE_WROTE_SONNET_DEFAULT","CLAUDE_CODE_3P_PROBE_WROTE_OPUS_DEFAULT"],hR=["ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES"],$1e=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],B1e=[...$1e,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var CTt=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...dR,...pR,...fR,...j1e,"CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH","CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS","CLAUDE_CODE_HOST_CREDS_FILE",...B1e,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT","GCE_METADATA_HOST","GCE_METADATA_IP","METADATA_SERVER_DETECTION","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","AWS_EC2_METADATA_SERVICE_ENDPOINT","AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE","AWS_REGION","AWS_DEFAULT_REGION",...mR,"ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_BEDROCK_REGION_PREFIX","CLAUDE_CODE_CERT_STORE","DISABLE_GROWTHBOOK","CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL",...hR]);var K1e="remote-settings.json";class G3{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;policySettingsNotified=!1;verifiedPayload=null;consentedPayload=null;resetEpoch=0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified)this.verifiedPayload=e}seedFromDisk(e){this.sessionCache=e,this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}markPolicySettingsNotified(){this.policySettingsNotified=!0}recordEligibility(e,t){if(this.eligible=e,t.memoize)this.eligibilityMemo=e}reset(){this.sessionCache=null,this.eligible=void 0,this.eligibilityMemo=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,this.consentedPayload=null,this.resetEpoch++}}var If=new G3;function gR(){return}function q1e(){return gR()??H1e(qt(),K1e)}function G1e(){try{let e=Kl(q1e()),t=pt(ml(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return t}catch{return null}}var W1e=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",...dR,...pR,"CLAUDE_CODE_CUSTOM_OAUTH_URL",...fR,"CLAUDE_CODE_API_BASE_URL","CLAUDE_CODE_OAUTH_REFRESH_TOKEN","CLAUDE_CODE_OAUTH_SCOPES","CLAUDE_CODE_OAUTH_CLIENT_ID","CLAUDE_CODE_SESSION_ACCESS_TOKEN","CLAUDE_SESSION_INGRESS_TOKEN_FILE","CLAUDE_CODE_ENVIRONMENT_KIND","CLAUDE_CODE_REMOTE_SESSION_ID","ANTHROPIC_FEDERATION_RULE_ID","ANTHROPIC_ORGANIZATION_ID","ANTHROPIC_WORKSPACE_ID","ANTHROPIC_SERVICE_ACCOUNT_ID","ANTHROPIC_IDENTITY_TOKEN","ANTHROPIC_IDENTITY_TOKEN_FILE","ANTHROPIC_SCOPE","ANTHROPIC_PROFILE","ANTHROPIC_CONFIG_DIR","HOME","XDG_CONFIG_HOME","APPDATA","USERPROFILE","ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MANAGED_SETTINGS_PATH","CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE","CLAUDE_LOCAL_OAUTH_APPS_BASE","CLAUDE_LOCAL_OAUTH_CONSOLE_BASE","CLAUDE_BRIDGE_BASE_URL","CLAUDE_BRIDGE_OAUTH_TOKEN","CLAUDE_BRIDGE_SESSION_INGRESS_URL","CLAUDE_REMOTE_TOOLS_BRIDGE_URL"].map((e)=>e.toUpperCase()));function V1e(e){if(!e?.env)return e;let t=j3(e.env,(n,r)=>W1e.has(r.toUpperCase()));return{...e,env:t}}function Z1e(){if(!gR()&&If.eligible!==!0)return null;if(If.sessionCache)return If.sessionCache;let e=G1e();if(e)return If.seedFromDisk(e),Xv(),e;return null}function W3(){let e=Z1e();if(e===If.verifiedPayload||gR())return e;return V1e(e)}import{isAbsolute as V3}from"path";var Y1e=L(()=>w({allowedDomains:I(_()).optional(),deniedDomains:I(_()).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."),strictAllowlist:C().optional().describe("When true, the sandbox runtime deterministically denies hosts not in allowedDomains instead of prompting. "+"Enforced for sandboxed commands only — in-process tools such as WebFetch are not gated by this setting. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored."),allowManagedDomainsOnly:C().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:I(_()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:C().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:C().optional(),allowMachLookup:I(_().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:j().optional(),socksProxyPort:j().optional(),tlsTerminate:w({caCertPath:_().min(1).optional(),caKeyPath:_().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. On native Windows an ephemeral CA cannot pass the sandbox trust check, so omitting the paths uses a persistent CA managed by the sandbox runtime (set up and trusted via /sandbox install); configured paths are passed to the sandbox runtime verbatim, which rejects a bad or incomplete pair at sandbox initialization. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — project settings "+"(.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),J1e=L(()=>w({allowWrite:I(_()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:I(_()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:I(_()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:I(_()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:C().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used."),disabled:C().optional().describe("macOS and Linux/WSL only: skip filesystem isolation entirely while keeping network and seccomp isolation. Ignored on native Windows, where the sandboxed process runs as a separate user with no inherent rights, so skipping the filesystem rules would "+"withhold every access grant rather than loosen them — filesystem isolation stays on there. "+"Sandboxed commands get unrestricted read/write access to the host filesystem; network egress is still confined to network.allowedDomains. Intended for deployments whose goal is egress control rather than filesystem containment. Does not change Bash prompting: sandbox.autoAllowBashIfSandboxed is independent and still defaults to true, so set it to false to keep prompting for sandboxed commands. Drops the read protection from filesystem.denyRead and credentials.files deny entries for sandboxed commands, since both are enforced by the filesystem layer this turns off; credentials.files mask entries (sentinel binds) and credentials.envVars deny/mask are unaffected. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. If managed settings configure sandbox.filesystem at all, or list any sandbox.credentials.files deny entry, only managed settings can set this: an admin who deployed filesystem restrictions must not have them switched off by a user-writable file. (sandbox.credentials.envVars and credentials.files mask entries "+"do not pin it — env scrubbing and sentinel binds are independent of the filesystem "+"layer and survive this setting.) When unset, filesystem isolation stays on.")}).optional());function Z3(e,t,n){if(e.length===0||e.some((r)=>r.length===0))n.addIssue({code:hr.custom,path:["maskClaims"],message:"maskClaims must name at least one non-empty claim — omit maskClaims for whole-token masking."});if(t===void 0)n.addIssue({code:hr.custom,path:["maskClaims"],message:"maskClaims requires decode — without a decode format there is no token to read claims from. Set decode, or omit maskClaims."})}function Y3(e,t){let n;try{n=new RegExp(e)}catch(o){t.addIssue({code:hr.custom,path:["extract"],message:`extract is not a valid regular expression: ${Uo(o)}`});return}if(new RegExp(n.source+"|").exec("").length-1<1)t.addIssue({code:hr.custom,path:["extract"],message:"extract must contain at least one capturing group — "+'group 1 is the credential value to mask (e.g. "token:\\s*(\\S+)").'})}function J3(e){if(typeof e!=="object"||e===null)return e;let t=e;if(t.mode!=="deny")return e;let n={...t};if("extract"in n&&typeof n.extract!=="string")delete n.extract;if("onExtractNoMatch"in n&&n.onExtractNoMatch!=="warn"&&n.onExtractNoMatch!=="deny"&&n.onExtractNoMatch!=="error")delete n.onExtractNoMatch;if("decode"in n&&n.decode!=="jwt")delete n.decode;if("maskClaims"in n&&!(Array.isArray(n.maskClaims)&&n.maskClaims.every((r)=>typeof r==="string")))delete n.maskClaims;if("maskDuplicates"in n&&typeof n.maskDuplicates!=="boolean")delete n.maskDuplicates;if("injectHosts"in n&&!(Array.isArray(n.injectHosts)&&n.injectHosts.every((r)=>typeof r==="string")))delete n.injectHosts;return n}var Oy=L(()=>xt(J3,w({path:_().min(1).describe("Path to a credential file or directory. Same resolution as sandbox.filesystem.* paths: absolute, ~ expanded, or relative to the settings file root (project root for project settings, ~/.claude for user settings)."),mode:G(["deny","mask"]).describe("Access mode for this path. `deny` blocks reads inside the sandbox; `mask` shows sandboxed commands a sentinel-substituted copy (whole-file, or only the spans captured by `extract`) and the "+"host proxy swaps sentinel→real on egress to `injectHosts`. "+"On macOS and Windows `mask` currently degrades to `deny`."),extract:_().optional().describe("Optional regex for structured masking when mode is `mask`. Applied globally to the file; capture group 1 of each match is a credential value, and only those captured spans are replaced "+"with sentinels — the rest of the file is preserved so a tool "+"that parses it (.netrc, JSON, YAML) still succeeds. Without `extract`, the entire file content is replaced with one sentinel (whole-file masking, suited to single-secret files). If the regex matches nothing, behavior is governed by `onExtractNoMatch` (default `warn`). Accepted but ignored for `deny`."),onExtractNoMatch:G(["warn","deny","error"]).optional().describe("What to do when `extract` matches nothing in the file — or, "+"with `decode`, when no candidate survives verification. `warn` (default) emits a stderr warning and leaves the file readable as-is inside the sandbox (fail-open, for credentials that may be legitimately absent); `deny` degrades the entry to "+"mode `deny` so the file is unreadable (fail-closed) — under "+"`sandbox.filesystem.disabled` it is treated as `error`, since read-denies are dropped in that mode; `error` aborts at sandbox setup so nothing runs until the config is fixed. Only meaningful when mode is `mask` and `extract` or `decode` is set; accepted but ignored otherwise."),decode:G(["jwt"]).optional().describe("Optional encoded-credential format for `mask` mode. `jwt`: candidates are located with a built-in JWT regex (or the explicit `extract` pattern, if set), verified to actually be JWTs before masking, and replaced with a structurally valid fake JWT so client-side token parsing inside the sandbox keeps working. If no candidate verifies, behavior is governed by `onExtractNoMatch` (default `warn`). Accepted but ignored for `deny`."),maskClaims:I(_()).optional().describe("Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel and the token is rebuilt around the modified payload; all other claims are preserved so a tool that decodes the token and reads a non-secret claim keeps working. Requires `decode`. If no named claim matches in any verified token, behavior is governed by `onExtractNoMatch` (default `warn`). Only meaningful when mode is `mask`; accepted but ignored for `deny`."),maskDuplicates:C().optional().describe("If true, verbatim occurrences of each captured credential value outside the regex-matched spans are also replaced with the "+"corresponding sentinel — for a secret repeated where the regex "+"does not reach (e.g. pasted into a comment). Matches raw substrings, so short or common values may corrupt unrelated content; intended for long, high-entropy secrets. Defaults to false. Only meaningful when mode is `mask` and `extract` or `decode` is set; accepted but ignored otherwise."),injectHosts:I(_()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")}).superRefine((e,t)=>{if(e.mode==="mask"&&e.path.endsWith("/"))t.addIssue({code:hr.custom,path:["path"],message:'Credential mode "mask" applies to a single file, not a directory. List the specific credential file(s), or use "deny" for the directory.'});if(e.mode==="mask"&&e.extract!==void 0)Y3(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)Z3(e.maskClaims,e.decode,t)}))),Xl=()=>_().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores"),Py=L(()=>xt(J3,w({name:Xl().describe("Environment variable name."),mode:G(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the "+"host proxy swaps sentinel→real on egress to `injectHosts`."),extract:_().optional().describe("Optional regex for structured masking when mode is `mask`. Applied globally to the value; capture group 1 of each match is a credential value, and only those captured spans are "+"replaced with sentinels — the rest of the value is preserved "+"so a tool that parses it (a `DATABASE_URL` connection string, a composite `KEY:SECRET` pair) still succeeds inside the sandbox. Without `extract`, the entire value is replaced with one sentinel (whole-value masking, suited to bare tokens). If the regex matches nothing, behavior is governed by `onExtractNoMatch` (default `warn`). Cannot be combined with `decode` (the decode path never consults it). Accepted but ignored for `deny`."),onExtractNoMatch:G(["warn","deny","error"]).optional().describe("What to do when `extract` matches nothing in the value. `warn` (default) emits a stderr warning and lets the variable pass through unmasked (fail-open, for credentials that may be legitimately absent); `deny` unsets the variable inside the sandbox (fail-closed); `error` aborts at sandbox setup so nothing runs until the config is fixed. Only meaningful when mode is `mask` and `extract` is set without `decode`. On a mask entry with `decode`, the runtime takes the decode path and never consults this field, so a fail-closed setting "+"cannot be honored — `deny` and `error` are rejected there; "+"only `warn` is accepted. In all other shapes the field is accepted but ignored."),decode:G(["jwt"]).optional().describe("Optional encoded-credential format for `mask` mode. `jwt`: the variable's whole value is verified to actually be a JWT and replaced with a structurally valid fake JWT so client-side token parsing inside the sandbox keeps working; the proxy swaps the whole fake token on egress. If the value does not verify, the variable is left unmasked with a stderr warning "+"(fail-open). Cannot be combined with `extract` — the decode "+"path never consults it. Accepted but ignored for `deny`."),maskClaims:I(_()).optional().describe("Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel and the token is rebuilt around the modified payload; all other claims are preserved so claim-reading clients keep working. Requires `decode`. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is `mask`; accepted but ignored for `deny`."),injectHosts:I(_()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")}).superRefine((e,t)=>{if(e.mode==="mask"&&e.extract!==void 0)Y3(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)Z3(e.maskClaims,e.decode,t);if(e.mode==="mask"&&e.decode!==void 0&&e.extract!==void 0)t.addIssue({code:hr.custom,path:["extract"],message:"extract cannot be combined with decode on an env entry — the runtime takes the decode path (whole-value JWT verification) and never consults extract, silently disabling the structured masking. Remove one of the two."});if(e.mode==="mask"&&e.decode!==void 0&&(e.onExtractNoMatch==="deny"||e.onExtractNoMatch==="error"))t.addIssue({code:hr.custom,path:["onExtractNoMatch"],message:"onExtractNoMatch cannot be honored on an env entry with decode — the runtime takes the decode path (which is unconditionally fail-open on verify failure) and never consults extract or onExtractNoMatch. Remove onExtractNoMatch, or drop decode to use extract-based masking (whose no-match handling does honor it)."})}))),Ql=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"];var _R="_INVALID_PAIR_",X3="_PARENT_PAIR_SUPPRESSOR_";var Iy=L(()=>w({accessKeyIdVar:Xl().describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:Xl().describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:Xl().optional().describe("Optional name of the masked env var holding the AWS session token (temporary credentials). When set, the proxy sends the real token as x-amz-security-token on re-signed requests and adds it to the signed header set if the client did not.")}).superRefine((e,t)=>{let n=new Map;for(let[r,o]of[["accessKeyIdVar",e.accessKeyIdVar],["secretAccessKeyVar",e.secretAccessKeyVar],["sessionTokenVar",e.sessionTokenVar]]){if(o===void 0)continue;let s=n.get(o);if(s!==void 0)t.addIssue({code:hr.custom,path:[r],message:`${r} names the same env var ('${o}') as ${s} — each pair member must be a distinct variable.`});else n.set(o,r)}})),X1e=L(()=>{let e=G(["deny","passthrough"]);return w({streaming:e.optional().describe("Policy for aws-chunked streaming uploads (x-amz-content-sha256: STREAMING-*): per-chunk signatures chain off the seed signature, so re-signing would require rewriting the body. `deny` (default) fails closed with a 403; `passthrough` forwards the request unre-signed (the upstream will reject its signature)."),presigned:e.optional().describe("Policy for presigned URLs (X-Amz-Algorithm/X-Amz-Signature in the query, no Authorization header): the signature lives in the URL itself. `deny` (default) or `passthrough`."),sigv4a:e.optional().describe("Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. `deny` (default) or `passthrough`.")})}),Q1e=L(()=>w({files:I(Oy()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox; `mask` substitutes a sentinel inside the sandbox (whole-file, or per-`extract` capture) and injects the real value at the proxy. On macOS and Windows `mask` degrades to `deny`."),envVars:I(Py()).optional().describe("Environment variables to protect. `deny` unsets the variable for sandboxed commands; `mask` substitutes a sentinel inside the sandbox and injects the real value at the proxy."),allowPlaintextInject:C().optional().describe("Allow sentinel→real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored."),awsPairs:I(Iy()).optional().describe("Explicit groupings of masked env vars into AWS credential pairs for SigV4 re-signing, for non-standard variable names. The conventional AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN trio is paired automatically when masked. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored. A member is only usable when its env var is forwarded as a whole-value `mask` entry (an entry carrying `extract` or `decode` does not "+"qualify — re-signing needs the whole real value). A pair "+"whose key id or secret member is unusable never re-signs: it is dropped, unless it names a conventional AWS variable, in which case it is forwarded as an inert suppressor so implicit auto-pairing stays overridden. A pair whose ONLY unusable member is the session token still re-signs, without an x-amz-security-token (temporary-credential requests fail upstream until the entry is fixed)."),sigv4:X1e().optional().describe("Policies for AWS SigV4 request shapes the proxy cannot re-sign (streaming, presigned, sigv4a) when they reference a masked credential pair: `deny` (default) or `passthrough`. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored.")}).superRefine((e,t)=>{let n=new Set;for(let[r,o]of(e?.awsPairs??[]).entries()){let s=[["accessKeyIdVar",o.accessKeyIdVar],["secretAccessKeyVar",o.secretAccessKeyVar],["sessionTokenVar",o.sessionTokenVar]],i=new Set;for(let[a,c]of s){if(c===void 0)continue;if(n.has(c))t.addIssue({code:hr.custom,path:["awsPairs",r,a],message:`"${c}" appears in more than one awsPairs slot (within or across pairs) — each variable can fill exactly one slot.`});i.add(c)}for(let a of i)n.add(a)}}).optional()),yR=L(()=>w({enabled:C().optional(),failIfUnavailable:C().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:C().optional(),allowUnsandboxedCommands:C().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:Y1e(),filesystem:J1e(),credentials:Q1e(),ignoreViolations:q(_(),I(_())).optional(),enableWeakerNestedSandbox:C().optional(),enableWeakerNetworkIsolation:C().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** — opens a potential data exfiltration vector through the trustd service. Default: false"),allowAppleEvents:C().optional().describe("macOS only: Allow sandboxed commands to send Apple Events (and look up the appleeventsd Mach service). Needed for `open`, `osascript`, and browser-based auth flows that open URLs. "+"**Removes code-execution isolation** — sandboxed commands can launch other applications "+"unsandboxed with no user prompt, and can script running apps (e.g. Terminal) subject to the user's per-app TCC automation consent. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. Default: false"),excludedCommands:I(_()).optional(),ripgrep:w({command:_(),args:I(_()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:xt((e)=>typeof e==="string"&&V3(e)?e:void 0,_()).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:xt((e)=>typeof e==="string"&&V3(e)?e:void 0,_()).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());function fa(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Q3=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];function eBe(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function e9(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&eBe(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{userInfo as tBe}from"os";var t9="com.anthropic.claudecode",Df="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Lf="HKCU\\SOFTWARE\\Policies\\ClaudeCode",ni="Settings",n9="/usr/bin/plutil",r9=["-convert","json","-o","-","--"],o9=5000,bR="/mnt/c/Windows/System32/reg.exe",eu="/mnt/c/Program Files/ClaudeCode";function Dy(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Pe("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function s9(){let e="";try{e=tBe().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${t9}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${t9}.plist`,label:"device-level managed preferences"}),t}var Mf=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],i9=[...Mf],a9=i9;function Nf(e){return e==="manual"?"default":e}var sAt=`Cannot set permission mode: must be one of ${i9.join(", ")}`;var c9=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"],l9=["normal","vim"],u9=["auto","tmux","iterm2","in-process"],nBe=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],d9=["auto",...nBe],p9=["auto","alwaysAsk","disabled"];var lAt=Bo()==="macos"?"⏺":"●";var gAt=L(()=>xt(Nf,G(a9))),_At=L(()=>xt(Nf,G(Mf)));import{posix as hBe,win32 as gBe}from"path";import{isIPv4 as _Be,isIPv6 as yBe}from"net";var f9=["bash","powershell"];var Uf=L(()=>_().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 rBe(){let e=w({type:N("command").describe("Shell command hook type"),command:_().describe("Shell command to execute"),args:I(_()).optional().describe("Argument list for exec form. When present, `command` is resolved as "+"an executable and spawned directly with these arguments — 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:Uf(),shell:G(f9).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:j().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution"),async:C().optional().describe("If true, hook runs in background without blocking"),asyncRewake:C().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:_().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:_().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=w({type:N("prompt").describe("LLM prompt hook type"),prompt:_().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:_().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:C().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:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")}),n=w({type:N("mcp_tool").describe("MCP tool hook type"),server:_().describe("Name of an already-configured MCP server to invoke"),tool:_().describe("Name of the tool on that server to call"),input:q(_(),Se()).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:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")}),r=w({type:N("http").describe("HTTP hook type"),url:_().url().describe("URL to POST the hook input JSON to"),if:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for this specific request"),headers:q(_(),_()).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:I(_()).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:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")}),o=w({type:N("agent").describe("Agentic verifier hook type"),prompt:_().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:_().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:r,AgentHookSchema:o,McpToolHookSchema:n}}var m9=L(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:r,McpToolHookSchema:o}=rBe();return pi("type",[e,t,n,r,o])}),h9=L(()=>w({matcher:_().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:I(m9()).describe("List of hooks to execute when the matcher matches")})),ma=L(()=>ZI(G(wa),I(h9())));var TAt=L(()=>G(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),AAt=L(()=>G(["stdio","sse","sse-ide","http","ws","sdk"])),tu=L(()=>N("comms").optional().catch(void 0)),ri=L(()=>j().int().positive()),oBe=300000,g9=L(()=>j().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function _9({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,oBe)}}}var sBe=L(()=>w({type:N("stdio").optional(),command:_().min(1,"Command cannot be empty"),args:I(_()).default([]),env:q(_(),_()).optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),iBe=L(()=>C()),y9=L(()=>w({clientId:_().optional(),callbackPort:j().int().positive().optional(),authServerMetadataUrl:_().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:_().min(1).optional(),xaa:iBe().optional()})),b9=L(()=>w({name:_(),permission_policy:G(["always_allow","always_ask","always_deny"]).optional()})),aBe=L(()=>w({type:N("sse"),url:_(),headers:q(_(),_()).optional(),headersHelper:_().optional(),oauth:y9().optional(),timeout:ri().optional(),request_timeout_ms:g9(),tools:I(b9()).optional(),alwaysLoad:C().optional(),discoveryCache:C().optional(),role:tu(),toolPermissions:q(_(),SR()).optional()}).transform(_9)),cBe=L(()=>w({type:N("sse-ide"),url:_(),ideName:_(),ideRunningInWindows:C().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),lBe=L(()=>w({type:N("ws-ide"),url:_(),ideName:_(),authToken:_().optional(),ideRunningInWindows:C().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),uBe=L(()=>w({type:G(["http","streamable-http"]).transform(()=>"http"),url:_(),headers:q(_(),_()).optional(),headersHelper:_().optional(),oauth:y9().optional(),timeout:ri().optional(),request_timeout_ms:g9(),tools:I(b9()).optional(),alwaysLoad:C().optional(),discoveryCache:C().optional(),role:tu(),toolPermissions:q(_(),SR()).optional()}).transform(_9)),dBe=L(()=>w({type:N("ws"),url:_(),headers:q(_(),_()).optional(),headersHelper:_().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),pBe=L(()=>w({type:N("sdk"),name:_(),timeout:ri().optional(),alwaysLoad:C().optional()})),SR=L(()=>G(["allow","ask","blocked"])),fBe=L(()=>w({type:N("claudeai-proxy"),url:_(),id:_(),displayName:_().optional(),iconUrl:_().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),toolPermissions:q(_(),SR()).optional(),stateless:C().optional(),cachedInitResponse:q(_(),Se()).nullish(),discoverSupport:G(["supported","legacy","unknown"]).optional().catch(void 0),cachedDiscoverResponse:q(_(),Se()).nullish(),eligible:C().nullish(),ineligibleReason:_().nullish()})),Ly=L(()=>oe([sBe(),aBe(),cBe(),lBe(),uBe(),dBe(),pBe(),fBe()]));var kAt=L(()=>w({mcpServers:q(_(),Ly())}));function mBe(e){return r2(e).replace(/ {2,}/g," ").trim()}function S9(e,t=160){let n=mBe(e);return n.length>t?`${Zf(n,t)}…`:n}var A9=500,bBe=32;function k9(){return{sourceCommand:_().max(A9+20).optional().catch(void 0).describe("The `command`-source command the user accepted at explicit install/update. The once-per-session background re-resolve only runs while the marketplace entry still declares this exact command; a changed command (or an entry that became command-sourced later) is skipped with a warning until the user runs an explicit update."),sourceProducerPath:_().max(4096).refine(x9,{message:"must be an absolute path"}).optional().catch(void 0).describe("The directory a `command`-source plugin was last resolved to (what its command printed). Served in place in link mode and re-copied every session in copy mode, so the sandbox write-denies it; refreshed on every install/update, including no-op updates that resolve to a new location."),previousProducerPaths:I(Se()).transform((e)=>e.filter((t)=>typeof t==="string"&&t.length<=4096&&x9(t)).slice(-bBe)).optional().catch(void 0).describe("Producer directories this installation was resolved to before the current one (most recent last, bounded). A concurrent older session may still serve one of them, so the sandbox keeps write-denying them too.")}}function x9(e){return hBe.isAbsolute(e)||gBe.isAbsolute(e)}var SBe=/[^\x20-\x7E]| {4,}/,xBe=new Set(["claude-community","claude-plugins-community","healthcare"]),EBe=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","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins"]),C9=new Set([...EBe,...xBe]);var vBe=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,wBe=/[^\u0020-\u007E]/;function TBe(e){if(C9.has(e.toLowerCase()))return!1;if(wBe.test(e))return!0;return vBe.test(e)}var Ao=L(()=>_().startsWith("./")),ha=L(()=>Ao().endsWith(".json")),E9=L(()=>oe([N("."),Ao()])),v9=L(()=>oe([Ao().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"),_().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),ER=L(()=>Ao().endsWith(".md")),vR=L(()=>oe([ER(),Ao()])),R9=L(()=>_().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)=>!TBe(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/'})),TR=L(()=>w({name:_().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:_().optional().describe("Contact email for support or feedback"),url:_().optional().describe("Website, GitHub profile, or organization URL")})),ABe=L(()=>w({$schema:_().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:_().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)"),displayName:_().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version:_().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:_().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:TR().optional().describe("Information about the plugin creator or maintainer"),homepage:_().url().optional().describe("Plugin homepage or documentation URL"),repository:_().optional().describe("Source code repository URL"),license:_().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:I(_()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:C().optional().describe("Whether the plugin starts enabled when the user has no explicit enabled/disabled setting for it (default: true). Explicit enabledPlugins values always win, and a plugin required by an enabled dependent is enabled regardless of this value."),dependencies:I(hHe()).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.`),metadata:xt((e)=>fa(e)?e:void 0,q(_(),Se()).optional()).describe("Free-form metadata for the plugin author's own use (e.g. entitlement or catalog fields). Preserved on the parsed manifest but not read by Claude Code.")})),qAt=L(()=>w({description:_().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:bm(()=>ma()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),kBe=L(()=>w({hooks:oe([ha().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),bm(()=>ma()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),I(oe([ha().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),bm(()=>ma()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),CBe=L(()=>w({source:vR().optional().describe("Path to command markdown file, relative to plugin root"),content:_().optional().describe("Inline markdown content for the command"),description:_().optional().describe("Command description override"),argumentHint:_().optional().describe('Hint for command arguments (e.g., "[file]")'),model:_().optional().describe("Default model for this command"),allowedTools:I(_()).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'})),RBe=L(()=>w({commands:oe([vR().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both."),I(vR().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — 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."),q(_(),CBe()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),OBe=L(()=>w({agents:oe([ER().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both."),I(ER().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both.")).describe("List of agent file paths. When set, the agents/ directory is not auto-loaded.")])})),PBe=L(()=>w({skills:oe([E9().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself). Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan).'),I(E9().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself).')).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),O9=L(()=>w({outputStyles:oe([Ao().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — list its files here if you want both."),I(Ao().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — 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.")])})),IBe=L(()=>_().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),DBe=16,LBe=L(()=>w({id:IBe(),remote:_().max(256).regex(/^(npm:[@a-z0-9/._-]+(@[a-z0-9._+-]+)?|github:[\w.-]+\/[\w.-]+@[\w./-]+#.+\.js)$/,"must be npm:<pkg>[@ver] or github:<owner>/<repo>@<ref>#<path>.js").optional(),integrity:_().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),MBe=L(()=>w({syntaxHighlighting:w({hljsLanguages:I(LBe()).max(DBe)}).strict()})),P9=L(()=>w({themes:oe([Ao().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — list its files here if you want both."),I(Ao().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — 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.")])})),NBe=L(()=>w({})),w9=L(()=>_().min(1)),UBe=L(()=>_().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),zBe=L(()=>w({mcpServers:oe([ha().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),v9().describe("Path or URL to MCPB file containing MCP server configuration"),q(_(),Ly()).describe("MCP server configurations keyed by server name"),I(oe([ha().describe("Path to MCP servers configuration file"),v9().describe("Path or URL to MCPB file"),q(_(),Ly()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),I9=L(()=>w({type:G(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:_().describe("Human-readable label shown in the config dialog"),description:_().describe("Help text shown beneath the field in the config dialog"),required:C().optional().describe("If true, validation fails when this field is empty"),default:oe([_(),j(),C(),I(_())]).optional().describe("Default value used when the user provides nothing"),multiple:C().optional().describe("For string type: allow an array of strings"),sensitive:C().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:j().optional().describe("Minimum value (number type only)"),max:j().optional().describe("Maximum value (number type only)")}).strict()),FBe=L(()=>w({userConfig:q(_().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) — they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),I9()).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.")})),jBe=L(()=>w({channels:I(w({server:_().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:_().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:q(_(),I9()).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.")})),T9=L(()=>Sx({command:_().min(1).refine((e)=>{if(e.includes(" ")&&!e.startsWith("/"))return!1;return!0},{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:I(w9()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:q(UBe(),w9()).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:G(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:q(_(),_()).optional().describe("Environment variables to set when starting the server"),initializationOptions:Se().optional().describe("Initialization options passed to the server during initialization"),settings:Se().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:_().optional().describe("Workspace folder path to use for the server"),startupTimeout:j().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:j().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:C().optional().describe("Whether to restart the server if it crashes"),maxRestarts:j().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:C().optional().describe("Whether to push publishDiagnostics into the agent context after edits. Set to false to keep LSP navigation (goToDefinition, hover, etc.) but suppress automatic diagnostic injection. Defaults to true.")})),$Be=L(()=>Sx({name:_().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:_().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 — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:_().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:oe([N("always"),_().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).')})),BBe=L(()=>I($Be()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),D9=L(()=>w({monitors:oe([ha().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),BBe()]).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.")})),HBe=L(()=>w({lspServers:oe([ha().describe("Path to .lsp.json configuration file relative to plugin root"),q(_(),T9()).describe("LSP server configurations keyed by server name"),I(oe([ha().describe("Path to LSP configuration file"),q(_(),T9()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),L9=L(()=>_().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")),KBe=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,qBe=/^[0-9a-f]{64}$/;var GBe=64;var WBe=L(()=>w({sha256:_().regex(qBe)}));function VBe(e){let t=q(_(),Se()).safeParse(e);if(!t.success)return;let n=Object.create(null),r=0;for(let[o,s]of Object.entries(t.data)){if(r>=GBe)break;let i=WBe().safeParse(s);if(KBe.test(o)&&i.success)n[o]=i.data,r++}return r>0?n:void 0}var ZBe=L(()=>w({binaries:Se().transform(VBe).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),YBe=L(()=>w({settings:q(_(),Se()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),JBe=L(()=>w({experimental:xt((e)=>fa(e)?e:void 0,w({...P9().partial().shape,...MBe().partial().shape,...D9().partial().shape,...O9().partial().shape,evals:oe([_(),I(_())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))}));var XBe=L(()=>w({...ABe().shape,...kBe().partial().shape,...RBe().partial().shape,...OBe().partial().shape,...PBe().partial().shape,...O9().partial().shape,...P9().partial().shape,...NBe().shape,...jBe().partial().shape,...zBe().partial().shape,...HBe().partial().shape,...D9().partial().shape,...YBe().partial().shape,...FBe().partial().shape,...ZBe().partial().shape,...JBe().partial().shape})),M9=new Set(["url","github","git","npm","file","directory","skills-dir","hostPattern","pathPattern","settings"]),zf=L(()=>pi("source",[w({source:N("url"),url:_().url().describe("Direct URL to marketplace.json file"),headers:q(_(),_()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),w({source:N("github"),repo:_().describe('GitHub repository in owner/repo format. ONLY in the managed-settings policy lists (strictKnownMarketplaces / blockedMarketplaces) the owner-wildcard form "owner/*" matches every repository under exactly that owner. Everywhere else (marketplace add, extraKnownMarketplaces, known_marketplaces.json) the value '+"must name a single repository — a wildcard is taken literally and fails to clone."),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:_().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:I(_()).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.'),skipLfs:C().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),w({source:N("git"),url:_().describe("Full git repository URL"),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:_().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:I(_()).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.'),skipLfs:C().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),w({source:N("npm"),package:L9().describe("NPM package containing marketplace.json")}),w({source:N("file"),path:_().describe("Local file path to marketplace.json")}),w({source:N("directory"),path:_().describe("Local directory containing .claude-plugin/marketplace.json")}),w({source:N("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),w({source:N("hostPattern"),hostPattern:_().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$").')}),w({source:N("pathPattern"),pathPattern:_().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.')}),w({source:N("settings"),name:R9().refine((e)=>!C9.has(e.toLowerCase()),{message:"Reserved 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 — "+"validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:I(rHe()).describe("Plugin entries declared inline in settings.json"),owner:TR().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).")])),xR=L(()=>_().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),QBe=L(()=>_().regex(/^[0-9a-fA-F]{64}$/,"Must be a 64-character hex SHA-256 digest"));function wR(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t.endsWith("."))t=t.slice(0,-1);if(t===""||t==="localhost"||t.endsWith(".localhost"))return!0;if(_Be(t)){let[s=0,i=0,a=0,c=0]=t.split(".").map(Number);return s===127||s===169&&i===254||s===0||s===100&&i===100&&a===100&&c===200}if(!yBe(t))return!1;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);if(n?.[1])return wR(n[1]);let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(r?.[1]!==void 0&&r[2]!==void 0){let s=parseInt(r[1],16),i=parseInt(r[2],16);return wR(`${s>>8}.${s&255}.${i>>8}.${i&255}`)}if(t==="::1"||t==="::"||t==="fd00:ec2::254")return!0;let o=parseInt(/^([0-9a-f]{1,4}):/.exec(t)?.[1]??"0",16);return o>=65152&&o<=65215}var eHe="Archive URLs must use https:// and must not point at a loopback, link-local, or cloud-metadata host";function tHe(e){try{let t=new URL(e);return t.protocol==="https:"&&!wR(t.hostname)}catch{return!1}}var nHe=L(()=>w({source:N("archive"),url:_().url().refine(tHe,{message:eHe}).describe("HTTPS URL of a zip archive containing the plugin. The plugin root (the directory holding .claude-plugin/) may be at the top of the archive "+"or nested one directory deep — a single wrapping directory is stripped."),sha256:QBe().optional().describe("SHA-256 digest of the archive. When set, every download is verified against it and the install is refused on mismatch. It also serves as the version identity when neither plugin.json nor the marketplace entry declares a `version`. Recommended. Note the update signal is the version string (plugin.json "+"version, else the entry version, else this digest) — changing only the digest "+"while a version is declared does not trigger an update.")}).describe("Plugin distributed as a zip archive fetched over HTTPS — for hosting on any "+"static file server or artifact repository (S3, GitLab, nginx) with no git or npm on the client. Authentication comes from the enclosing marketplace: when the archive URL shares the marketplace url-source's origin, that source's headers are sent with the download.")),N9=L(()=>oe([xt((e)=>e==="."?"./":e,Ao()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),w({source:N("npm"),package:L9().or(_().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:_().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:_().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),w({source:N("url"),url:_().describe("Full git repository URL (https:// or git@)"),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:xR().optional().describe("Specific commit SHA to use")}),w({source:N("github"),repo:_().describe("GitHub repository in owner/repo format"),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:xR().optional().describe("Specific commit SHA to use")}),w({source:N("git-subdir"),url:_().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:_().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:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:xR().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."),nHe(),w({source:N("command"),command:_().min(1).max(A9,{message:"command must not be longer than the install consent UI can display"}).refine((e)=>!SBe.test(e),{message:"command must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"}).describe("Shell command that prints the absolute path of the plugin directory on stdout (exactly one line) and exits 0. It must leave a complete plugin in that directory before exiting; the directory is copied into the plugin cache, so the printed path may change between runs (it is re-resolved on every install and update, and once per session in the background). Runs through the platform shell (sh on macOS/Linux, cmd.exe on Windows) from the user's home directory with Claude Code's subprocess environment."),timeout:j().int().positive().max(600).optional().describe("Seconds to wait for the command before giving up (default: 60)"),mode:G(["copy","link"]).optional().describe("copy (default): the printed directory is copied into the plugin cache and content-hashed, so it may be deleted afterwards. link: the cache entry links to the printed directory "+"in place (no copy, no size limit; macOS/Linux) — for large exports; the directory must then stay "+"valid while Claude Code runs, and a different printed path is what signals new content.")}).describe("Plugin directory produced by a locally installed tool (e.g. an IDE that renders its plugin for the currently selected SDK). Claude Code runs the command, copies the directory it prints, and re-runs it in the background at startup to pick up changes."),w({source:N("unsupported"),error:_().optional()}).describe("Placeholder for source types this Claude Code version does not recognize, or a known type whose fields failed validation (then `error` "+"holds the reason). Never authored by hand — 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 an actionable message.")])),rHe=L(()=>w({name:_().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:N9().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:_().optional(),version:_().optional(),strict:C().optional()}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url, archive, command). 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, archive, command)."}));var oHe=L(()=>w({cli:I(_().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:I(_().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) — exact, case-insensitive match against '+"hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path."),filesRead:I(_().max(256)).max(10).optional().describe('Glob patterns (e.g. ["**/*.tf"]) — the plugin is relevant when a file Claude has read '+"this session matches any pattern. Matched against read-file paths, forward-slash normalized, case-insensitive."),manifestDeps:I(w({file:_().max(256),pattern:_().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: "+"`file` matches the manifest filename (package.json, go.mod, requirements.txt, …); "+"`pattern` matches the dependency declaration inside that file. Evaluated against files read this session."),cwd:I(_().max(256)).max(10).optional().describe('Glob patterns (e.g. ["Engine/Source/Runtime/Renderer/**"]) — the plugin is relevant when the '+`session's working directory is at or under a directory matching the pattern. Matched against the cwd both relative to the enclosing git repo root and as an absolute path, forward-slash normalized, case-insensitive. A bare directory (no glob characters) means "cwd is at or under this directory". Known at session start, so this signal can surface a suggestion before the first turn.`)})),sHe=L(()=>w({topic:_().max(64).optional().describe('What the user is working with when this plugin is relevant — fills "Working with {topic}?". '+'Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:oHe().optional().describe("Matchers that determine when the plugin is relevant.")})),iHe=L(()=>XBe().partial().extend({name:_().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:N9().describe("Where to fetch the plugin from"),category:_().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:I(_()).optional().describe("Tags for searchability and discovery"),strict:C().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:xt((e)=>fa(e)?e:void 0,sHe().optional()).describe(`Declares when this plugin is relevant to the user's work. Consumed by the spinner tip ("Working with {topic}?"), session-start auto-suggest, and marketplace browse ranking.`)})),aHe=L(()=>w({name:_().min(1).refine((e)=>!e.includes(" "))}));function cHe(e){let t=iHe();return e.flatMap((n,r)=>{let o=t.safeParse(n);if(o.success){let a=o.data.source;if(typeof a==="object"&&a.source==="unsupported"&&a.error!==void 0)return[{...o.data,source:{source:"unsupported"}}];return[o.data]}let s=aHe().safeParse(n).data?.name,i=o.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(s){ce(`Stubbing unparseable marketplace plugin entry (${s}): ${i}`,{level:"warn"});let a=AR(n)?void 0:uHe(o.error.issues)??My(o.error.issues);return[{name:s,source:{source:"unsupported",...a&&{error:a}},strict:!0}]}return ce(`Dropping unparseable marketplace plugin entry (index ${r}): ${i}`,{level:"warn"}),[]})}var lHe=new Set(["npm","url","github","git-subdir","archive","command","unsupported"]);function AR(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.source;return typeof n==="string"&&!lHe.has(n)}function uHe(e){let t=e.find((r)=>r.path.length===1&&r.path[0]==="source");if(!t||t.code!=="invalid_union")return;let n=t.errors.find((r)=>!r.some((o)=>o.path.length===0||o.code==="invalid_value"&&o.path[0]==="source"));if(!n||n.length===0)return;return My(n.map((r)=>({...r,path:["source",...r.path]})))}var dHe=/^[A-Za-z0-9_$.-]{1,40}$/;function nu(e){return dHe.test(e)?e:"<key>"}var pHe=3,fHe=160;function My(e){let t=e.slice(0,pHe).map((r)=>{let o=r.path.map(String).map((i)=>nu(i)).join("."),s=r.code==="unrecognized_keys"?`Unrecognized ${r.keys.length===1?"field":"fields"}: ${r.keys.map(nu).join(", ")}`:S9(r.message,fHe);return o?`${o}: ${s}`:s}),n=e.length-t.length;return n>0?`${t.join(", ")} (+${n} more)`:t.join(", ")}var GAt=L(()=>w({$schema:_().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:R9(),version:_().optional().describe("Marketplace manifest version"),description:_().optional().describe("Human-readable description of this marketplace"),owner:TR().describe("Marketplace maintainer or curator information"),plugins:I(Se()).transform(cHe).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:C().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:w({pluginRoot:_().optional().describe("Base path for relative plugin sources"),version:_().optional().describe("Marketplace version"),description:_().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:I(_()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:q(_(),_().nullable()).optional().catch(void 0).describe("Append-only map of old plugin name → current name (or null when removed). The loader follows this on plugin-not-found and migrates user settings to the new name.")})),U9=L(()=>_().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")),mHe=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,hHe=L(()=>oe([_().regex(mHe,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),w({name:_().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:_().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),gHe=L(()=>w({version:_().describe("Currently installed version"),installedAt:_().describe("ISO 8601 timestamp of installation"),lastUpdated:_().optional().describe("ISO 8601 timestamp of last update"),installPath:_().describe("Absolute path to the installed plugin directory"),gitCommitSha:_().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:_().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:C().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)."),...k9()})),WAt=L(()=>w({version:N(1).describe("Schema version 1"),plugins:q(U9(),gHe()).describe("Map of plugin IDs to their installation metadata")})),_He=L(()=>G(["managed","user","project","local"])),yHe=L(()=>w({scope:_He().describe("Installation scope"),projectPath:_().optional().describe("Project path (required for project/local scopes)"),installPath:_().describe("Absolute path to the versioned plugin directory"),version:_().optional().describe("Currently installed version"),installedAt:_().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:_().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:_().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:_().optional().describe("Tag-derived semver this install resolved to"),auto:C().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep."),...k9()})),VAt=L(()=>w({version:N(2).describe("Schema version 2"),plugins:q(U9(),I(yHe())).describe("Map of plugin IDs to arrays of installation entries")})),bHe=L(()=>w({source:zf().describe("Where to fetch the marketplace from"),installLocation:_().describe("Local cache path where marketplace manifest is stored"),lastUpdated:_().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:C().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),ZAt=L(()=>q(_(),bHe()));var SHe=["autoMode","deepLink","voice","briefView","screenReader"],kR={},Ny={autoMode:{buildGate:()=>!1,shape:()=>kR,permissionsShape:()=>kR,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:G(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!0,shape:()=>({voiceEnabled:C().optional().describe("Enable voice mode (hold-to-talk dictation)")})},briefView:{buildGate:()=>!0,shape:()=>({defaultView:G(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>kR}};function CR(){return SHe.filter((e)=>Ny[e].buildGate())}function z9(e){let t={};for(let n of e)t={...t,...Ny[n].shape()};return t}function F9(e){let t={};for(let n of e)t={...t,...Ny[n].permissionsShape?.()};return t}function j9(e){let t=[];for(let n of e)t.push(...Ny[n].permissionModes?.()??[]);return t}function RR(e){let t=e.split("__"),[n,r,...o]=t;if(n!=="mcp"||!r)return null;let s=o.length>0?o.join("__"):void 0;return{serverName:r,toolName:s}}var $9={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool",ReadMcpResourceDir:"ReadMcpResourceDirTool"};function ru(e){return Object.hasOwn($9,e)?$9[e]:e}var B9="workspace",skt=`mcp__${B9}__bash`,ikt=`mcp__${B9}__web_fetch`;function OR(e){return e.includes("*")}function xHe(e){return e.replaceAll("\\","\\\\").replaceAll("(","\\(").replaceAll(")","\\)")}function EHe(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function H9(e){let t=vHe(e,"(");if(t===-1)return{toolName:ru(e)};let n=wHe(e,")");if(n===-1||n<=t)return{toolName:ru(e)};if(n!==e.length-1)return{toolName:ru(e)};let r=e.substring(0,t),o=e.substring(t+1,n);if(!r)return{toolName:ru(e)};if(o===""||o==="*")return{toolName:ru(r)};let s=EHe(o);return{toolName:ru(r),ruleContent:s}}function PR(e){if(!e.ruleContent)return e.toolName;let t=xHe(e.ruleContent);return`${e.toolName}(${t})`}function vHe(e,t){for(let n=0;n<e.length;n++)if(e[n]===t){let r=0,o=n-1;while(o>=0&&e[o]==="\\")r++,o--;if(r%2===0)return n}return-1}function wHe(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){let r=0,o=n-1;while(o>=0&&e[o]==="\\")r++,o--;if(r%2===0)return n}return-1}var Uy={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit","Cd"],bashPrefixTools:["Bash"],customValidation:{WebSearch:(e)=>{if(e.includes("*")||e.includes("?"))return{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]};return{valid:!0}},WebFetch:(e)=>{if(e.includes("://")||e.startsWith("http"))return{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]};if(!e.startsWith("domain:"))return{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]};return{valid:!0}}}};function K9(e){return Uy.filePatternTools.includes(e)}function q9(e){return Uy.bashPrefixTools.includes(e)}function G9(e){return Object.hasOwn(Uy.customValidation,e)?Uy.customValidation[e]:void 0}function V9(e,t){let n=0,r=t-1;while(r>=0&&e[r]==="\\")n++,r--;return n%2!==0}function IR(e,t){let n=0;for(let r=0;r<e.length;r++)if(e[r]===t&&!V9(e,r))n++;return n}function THe(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!V9(e,t))return!0}return!1}function W9(e){if(!OR(e))return null;let t=RR(e);if(t&&!OR(t.serverName))return null;return{valid:!1,error:`Wildcard tool name "${e}" is not supported in allow rules`,suggestion:"An allow pattern must name the scope it widens — globs are permitted only in the tool position after a literal mcp__<server>__ prefix. Deny and ask rules accept wildcards anywhere",examples:["mcp__puppeteer__*","mcp__github__get_*"]}}function DR(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=IR(e,"("),r=IR(e,")");if(n!==r)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(THe(e)){let a=e.substring(0,e.indexOf("("));if(!a)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}}let o=H9(e),s=RR(o.toolName);if(s){if(o.ruleContent!==void 0||IR(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${o.toolName}" without parentheses, or use "mcp__${s.serverName}__*" for all tools`,examples:[`mcp__${s.serverName}`,`mcp__${s.serverName}__*`,s.toolName&&s.toolName!=="*"?`mcp__${s.serverName}__${s.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let a=W9(o.toolName);if(a)return a}return{valid:!0}}if(!o.toolName||o.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let a=W9(o.toolName);if(a)return a}if(!o.toolName.includes("_")&&o.toolName[0]!==o.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${du(String(o.toolName))}"`};let i=G9(o.toolName);if(i&&o.ruleContent!==void 0){let a=i(o.ruleContent);if(!a.valid)return a}if(q9(o.toolName)&&o.ruleContent!==void 0){let a=o.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(K9(o.toolName)&&o.ruleContent!==void 0){if(o.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${o.toolName}(*.ts) - matches .ts files`,`${o.toolName}(src/**) - matches all files in src`,`${o.toolName}(**/*.test.ts) - matches test files`]}}if(o.ruleContent!==void 0){let a=o.toolName==="Write"||o.toolName==="NotebookEdit"||o.toolName==="MultiEdit"?"Edit":o.toolName==="Glob"?"Read":void 0;if(a!==void 0&&!o.ruleContent.includes(":*"))return{valid:!0,warning:`${PR(o)} is not matched by file permission checks — only ${a}(path) rules are. Use ${PR({toolName:a,ruleContent:o.ruleContent})} instead (${a} rules cover all file-${a==="Edit"?"editing":"reading"} tools).`}}return{valid:!0}}var LR=L(()=>Y9()),Z9=L(()=>Y9("allow"));function Y9(e){return _().superRefine((t,n)=>{let r=DR(t,e);if(!r.valid){let o=r.error;if(r.suggestion)o+=`. ${r.suggestion}`;if(r.examples&&r.examples.length>0)o+=`. Examples: ${r.examples.join(", ")}`;n.addIssue({code:hr.custom,message:o,params:{received:t}})}})}var AHe=L(()=>q(_(),Sm.string()));function tZ(e){return w({allow:I(Z9()).optional().describe("List of permission rules for allowed operations"),deny:I(LR()).optional().describe("List of permission rules for denied operations"),ask:I(LR()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:xt(Nf,G([...Mf,...j9(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:G(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...F9(e),additionalDirectories:I(_()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var Akt=L(()=>tZ(CR())),NR=L(()=>w({source:zf().describe("Where to fetch the marketplace from"),installLocation:_().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:C().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),Fy=L(()=>w({serverName:_().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:I(_()).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:_().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>np([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"'})),jy=L(()=>w({serverName:_().min(1,"Server name must be non-empty").refine((e)=>e.trim().length>0,{message:"Server name must not be whitespace-only"}).refine((e)=>e===e.trim(),{message:"Server name has leading or trailing whitespace and will never match (names are compared verbatim)"}).optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:I(_()).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:_().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>np([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=L(()=>w({path:_().describe("Absolute path to the helper executable"),timeoutMs:j().int().min(1000).optional(),refreshIntervalMs:oe([N(0),j().int().min(60000)]).optional()})),MR=["macos","linux","windows","wsl"],kHe=L(()=>w(Object.fromEntries(MR.map((e)=>[e,zy().optional()])))),J9=["skills","agents","hooks","mcp"],X9=Object.freeze({type:"invalid-entry-stripped"}),CHe=L(()=>oe([w({type:N("regex").describe('Config variant. This client understands "regex": matches turn output and builds a URL from named capture groups. Entries with other variants are preserved but skipped at runtime.'),pattern:_().describe("Regex matched against turn output (tool results and assistant text)"),url:_().describe("Link target. {name} placeholders are filled from named regex capture groups, e.g. (?<id>...) -> {id}. Values are URL-encoded; the origin must be literal in the template. The scheme must be https, http, or a recognized editor or workspace deep-link scheme: vscode, vscode-insiders, cursor, windsurf, zed, jetbrains, idea, slack, linear, notion, figma."),label:_().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),w({type:_().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function nZ(e){return w({$schema:_().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:_().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:_().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:_().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:_().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:_().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),processWrapper:_().optional().describe("Corporate launcher argv prefix for the background-agent supervisor, the sessions and workers it hosts, and the other covered background processes listed in the Claude Code corporate-launcher documentation. Equivalent to the CLAUDE_CODE_PROCESS_WRAPPER environment variable, which takes precedence when set. Honored from managed settings, a --settings/SDK-supplied settings file, and user settings, in that precedence order; project and local settings are ignored."),policyHelper:zy().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),policyHelpers:kHe().optional().describe("Per-OS variant of policyHelper, keyed by platform: macos, linux, windows, wsl. The entry for the current platform wins over policyHelper; a platform with no entry falls back to policyHelper (wsl falls back to the linux entry first). Honored only from admin-controlled policy sources."),...xn.CLAUDE_CODE_ENABLE_XAA&&{xaaIdp:w({issuer:_().url().describe("IdP issuer URL for OIDC discovery"),clientId:_().describe("Claude Code's client_id registered at the IdP"),callbackPort:j().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:w({type:N("command"),command:_()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:C().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:w({enabled:C().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:j().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:j().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:_().optional().describe("Custom reminder text. Leave unset for a rotating set of friendly nudges.")}).optional().describe("@internal Opt-in break reminder. When enabled, shows a dismissible nudge after sustained continuous use. Never blocks — just a friendly heads-up."),quietHours:w({enabled:C().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:_().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "22:00")').optional().describe('Start of the quiet-hours window, 24-hour local time "HH:MM".'),end:_().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "07:00")').optional().describe('End of the quiet-hours window, 24-hour local time "HH:MM". May be earlier than start for an overnight range.')}).optional().describe("@internal Opt-in quiet hours. When enabled, shows a single soft nudge per session while inside the configured local-time window. Never blocks."),cleanupPeriodDays:j().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:j().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:j().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:C().optional().describe("When set to true in either admin-only Windows source — the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json — 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:AHe().optional().describe("Environment variables to set for Claude Code sessions"),attribution:w({commit:_().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:_().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:C().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link."),...!1}).passthrough().optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:C().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,includeGitInstructions:C().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:tZ(e).optional().describe("Tool usage permissions configuration"),model:_().optional().describe("Override the default model used by Claude Code"),fallbackModel:I(_()).optional().describe('Fallback model(s) tried in order when the primary model is overloaded or unavailable. Each element accepts a model name or alias; "default" expands to the default model. CLI --fallback-model takes precedence.'),availableModels:I(_()).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.'),enforceAvailableModels:C().optional().describe("When true and availableModels is a non-empty array, the Default model selection is also constrained: if the default model for the user tier is not in availableModels, Default resolves to the first allowed availableModels entry instead. Has no effect when availableModels is unset or an empty array. Typically set in managed settings by enterprise administrators."),modelOverrides:q(_(),_()).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:C().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:I(_()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:I(_()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:C().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected. "+"Only gates auto-fetched connectors — a claudeai-proxy server passed explicitly "+"(e.g. via --mcp-config or the SDK mcpServers option) still follows the normal MCP config trust flow. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:q(_(),G(["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.'),disableBundledSkills:C().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:I(Fy()).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:I(jy()).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:ma().optional().describe("Custom commands to run before/after tool executions"),worktree:w({symlinkDirectories:I(_()).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:I(_()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos — only the listed paths are written to disk."),baseRef:G(["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."),bgIsolation:G(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:C().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:C().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:C().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."),disableWorkflows:C().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:C().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableArtifact:C().optional().describe("Enable or disable the Artifact tool for this user. Unset defaults to enabled once the feature is available."),enableWorkflows:C().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowSizeGuideline:G(["unrestricted","small","medium","large"]).optional().describe('Advisory size guideline for the dynamic workflows Claude writes: "small" aims for fewer than 5 agents, "medium" (the default) fewer than 15, "large" fewer than 50, and "unrestricted" sends no guideline. A value here — including from managed settings — takes precedence over the "Dynamic workflow size" choice in /config, and that /config row is hidden while a settings file provides the key. This is a guideline, not an enforced limit.'),workflowKeywordTriggerEnabled:C().optional().describe('Enable the "ultracode" keyword trigger: including the keyword in a prompt opts that turn into the Workflow tool. Set to false to disable the trigger. Default: true.'),disableSkillShellExecution:C().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:G(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:C().optional().describe("Whether Claude responds after an input-box ! bash command runs. Set to false to add the command output to context without a response. Default: true."),allowManagedHooksOnly:C().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:I(_()).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:I(_()).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:C().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:C().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."),allowAllClaudeAiMcps:C().optional().describe("When true (and set in managed settings), claude.ai cloud MCP connectors load alongside managed-mcp.json instead of being suppressed by its exclusive-control lockdown. Default off preserves the lockdown. Read from managed settings only."),strictPluginOnlyCustomization:xt((t)=>Array.isArray(t)?t.filter((n)=>J9.includes(n)):t,oe([C(),I(G(J9))])).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 — plugins gated by "+"marketplace allowlist, everything else blocked here."),statusLine:w({type:N("command"),command:_(),padding:j().optional(),refreshInterval:j().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:C().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:_().optional().describe('URL template for PR links in the footer link badges and inline messages. The detected git PR is rendered as the first footer-link badge. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),footerLinksRegexes:I(CHe().catch(X9)).transform((t)=>t.filter((n)=>n!==X9)).optional().catch(void 0).describe("Extra clickable footer badges that appear when a regex matches turn output (tool results and assistant responses). Read from user, flag, and managed settings only; ignored in project .claude/settings.json and local .claude/settings.local.json. At most 5 badges render; the oldest is displaced by newer matches and /clear removes them. Use to surface IDs printed by project CLIs as session links."),subagentStatusLine:w({type:N("command"),command:_()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:q(_(),oe([I(_()),C(),_x()])).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 — setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:q(_(),NR()).check((t)=>{for(let[n,r]of Object.entries(t.value))if(r.source.source==="settings"&&r.source.name!==n)t.issues.push({code:"custom",input:r.source.name,path:[n,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${n}" but source.name "${r.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:I(zf()).optional().describe('Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these sources can be added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to allow every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem. '+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:I(zf()).optional().describe('Enterprise blocklist of marketplace sources. When set in managed settings, these sources are blocked from being added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to block every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem.'),disableCommandPluginSources:C().optional().describe("Controls the `command` plugin source, whose plugin directory is produced by running a marketplace-declared command on this machine. true: command-sourced plugins are never installed, updated, or re-resolved (the command never runs). false: explicitly allowed. "+"Unset: follows allowManagedHooksOnly — an org that restricts hook execution to managed "+"settings gets command sources disabled too. Only honored from managed settings."),disableSideloadFlags:C().optional().describe("When true (and set in managed settings), rejects the --plugin-dir, --plugin-url, --agents, and non-sdk --mcp-config CLI flags at startup. Closes the CLI-flag bypass of strictKnownMarketplaces. Pair with allowedMcpServers for per-server MCP control; this setting does not gate other MCP entry points (SDK setMcpServers, claude mcp add, .mcp.json). Also blocks surfaces that spawn the CLI with these flags internally (see settings documentation). Only honored from managed settings; ignored in user/project/local settings."),pluginSuggestionMarketplaces:I(_()).optional().describe("Marketplace names whose plugins may surface as contextual install suggestions (relevance-based tips). No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Only honored when set in managed settings (policy scope); the key is ignored in user, project, and local settings. A name only takes effect when the marketplace is registered on the machine AND its registered source is also declared in managed settings, either as the extraKnownMarketplaces entry for that name or as an entry of strictKnownMarketplaces. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source."),forceLoginMethod:G(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:_().url().optional().catch(void 0).describe('Cloud gateway URL to pre-fill and auto-connect to during login, alongside forceLoginMethod: "gateway". Honored only from admin-controlled managed settings (MDM / managed-settings.json / policy helper); ignored in user, project, and remote-delivered settings.'),parentSettingsBehavior:G(["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 — 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:oe([_(),I(_())]).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:C().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:_().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:_().optional().describe("Controls the output style for assistant responses"),viewMode:G(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:_().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:C().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:yR().optional(),feedbackSurveyRate:j().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),feedbackDrafts:G(["notify","quiet","off"]).optional().describe('Model-drafted feedback (the SendFeedback tool). "notify" (default) shows a one-line notice when a draft is queued; "quiet" shows only the footer counter; "off" disables the tool entirely so drafts are never queued.'),spinnerTipsEnabled:C().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:w({mode:G(["append","replace"]),verbs:I(_())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:w({excludeDefault:C().optional(),tips:I(_())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:C().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:C().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:C().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:G(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:C().optional().catch(void 0).describe("Enable ultracode for the session: xhigh effort plus standing dynamic-workflow orchestration. "+"Session-scoped — typically provided via --settings or the apply_flag_settings control request; "+"interactive toggles never persist it. Requires workflows to be enabled and an xhigh-capable model."),autoCompactWindow:j().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:_().optional().describe("Advisor model for the server-side advisor tool."),fastMode:C().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:C().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:C().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),emojiCompletionEnabled:C().optional().describe("When false, the :emoji: shortcode typeahead (the suggestion popup and the :name: inline replacement) is disabled. When absent or true, it is enabled."),awaySummaryEnabled:C().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:C().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:G(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers "+"selected so far. Defaults to never — auto-continue only runs "+"when explicitly set to 60s/5m/10m."),dialogExpiry:G(["60s","5m","10m","never"]).optional().catch(void 0).describe('Max time a permission/user dialog forwarded to a remote client stays parked awaiting an answer, and how long a HELD cross-session message awaits approval, before either resolves to its safe no-action default (cancelled / dropped-with-denial). Defaults to 5m to match the long-standing remote-dialog deadline; "never" disables the deadline. Local-only permission prompts (no remote client) are unaffected. The CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS env var, when set, overrides this. Read from trusted sources only (never a checked-in repo settings file).'),agent:_().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."),modelProposedGoals:G(p9).optional().catch(void 0).describe("@internal Controls the ProposeGoal tool (model-proposed session goals). 'auto' (the default when absent) lets the model choose per proposal whether to ask for approval via its ask_user parameter; 'alwaysAsk' routes every model-proposed goal through the approval dialog; 'disabled' turns the tool off. A typed /goal is unaffected. Consent-affecting, so it is read "+"from trusted sources only (user/policy/flag) — "+"workspace-resident project and local settings are ignored."),companyAnnouncements:I(_()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:q(_(),w({mcpServers:q(_(),q(_(),oe([_(),j(),C(),I(_())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:q(_(),oe([_(),j(),C(),I(_())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(_x())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:w({defaultEnvironmentId:_().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:G(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:_().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:_().optional().describe("Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup with instructions to update. Only enforced from managed (policy) settings."),requiredMaximumVersion:_().optional().describe("Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. Only enforced from managed (policy) settings."),plansDirectory:_().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:G(["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.'),...!1,voice:w({enabled:C().optional(),mode:G(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:C().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:C().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:I(w({marketplace:_(),plugin:_()})).optional().describe("Managed-org allowlist of channel plugins. When set, "+"replaces the default Anthropic allowlist — admins decide which "+"plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:C().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:C().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."),totalTokensReminder:G(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn "+"is on — task-budget semantics). Defaults to off. Env var "+"CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:j().int().positive().optional().describe("@internal Starting budget (tokens) for totalTokensReminder 'padded-countdown' mode. Defaults to 15000000. Server-controlled via GrowthBook; env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_BUDGET overrides."),totalTokensReminderAfterUserTurn:C().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:C().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:_().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:C().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:C().optional().describe("Request API-side thinking summaries and show them in the conversation and in the transcript view (ctrl+o). Set explicitly to override the default for your install."),skipDangerousModePermissionPrompt:C().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:C().optional().describe("@internal Whether the user has accepted the multi-agent workflow usage warning. Until set, auto permission mode prompts before running a workflow."),disableAutoMode:G(["disable"]).optional().describe("Disable auto mode"),sshConfigs:I(w({id:_().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:_().describe("Display name for the SSH connection"),sshHost:_().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:j().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:_().optional().describe("Path to SSH identity file (private key)"),startDirectory:_().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:_().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:I(_()).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:_().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:oe([G(d9),_().startsWith("custom:").transform((t)=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:G(l9).optional().catch(void 0).describe("Key binding mode for the prompt input"),vimInsertModeRemaps:q(_(),Se()).optional().catch(void 0).describe('Vim INSERT-mode key-sequence remaps, e.g. {"jj": "<Esc>"}. Each key is exactly two printable characters typed in sequence; "<Esc>" (return to NORMAL mode) is the only supported target. Applies when editorMode is "vim".'),verbose:C().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:G(c9).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:C().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:C().optional().describe("Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:C().optional().describe("When safeguards flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:C().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:C().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:C().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:C().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:C().optional().describe("Stamp each message with its arrival time"),terminalProgressBarEnabled:C().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:C().optional().describe("Enable the todo / task tracking panel"),teammateMode:G(u9).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:C().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:C().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:G(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),crossSessionInbound:G(["accept","hold","refuse"]).optional().catch(void 0).describe("Inbound cross-session peer messages (SendMessage from your other sessions): 'accept' delivers them, 'hold' parks them for your review without letting Claude act, 'refuse' opts this session out. An explicit value always wins. Unset (mode parity): a message auto-delivers only when the sending session's permission-mode class matches yours (bypass↔bypass or prompting↔prompting); a mismatched sender's message is held for your approval; a sender that asserts no class is held only while this session bypasses permission prompts."),autoUploadSessions:C().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:C().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:C().optional().describe("Allow Claude to push proactive mobile notifications"),...z9(e)}).passthrough()}var ga=L(()=>nZ(CR())),Q9=Object.freeze({serverName:"invalid-entry-stripped"});function eZ(e,t,n){return I(t.catch((r)=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${r.issues[0]?.message??"failed validation"}`}),Q9))).transform((r)=>r.filter((o)=>o!==Q9)).optional()}function UR(e,t){let n=ga(),r={};for(let[h,g]of Object.entries(n.shape))r[h]=g.catch((y)=>{e({path:h,message:`${y.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});r.allowedMcpServers=eZ("allowedMcpServers",Fy(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[])),r.deniedMcpServers=eZ("deniedMcpServers",jy(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return}),r.allowManagedHooksOnly=n.shape.allowManagedHooksOnly.catch(()=>(e({path:"allowManagedHooksOnly",message:'"allowManagedHooksOnly" was present but invalid; treating it as true (only managed hooks run; command-sourced plugins disabled) until it is fixed.'}),!0)),r.disableCommandPluginSources=n.shape.disableCommandPluginSources.catch(()=>(e({path:"disableCommandPluginSources",message:'"disableCommandPluginSources" was present but invalid; treating it as true (command-sourced plugins disabled) until it is fixed.'}),!0)),r.allowManagedMcpServersOnly=n.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),r.enforceAvailableModels=n.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),r.availableModels=I(Se()).transform((h,g)=>{let y=[];for(let b of h)if(typeof b==="string")y.push(b);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(b)}); the entry was ignored.`});return y}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),r.forceLoginOrgUUID=n.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[])),r.policyHelper=xt((h)=>h===null?void 0:h,zy().optional()).catch((h)=>{e({path:"policyHelper",message:`${h.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});let o=(h)=>xt((g)=>g===null?void 0:g,zy().optional()).catch((g)=>{e({path:`policyHelpers.${h}`,message:`Invalid entry was ignored: ${g.issues[0]?.message??"failed validation"}. No policy helper runs on ${h} from this entry.`,statusOnly:!0});return});r.policyHelpers=xt((h)=>h===null?void 0:h,w(Object.fromEntries(MR.map((h)=>[h,o(h)]))).transform((h)=>{for(let g of Object.keys(h))if(h[g]===void 0)delete h[g];return h}).optional().catch((h)=>(e({path:"policyHelpers",message:`"policyHelpers" could not be parsed: expected an object mapping OS keys (${MR.join(", ")}) to helper entries (${h.issues[0]?.message??"failed schema validation"}). When delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0}),{})));let s=Object.freeze({mode:"deny"}),i=Object.freeze({accessKeyIdVar:"_STRIPPED_",secretAccessKeyVar:"_STRIPPED_2_"}),a=0,c=[],l=t===void 0?"":`${[...t].reduce((h,g)=>Math.imul(h^g.charCodeAt(0),16777619)>>>0,2166136261).toString(16).toUpperCase().padStart(8,"0")}_`,u=(h,g)=>{if(typeof h!=="object"||h===null)return;let y=(ye)=>g.some((Ve)=>Ve.path?.includes(ye)),b=(ye)=>{let Ve=h[ye];if(typeof Ve==="string")return Ve;return y(ye)?"":void 0},x=b("accessKeyIdVar"),E=b("secretAccessKeyVar"),k=b("sessionTokenVar"),R=Ql;if(![x,E,k].some((ye)=>ye!==void 0&&R.includes(ye)))return;let V=(ye)=>ye!==void 0&&Xl().safeParse(ye).success;a+=1;let K=(ye)=>`${_R}${ye}_${l}${a}_`,Q=V(x)?x:K("ACCESS_KEY_ID"),X=V(E)&&E!==Q?E:K("SECRET_ACCESS_KEY"),me=k===void 0?void 0:V(k)&&k!==Q&&k!==X?k:K("SESSION_TOKEN"),Ce=(ye)=>ye.startsWith(_R);if(!Ce(Q)&&!Ce(X)){let ye=R.includes(X)?X:void 0;if(X=K("SECRET_ACCESS_KEY"),ye!==void 0){let Ve=u({accessKeyIdVar:ye},[]);if(Ve!==void 0)c.push(Ve)}}let tt=Iy().safeParse({accessKeyIdVar:Q,secretAccessKeyVar:X,...me!==void 0&&{sessionTokenVar:me}});return tt.success?tt.data:void 0},p=(h,g,y)=>I(g.catch((b)=>{let x=y(b.value);if(x!==void 0)return e({path:`sandbox.credentials.${h}[]`,message:`Invalid entry was degraded to mode "deny": ${b.issues[0]?.message??"failed validation"}. The credential stays blocked (not masked) until the entry is fixed.${h==="files"?" Under sandbox.filesystem.disabled, file read-denies are not enforced.":""}`}),x;return e({path:`sandbox.credentials.${h}[]`,message:`Invalid entry was ignored: ${b.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),s})).transform((b)=>b.filter((x)=>x!==s)).optional().catch((b)=>{if(typeof b.value==="object"&&b.value!==null&&!Array.isArray(b.value)){let x=g.safeParse(b.value);if(x.success)return e({path:`sandbox.credentials.${h}`,message:`"${h}" must be an array; a lone entry object was accepted as a one-element list. Wrap it in [ ] to silence this warning.`}),[x.data];let E=y(b.value);if(E!==void 0)return e({path:`sandbox.credentials.${h}`,message:`"${h}" must be an array; its lone entry object was invalid and was degraded to mode "deny". The credential stays blocked (not masked) until it is fixed.`}),[E]}return e({path:`sandbox.credentials.${h}`,message:`${b.issues[0]?.message??"Invalid value"}. "${h}" was ignored; these credential entries are NOT protected until it is fixed.`}),[]}),f=w({files:p("files",Oy(),(h)=>{if(typeof h!=="object"||h===null||!("mode"in h)||h.mode!=="mask"&&h.mode!=="deny"||!("path"in h)||typeof h.path!=="string")return;let g=Oy().safeParse({path:h.path,mode:"deny"});return g.success?g.data:void 0}),envVars:p("envVars",Py(),(h)=>{if(typeof h!=="object"||h===null||!("mode"in h)||h.mode!=="mask"&&h.mode!=="deny"||!("name"in h)||typeof h.name!=="string")return;let g=Py().safeParse({name:h.name,mode:"deny"});return g.success?g.data:void 0}),allowPlaintextInject:C().optional().catch((h)=>(e({path:"sandbox.credentials.allowPlaintextInject",message:`${h.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was degraded to an explicit false; plaintext credential injection stays disabled (lower-precedence values cannot enable it) until it is fixed.`}),!1)),awsPairs:I(Iy().catch((h)=>{let g=u(h.value,h.issues);if(g!==void 0)return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was degraded to a non-functional suppressor: ${h.issues[0]?.message??"failed validation"}. It keeps implicit AWS auto-pairing suppressed but re-signs nothing until it is fixed.`}),g;return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was ignored: ${h.issues[0]?.message??"failed validation"}. SigV4 re-signing stays unconfigured for this pair until it is fixed.`}),i})).transform((h)=>{let g=h.filter((y)=>y!==i);if(c.length>0)g.push(...c),c.length=0;return g}).optional().catch((h)=>{let g=typeof h.value==="object"&&h.value!==null?u(h.value,[]):void 0,y=typeof h.value==="object"&&h.value!==null&&(("accessKeyIdVar"in h.value)||("secretAccessKeyVar"in h.value)||("sessionTokenVar"in h.value));if(g===void 0&&y)return c.length=0,e({path:"sandbox.credentials.awsPairs",message:`${h.issues[0]?.message??"Invalid value"}. "awsPairs" must be an array; its lone pair-shaped entry claimed no conventional AWS name and was ignored. SigV4 re-signing stays unconfigured until it is fixed.`}),[];let b=g!==void 0?[g]:Ql.flatMap((x)=>{let E=u({accessKeyIdVar:x},[]);return E!==void 0?[E]:[]});if(c.length>0)b.push(...c),c.length=0;return e({path:"sandbox.credentials.awsPairs",message:`${h.issues[0]?.message??"Invalid value"}. "awsPairs" was degraded to non-functional suppressor pair(s); implicit AWS auto-pairing stays suppressed but nothing re-signs until it is fixed.`}),b}),sigv4:w(Object.fromEntries(["streaming","presigned","sigv4a"].map((h)=>[h,G(["deny","passthrough"]).optional().catch((g)=>(e({path:`sandbox.credentials.sigv4.${h}`,message:`${g.issues[0]?.message??"Invalid value"}. "${h}" was degraded to an explicit deny; this SigV4 request shape stays denied until it is fixed.`}),"deny"))]))).optional().catch((h)=>(e({path:"sandbox.credentials.sigv4",message:`${h.issues[0]?.message??"Invalid value"}. "sigv4" was degraded to an all-deny block (all shapes stay denied, and lower-precedence sigv4 values cannot take effect) until it is fixed.`}),{streaming:"deny",presigned:"deny",sigv4a:"deny"}))}).optional().catch((h)=>{e({path:"sandbox.credentials",message:`${h.issues[0]?.message??"Failed schema validation"}. The credentials block was degraded to a fail-closed skeleton (all-deny sigv4, implicit AWS auto-pairing suppressed, no masking) until it is fixed.`});let g=Ql.flatMap((y)=>{let b=u({accessKeyIdVar:y},[]);return b!==void 0?[b]:[]});return c.length=0,{allowPlaintextInject:!1,awsPairs:g,sigv4:{streaming:"deny",presigned:"deny",sigv4a:"deny"}}});return r.sandbox=yR().extend({credentials:f}).optional().catch((h)=>{e({path:"sandbox",message:`${h.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});let g=h.value;if(typeof g==="object"&&g!==null&&"credentials"in g){let y=f.safeParse(g.credentials);if(y.success&&y.data!==void 0)return e({path:"sandbox.credentials",message:"The credentials block was salvaged from the invalid sandbox value and stays enforced; every other sandbox field was ignored."}),{credentials:y.data}}return}),w(r).passthrough().transform((h)=>{for(let g of Object.keys(h))if(h[g]===void 0)delete h[g];return h})}var es="https://code.claude.com/docs/en",RHe=[{matches:(e)=>e.path==="permissions.defaultMode"&&e.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:`${es}/iam#permission-modes`}},{matches:(e)=>e.path==="apiKeyHelper"&&e.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:(e)=>e.path==="cleanupPeriodDays"&&e.code==="too_small",tip:{suggestion:'cleanupPeriodDays must be at least 1. To keep transcripts for a long time, set a large number (e.g. 3650 for ~10 years). To disable transcript writes entirely, remove this setting and use the --no-session-persistence CLI flag or the SDK persistSession:false option instead. (0 is rejected because it previously silently disabled all transcript writes, which users setting it to mean "never clean up" did not expect.)'}},{matches:(e)=>e.path.startsWith("env.")&&e.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:`${es}/settings#environment-variables`}},{matches:(e)=>(e.path==="permissions.allow"||e.path==="permissions.deny")&&e.code==="invalid_type"&&e.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:(e)=>e.path.startsWith("hooks.")&&e.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${es}/hooks`}},{matches:(e)=>/\.hooks\.\d+\.command$/.test(e.path)&&e.code==="invalid_type"&&e.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${es}/hooks#exec-form-and-shell-form`}},{matches:(e)=>e.path.includes("hooks")&&e.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:(e)=>e.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:`${es}/settings`}},{matches:(e)=>e.code==="invalid_value"&&e.enumValues!==void 0,tip:{suggestion:void 0}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="object"&&e.received===null&&e.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:(e)=>e.path==="permissions.additionalDirectories"&&e.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:`${es}/iam#working-directories`}}],OHe={permissions:`${es}/iam#configuring-permissions`,env:`${es}/settings#environment-variables`,hooks:`${es}/hooks`};function rZ(e){let t=RHe.find((r)=>r.matches(e));if(!t)return null;let n={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!n.suggestion)n.suggestion=`Valid values: ${e.enumValues.map((r)=>`"${r}"`).join(", ")}`;if(!n.docLink&&e.path)n.docLink=OHe[nb(e.path,".")];return n}var Gkt=L(()=>ga().strict());function oZ(e){return e.code==="invalid_type"}function sZ(e){return e.code==="invalid_value"}function PHe(e){return e.code==="unrecognized_keys"}function iZ(e){return e.code==="too_small"}function _a(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function aZ(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function jf(e,t){return e.issues.map((n)=>{let r=n.path.map(String).join("."),o=n.message,s,i,a,c,l;if(sZ(n))i=n.values.map((p)=>String(p)),a=i.join(" | "),c=void 0,l=void 0;else if(oZ(n)){a=n.expected;let p=aZ(n.message);c=p??_a(n.input),l=p??_a(n.input)}else if(iZ(n))a=String(n.minimum);else if(n.code==="custom"&&"params"in n)c=n.params.received,l=c;let u=rZ({path:r,code:n.code,expected:a,received:c,enumValues:i,message:n.message,value:c});if(sZ(n))s=i?.map((p)=>`"${p}"`).join(", "),o=`Invalid value. Expected one of: ${s}`;else if(oZ(n)){let p=aZ(n.message)??_a(n.input);if(n.expected==="object"&&p==="null"&&r==="")o="Invalid or malformed JSON";else o=`Expected ${n.expected}, but received ${p}`}else if(PHe(n)){let p=n.keys.join(", ");o=`Unrecognized ${wO(n.keys.length,"field")}: ${p}`}else if(iZ(n))o=`Number must be greater than or equal to ${n.minimum}`,s=String(n.minimum);return{file:t,path:r,message:o,expected:s,invalidValue:l,suggestion:u?.suggestion,docLink:u?.docLink}})}function IHe(e,t){if(!e||typeof e!=="object")return[];let n=e;if(!n.permissions||typeof n.permissions!=="object")return[];let r=n.permissions,o=[];for(let s of["allow","deny","ask"]){let i=r[s];if(!Array.isArray(i))continue;r[s]=i.filter((a)=>{if(typeof a!=="string")return o.push({file:t,path:`permissions.${s}`,message:`Non-string value in ${s} array was removed`,severity:"warning",invalidValue:a}),!1;let c=DR(a,s);if(!c.valid){let l=`Invalid permission rule "${a}" was skipped: ${c.error}`;if(c.suggestion)l+=`. ${c.suggestion}`;return o.push({file:t,path:`permissions.${s}`,message:l,severity:"warning",invalidValue:a}),!1}return!0})}return o}var DHe=new Set(wa);function LHe(e,t){if(!e||typeof e!=="object")return[];let n=e;if(!("hooks"in n))return[];if(n.hooks===null||typeof n.hooks!=="object"||Array.isArray(n.hooks)){let s=_a(n.hooks);return delete n.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${s}. This field was ignored.`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"}]}let r=n.hooks,o=[];for(let s of Object.keys(r)){if(!DHe.has(s)){delete r[s],o.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${wa.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(r[s])){let i=_a(r[s]);delete r[s],o.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${i}. This entry was ignored.`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"})}}if(o.length>0&&Object.keys(r).length===0)delete n.hooks;return o}var MHe=[{key:"allowedMcpServers",schema:Fy},{key:"deniedMcpServers",schema:jy}];function NHe(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of MHe){if(!(s in r))continue;if(!Array.isArray(r[s])){if(n?.keepWholeFieldInvalid)continue;let l=r[s];delete r[s],o.push({file:t,path:s,message:`"${s}" must be an array; received ${_a(l)}. This field was ignored.`,severity:"warning",invalidValue:l});continue}let a=r[s],c=[];for(let l=0;l<a.length;l++){let u=i().safeParse(a[l]);if(u.success)c.push(a[l]);else o.push({file:t,path:`${s}[${l}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:a[l]})}if(c.length<a.length)r[s]=c}return o}function UHe(e){if(!e||typeof e!=="object")return;let t=e.source;if(!t||typeof t!=="object")return;let n=t.source;return typeof n==="string"?n:void 0}function zHe(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.plugins;return Array.isArray(n)&&n.some(AR)}function FHe(e,t){if(!e||typeof e!=="object")return[];let n=e,r="extraKnownMarketplaces";if(!(r in n))return[];let o=n[r];if(!o||typeof o!=="object"||Array.isArray(o)){let a=_a(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object mapping marketplace names to declarations; received ${a}. This field was ignored.`,severity:"warning",invalidValue:a}]}let s=o,i=[];for(let a of Object.keys(s)){let c=NR().safeParse(s[a]),l;if(!c.success){let u=UHe(s[a]);if(u!==void 0&&!M9.has(u)||zHe(s[a]))continue;l=My(c.error.issues)}else if(c.data.source.source==="settings"&&c.data.source.name!==a)l=`key "${nu(a)}" must match the settings source name "${nu(c.data.source.name)}"`;if(l!==void 0)i.push({file:t,path:`${r}.${nu(a)}`,message:`Invalid marketplace entry was ignored: ${l}`,severity:"warning"}),delete s[a]}return i}function ya(e,t,n){return[...IHe(e,t),...LHe(e,t),...FHe(e,t),...n?.skipMcpServerEntryFilter?[]:NHe(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly})]}function jR(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),Q3.filter((n)=>t.has(n))}function BHe(){return ao(pa(),"managed-settings.json")}function uZ(e){if(Bo()==="wsl"&&e.wslInherits?.()){let t=zR(eu,e.store);if(t.settings)return t;let n=zR(pa(),e.store);return{settings:n.settings,errors:[...t.errors,...n.errors]}}return zR(pa(),e.store)}function zR(e,t){let n=[],r={},o=!1,{settings:s,errors:i}=ou(ao(e,"managed-settings.json"),t,void 0,!0);if(n.push(...i),s&&Object.keys(s).length>0)r=io(r,s,ko),o=!0;let a=ao(e,"managed-settings.d");try{let u=We().readdirSync(a).filter((p)=>(p.isFile()||p.isSymbolicLink())&&p.name.endsWith(".json")&&!p.name.startsWith(".")).map((p)=>p.name).sort();for(let p of u){let{settings:f,errors:m}=ou(ao(a,p),t,void 0,!0);if(n.push(...m),f&&Object.keys(f).length>0)r=io(r,f,ko),o=!0}}catch(u){let p=Me(u);if(p!=="ENOENT"&&p!=="ENOTDIR")ce(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:c,...l}=r;return{settings:o&&Object.keys(l).length>0?r:null,errors:n}}function HHe(e,t){if(rr(e))ce(`Broken symlink or missing file encountered for settings.json at path: ${t}`);else ce(`settings file read failed at ${t}: ${e}`,{level:"error"})}function ou(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{settings:s.settings?Ds(s.settings):null,errors:s.errors};let i=GHe(e,n,r);return t.parsedFiles.set(o,i),{settings:i.settings?Ds(i.settings):null,errors:i.errors}}function dZ(e){if(!e.mdm)return{settings:null,errors:[]};let t=e.mdm();return{settings:Object.keys(t.settings).length>0?t.settings:null,errors:t.errors}}function By(e,t){let n=Ds(e),r=ya(n,t,{skipMcpServerEntryFilter:!0}),o=[],s=UR(pZ(t,o),t).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...jf(s.error,t)]};return{settings:Object.keys(s.data).length>0?s.data:null,errors:[...r,...o]}}function pZ(e,t){return(n)=>{if(t.push({file:e,path:n.path,message:n.message,severity:"warning",...n.statusOnly&&{statusOnly:n.statusOnly},...n.startupFatal&&{startupFatal:n.startupFatal}}),n.statusOnly||n.startupFatal)ce(`${e}: ${n.path}: ${n.message}`,{level:n.startupFatal?"error":"warn"})}}function fZ(e){let t=e?.remote?e.remote():W3();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return By(t,"remote managed settings")}function KHe(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return By(t,"parent managed settings")}function mZ(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=Ds(t),r=ya(n,"SDK inline settings"),o=ga().safeParse(n);if(!o.success)return{settings:null,errors:[...r,...jf(o.error,"SDK inline settings")]};return{settings:o.data,errors:r}}var qHe=2097152;function GHe(e,t,n){try{let r;if(t!==void 0)r=t;else{let{resolvedPath:o}=ap(We(),e);r=Kl(o,qHe)}return WHe(r,e,n)}catch(r){return VHe(r,e)}}function WHe(e,t,n){if(e.trim()==="")return{settings:{},errors:[]};let r=Ds(Wl(e,!1));if(n){let i=ya(r,t,{skipMcpServerEntryFilter:!0}),a=[],c=UR(pZ(t,a),t).safeParse(r);if(!c.success)return{settings:null,errors:[...i,...jf(c.error,t)]};return{settings:c.data,errors:[...i,...a]}}let o=ya(r,t),s=ga().safeParse(r);if(!s.success){let i=jf(s.error,t);return{settings:null,errors:[...o,...i]}}return{settings:s.data,errors:o}}function VHe(e,t){if(HHe(e,t),rr(e))return{settings:null,errors:[]};return{settings:null,errors:[{file:t,path:"",message:`Settings file could not be read: ${e instanceof Error?e.message:String(e)}`,severity:"fatal"}]}}function cZ(e,t){switch(e){case"userSettings":return Or(qt());case"policySettings":case"projectSettings":return Or(t.cwd);case"localSettings":return hZ(t.cwd,t.canonicalGitRoot);case"flagSettings":return t.flagPath?$He(Or(t.flagPath)):Or(t.cwd)}}function hZ(e,t){let n=t?.(e);if(!n)return Or(e);let r=Or(n),o=Or(e);if(r===o)return r;let s;try{s=XHe()}catch{return o}if(r===s)return o;if(!JHe(r))return o;return r}function ZHe(e){return _Z.canonicalRootOwnerUids(e)}class gZ{ownerUidsByRoot=new Map;realHomeDir=void 0;canonicalRootOwnerUids(e){let t=this.ownerUidsByRoot.get(e);if(t!==void 0)return t;let n=YHe(e);return this.ownerUidsByRoot.set(e,n),n}hasCanonicalRootOwnerUids(e){return this.ownerUidsByRoot.has(e)}clearCanonicalRootOwnerUids(){this.ownerUidsByRoot.clear()}normalizedRealHomeDir(){return this.realHomeDir??=QHe(),this.realHomeDir}clearNormalizedRealHomeDir(){this.realHomeDir=void 0}reset(){this.ownerUidsByRoot.clear(),this.realHomeDir=void 0}}var _Z=new gZ;function YHe(e){let t=We(),n=null;try{n=t.lstatSync(ao(e,".claude")).uid}catch(r){if(!rr(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:t.lstatSync(ao(e,".git")).uid,claudeEntryUid:n}}function JHe(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return ce(`localSettings: not canonicalizing the consent store to ${e} — this platform has no uid semantics to verify directory ownership with, so the store stays at the session cwd (canonicalization is POSIX-only)`,{level:"warn"}),!1;let t=typeof process.geteuid==="function"?process.geteuid():process.getuid?.();try{let{rootUid:n,gitEntryUid:r,claudeEntryUid:o}=ZHe(e);if(n===t&&r===t&&(o===null||o===t))return!0;return ce(`localSettings: not canonicalizing the consent store to ${e} — it (uid ${n}), its .git entry (uid ${r}), or its .claude entry (uid ${o??"absent"}) is not owned by the current user (uid ${t}); the store stays at the session cwd (the pre-canonicalization behavior). If you own this repo, chown it (including .git and .claude) or run from a directory you own.`,{level:"warn"}),!1}catch(n){return ce(`localSettings: not canonicalizing the consent store to ${e} — its ownership could not be verified (${n instanceof Error?n.message:String(n)}); the store stays at the session cwd`,{level:"warn"}),!1}}function XHe(){return _Z.normalizedRealHomeDir()}function QHe(){let e=eb(jHe());if(e===null)throw Error("home directory realpath unavailable");return kt(e)}function e2e(e){if(e.coworkPlugins||xn.CLAUDE_CODE_USE_COWORK_PLUGINS)return"cowork_settings.json";return"settings.json"}function $f(e,t){switch(e){case"userSettings":return ao(cZ(e,t),e2e(t));case"projectSettings":case"localSettings":return ao(cZ(e,t),yZ(e));case"policySettings":return BHe();case"flagSettings":return t.flagPath}}function yZ(e){switch(e){case"projectSettings":return ao(".claude","settings.json");case"localSettings":return ao(".claude","settings.local.json")}}function bZ(e){if(hZ(e.cwd,e.canonicalGitRoot)===Or(e.cwd))return;return ao(Or(e.cwd),yZ("localSettings"))}function SZ(e,t){let n=t.store.perSource.get(e);if(n!==void 0)return n;let r=u2e(e,t);return t.store.perSource.set(e,r),r}function t2e(e){return!e||e.parentSettingsBehavior==="merge"}function n2e(e,t){let n={};if(e.allowManagedHooksOnly===!0)n.allowManagedHooksOnly=!0;if(e.disableCommandPluginSources===!0)n.disableCommandPluginSources=!0;if(e.allowManagedMcpServersOnly===!0)n.allowManagedMcpServersOnly=!0;if(e.disableClaudeAiConnectors===!0)n.disableClaudeAiConnectors=!0;if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(e9(e.attribution,e.includeCoAuthoredBy)==="disabled")n.attribution={...n.attribution,commitTrailers:!1};if(e.attribution?.sessionUrl===!1)n.attribution={...n.attribution,sessionUrl:!1};let r=e.strictPluginOnlyCustomization;if(r===!0||Array.isArray(r)&&r.length>0)n.strictPluginOnlyCustomization=r;if(e.deniedMcpServers)n.deniedMcpServers=e.deniedMcpServers;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)n.forceLoginOrgUUID=e.forceLoginOrgUUID;if(t.allowedMcpServers===void 0&&e.allowedMcpServers)n.allowedMcpServers=e.allowedMcpServers;if(t.availableModels===void 0&&e.availableModels)n.availableModels=e.availableModels;if(e.enforceAvailableModels===!0)n.enforceAvailableModels=!0;if(e.permissions){let o=Ry(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable")o.disableBypassPermissionsMode="disable";if(t.allowManagedPermissionRulesOnly!==!0){let{allow:s,additionalDirectories:i}=e.permissions;if(s&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)o.allow=s;if(i)o.additionalDirectories=i}if(Object.keys(o).length>0)n.permissions=o}if(e.sandbox){let{network:o,filesystem:s,credentials:i}=e.sandbox,a={};if(e.sandbox.enabled===!0)a.enabled=!0;if(e.sandbox.failIfUnavailable===!0)a.failIfUnavailable=!0;if(e.sandbox.allowUnsandboxedCommands===!1)a.allowUnsandboxedCommands=!1;if(e.sandbox.autoAllowBashIfSandboxed===!1)a.autoAllowBashIfSandboxed=!1;if(o){let c=Ry(o,["deniedDomains"]);if(o.allowManagedDomainsOnly===!0)c.allowManagedDomainsOnly=!0;if(o.strictAllowlist===!0)c.strictAllowlist=!0;if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&o.allowedDomains)c.allowedDomains=o.allowedDomains;if(Object.keys(c).length>0)a.network=c}if(s){let c=Ry(s,["denyRead","denyWrite"]);if(s.allowManagedReadPathsOnly===!0)c.allowManagedReadPathsOnly=!0;if(s.disabled===!1)c.disabled=!1;if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&s.allowRead)c.allowRead=s.allowRead;if(Object.keys(c).length>0)a.filesystem=c}if(i){let c=(i.files??[]).map((p)=>p.mode==="deny"?{path:p.path,mode:"deny"}:{path:p.path,mode:"mask",injectHosts:[]}),l=(i.envVars??[]).filter((p)=>p.mode==="deny").map((p)=>({name:p.name,mode:"deny"})),u={...c.length>0&&{files:c},...l.length>0&&{envVars:l}};if(i.allowPlaintextInject===!1)u.allowPlaintextInject=!1;if(i.sigv4){let p={};for(let f of["streaming","presigned","sigv4a"])if(i.sigv4[f]==="deny")p[f]="deny";u.sigv4=p}{let p=Ql,f=Ni((i.awsPairs??[]).flatMap((m)=>[m.accessKeyIdVar,m.secretAccessKeyVar,...m.sessionTokenVar!==void 0?[m.sessionTokenVar]:[]]).filter((m)=>p.includes(m)));if(f.length>0)u.awsPairs=f.map((m,h)=>({accessKeyIdVar:m,secretAccessKeyVar:`${X3}${h+1}_`}))}if(Object.keys(u).length>0)a.credentials=u}if(Object.keys(a).length>0)n.sandbox=a}return n}var r2e=new Set([...[...mR].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...hR,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL"]);function o2e(e,t){if(!t||!e)return null;let n={};if(e.model!==void 0)n.model=e.model;if(e.availableModels!==void 0)n.availableModels=e.availableModels;if(e.enforceAvailableModels!==void 0)n.enforceAvailableModels=e.enforceAvailableModels;if(e.fallbackModel!==void 0)n.fallbackModel=e.fallbackModel;return Object.keys(n).length>0?n:null}function $y(e){if(delete e.model,delete e.fallbackModel,delete e.modelOverrides,e.env){let t={};for(let[n,r]of Object.entries(e.env))if(!r2e.has(n.toUpperCase()))t[n]=r;e.env=t}}function xZ(e){if(e.helper?.())return"helper";if(fZ(e).settings)return"remote";if(dZ(e).settings)return Bo()==="macos"?"plist":"hklm";if((e.file?.()??uZ(e)).settings)return"file";let t=FR(e);if(t.parentSlice||t.hostModelOverlay)return"parent";let n=e.hkcu?.();return n&&Object.keys(n.settings).length>0?"hkcu":null}function FR(e){let t=[],{settings:n,errors:r}=fZ(e);t.push(...r);let{settings:o,errors:s}=dZ(e);t.push(...s);let{settings:i,errors:a}=e.file?.()??uZ(e);t.push(...a);let{settings:c,errors:l}=KHe(e);t.push(...l);let u=[n,o,i].filter((b)=>b!==null),p=u[0]??null,f={remote:n!==null,mdm:o!==null,file:i!==null},m={allowManagedPermissionRulesOnly:u.some((b)=>b.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:u[0]?.forceLoginOrgUUID,allowedMcpServers:u[0]?.allowedMcpServers,availableModels:u[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:u.some((b)=>b.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:u.some((b)=>b.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},h=c&&t2e(p)?n2e(c,m):null,g=h&&Object.keys(h).length>0?h:null,y=o2e(c,e.hostManagedProvider);return{tiers:u,admin:p,parentSlice:g,hostModelOverlay:y,errors:t,present:f}}var s2e=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];function i2e(e){return K3.some((t)=>e.startsWith(t))||H3.includes(e)}function a2e(e,t,n){let r=new Map,o=new Map,s=!1;for(let[i,a]of e.entries()){let c=new Set,l=t?.[i]===!0;for(let[u,p]of Object.entries(a??{})){let f=u.toUpperCase(),m=i2e(f);if(m&&p.trim()==="")continue;if(m&&s)continue;if(m&&i>0&&t?.[i]===!0)continue;let h=r.get(f);if(h!==void 0){if(c.has(f))o.set(u,p);else if(!o.has(u))o.set(u,h);continue}if(i>0&&n?.[i]?.has(f))continue;if(o.set(u,p),c.add(f),r.set(f,p),m)l=!0}if(l)s=!0}return Object.fromEntries(o)}var c2e="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function lZ(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==c2e)t[n]=r;return t}function l2e(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function EZ(e){let t=e.helper?.(),n=e.helperWarnings?.()??[];if(t){e.store.lastPolicyEnvComposition=null;let h=e.hostManagedProvider?{...t}:t;if(e.hostManagedProvider)$y(h);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&t.availableModels!==void 0?t.modelOverrides:void 0};let g=e.store.policy.helperBaseStatusNotices??=FR(e).errors.filter((y)=>y.statusOnly);return{settings:h,errors:[...g,...n]}}let{tiers:r,admin:o,parentSlice:s,hostModelOverlay:i,errors:a,present:c}=FR(e);if(a.push(...n),!o&&!s){e.store.lastPolicyEnvComposition=null,e.store.policy.pairedModelOverrides={value:void 0};let h=e.hkcu?.();if(h&&Object.keys(h.settings).length>0){let g=e.hostManagedProvider?{...h.settings}:h.settings;if(e.hostManagedProvider){if($y(g),i)Object.assign(g,i)}return{settings:g,errors:[...a,...h.errors]}}if(i)return{settings:{...i},errors:[...a,...h?.errors??[]]};return{settings:null,errors:[...a,...h?.errors??[]]}}let l=io({},s??{},o??{},ko);if(r.some((h)=>h.forceRemoteSettingsRefresh===!0))l.forceRemoteSettingsRefresh=!0;let u=xn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,p=l.env;if(!u){let h=a2e(r.map((g)=>g.env),r.map((g)=>(g.otelHeadersHelper??"").trim()!==""),r.map((g)=>{let y=new Set;for(let b of s2e){let x=g[b];if(typeof x==="string"&&x.trim()!=="")for(let E of q3[b])y.add(E)}return y.size>0?y:void 0}));if(Object.keys(h).length>0)l.env=h;else delete l.env}if(l.env){let h=lZ(l.env);if(h&&Object.keys(h).length>0)l.env=h;else delete l.env}if(e.hostManagedProvider){if($y(l),i)Object.assign(l,i)}let f={env:lZ(p)};if(e.hostManagedProvider)$y(f);let m=!u&&!l2e(l.env,f.env);return e.store.lastPolicyEnvComposition={unionOptedOut:u,unionChangedEnv:m,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:np(r,(h)=>Object.keys(h.env??{}).length>0)},e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&o?.availableModels!==void 0&&o.modelOverrides!==void 0&&i?.availableModels===void 0?o.modelOverrides:void 0},{settings:l,errors:a}}function u2e(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return EZ(t).settings;let r=$f(e,t),{settings:o}=r?ou(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=mZ(t);if(s)return io(o||{},s,ko)}if(e==="localSettings"&&n){let s=bZ(t);if(s){let{settings:i}=ou(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),io(i,o||{},ko)}}return o}function d2e(e,t){return{...e,...t}}function ko(e,t,n){if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Ni([...e,...t])}if(n==="extraKnownMarketplaces"&&fa(e)&&fa(t))return d2e(e,t);return}function p2e(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();Cf("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=io(r,n,ko);let o=[],s=new Set,i=new Set,a=(l)=>{for(let u of l){let p=`${u.file}:${u.path}:${u.message}`;if(!s.has(p))s.add(p),o.push(u)}},c=null;for(let l of jR(e)){if(l==="policySettings"){let{settings:p,errors:f}=EZ(e);if(c=p,p)r=io(r,p,ko);a(f);continue}if(l==="localSettings"){let p=bZ(e);if(p&&!i.has(Or(p))){i.add(Or(p));let{settings:f,errors:m}=ou(p,e.store);if(a(m),f)e.onLegacyLocalSettingsRead?.("cascade"),r=io(r,f,ko)}}let u=$f(l,e);if(u){let p=Or(u),f=l==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(p)||f){i.add(p);let{settings:m,errors:h}=ou(u,e.store,l==="flagSettings"?e.flagExpectedContent:void 0);if(a(h),m)r=io(r,m,ko)}}if(l==="flagSettings"){let{settings:p,errors:f}=mZ(e);if(a(f),p)r=io(r,p,ko)}}if(c){if(c.availableModels!==void 0)r.availableModels=[...c.availableModels];if(c.enforceAvailableModels!==void 0)r.enforceAvailableModels=c.enforceAvailableModels}return Cf("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:i.size,error_count:o.length}),{settings:r,errors:o}}finally{e.store.isLoadingFromDisk=!1}}function f2e(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=p2e(e);return e.store.mergedSettings=n,n}function m2e(e){let{settings:t}=f2e(e);return t||{}}function vZ(e){e.store.invalidateAll();let t=[];for(let n of jR(e)){let r=SZ(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:m2e(e),sources:t}}function wZ(e,t){let n=jR(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(SZ(o,t)?.[e]!==void 0)return o}return null}import{execFile as h2e}from"child_process";import{existsSync as g2e}from"fs";class TZ{promise=null;start(){if(this.promise)return;this.promise=$R()}reset(){this.promise=null}}var _2e=new TZ;function Bf(e,t){return new Promise((n)=>{try{h2e(e,t,{encoding:"utf-8",timeout:o9,windowsHide:!0},(r,o)=>{n({stdout:o??"",code:r?1:0})})}catch{n({stdout:"",code:1})}})}function $R(){return(async()=>{if(process.platform==="darwin"){let e=s9(),n=(await Promise.all(e.map(async({path:r,label:o})=>{if(!g2e(r))return{stdout:"",label:o,ok:!1};let{stdout:s,code:i}=await Bf(n9,[...r9,r]);return{stdout:s,label:o,ok:i===0&&!!s}}))).find((r)=>r.ok);return{plistStdouts:n?[{stdout:n.stdout,label:n.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[n,r]=await Promise.all([Bf(t,["query",Df,"/v",ni]),Bf(t,["query",Lf,"/v",ni])]);return{plistStdouts:null,hklmStdout:n.code===0?n.stdout:null,hkcuStdout:r.code===0?r.stdout:null}}if(Dy()){let[e,t]=await Promise.all([Bf(bR,["query",Df,"/v",ni]),Bf(bR,["query",Lf,"/v",ni])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function AZ(){return _2e.promise}var oi=Object.freeze({settings:{},errors:[]});class OZ{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),n=AZ()??$R(),{mdm:r,hkcu:o,wslInherits:s}=await b2e(await n,e);this.replace(r,o,s);let i=Date.now()-t;if(ce(`MDM settings load completed in ${i}ms`),Object.keys(r.settings).length>0){ce(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{Cf("info","mdm_settings_loaded",{duration_ms:i,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})()}replace(e,t,n){this.mdm=e,this.hkcu=t,this.wslInherits=n}reset(){this.mdm=null,this.hkcu=null,this.wslInherits=!1,this.loadPromise=null}}var iu=new OZ;function y2e(e){iu.startLoad(e)}async function PZ(){if(!iu.loadPromise)y2e();await iu.loadPromise}function IZ(){return iu.mdm??oi}function DZ(){return iu.hkcu??oi}function LZ(){return iu.wslInherits}function BR(e,t){let n=Wl(e,!1);if(!n||typeof n!=="object")return{settings:{},errors:[]};let{settings:r,errors:o}=By(n,t);return{settings:r??{},errors:o}}function kZ(e,t="Settings"){let n=e.split(/\r?\n/),r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^\\s+${r}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let s of n){let i=s.match(o);if(i&&i[1])return i[1].trimEnd()}return null}async function b2e(e,t){let n=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:a,label:c}=e.plistStdouts[0],l=BR(a,c),{wslInheritsWindowsSettings:u,...p}=l.settings;if(Object.keys(p).length>0)return{mdm:l,hkcu:oi,wslInherits:!1};n.push(...l.errors)}let r=null;if(e.hklmStdout){let a=kZ(e.hklmStdout);if(a)r=BR(a,`Registry: ${Df}\\${ni}`)}if(r)n.push(...r.errors);let o=n.length>0?{settings:{},errors:n}:oi,s=Dy(),i=!1;if(s){if(i=r?.settings.wslInheritsWindowsSettings===!0||await x2e(t),!i)return{mdm:o,hkcu:oi,wslInherits:!1}}if(r){let{wslInheritsWindowsSettings:a,...c}=r.settings;if(Object.keys(c).length>0)return{mdm:r,hkcu:oi,wslInherits:i}}if(await S2e(i,t))return{mdm:o,hkcu:oi,wslInherits:i};if(e.hkcuStdout){let a=kZ(e.hkcuStdout);if(a){let c=BR(a,`Registry: ${Lf}\\${ni}`);if(!s||c.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:l,...u}=c.settings;return{mdm:o,hkcu:{settings:u,errors:c.errors},wslInherits:i}}if(c.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:c.errors},wslInherits:i}}}return{mdm:o,hkcu:oi,wslInherits:i}}async function MZ(e,t){if(t!==void 0)return(await N6(e)).content;return Kl(e)}async function NZ(e,t){if(t!==void 0)return await We().readdir(e);return We().readdirSync(e)}async function S2e(e,t){if(e&&await RZ(eu,t))return!0;return RZ(pa(),t)}async function CZ(e,t){let n=Ds(Wl(await MZ(e,t),!1));if(!n||typeof n!=="object")return!1;ya(n,e);let{wslInheritsWindowsSettings:r,...o}=n;return Object.keys(o).length>0}async function x2e(e){async function t(n){try{let r=Wl(await MZ(n,e),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(await t(su(eu,"managed-settings.json")))return!0;try{let n=su(eu,"managed-settings.d");for(let r of await NZ(n,e))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&await t(su(n,r.name)))return!0}catch{}return!1}async function RZ(e,t){try{if(await CZ(su(e,"managed-settings.json"),t))return!0}catch{}try{let n=su(e,"managed-settings.d"),r=await NZ(n,t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(await CZ(su(n,o.name),t))return!0}catch{}}}catch{}return!1}var v2e={user:"userSettings",project:"projectSettings",local:"localSettings"},UZ={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},w2e=["user","project","local"],T2e=new Set(["bypassPermissions","auto","acceptEdits"]),A2e=new Set(["project"]);function k2e(e){let t=e.effective.permissions?.defaultMode;if(!t||!T2e.has(t))return e.effective;for(let n=e.sources.length-1;n>=0;n--){let r=e.sources[n];if(r.settings.permissions?.defaultMode!==void 0){if(A2e.has(r.source)){let{defaultMode:o,...s}=e.effective.permissions??{};return{...e.effective,permissions:s}}return e.effective}}return e.effective}async function zZ(e={}){await PZ();let t={store:new Qh,cwd:E2e(e.cwd??We().cwd()),allowedSources:(e.settingSources??w2e).map((a)=>v2e[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:IZ,hkcu:DZ,wslInherits:LZ,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=vZ(t),o=xZ(t)??void 0,s=r.map(({source:a,settings:c})=>({source:UZ[a],settings:c,path:a==="policySettings"?void 0:$f(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let c=wZ(a,t);if(c)i[a]={source:UZ[c],path:c==="policySettings"?void 0:$f(c,t),...c==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function CRt(e){return zZ(e)}var U2e=["enabledPlugins","extraKnownMarketplaces"];function FZ(e){let t;try{t=pt(ml(e.toString("utf8")))}catch{return e}if(!jZ(t))return e;let n=!1;for(let o of U2e)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(jZ(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?xe(t):e}function jZ(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function z2e(e,t){if(!e)return;let n=e;try{let r=pt(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=xe(r)}catch{}await KZ(t,n,{mode:384})}function F2e(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=DK(IK);return new Promise((t)=>{C2e("security",["find-generic-password","-a",LK(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function WZ(e,t,n,r,o=60000,s){if(!Xe(t))return;let i=Pr(n),a=await fr(e.load({projectKey:i,sessionId:t}),o,`SessionStore.load() timed out after ${o}ms for session ${t}`);if(!a||a.length===0)return;let c=on(L2e(),`claude-resume-${WR()}`);try{let l=on(c,"projects",i);await HR(l,{recursive:!0,mode:448});let u=on(l,`${t}.jsonl`);await Bp(u,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??on(KR(),".claude"),m;try{m=await HZ(on(f,".credentials.json"),"utf-8")}catch(b){if(!rr(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await F2e()??m;await z2e(m,on(c,".credentials.json"));let h=PK(xn.CLAUDE_CONFIG_DIR),g=on(p??KR(),".claude.json");await u_(g,on(c,".claude.json"),void 0,wk(s,g,h.globalConfig,jn.globalConfig()));let y=on(f,"settings.json");if(await u_(y,on(c,"settings.json"),FZ,wk(s,y,h.userSettings,jn.userSettings())),await u_(on(f,"cowork_settings.json"),on(c,"cowork_settings.json"),FZ),e.listSubkeys)await j2e(e,{projectKey:i,sessionId:t},on(l,t),o);return c}catch(l){throw await Hy(c),l}}async function j2e(e,t,n,r){let o=await fr(e.listSubkeys({projectKey:t.projectKey,sessionId:t.sessionId}),r,`SessionStore.listSubkeys() timed out after ${r}ms for session ${t.sessionId}`);for(let s of o){let i=Hf(n,s+".jsonl");if(!s||qZ(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+VR)){ce(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await fr(e.load({projectKey:t.projectKey,sessionId:t.sessionId,subpath:s}),r,`SessionStore.load() timed out after ${r}ms for session ${t.sessionId} subpath ${s}`);if(!a||a.length===0)continue;let c=[],l=[];for(let u of a)if(GR(u))c.push(u);else l.push(u);if(l.length>0)await HR(qR(i),{recursive:!0}),await Bp(i,l);if(c.length>0){let u=c.at(-1),p=Hf(n,s+".meta.json");await HR(qR(p),{recursive:!0});let{type:f,...m}=u;await KZ(p,xe(m),{mode:384})}}}function ZR(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o}=t,{systemPrompt:s,settings:i,managedSettings:a,settingSources:c,sandbox:l,...u}=e??{},p,f,m;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.229";let{abortController:h=lu(),additionalDirectories:g=[],agent:y,agents:b,allowedTools:x=[],betas:E,canUseTool:k,continue:R,cwd:V,debug:K,debugFile:Q,disallowedTools:X=[],tools:me,env:Ce,executable:tt=Ta()?"bun":"node",executableArgs:ye=[],extraArgs:Ve={},fallbackModel:fn,enableFileCheckpointing:Z,toolConfig:pr,forkSession:mn,hooks:lt,includeHookEvents:Gn,includePartialMessages:yt,forwardSubagentText:te,onElicitation:Y,onUserDialog:J,supportedDialogKinds:Le,persistSession:be,sessionStore:Ze,sessionStoreFlush:Wn,thinking:Qe,effort:Ir,maxThinkingTokens:Co,maxTurns:Ot,maxBudgetUsd:Kf,taskBudget:e5,mcpServers:JR,model:t5,outputFormat:XR,permissionMode:n5,allowDangerouslySkipPermissions:r5=!1,permissionPromptToolName:o5,plugins:s5,getOAuthToken:QR,getHostAuthToken:eO,workload:tO,resume:nO,resumeSessionAt:i5,resumeDropsTurn:a5,sessionId:c5,skills:rO,stderr:l5,strictMcpConfig:u5}=u,oO=n5??(e?.resolvePermissionModeInCli?void 0:"default");if(Ze&&be===!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(Le!==void 0&&Le.length>0&&!J)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if(Ze&&R&&!nO&&!Ze.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(Ze&&Z)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(Ze&&u.spawnClaudeCodeProcess)ce("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"});MK(!!k,oO??"default",x);let qy=u.pathToClaudeCodeExecutable;if(!qy){let Vn=N2e(import.meta.url),Dr=D2e(Vn),si=s1((ba)=>Dr.resolve(ba));if(!si)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.`);qy=si}let sO=XR?.type==="json_schema"?XR.schema:void 0,hn=Ce?{...Ce}:{...process.env};if(!hn.CLAUDE_CODE_ENTRYPOINT)hn.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!hn.CLAUDE_AGENT_SDK_VERSION)hn.CLAUDE_AGENT_SDK_VERSION="0.3.229";if(Z)hn.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(QR)hn.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(eO)hn.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(pr?.askUserQuestion?.previewFormat)hn.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=pr.askUserQuestion.previewFormat;let Gy={};if(Ky.propagation.inject(Ky.context.active(),Gy),"traceparent"in Gy){for(let Vn of["TRACEPARENT","TRACESTATE"])if(!(Vn in(Ce??{})))delete hn[Vn]}for(let[Vn,Dr]of Object.entries(Gy)){let si=Vn.toUpperCase();if(!(si in(Ce??{})))hn[si]=Dr}let iO={},aO=new Map;if(JR)for(let[Vn,Dr]of Object.entries(JR))if(Dr.type==="sdk"&&Dr.instance)aO.set(Vn,Dr.instance);else iO[Vn]=Dr;let au;if(Qe)switch(Qe.type){case"adaptive":au={type:"adaptive",display:Qe.display};break;case"enabled":au={type:"enabled",budgetTokens:Qe.budgetTokens,display:Qe.display};break;case"disabled":au={type:"disabled"};break}else if(Co!==void 0)au=Co===0?{type:"disabled"}:{type:"enabled",budgetTokens:Co};if(r){if(hn.CLAUDE_CONFIG_DIR=r,process.platform==="win32")hn.CLAUDE_SECURESTORAGE_CONFIG_DIR=Ce?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??Ce?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let cO=new fA({abortController:h,additionalDirectories:g,agent:y,betas:E,cwd:V,debug:K,debugFile:Q,executable:tt,executableArgs:ye,extraArgs:tO?{...Ve,workload:tO}:Ve,pathToClaudeCodeExecutable:qy,env:hn,forkSession:mn,stderr:l5,thinkingConfig:au,effort:Ir,maxTurns:Ot,maxBudgetUsd:Kf,taskBudget:e5,model:t5,fallbackModel:fn,jsonSchema:sO,permissionMode:oO,allowDangerouslySkipPermissions:r5,permissionPromptToolName:o5,continueConversation:Ze?void 0:R,resume:nO,resumeSessionAt:i5,resumeDropsTurn:a5,sessionId:c5,settings:typeof i==="object"?xe(i):i,managedSettings:a?xe(a):void 0,settingSources:c,skills:rO,allowedTools:x,disallowedTools:X,tools:me,mcpServers:iO,strictMcpConfig:u5,canUseTool:!!k,hooks:!!lt,includeHookEvents:Gn,includePartialMessages:yt,persistSession:be,sessionMirror:!!Ze,plugins:s5,sandbox:l,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),d5={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:b,title:u.title,skills:rO,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:te,supportedDialogKinds:Le},Wy=new jg(cO,n,k,lt,h,aO,sO,d5,Y,QR,eO,J);if(Ze){let Vn=()=>on(hn.CLAUDE_CONFIG_DIR??on(KR(),".claude"),"projects"),Dr=Wn==="eager",si=new _A(async(ba,Vy)=>{let cu=BZ(ba,Vn());if(cu)await Ze.append(cu,Vy);else ce(`[SessionStore] dropping mirror frame: filePath ${ba} is not under ${Vn()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(ba,Vy)=>{let cu=BZ(ba,Vn());if(cu)Wy.reportMirrorError(cu,Vy.message)},maxPendingEntries:Dr?0:$g,maxPendingBytes:Dr?0:ll});Wy.setTranscriptMirrorBatcher(si)}return{queryInstance:Wy,transport:cO,abortController:h,processEnv:hn}}function YR(e,t,n,r){if(typeof n==="string")t.write(xe({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
151
+ `+"\t".repeat(t))}};var F6;(function(e){e.DEFAULT={allowTrailingComma:!1}})(F6||(F6={}));var j6;(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"})(j6||(j6={}));var $6;(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"})($6||($6={}));var B6;(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"})(B6||(B6={}));var ql=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,K6=new Set,lR=typeof process==="object"&&!!process?process:{},q6=(e,t,n,r)=>{typeof lR.emitWarning==="function"?lR.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},xy=globalThis.AbortController,H6=globalThis.AbortSignal;if(typeof xy>"u"){H6=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},xy=class{constructor(){t()}signal=new H6;abort(r){if(this.signal.aborted)return;this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}};let e=lR.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{if(!e)return;e=!1,q6("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 R$e=(e)=>!K6.has(e),gEt=Symbol("type"),ti=(e)=>e&&e===Math.floor(e)&&e>0&&isFinite(e),G6=(e)=>!ti(e)?null:e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Rf:null;class Rf extends Array{constructor(e){super(e);this.fill(0)}}class Gl{heap;length;static#e=!1;static create(e){let t=G6(e);if(!t)return[];Gl.#e=!0;let n=new Gl(e,t);return Gl.#e=!1,n}constructor(e,t){if(!Gl.#e)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class Ey{#e;#t;#n;#r;#o;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#s;#l;#u;#i;#c;#p;#h;#d;#f;#_;#m;#b;#S;#y;#E;#T;#x;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#y,sizes:e.#b,keyMap:e.#u,keyList:e.#i,valList:e.#c,next:e.#p,prev:e.#h,get head(){return e.#d},get tail(){return e.#f},free:e.#_,isBackgroundFetch:(t)=>e.#g(t),backgroundFetch:(t,n,r,o)=>e.#M(t,n,r,o),moveToTail:(t)=>e.#I(t),indexes:(t)=>e.#k(t),rindexes:(t)=>e.#C(t),isStale:(t)=>e.#w(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#l}get size(){return this.#s}get fetchMethod(){return this.#o}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:i,allowStale:a,dispose:c,disposeAfter:l,noDisposeOnSet:u,noUpdateTTL:p,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:x,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:k,ignoreFetchAbort:R}=e;if(t!==0&&!ti(t))throw TypeError("max option must be a nonnegative integer");let V=t?G6(t):Array;if(!V)throw Error("invalid max value: "+t);if(this.#e=t,this.#t=f,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!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(y!==void 0&&typeof y!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#a=y,g!==void 0&&typeof g!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#o=g,this.#T=!!g,this.#u=new Map,this.#i=Array(t).fill(void 0),this.#c=Array(t).fill(void 0),this.#p=new V(t),this.#h=new V(t),this.#d=0,this.#f=0,this.#_=Gl.create(t),this.#s=0,this.#l=0,typeof c==="function")this.#n=c;if(typeof l==="function")this.#r=l,this.#m=[];else this.#r=void 0,this.#m=void 0;if(this.#E=!!this.#n,this.#x=!!this.#r,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!R,this.maxEntrySize!==0){if(this.#t!==0){if(!ti(this.#t))throw TypeError("maxSize must be a positive integer if specified")}if(!ti(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!x,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!i,this.ttlResolution=ti(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!ti(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#O()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){if(R$e("LRU_CACHE_UNBOUNDED"))K6.add("LRU_CACHE_UNBOUNDED"),q6("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",Ey)}}getRemainingTTL(e){return this.#u.has(e)?1/0:0}#O(){let e=new Rf(this.#e),t=new Rf(this.#e);this.#y=e,this.#S=t,this.#N=(o,s,i=ql.now())=>{if(t[o]=s!==0?i:0,e[o]=s,s!==0&&this.ttlAutopurge){let a=setTimeout(()=>{if(this.#w(o))this.#R(this.#i[o],"expire")},s+1);if(a.unref)a.unref()}},this.#A=(o)=>{t[o]=e[o]!==0?ql.now():0},this.#v=(o,s)=>{if(e[s]){let i=e[s],a=t[s];if(!i||!a)return;o.ttl=i,o.start=a,o.now=n||r();let c=o.now-a;o.remainingTTL=i-c}};let n=0,r=()=>{let o=ql.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);if(s.unref)s.unref()}return o};this.getRemainingTTL=(o)=>{let s=this.#u.get(o);if(s===void 0)return 0;let i=e[s],a=t[s];if(!i||!a)return 1/0;let c=(n||r())-a;return i-c},this.#w=(o)=>{let s=t[o],i=e[o];return!!i&&!!s&&(n||r())-s>i}}#A=()=>{};#v=()=>{};#N=()=>{};#w=()=>!1;#$(){let e=new Rf(this.#e);this.#l=0,this.#b=e,this.#P=(t)=>{this.#l-=e[t],e[t]=0},this.#U=(t,n,r,o)=>{if(this.#g(n))return 0;if(!ti(r))if(o){if(typeof o!=="function")throw TypeError("sizeCalculation must be a function");if(r=o(n,t),!ti(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.#D=(t,n,r)=>{if(e[t]=n,this.#t){let o=this.#t-e[t];while(this.#l>o)this.#L(!0)}if(this.#l+=e[t],r)r.entrySize=n,r.totalCalculatedSize=this.#l}}#P=(e)=>{};#D=(e,t,n)=>{};#U=(e,t,n,r)=>{if(n||r)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:e=this.allowStale}={}){if(this.#s)for(let t=this.#f;;){if(!this.#z(t))break;if(e||!this.#w(t))yield t;if(t===this.#d)break;else t=this.#h[t]}}*#C({allowStale:e=this.allowStale}={}){if(this.#s)for(let t=this.#d;;){if(!this.#z(t))break;if(e||!this.#w(t))yield t;if(t===this.#f)break;else t=this.#p[t]}}#z(e){return e!==void 0&&this.#u.get(this.#i[e])===e}*entries(){for(let e of this.#k())if(this.#c[e]!==void 0&&this.#i[e]!==void 0&&!this.#g(this.#c[e]))yield[this.#i[e],this.#c[e]]}*rentries(){for(let e of this.#C())if(this.#c[e]!==void 0&&this.#i[e]!==void 0&&!this.#g(this.#c[e]))yield[this.#i[e],this.#c[e]]}*keys(){for(let e of this.#k()){let t=this.#i[e];if(t!==void 0&&!this.#g(this.#c[e]))yield t}}*rkeys(){for(let e of this.#C()){let t=this.#i[e];if(t!==void 0&&!this.#g(this.#c[e]))yield t}}*values(){for(let e of this.#k())if(this.#c[e]!==void 0&&!this.#g(this.#c[e]))yield this.#c[e]}*rvalues(){for(let e of this.#C())if(this.#c[e]!==void 0&&!this.#g(this.#c[e]))yield this.#c[e]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#k()){let r=this.#c[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;if(e(o,this.#i[n],this))return this.get(this.#i[n],t)}}forEach(e,t=this){for(let n of this.#k()){let r=this.#c[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#i[n],this)}}rforEach(e,t=this){for(let n of this.#C()){let r=this.#c[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#i[n],this)}}purgeStale(){let e=!1;for(let t of this.#C({allowStale:!0}))if(this.#w(t))this.#R(this.#i[t],"expire"),e=!0;return e}info(e){let t=this.#u.get(e);if(t===void 0)return;let n=this.#c[t],r=this.#g(n)?n.__staleWhileFetching:n;if(r===void 0)return;let o={value:r};if(this.#y&&this.#S){let s=this.#y[t],i=this.#S[t];if(s&&i){let a=s-(ql.now()-i);o.ttl=a,o.start=Date.now()}}if(this.#b)o.size=this.#b[t];return o}dump(){let e=[];for(let t of this.#k({allowStale:!0})){let n=this.#i[t],r=this.#c[t],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#y&&this.#S){s.ttl=this.#y[t];let i=ql.now()-this.#S[t];s.start=Math.floor(Date.now()-i)}if(this.#b)s.size=this.#b[t];e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let r=Date.now()-n.start;n.start=ql.now()-r}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:i=this.sizeCalculation,status:a}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#U(e,t,n.size||0,i);if(this.maxEntrySize&&l>this.maxEntrySize){if(a)a.set="miss",a.maxEntrySizeExceeded=!0;return this.#R(e,"set"),this}let u=this.#s===0?void 0:this.#u.get(e);if(u===void 0){if(u=this.#s===0?this.#f:this.#_.length!==0?this.#_.pop():this.#s===this.#e?this.#L(!1):this.#s,this.#i[u]=e,this.#c[u]=t,this.#u.set(e,u),this.#p[this.#f]=u,this.#h[u]=this.#f,this.#f=u,this.#s++,this.#D(u,l,a),a)a.set="add";c=!1}else{this.#I(u);let p=this.#c[u];if(t!==p){if(this.#T&&this.#g(p)){p.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=p;if(f!==void 0&&!s){if(this.#E)this.#n?.(f,e,"set");if(this.#x)this.#m?.push([f,e,"set"])}}else if(!s){if(this.#E)this.#n?.(p,e,"set");if(this.#x)this.#m?.push([p,e,"set"])}if(this.#P(u),this.#D(u,l,a),this.#c[u]=t,a){a.set="replace";let f=p&&this.#g(p)?p.__staleWhileFetching:p;if(f!==void 0)a.oldValue=f}}else if(a)a.set="update"}if(r!==0&&!this.#y)this.#O();if(this.#y){if(!c)this.#N(u,r,o);if(a)this.#v(a,u)}if(!s&&this.#x&&this.#m){let p=this.#m,f;while(f=p?.shift())this.#r?.(...f)}return this}pop(){try{while(this.#s){let e=this.#c[this.#d];if(this.#L(!0),this.#g(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#x&&this.#m){let e=this.#m,t;while(t=e?.shift())this.#r?.(...t)}}}#L(e){let t=this.#d,n=this.#i[t],r=this.#c[t];if(this.#T&&this.#g(r))r.__abortController.abort(Error("evicted"));else if(this.#E||this.#x){if(this.#E)this.#n?.(r,n,"evict");if(this.#x)this.#m?.push([r,n,"evict"])}if(this.#P(t),e)this.#i[t]=void 0,this.#c[t]=void 0,this.#_.push(t);if(this.#s===1)this.#d=this.#f=0,this.#_.length=0;else this.#d=this.#p[t];return this.#u.delete(n),this.#s--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,o=this.#u.get(e);if(o!==void 0){let s=this.#c[o];if(this.#g(s)&&s.__staleWhileFetching===void 0)return!1;if(!this.#w(o)){if(n)this.#A(o);if(r)r.has="hit",this.#v(r,o);return!0}else if(r)r.has="stale",this.#v(r,o)}else if(r)r.has="miss";return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#u.get(e);if(r===void 0||!n&&this.#w(r))return;let o=this.#c[r];return this.#g(o)?o.__staleWhileFetching:o}#M(e,t,n,r){let o=t===void 0?void 0:this.#c[t];if(this.#g(o))return o;let s=new xy,{signal:i}=n;i?.addEventListener("abort",()=>s.abort(i.reason),{signal:s.signal});let a={signal:s.signal,options:n,context:r},c=(h,g=!1)=>{let{aborted:y}=s.signal,b=n.ignoreFetchAbort&&h!==void 0;if(n.status)if(y&&!g){if(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,b)n.status.fetchAbortIgnored=!0}else n.status.fetchResolved=!0;if(y&&!b&&!g)return u(s.signal.reason);let x=f;if(this.#c[t]===f)if(h===void 0)if(x.__staleWhileFetching)this.#c[t]=x.__staleWhileFetching;else this.#R(e,"fetch");else{if(n.status)n.status.fetchUpdated=!0;this.set(e,h,a.options)}return h},l=(h)=>{if(n.status)n.status.fetchRejected=!0,n.status.fetchError=h;return u(h)},u=(h)=>{let{aborted:g}=s.signal,y=g&&n.allowStaleOnFetchAbort,b=y||n.allowStaleOnFetchRejection,x=b||n.noDeleteOnFetchRejection,E=f;if(this.#c[t]===f){if(!x||E.__staleWhileFetching===void 0)this.#R(e,"fetch");else if(!y)this.#c[t]=E.__staleWhileFetching}if(b){if(n.status&&E.__staleWhileFetching!==void 0)n.status.returnedStale=!0;return E.__staleWhileFetching}else if(E.__returned===E)throw h},p=(h,g)=>{let y=this.#o?.(e,o,a);if(y&&y instanceof Promise)y.then((b)=>h(b===void 0?void 0:b),g);s.signal.addEventListener("abort",()=>{if(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort){if(h(void 0),n.allowStaleOnFetchAbort)h=(b)=>c(b,!0)}})};if(n.status)n.status.fetchDispatched=!0;let f=new Promise(p).then(c,l),m=Object.assign(f,{__abortController:s,__staleWhileFetching:o,__returned:void 0});if(t===void 0)this.set(e,m,{...a.options,status:void 0}),t=this.#u.get(e);else this.#c[t]=m;return m}#g(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof xy}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:i=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:y,signal:b}=t;if(!this.#T){if(y)y.fetch="get";return this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:y})}let x={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:i,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:y,signal:b},E=this.#u.get(e);if(E===void 0){if(y)y.fetch="miss";let k=this.#M(e,E,x,h);return k.__returned=k}else{let k=this.#c[E];if(this.#g(k)){let X=n&&k.__staleWhileFetching!==void 0;if(y){if(y.fetch="inflight",X)y.returnedStale=!0}return X?k.__staleWhileFetching:k.__returned=k}let R=this.#w(E);if(!g&&!R){if(y)y.fetch="hit";if(this.#I(E),r)this.#A(E);if(y)this.#v(y,E);return k}let V=this.#M(e,E,x,h),Q=V.__staleWhileFetching!==void 0&&n;if(y){if(y.fetch=R?"stale":"refresh",Q&&R)y.returnedStale=!0}return Q?V.__staleWhileFetching:V.__returned=V}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#a;if(!n)throw Error("no memoMethod provided to constructor");let{context:r,forceRefresh:o,...s}=t,i=this.get(e,s);if(!o&&i!==void 0)return i;let a=n(e,i,{options:s,context:r});return this.set(e,a,s),a}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=t,i=this.#u.get(e);if(i!==void 0){let a=this.#c[i],c=this.#g(a);if(s)this.#v(s,i);if(this.#w(i)){if(s)s.get="stale";if(!c){if(!o)this.#R(e,"expire");if(s&&n)s.returnedStale=!0;return n?a:void 0}else{if(s&&n&&a.__staleWhileFetching!==void 0)s.returnedStale=!0;return n?a.__staleWhileFetching:void 0}}else{if(s)s.get="hit";if(c)return a.__staleWhileFetching;if(this.#I(i),r)this.#A(i);return a}}else if(s)s.get="miss"}#F(e,t){this.#h[t]=e,this.#p[e]=t}#I(e){if(e!==this.#f){if(e===this.#d)this.#d=this.#p[e];else this.#F(this.#h[e],this.#p[e]);this.#F(this.#f,e),this.#f=e}}delete(e){return this.#R(e,"delete")}#R(e,t){let n=!1;if(this.#s!==0){let r=this.#u.get(e);if(r!==void 0)if(n=!0,this.#s===1)this.#j(t);else{this.#P(r);let o=this.#c[r];if(this.#g(o))o.__abortController.abort(Error("deleted"));else if(this.#E||this.#x){if(this.#E)this.#n?.(o,e,t);if(this.#x)this.#m?.push([o,e,t])}if(this.#u.delete(e),this.#i[r]=void 0,this.#c[r]=void 0,r===this.#f)this.#f=this.#h[r];else if(r===this.#d)this.#d=this.#p[r];else{let s=this.#h[r];this.#p[s]=this.#p[r];let i=this.#p[r];this.#h[i]=this.#h[r]}this.#s--,this.#_.push(r)}}if(this.#x&&this.#m?.length){let r=this.#m,o;while(o=r?.shift())this.#r?.(...o)}return n}clear(){return this.#j("delete")}#j(e){for(let t of this.#C({allowStale:!0})){let n=this.#c[t];if(this.#g(n))n.__abortController.abort(Error("deleted"));else{let r=this.#i[t];if(this.#E)this.#n?.(n,r,e);if(this.#x)this.#m?.push([n,r,e])}}if(this.#u.clear(),this.#c.fill(void 0),this.#i.fill(void 0),this.#y&&this.#S)this.#y.fill(0),this.#S.fill(0);if(this.#b)this.#b.fill(0);if(this.#d=0,this.#f=0,this.#_.length=0,this.#l=0,this.#s=0,this.#x&&this.#m){let t=this.#m,n;while(n=t?.shift())this.#r?.(...n)}}}function W6(e,t,n=100){let r=new Ey({max:n}),o=(...s)=>{let i=t(...s),a=r.get(i);if(a!==void 0)return a;let c=e(...s);return r.set(i,c),c};return o.cache={clear:()=>r.clear(),size:()=>r.size,delete:(s)=>r.delete(s),get:(s)=>r.peek(s),has:(s)=>r.has(s)},o}var O$e=8192;function Z6(e,t){try{return{ok:!0,value:JSON.parse(ml(e))}}catch(n){if(t)tg($L(n,`safeParseJSON: invalid JSON (${n instanceof Error?n.constructor.name:typeof n}, ${e.length} bytes)`));return{ok:!1}}}class Y6{cached=W6(Z6,(e)=>e,50);cache=this.cached.cache;parse(e,t){return this.cached(e,t)}}var V6=new Y6;var Wl=Object.assign(function(t,n=!0){if(!t)return null;let r=t.length>O$e?Z6(t,n):V6.parse(t,n);return r.ok?r.value:null},{cache:V6.cache});import{join as P$e}from"path";class J6{managedFilePath=void 0;dropInDir=void 0;getManagedFilePath(){return this.managedFilePath??=D$e(),this.managedFilePath}getDropInDir(){return this.dropInDir??=P$e(pa(),"managed-settings.d"),this.dropInDir}clearDropInDir(){this.dropInDir=void 0}reset(){this.managedFilePath=void 0,this.dropInDir=void 0}}var I$e=new J6;function pa(){return I$e.getManagedFilePath()}function D$e(){switch(Bo()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}var L$e=function(){try{var e=An(Object,"defineProperty");return e({},"",{}),e}catch(t){}}(),Vl=L$e;function M$e(e,t,n){if(t=="__proto__"&&Vl)Vl(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0});else e[t]=n}var Zl=M$e;function N$e(e,t,n){if(n!==void 0&&!co(e[t],n)||n===void 0&&!(t in e))Zl(e,t,n)}var Of=N$e;function U$e(e){return function(t,n,r){var o=-1,s=Object(t),i=r(t),a=i.length;while(a--){var c=i[e?a:++o];if(n(s[c],c,s)===!1)break}return t}}var X6=U$e;var z$e=X6(),Q6=z$e;var wy={};Ht(wy,{default:()=>uR});var r3=typeof wy=="object"&&wy&&!wy.nodeType&&wy,e3=r3&&typeof vy=="object"&&vy&&!vy.nodeType&&vy,F$e=e3&&e3.exports===r3,t3=F$e?Pt.Buffer:void 0,n3=t3?t3.allocUnsafe:void 0;function j$e(e,t){if(t)return e.slice();var n=e.length,r=n3?n3(n):new e.constructor(n);return e.copy(r),r}var uR=j$e;function $$e(e){var t=new e.constructor(e.byteLength);return new Oc(t).set(new Oc(e)),t}var o3=$$e;function B$e(e,t){var n=t?o3(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}var s3=B$e;function H$e(e,t){var n=-1,r=e.length;t||(t=Array(r));while(++n<r)t[n]=e[n];return t}var i3=H$e;var a3=Object.create,K$e=function(){function e(){}return function(t){if(!Nt(t))return{};if(a3)return a3(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}(),c3=K$e;var q$e=Bh(Object.getPrototypeOf,Object),Yl=q$e;function G$e(e){return typeof e.constructor=="function"&&!Lc(e)?c3(Yl(e)):{}}var l3=G$e;function W$e(e){return Sn(e)&&Os(e)}var u3=W$e;var V$e="[object Object]",Z$e=Function.prototype,Y$e=Object.prototype,d3=Z$e.toString,J$e=Y$e.hasOwnProperty,X$e=d3.call(Object);function Q$e(e){if(!Sn(e)||Yn(e)!=V$e)return!1;var t=Yl(e);if(t===null)return!0;var n=J$e.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&d3.call(n)==X$e}var p3=Q$e;function e1e(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var Pf=e1e;var t1e=Object.prototype,n1e=t1e.hasOwnProperty;function r1e(e,t,n){var r=e[t];if(!(n1e.call(e,t)&&co(r,n))||n===void 0&&!(t in e))Zl(e,t,n)}var Ty=r1e;function o1e(e,t,n,r){var o=!n;n||(n={});var s=-1,i=t.length;while(++s<i){var a=t[s],c=r?r(n[a],e[a],a,n,e):void 0;if(c===void 0)c=e[a];if(o)Zl(n,a,c);else Ty(n,a,c)}return n}var f3=o1e;function s1e(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var m3=s1e;var i1e=Object.prototype,a1e=i1e.hasOwnProperty;function c1e(e){if(!Nt(e))return m3(e);var t=Lc(e),n=[];for(var r in e)if(!(r=="constructor"&&(t||!a1e.call(e,r))))n.push(r);return n}var h3=c1e;function l1e(e){return Os(e)?$h(e,!0):h3(e)}var Jl=l1e;function u1e(e){return f3(e,Jl(e))}var g3=u1e;function d1e(e,t,n,r,o,s,i){var a=Pf(e,n),c=Pf(t,n),l=i.get(c);if(l){Of(e,n,l);return}var u=s?s(a,c,n+"",e,t,i):void 0,p=u===void 0;if(p){var f=Tt(c),m=!f&&Cs(c),h=!f&&!m&&Dc(c);if(u=c,f||m||h)if(Tt(a))u=a;else if(u3(a))u=i3(a);else if(m)p=!1,u=uR(c,!0);else if(h)p=!1,u=s3(c,!0);else u=[];else if(p3(c)||$o(c)){if(u=a,$o(a))u=g3(a);else if(!Nt(a)||Aa(a))u=l3(c)}else p=!1}if(p)i.set(c,u),o(u,c,r,s,i),i.delete(c);Of(e,n,u)}var _3=d1e;function y3(e,t,n,r,o){if(e===t)return;Q6(t,function(s,i){if(o||(o=new ks),Nt(s))_3(e,t,i,n,y3,r,o);else{var a=r?r(Pf(e,i),s,i+"",e,t,o):void 0;if(a===void 0)a=s;Of(e,i,a)}},Jl)}var b3=y3;function p1e(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 S3=p1e;var x3=Math.max;function f1e(e,t,n){return t=x3(t===void 0?e.length-1:t,0),function(){var r=arguments,o=-1,s=x3(r.length-t,0),i=Array(s);while(++o<s)i[o]=r[t+o];o=-1;var a=Array(t+1);while(++o<t)a[o]=r[o];return a[t]=n(i),S3(e,this,a)}}var Ay=f1e;function m1e(e){return function(){return e}}var E3=m1e;var h1e=!Vl?Fc:function(e,t){return Vl(e,"toString",{configurable:!0,enumerable:!1,value:E3(t),writable:!0})},v3=h1e;var g1e=800,_1e=16,y1e=Date.now;function b1e(e){var t=0,n=0;return function(){var r=y1e(),o=_1e-(r-n);if(n=r,o>0){if(++t>=g1e)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var w3=b1e;var S1e=w3(v3),ky=S1e;function x1e(e,t){return ky(Ay(e,t,Fc),e+"")}var T3=x1e;function E1e(e,t,n){if(!Nt(n))return!1;var r=typeof t;if(r=="number"?Os(n)&&Rs(t,n.length):r=="string"&&(t in n))return co(n[t],e);return!1}var A3=E1e;function v1e(e){return T3(function(t,n){var r=-1,o=n.length,s=o>1?n[o-1]:void 0,i=o>2?n[2]:void 0;if(s=e.length>3&&typeof s=="function"?(o--,s):void 0,i&&A3(n[0],n[1],i))s=o<3?void 0:s,o=1;t=Object(t);while(++r<o){var a=n[r];if(a)e(t,a,r,s)}return t})}var k3=v1e;var w1e=k3(function(e,t,n,r){b3(e,t,n,r)}),io=w1e;function T1e(e,t,n,r){if(!Nt(e))return e;t=Ps(t,e);var o=-1,s=t.length,i=s-1,a=e;while(a!=null&&++o<s){var c=xo(t[o]),l=n;if(c==="__proto__"||c==="constructor"||c==="prototype")return e;if(o!=i){var u=a[c];if(l=r?r(u,c,a):void 0,l===void 0)l=Nt(u)?u:Rs(t[o+1])?[]:{}}Ty(a,c,l),a=a[c]}return e}var C3=T1e;function A1e(e,t,n){var r=-1,o=t.length,s={};while(++r<o){var i=t[r],a=zc(e,i);if(n(a,i))C3(s,Ps(i,e),a)}return s}var Cy=A1e;function k1e(e,t){return Cy(e,t,function(n,r){return Xh(e,r)})}var R3=k1e;var O3=gn?gn.isConcatSpreadable:void 0;function C1e(e){return Tt(e)||$o(e)||!!(O3&&e&&e[O3])}var P3=C1e;function I3(e,t,n,r,o){var s=-1,i=e.length;n||(n=P3),o||(o=[]);while(++s<i){var a=e[s];if(t>0&&n(a))if(t>1)I3(a,t-1,n,r,o);else Pc(o,a);else if(!r)o[o.length]=a}return o}var D3=I3;function R1e(e){var t=e==null?0:e.length;return t?D3(e,1):[]}var L3=R1e;function O1e(e){return ky(Ay(e,void 0,L3),e+"")}var M3=O1e;var P1e=M3(function(e,t){return e==null?{}:R3(e,t)}),Ry=P1e;import{homedir as jHe}from"os";import{dirname as $He,join as ao,resolve as Or}from"path";var I1e="Expected a function";function D1e(e){if(typeof e!="function")throw TypeError(I1e);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}var N3=D1e;var L1e=Object.getOwnPropertySymbols,M1e=!L1e?Lh:function(e){var t=[];while(e)Pc(t,Mh(e)),e=Yl(e);return t},U3=M1e;function N1e(e){return Dh(e,Jl,U3)}var z3=N1e;function U1e(e,t){if(e==null)return{};var n=Jh(z3(e),function(r){return[r]});return t=jc(t),Cy(e,n,function(r,o){return t(r,o[0])})}var F3=U1e;function z1e(e,t){return F3(e,N3(jc(t)))}var j3=z1e;import{join as H1e}from"path";var dR=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","ANTHROPIC_GOOGLE_CLOUD_PROJECT","ANTHROPIC_GOOGLE_CLOUD_LOCATION","ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID","CLOUD_ML_REGION"],$3=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE"];var B3="OTEL_EXPORTER_OTLP_",H3=["OTEL_LOG_RAW_API_BODIES","OTEL_LOG_USER_PROMPTS","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_TOOL_DETAILS","OTEL_LOGS_EXPORTER","ENABLE_BETA_TRACING_DETAILED","BETA_TRACING_ENDPOINT","ANT_OTEL_LOGS_EXPORTER"],K3=[B3,`ANT_${B3}`],q3={apiKeyHelper:["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],awsAuthRefresh:[...$3,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],awsCredentialExport:[...$3,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],gcpAuthRefresh:["CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL"]},F1e=["CLAUDE_CODE_MEMORY_API_BASE_URL","CLAUDE_CODE_MEMORY_API_TOKEN"];var pR=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_TOKEN","CLAUDE_CODE_ARTIFACT_ASSET_BASE_URL","CLAUDE_CODE_ARTIFACT_LIVE_BASE_URL","CLAUDE_CODE_ARTIFACT_VIEWER_BASE_URL",...F1e];var fR=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_AWS_API_KEY"],j1e=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],mR=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_3P_PROBE_WROTE_SONNET_DEFAULT","CLAUDE_CODE_3P_PROBE_WROTE_OPUS_DEFAULT"],hR=["ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES"],$1e=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],B1e=[...$1e,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var CTt=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...dR,...pR,...fR,...j1e,"CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH","CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS","CLAUDE_CODE_HOST_CREDS_FILE",...B1e,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT","GCE_METADATA_HOST","GCE_METADATA_IP","METADATA_SERVER_DETECTION","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","AWS_EC2_METADATA_SERVICE_ENDPOINT","AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE","AWS_REGION","AWS_DEFAULT_REGION",...mR,"ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_BEDROCK_REGION_PREFIX","CLAUDE_CODE_CERT_STORE","DISABLE_GROWTHBOOK","CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL",...hR]);var K1e="remote-settings.json";class G3{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;policySettingsNotified=!1;verifiedPayload=null;consentedPayload=null;resetEpoch=0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified)this.verifiedPayload=e}seedFromDisk(e){this.sessionCache=e,this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}markPolicySettingsNotified(){this.policySettingsNotified=!0}recordEligibility(e,t){if(this.eligible=e,t.memoize)this.eligibilityMemo=e}reset(){this.sessionCache=null,this.eligible=void 0,this.eligibilityMemo=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,this.consentedPayload=null,this.resetEpoch++}}var If=new G3;function gR(){return}function q1e(){return gR()??H1e(qt(),K1e)}function G1e(){try{let e=Kl(q1e()),t=pt(ml(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return t}catch{return null}}var W1e=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",...dR,...pR,"CLAUDE_CODE_CUSTOM_OAUTH_URL",...fR,"CLAUDE_CODE_API_BASE_URL","CLAUDE_CODE_OAUTH_REFRESH_TOKEN","CLAUDE_CODE_OAUTH_SCOPES","CLAUDE_CODE_OAUTH_CLIENT_ID","CLAUDE_CODE_SESSION_ACCESS_TOKEN","CLAUDE_SESSION_INGRESS_TOKEN_FILE","CLAUDE_CODE_ENVIRONMENT_KIND","CLAUDE_CODE_REMOTE_SESSION_ID","ANTHROPIC_FEDERATION_RULE_ID","ANTHROPIC_ORGANIZATION_ID","ANTHROPIC_WORKSPACE_ID","ANTHROPIC_SERVICE_ACCOUNT_ID","ANTHROPIC_IDENTITY_TOKEN","ANTHROPIC_IDENTITY_TOKEN_FILE","ANTHROPIC_SCOPE","ANTHROPIC_PROFILE","ANTHROPIC_CONFIG_DIR","HOME","XDG_CONFIG_HOME","APPDATA","USERPROFILE","ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MANAGED_SETTINGS_PATH","CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE","CLAUDE_LOCAL_OAUTH_APPS_BASE","CLAUDE_LOCAL_OAUTH_CONSOLE_BASE","CLAUDE_BRIDGE_BASE_URL","CLAUDE_BRIDGE_OAUTH_TOKEN","CLAUDE_BRIDGE_SESSION_INGRESS_URL","CLAUDE_REMOTE_TOOLS_BRIDGE_URL"].map((e)=>e.toUpperCase()));function V1e(e){if(!e?.env)return e;let t=j3(e.env,(n,r)=>W1e.has(r.toUpperCase()));return{...e,env:t}}function Z1e(){if(!gR()&&If.eligible!==!0)return null;if(If.sessionCache)return If.sessionCache;let e=G1e();if(e)return If.seedFromDisk(e),Xv(),e;return null}function W3(){let e=Z1e();if(e===If.verifiedPayload||gR())return e;return V1e(e)}import{isAbsolute as V3}from"path";var Y1e=L(()=>w({allowedDomains:I(_()).optional(),deniedDomains:I(_()).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."),strictAllowlist:C().optional().describe("When true, the sandbox runtime deterministically denies hosts not in allowedDomains instead of prompting. "+"Enforced for sandboxed commands only — in-process tools such as WebFetch are not gated by this setting. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored."),allowManagedDomainsOnly:C().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:I(_()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:C().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:C().optional(),allowMachLookup:I(_().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:j().optional(),socksProxyPort:j().optional(),tlsTerminate:w({caCertPath:_().min(1).optional(),caKeyPath:_().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. On native Windows an ephemeral CA cannot pass the sandbox trust check, so omitting the paths uses a persistent CA managed by the sandbox runtime (set up and trusted via /sandbox install); configured paths are passed to the sandbox runtime verbatim, which rejects a bad or incomplete pair at sandbox initialization. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — project settings "+"(.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),J1e=L(()=>w({allowWrite:I(_()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:I(_()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:I(_()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:I(_()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:C().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used."),disabled:C().optional().describe("macOS and Linux/WSL only: skip filesystem isolation entirely while keeping network and seccomp isolation. Ignored on native Windows, where the sandboxed process runs as a separate user with no inherent rights, so skipping the filesystem rules would "+"withhold every access grant rather than loosen them — filesystem isolation stays on there. "+"Sandboxed commands get unrestricted read/write access to the host filesystem; network egress is still confined to network.allowedDomains. Intended for deployments whose goal is egress control rather than filesystem containment. Does not change Bash prompting: sandbox.autoAllowBashIfSandboxed is independent and still defaults to true, so set it to false to keep prompting for sandboxed commands. Drops the read protection from filesystem.denyRead and credentials.files deny entries for sandboxed commands, since both are enforced by the filesystem layer this turns off; credentials.files mask entries (sentinel binds) and credentials.envVars deny/mask are unaffected. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. If managed settings configure sandbox.filesystem at all, or list any sandbox.credentials.files deny entry, only managed settings can set this: an admin who deployed filesystem restrictions must not have them switched off by a user-writable file. (sandbox.credentials.envVars and credentials.files mask entries "+"do not pin it — env scrubbing and sentinel binds are independent of the filesystem "+"layer and survive this setting.) When unset, filesystem isolation stays on.")}).optional());function Z3(e,t,n){if(e.length===0||e.some((r)=>r.length===0))n.addIssue({code:hr.custom,path:["maskClaims"],message:"maskClaims must name at least one non-empty claim — omit maskClaims for whole-token masking."});if(t===void 0)n.addIssue({code:hr.custom,path:["maskClaims"],message:"maskClaims requires decode — without a decode format there is no token to read claims from. Set decode, or omit maskClaims."})}function Y3(e,t){let n;try{n=new RegExp(e)}catch(o){t.addIssue({code:hr.custom,path:["extract"],message:`extract is not a valid regular expression: ${Uo(o)}`});return}if(new RegExp(n.source+"|").exec("").length-1<1)t.addIssue({code:hr.custom,path:["extract"],message:"extract must contain at least one capturing group — "+'group 1 is the credential value to mask (e.g. "token:\\s*(\\S+)").'})}function J3(e){if(typeof e!=="object"||e===null)return e;let t=e;if(t.mode!=="deny")return e;let n={...t};if("extract"in n&&typeof n.extract!=="string")delete n.extract;if("onExtractNoMatch"in n&&n.onExtractNoMatch!=="warn"&&n.onExtractNoMatch!=="deny"&&n.onExtractNoMatch!=="error")delete n.onExtractNoMatch;if("decode"in n&&n.decode!=="jwt")delete n.decode;if("maskClaims"in n&&!(Array.isArray(n.maskClaims)&&n.maskClaims.every((r)=>typeof r==="string")))delete n.maskClaims;if("maskDuplicates"in n&&typeof n.maskDuplicates!=="boolean")delete n.maskDuplicates;if("injectHosts"in n&&!(Array.isArray(n.injectHosts)&&n.injectHosts.every((r)=>typeof r==="string")))delete n.injectHosts;return n}var Oy=L(()=>xt(J3,w({path:_().min(1).describe("Path to a credential file or directory. Same resolution as sandbox.filesystem.* paths: absolute, ~ expanded, or relative to the settings file root (project root for project settings, ~/.claude for user settings)."),mode:G(["deny","mask"]).describe("Access mode for this path. `deny` blocks reads inside the sandbox; `mask` shows sandboxed commands a sentinel-substituted copy (whole-file, or only the spans captured by `extract`) and the "+"host proxy swaps sentinel→real on egress to `injectHosts`. "+"On macOS and Windows `mask` currently degrades to `deny`."),extract:_().optional().describe("Optional regex for structured masking when mode is `mask`. Applied globally to the file; capture group 1 of each match is a credential value, and only those captured spans are replaced "+"with sentinels — the rest of the file is preserved so a tool "+"that parses it (.netrc, JSON, YAML) still succeeds. Without `extract`, the entire file content is replaced with one sentinel (whole-file masking, suited to single-secret files). If the regex matches nothing, behavior is governed by `onExtractNoMatch` (default `warn`). Accepted but ignored for `deny`."),onExtractNoMatch:G(["warn","deny","error"]).optional().describe("What to do when `extract` matches nothing in the file — or, "+"with `decode`, when no candidate survives verification. `warn` (default) emits a stderr warning and leaves the file readable as-is inside the sandbox (fail-open, for credentials that may be legitimately absent); `deny` degrades the entry to "+"mode `deny` so the file is unreadable (fail-closed) — under "+"`sandbox.filesystem.disabled` it is treated as `error`, since read-denies are dropped in that mode; `error` aborts at sandbox setup so nothing runs until the config is fixed. Only meaningful when mode is `mask` and `extract` or `decode` is set; accepted but ignored otherwise."),decode:G(["jwt"]).optional().describe("Optional encoded-credential format for `mask` mode. `jwt`: candidates are located with a built-in JWT regex (or the explicit `extract` pattern, if set), verified to actually be JWTs before masking, and replaced with a structurally valid fake JWT so client-side token parsing inside the sandbox keeps working. If no candidate verifies, behavior is governed by `onExtractNoMatch` (default `warn`). Accepted but ignored for `deny`."),maskClaims:I(_()).optional().describe("Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel and the token is rebuilt around the modified payload; all other claims are preserved so a tool that decodes the token and reads a non-secret claim keeps working. Requires `decode`. If no named claim matches in any verified token, behavior is governed by `onExtractNoMatch` (default `warn`). Only meaningful when mode is `mask`; accepted but ignored for `deny`."),maskDuplicates:C().optional().describe("If true, verbatim occurrences of each captured credential value outside the regex-matched spans are also replaced with the "+"corresponding sentinel — for a secret repeated where the regex "+"does not reach (e.g. pasted into a comment). Matches raw substrings, so short or common values may corrupt unrelated content; intended for long, high-entropy secrets. Defaults to false. Only meaningful when mode is `mask` and `extract` or `decode` is set; accepted but ignored otherwise."),injectHosts:I(_()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")}).superRefine((e,t)=>{if(e.mode==="mask"&&e.path.endsWith("/"))t.addIssue({code:hr.custom,path:["path"],message:'Credential mode "mask" applies to a single file, not a directory. List the specific credential file(s), or use "deny" for the directory.'});if(e.mode==="mask"&&e.extract!==void 0)Y3(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)Z3(e.maskClaims,e.decode,t)}))),Xl=()=>_().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores"),Py=L(()=>xt(J3,w({name:Xl().describe("Environment variable name."),mode:G(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the "+"host proxy swaps sentinel→real on egress to `injectHosts`."),extract:_().optional().describe("Optional regex for structured masking when mode is `mask`. Applied globally to the value; capture group 1 of each match is a credential value, and only those captured spans are "+"replaced with sentinels — the rest of the value is preserved "+"so a tool that parses it (a `DATABASE_URL` connection string, a composite `KEY:SECRET` pair) still succeeds inside the sandbox. Without `extract`, the entire value is replaced with one sentinel (whole-value masking, suited to bare tokens). If the regex matches nothing, behavior is governed by `onExtractNoMatch` (default `warn`). Cannot be combined with `decode` (the decode path never consults it). Accepted but ignored for `deny`."),onExtractNoMatch:G(["warn","deny","error"]).optional().describe("What to do when `extract` matches nothing in the value. `warn` (default) emits a stderr warning and lets the variable pass through unmasked (fail-open, for credentials that may be legitimately absent); `deny` unsets the variable inside the sandbox (fail-closed); `error` aborts at sandbox setup so nothing runs until the config is fixed. Only meaningful when mode is `mask` and `extract` is set without `decode`. On a mask entry with `decode`, the runtime takes the decode path and never consults this field, so a fail-closed setting "+"cannot be honored — `deny` and `error` are rejected there; "+"only `warn` is accepted. In all other shapes the field is accepted but ignored."),decode:G(["jwt"]).optional().describe("Optional encoded-credential format for `mask` mode. `jwt`: the variable's whole value is verified to actually be a JWT and replaced with a structurally valid fake JWT so client-side token parsing inside the sandbox keeps working; the proxy swaps the whole fake token on egress. If the value does not verify, the variable is left unmasked with a stderr warning "+"(fail-open). Cannot be combined with `extract` — the decode "+"path never consults it. Accepted but ignored for `deny`."),maskClaims:I(_()).optional().describe("Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel and the token is rebuilt around the modified payload; all other claims are preserved so claim-reading clients keep working. Requires `decode`. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is `mask`; accepted but ignored for `deny`."),injectHosts:I(_()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")}).superRefine((e,t)=>{if(e.mode==="mask"&&e.extract!==void 0)Y3(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)Z3(e.maskClaims,e.decode,t);if(e.mode==="mask"&&e.decode!==void 0&&e.extract!==void 0)t.addIssue({code:hr.custom,path:["extract"],message:"extract cannot be combined with decode on an env entry — the runtime takes the decode path (whole-value JWT verification) and never consults extract, silently disabling the structured masking. Remove one of the two."});if(e.mode==="mask"&&e.decode!==void 0&&(e.onExtractNoMatch==="deny"||e.onExtractNoMatch==="error"))t.addIssue({code:hr.custom,path:["onExtractNoMatch"],message:"onExtractNoMatch cannot be honored on an env entry with decode — the runtime takes the decode path (which is unconditionally fail-open on verify failure) and never consults extract or onExtractNoMatch. Remove onExtractNoMatch, or drop decode to use extract-based masking (whose no-match handling does honor it)."})}))),Ql=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"];var _R="_INVALID_PAIR_",X3="_PARENT_PAIR_SUPPRESSOR_";var Iy=L(()=>w({accessKeyIdVar:Xl().describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:Xl().describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:Xl().optional().describe("Optional name of the masked env var holding the AWS session token (temporary credentials). When set, the proxy sends the real token as x-amz-security-token on re-signed requests and adds it to the signed header set if the client did not.")}).superRefine((e,t)=>{let n=new Map;for(let[r,o]of[["accessKeyIdVar",e.accessKeyIdVar],["secretAccessKeyVar",e.secretAccessKeyVar],["sessionTokenVar",e.sessionTokenVar]]){if(o===void 0)continue;let s=n.get(o);if(s!==void 0)t.addIssue({code:hr.custom,path:[r],message:`${r} names the same env var ('${o}') as ${s} — each pair member must be a distinct variable.`});else n.set(o,r)}})),X1e=L(()=>{let e=G(["deny","passthrough"]);return w({streaming:e.optional().describe("Policy for aws-chunked streaming uploads (x-amz-content-sha256: STREAMING-*): per-chunk signatures chain off the seed signature, so re-signing would require rewriting the body. `deny` (default) fails closed with a 403; `passthrough` forwards the request unre-signed (the upstream will reject its signature)."),presigned:e.optional().describe("Policy for presigned URLs (X-Amz-Algorithm/X-Amz-Signature in the query, no Authorization header): the signature lives in the URL itself. `deny` (default) or `passthrough`."),sigv4a:e.optional().describe("Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. `deny` (default) or `passthrough`.")})}),Q1e=L(()=>w({files:I(Oy()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox; `mask` substitutes a sentinel inside the sandbox (whole-file, or per-`extract` capture) and injects the real value at the proxy. On macOS and Windows `mask` degrades to `deny`."),envVars:I(Py()).optional().describe("Environment variables to protect. `deny` unsets the variable for sandboxed commands; `mask` substitutes a sentinel inside the sandbox and injects the real value at the proxy."),allowPlaintextInject:C().optional().describe("Allow sentinel→real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored."),awsPairs:I(Iy()).optional().describe("Explicit groupings of masked env vars into AWS credential pairs for SigV4 re-signing, for non-standard variable names. The conventional AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN trio is paired automatically when masked. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored. A member is only usable when its env var is forwarded as a whole-value `mask` entry (an entry carrying `extract` or `decode` does not "+"qualify — re-signing needs the whole real value). A pair "+"whose key id or secret member is unusable never re-signs: it is dropped, unless it names a conventional AWS variable, in which case it is forwarded as an inert suppressor so implicit auto-pairing stays overridden. A pair whose ONLY unusable member is the session token still re-signs, without an x-amz-security-token (temporary-credential requests fail upstream until the entry is fixed)."),sigv4:X1e().optional().describe("Policies for AWS SigV4 request shapes the proxy cannot re-sign (streaming, presigned, sigv4a) when they reference a masked credential pair: `deny` (default) or `passthrough`. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored.")}).superRefine((e,t)=>{let n=new Set;for(let[r,o]of(e?.awsPairs??[]).entries()){let s=[["accessKeyIdVar",o.accessKeyIdVar],["secretAccessKeyVar",o.secretAccessKeyVar],["sessionTokenVar",o.sessionTokenVar]],i=new Set;for(let[a,c]of s){if(c===void 0)continue;if(n.has(c))t.addIssue({code:hr.custom,path:["awsPairs",r,a],message:`"${c}" appears in more than one awsPairs slot (within or across pairs) — each variable can fill exactly one slot.`});i.add(c)}for(let a of i)n.add(a)}}).optional()),yR=L(()=>w({enabled:C().optional(),failIfUnavailable:C().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:C().optional(),allowUnsandboxedCommands:C().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:Y1e(),filesystem:J1e(),credentials:Q1e(),ignoreViolations:q(_(),I(_())).optional(),enableWeakerNestedSandbox:C().optional(),enableWeakerNetworkIsolation:C().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** — opens a potential data exfiltration vector through the trustd service. Default: false"),allowAppleEvents:C().optional().describe("macOS only: Allow sandboxed commands to send Apple Events (and look up the appleeventsd Mach service). Needed for `open`, `osascript`, and browser-based auth flows that open URLs. "+"**Removes code-execution isolation** — sandboxed commands can launch other applications "+"unsandboxed with no user prompt, and can script running apps (e.g. Terminal) subject to the user's per-app TCC automation consent. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. Default: false"),excludedCommands:I(_()).optional(),ripgrep:w({command:_(),args:I(_()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:xt((e)=>typeof e==="string"&&V3(e)?e:void 0,_()).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:xt((e)=>typeof e==="string"&&V3(e)?e:void 0,_()).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());function fa(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Q3=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];function eBe(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function e9(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&eBe(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{userInfo as tBe}from"os";var t9="com.anthropic.claudecode",Df="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Lf="HKCU\\SOFTWARE\\Policies\\ClaudeCode",ni="Settings",n9="/usr/bin/plutil",r9=["-convert","json","-o","-","--"],o9=5000,bR="/mnt/c/Windows/System32/reg.exe",eu="/mnt/c/Program Files/ClaudeCode";function Dy(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Pe("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function s9(){let e="";try{e=tBe().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${t9}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${t9}.plist`,label:"device-level managed preferences"}),t}var Mf=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],i9=[...Mf],a9=i9;function Nf(e){return e==="manual"?"default":e}var sAt=`Cannot set permission mode: must be one of ${i9.join(", ")}`;var c9=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"],l9=["normal","vim"],u9=["auto","tmux","iterm2","in-process"],nBe=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],d9=["auto",...nBe],p9=["auto","alwaysAsk","disabled"];var lAt=Bo()==="macos"?"⏺":"●";var gAt=L(()=>xt(Nf,G(a9))),_At=L(()=>xt(Nf,G(Mf)));import{posix as hBe,win32 as gBe}from"path";import{isIPv4 as _Be,isIPv6 as yBe}from"net";var f9=["bash","powershell"];var Uf=L(()=>_().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 rBe(){let e=w({type:N("command").describe("Shell command hook type"),command:_().describe("Shell command to execute"),args:I(_()).optional().describe("Argument list for exec form. When present, `command` is resolved as "+"an executable and spawned directly with these arguments — 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:Uf(),shell:G(f9).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:j().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution"),async:C().optional().describe("If true, hook runs in background without blocking"),asyncRewake:C().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:_().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:_().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=w({type:N("prompt").describe("LLM prompt hook type"),prompt:_().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:_().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:C().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:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")}),n=w({type:N("mcp_tool").describe("MCP tool hook type"),server:_().describe("Name of an already-configured MCP server to invoke"),tool:_().describe("Name of the tool on that server to call"),input:q(_(),Se()).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:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")}),r=w({type:N("http").describe("HTTP hook type"),url:_().url().describe("URL to POST the hook input JSON to"),if:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for this specific request"),headers:q(_(),_()).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:I(_()).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:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")}),o=w({type:N("agent").describe("Agentic verifier hook type"),prompt:_().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:Uf(),timeout:j().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:_().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:C().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:r,AgentHookSchema:o,McpToolHookSchema:n}}var m9=L(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:r,McpToolHookSchema:o}=rBe();return pi("type",[e,t,n,r,o])}),h9=L(()=>w({matcher:_().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:I(m9()).describe("List of hooks to execute when the matcher matches")})),ma=L(()=>ZI(G(wa),I(h9())));var TAt=L(()=>G(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),AAt=L(()=>G(["stdio","sse","sse-ide","http","ws","sdk"])),tu=L(()=>N("comms").optional().catch(void 0)),ri=L(()=>j().int().positive()),oBe=300000,g9=L(()=>j().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function _9({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,oBe)}}}var sBe=L(()=>w({type:N("stdio").optional(),command:_().min(1,"Command cannot be empty"),args:I(_()).default([]),env:q(_(),_()).optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),iBe=L(()=>C()),y9=L(()=>w({clientId:_().optional(),callbackPort:j().int().positive().optional(),authServerMetadataUrl:_().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:_().min(1).optional(),xaa:iBe().optional()})),b9=L(()=>w({name:_(),permission_policy:G(["always_allow","always_ask","always_deny"]).optional()})),aBe=L(()=>w({type:N("sse"),url:_(),headers:q(_(),_()).optional(),headersHelper:_().optional(),oauth:y9().optional(),timeout:ri().optional(),request_timeout_ms:g9(),tools:I(b9()).optional(),alwaysLoad:C().optional(),discoveryCache:C().optional(),role:tu(),toolPermissions:q(_(),SR()).optional()}).transform(_9)),cBe=L(()=>w({type:N("sse-ide"),url:_(),ideName:_(),ideRunningInWindows:C().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),lBe=L(()=>w({type:N("ws-ide"),url:_(),ideName:_(),authToken:_().optional(),ideRunningInWindows:C().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),uBe=L(()=>w({type:G(["http","streamable-http"]).transform(()=>"http"),url:_(),headers:q(_(),_()).optional(),headersHelper:_().optional(),oauth:y9().optional(),timeout:ri().optional(),request_timeout_ms:g9(),tools:I(b9()).optional(),alwaysLoad:C().optional(),discoveryCache:C().optional(),role:tu(),toolPermissions:q(_(),SR()).optional()}).transform(_9)),dBe=L(()=>w({type:N("ws"),url:_(),headers:q(_(),_()).optional(),headersHelper:_().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),role:tu()})),pBe=L(()=>w({type:N("sdk"),name:_(),timeout:ri().optional(),alwaysLoad:C().optional()})),SR=L(()=>G(["allow","ask","blocked"])),fBe=L(()=>w({type:N("claudeai-proxy"),url:_(),id:_(),displayName:_().optional(),iconUrl:_().optional(),timeout:ri().optional(),alwaysLoad:C().optional(),toolPermissions:q(_(),SR()).optional(),stateless:C().optional(),cachedInitResponse:q(_(),Se()).nullish(),discoverSupport:G(["supported","legacy","unknown"]).optional().catch(void 0),cachedDiscoverResponse:q(_(),Se()).nullish(),eligible:C().nullish(),ineligibleReason:_().nullish()})),Ly=L(()=>oe([sBe(),aBe(),cBe(),lBe(),uBe(),dBe(),pBe(),fBe()]));var kAt=L(()=>w({mcpServers:q(_(),Ly())}));function mBe(e){return r2(e).replace(/ {2,}/g," ").trim()}function S9(e,t=160){let n=mBe(e);return n.length>t?`${Zf(n,t)}…`:n}var A9=500,bBe=32;function k9(){return{sourceCommand:_().max(A9+20).optional().catch(void 0).describe("The `command`-source command the user accepted at explicit install/update. The once-per-session background re-resolve only runs while the marketplace entry still declares this exact command; a changed command (or an entry that became command-sourced later) is skipped with a warning until the user runs an explicit update."),sourceProducerPath:_().max(4096).refine(x9,{message:"must be an absolute path"}).optional().catch(void 0).describe("The directory a `command`-source plugin was last resolved to (what its command printed). Served in place in link mode and re-copied every session in copy mode, so the sandbox write-denies it; refreshed on every install/update, including no-op updates that resolve to a new location."),previousProducerPaths:I(Se()).transform((e)=>e.filter((t)=>typeof t==="string"&&t.length<=4096&&x9(t)).slice(-bBe)).optional().catch(void 0).describe("Producer directories this installation was resolved to before the current one (most recent last, bounded). A concurrent older session may still serve one of them, so the sandbox keeps write-denying them too.")}}function x9(e){return hBe.isAbsolute(e)||gBe.isAbsolute(e)}var SBe=/[^\x20-\x7E]| {4,}/,xBe=new Set(["claude-community","claude-plugins-community","healthcare"]),EBe=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","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins"]),C9=new Set([...EBe,...xBe]);var vBe=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,wBe=/[^\u0020-\u007E]/;function TBe(e){if(C9.has(e.toLowerCase()))return!1;if(wBe.test(e))return!0;return vBe.test(e)}var Ao=L(()=>_().startsWith("./")),ha=L(()=>Ao().endsWith(".json")),E9=L(()=>oe([N("."),Ao()])),v9=L(()=>oe([Ao().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"),_().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),ER=L(()=>Ao().endsWith(".md")),vR=L(()=>oe([ER(),Ao()])),R9=L(()=>_().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)=>!TBe(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/'})),TR=L(()=>w({name:_().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:_().optional().describe("Contact email for support or feedback"),url:_().optional().describe("Website, GitHub profile, or organization URL")})),ABe=L(()=>w({$schema:_().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:_().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)"),displayName:_().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version:_().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:_().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:TR().optional().describe("Information about the plugin creator or maintainer"),homepage:_().url().optional().describe("Plugin homepage or documentation URL"),repository:_().optional().describe("Source code repository URL"),license:_().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:I(_()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:C().optional().describe("Whether the plugin starts enabled when the user has no explicit enabled/disabled setting for it (default: true). Explicit enabledPlugins values always win, and a plugin required by an enabled dependent is enabled regardless of this value."),dependencies:I(hHe()).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.`),metadata:xt((e)=>fa(e)?e:void 0,q(_(),Se()).optional()).describe("Free-form metadata for the plugin author's own use (e.g. entitlement or catalog fields). Preserved on the parsed manifest but not read by Claude Code.")})),qAt=L(()=>w({description:_().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:bm(()=>ma()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),kBe=L(()=>w({hooks:oe([ha().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),bm(()=>ma()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),I(oe([ha().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),bm(()=>ma()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),CBe=L(()=>w({source:vR().optional().describe("Path to command markdown file, relative to plugin root"),content:_().optional().describe("Inline markdown content for the command"),description:_().optional().describe("Command description override"),argumentHint:_().optional().describe('Hint for command arguments (e.g., "[file]")'),model:_().optional().describe("Default model for this command"),allowedTools:I(_()).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'})),RBe=L(()=>w({commands:oe([vR().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both."),I(vR().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — 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."),q(_(),CBe()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),OBe=L(()=>w({agents:oe([ER().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both."),I(ER().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both.")).describe("List of agent file paths. When set, the agents/ directory is not auto-loaded.")])})),PBe=L(()=>w({skills:oe([E9().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself). Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan).'),I(E9().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself).')).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),O9=L(()=>w({outputStyles:oe([Ao().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — list its files here if you want both."),I(Ao().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — 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.")])})),IBe=L(()=>_().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),DBe=16,LBe=L(()=>w({id:IBe(),remote:_().max(256).regex(/^(npm:[@a-z0-9/._-]+(@[a-z0-9._+-]+)?|github:[\w.-]+\/[\w.-]+@[\w./-]+#.+\.js)$/,"must be npm:<pkg>[@ver] or github:<owner>/<repo>@<ref>#<path>.js").optional(),integrity:_().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),MBe=L(()=>w({syntaxHighlighting:w({hljsLanguages:I(LBe()).max(DBe)}).strict()})),P9=L(()=>w({themes:oe([Ao().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — list its files here if you want both."),I(Ao().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — 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.")])})),NBe=L(()=>w({})),w9=L(()=>_().min(1)),UBe=L(()=>_().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),zBe=L(()=>w({mcpServers:oe([ha().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),v9().describe("Path or URL to MCPB file containing MCP server configuration"),q(_(),Ly()).describe("MCP server configurations keyed by server name"),I(oe([ha().describe("Path to MCP servers configuration file"),v9().describe("Path or URL to MCPB file"),q(_(),Ly()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),I9=L(()=>w({type:G(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:_().describe("Human-readable label shown in the config dialog"),description:_().describe("Help text shown beneath the field in the config dialog"),required:C().optional().describe("If true, validation fails when this field is empty"),default:oe([_(),j(),C(),I(_())]).optional().describe("Default value used when the user provides nothing"),multiple:C().optional().describe("For string type: allow an array of strings"),sensitive:C().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:j().optional().describe("Minimum value (number type only)"),max:j().optional().describe("Maximum value (number type only)")}).strict()),FBe=L(()=>w({userConfig:q(_().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) — they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),I9()).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.")})),jBe=L(()=>w({channels:I(w({server:_().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:_().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:q(_(),I9()).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.")})),T9=L(()=>Sx({command:_().min(1).refine((e)=>{if(e.includes(" ")&&!e.startsWith("/"))return!1;return!0},{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:I(w9()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:q(UBe(),w9()).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:G(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:q(_(),_()).optional().describe("Environment variables to set when starting the server"),initializationOptions:Se().optional().describe("Initialization options passed to the server during initialization"),settings:Se().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:_().optional().describe("Workspace folder path to use for the server"),startupTimeout:j().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:j().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:C().optional().describe("Whether to restart the server if it crashes"),maxRestarts:j().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:C().optional().describe("Whether to push publishDiagnostics into the agent context after edits. Set to false to keep LSP navigation (goToDefinition, hover, etc.) but suppress automatic diagnostic injection. Defaults to true.")})),$Be=L(()=>Sx({name:_().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:_().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 — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:_().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:oe([N("always"),_().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).')})),BBe=L(()=>I($Be()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),D9=L(()=>w({monitors:oe([ha().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),BBe()]).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.")})),HBe=L(()=>w({lspServers:oe([ha().describe("Path to .lsp.json configuration file relative to plugin root"),q(_(),T9()).describe("LSP server configurations keyed by server name"),I(oe([ha().describe("Path to LSP configuration file"),q(_(),T9()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),L9=L(()=>_().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")),KBe=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,qBe=/^[0-9a-f]{64}$/;var GBe=64;var WBe=L(()=>w({sha256:_().regex(qBe)}));function VBe(e){let t=q(_(),Se()).safeParse(e);if(!t.success)return;let n=Object.create(null),r=0;for(let[o,s]of Object.entries(t.data)){if(r>=GBe)break;let i=WBe().safeParse(s);if(KBe.test(o)&&i.success)n[o]=i.data,r++}return r>0?n:void 0}var ZBe=L(()=>w({binaries:Se().transform(VBe).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),YBe=L(()=>w({settings:q(_(),Se()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),JBe=L(()=>w({experimental:xt((e)=>fa(e)?e:void 0,w({...P9().partial().shape,...MBe().partial().shape,...D9().partial().shape,...O9().partial().shape,evals:oe([_(),I(_())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))}));var XBe=L(()=>w({...ABe().shape,...kBe().partial().shape,...RBe().partial().shape,...OBe().partial().shape,...PBe().partial().shape,...O9().partial().shape,...P9().partial().shape,...NBe().shape,...jBe().partial().shape,...zBe().partial().shape,...HBe().partial().shape,...D9().partial().shape,...YBe().partial().shape,...FBe().partial().shape,...ZBe().partial().shape,...JBe().partial().shape})),M9=new Set(["url","github","git","npm","file","directory","skills-dir","hostPattern","pathPattern","settings"]),zf=L(()=>pi("source",[w({source:N("url"),url:_().url().describe("Direct URL to marketplace.json file"),headers:q(_(),_()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),w({source:N("github"),repo:_().describe('GitHub repository in owner/repo format. ONLY in the managed-settings policy lists (strictKnownMarketplaces / blockedMarketplaces) the owner-wildcard form "owner/*" matches every repository under exactly that owner. Everywhere else (marketplace add, extraKnownMarketplaces, known_marketplaces.json) the value '+"must name a single repository — a wildcard is taken literally and fails to clone."),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:_().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:I(_()).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.'),skipLfs:C().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),w({source:N("git"),url:_().describe("Full git repository URL"),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:_().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:I(_()).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.'),skipLfs:C().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),w({source:N("npm"),package:L9().describe("NPM package containing marketplace.json")}),w({source:N("file"),path:_().describe("Local file path to marketplace.json")}),w({source:N("directory"),path:_().describe("Local directory containing .claude-plugin/marketplace.json")}),w({source:N("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),w({source:N("hostPattern"),hostPattern:_().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$").')}),w({source:N("pathPattern"),pathPattern:_().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.')}),w({source:N("settings"),name:R9().refine((e)=>!C9.has(e.toLowerCase()),{message:"Reserved 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 — "+"validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:I(rHe()).describe("Plugin entries declared inline in settings.json"),owner:TR().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).")])),xR=L(()=>_().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),QBe=L(()=>_().regex(/^[0-9a-fA-F]{64}$/,"Must be a 64-character hex SHA-256 digest"));function wR(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t.endsWith("."))t=t.slice(0,-1);if(t===""||t==="localhost"||t.endsWith(".localhost"))return!0;if(_Be(t)){let[s=0,i=0,a=0,c=0]=t.split(".").map(Number);return s===127||s===169&&i===254||s===0||s===100&&i===100&&a===100&&c===200}if(!yBe(t))return!1;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);if(n?.[1])return wR(n[1]);let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(r?.[1]!==void 0&&r[2]!==void 0){let s=parseInt(r[1],16),i=parseInt(r[2],16);return wR(`${s>>8}.${s&255}.${i>>8}.${i&255}`)}if(t==="::1"||t==="::"||t==="fd00:ec2::254")return!0;let o=parseInt(/^([0-9a-f]{1,4}):/.exec(t)?.[1]??"0",16);return o>=65152&&o<=65215}var eHe="Archive URLs must use https:// and must not point at a loopback, link-local, or cloud-metadata host";function tHe(e){try{let t=new URL(e);return t.protocol==="https:"&&!wR(t.hostname)}catch{return!1}}var nHe=L(()=>w({source:N("archive"),url:_().url().refine(tHe,{message:eHe}).describe("HTTPS URL of a zip archive containing the plugin. The plugin root (the directory holding .claude-plugin/) may be at the top of the archive "+"or nested one directory deep — a single wrapping directory is stripped."),sha256:QBe().optional().describe("SHA-256 digest of the archive. When set, every download is verified against it and the install is refused on mismatch. It also serves as the version identity when neither plugin.json nor the marketplace entry declares a `version`. Recommended. Note the update signal is the version string (plugin.json "+"version, else the entry version, else this digest) — changing only the digest "+"while a version is declared does not trigger an update.")}).describe("Plugin distributed as a zip archive fetched over HTTPS — for hosting on any "+"static file server or artifact repository (S3, GitLab, nginx) with no git or npm on the client. Authentication comes from the enclosing marketplace: when the archive URL shares the marketplace url-source's origin, that source's headers are sent with the download.")),N9=L(()=>oe([xt((e)=>e==="."?"./":e,Ao()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),w({source:N("npm"),package:L9().or(_().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:_().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:_().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),w({source:N("url"),url:_().describe("Full git repository URL (https:// or git@)"),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:xR().optional().describe("Specific commit SHA to use")}),w({source:N("github"),repo:_().describe("GitHub repository in owner/repo format"),ref:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:xR().optional().describe("Specific commit SHA to use")}),w({source:N("git-subdir"),url:_().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:_().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:_().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:xR().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."),nHe(),w({source:N("command"),command:_().min(1).max(A9,{message:"command must not be longer than the install consent UI can display"}).refine((e)=>!SBe.test(e),{message:"command must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"}).describe("Shell command that prints the absolute path of the plugin directory on stdout (exactly one line) and exits 0. It must leave a complete plugin in that directory before exiting; the directory is copied into the plugin cache, so the printed path may change between runs (it is re-resolved on every install and update, and once per session in the background). Runs through the platform shell (sh on macOS/Linux, cmd.exe on Windows) from the user's home directory with Claude Code's subprocess environment."),timeout:j().int().positive().max(600).optional().describe("Seconds to wait for the command before giving up (default: 60)"),mode:G(["copy","link"]).optional().describe("copy (default): the printed directory is copied into the plugin cache and content-hashed, so it may be deleted afterwards. link: the cache entry links to the printed directory "+"in place (no copy, no size limit; macOS/Linux) — for large exports; the directory must then stay "+"valid while Claude Code runs, and a different printed path is what signals new content.")}).describe("Plugin directory produced by a locally installed tool (e.g. an IDE that renders its plugin for the currently selected SDK). Claude Code runs the command, copies the directory it prints, and re-runs it in the background at startup to pick up changes."),w({source:N("unsupported"),error:_().optional()}).describe("Placeholder for source types this Claude Code version does not recognize, or a known type whose fields failed validation (then `error` "+"holds the reason). Never authored by hand — 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 an actionable message.")])),rHe=L(()=>w({name:_().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:N9().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:_().optional(),version:_().optional(),strict:C().optional()}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url, archive, command). 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, archive, command)."}));var oHe=L(()=>w({cli:I(_().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:I(_().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) — exact, case-insensitive match against '+"hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path."),filesRead:I(_().max(256)).max(10).optional().describe('Glob patterns (e.g. ["**/*.tf"]) — the plugin is relevant when a file Claude has read '+"this session matches any pattern. Matched against read-file paths, forward-slash normalized, case-insensitive."),manifestDeps:I(w({file:_().max(256),pattern:_().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: "+"`file` matches the manifest filename (package.json, go.mod, requirements.txt, …); "+"`pattern` matches the dependency declaration inside that file. Evaluated against files read this session."),cwd:I(_().max(256)).max(10).optional().describe('Glob patterns (e.g. ["Engine/Source/Runtime/Renderer/**"]) — the plugin is relevant when the '+`session's working directory is at or under a directory matching the pattern. Matched against the cwd both relative to the enclosing git repo root and as an absolute path, forward-slash normalized, case-insensitive. A bare directory (no glob characters) means "cwd is at or under this directory". Known at session start, so this signal can surface a suggestion before the first turn.`)})),sHe=L(()=>w({topic:_().max(64).optional().describe('What the user is working with when this plugin is relevant — fills "Working with {topic}?". '+'Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:oHe().optional().describe("Matchers that determine when the plugin is relevant.")})),iHe=L(()=>XBe().partial().extend({name:_().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:N9().describe("Where to fetch the plugin from"),category:_().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:I(_()).optional().describe("Tags for searchability and discovery"),strict:C().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:xt((e)=>fa(e)?e:void 0,sHe().optional()).describe(`Declares when this plugin is relevant to the user's work. Consumed by the spinner tip ("Working with {topic}?"), session-start auto-suggest, and marketplace browse ranking.`)})),aHe=L(()=>w({name:_().min(1).refine((e)=>!e.includes(" "))}));function cHe(e){let t=iHe();return e.flatMap((n,r)=>{let o=t.safeParse(n);if(o.success){let a=o.data.source;if(typeof a==="object"&&a.source==="unsupported"&&a.error!==void 0)return[{...o.data,source:{source:"unsupported"}}];return[o.data]}let s=aHe().safeParse(n).data?.name,i=o.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(s){ce(`Stubbing unparseable marketplace plugin entry (${s}): ${i}`,{level:"warn"});let a=AR(n)?void 0:uHe(o.error.issues)??My(o.error.issues);return[{name:s,source:{source:"unsupported",...a&&{error:a}},strict:!0}]}return ce(`Dropping unparseable marketplace plugin entry (index ${r}): ${i}`,{level:"warn"}),[]})}var lHe=new Set(["npm","url","github","git-subdir","archive","command","unsupported"]);function AR(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.source;return typeof n==="string"&&!lHe.has(n)}function uHe(e){let t=e.find((r)=>r.path.length===1&&r.path[0]==="source");if(!t||t.code!=="invalid_union")return;let n=t.errors.find((r)=>!r.some((o)=>o.path.length===0||o.code==="invalid_value"&&o.path[0]==="source"));if(!n||n.length===0)return;return My(n.map((r)=>({...r,path:["source",...r.path]})))}var dHe=/^[A-Za-z0-9_$.-]{1,40}$/;function nu(e){return dHe.test(e)?e:"<key>"}var pHe=3,fHe=160;function My(e){let t=e.slice(0,pHe).map((r)=>{let o=r.path.map(String).map((i)=>nu(i)).join("."),s=r.code==="unrecognized_keys"?`Unrecognized ${r.keys.length===1?"field":"fields"}: ${r.keys.map(nu).join(", ")}`:S9(r.message,fHe);return o?`${o}: ${s}`:s}),n=e.length-t.length;return n>0?`${t.join(", ")} (+${n} more)`:t.join(", ")}var GAt=L(()=>w({$schema:_().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:R9(),version:_().optional().describe("Marketplace manifest version"),description:_().optional().describe("Human-readable description of this marketplace"),owner:TR().describe("Marketplace maintainer or curator information"),plugins:I(Se()).transform(cHe).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:C().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:w({pluginRoot:_().optional().describe("Base path for relative plugin sources"),version:_().optional().describe("Marketplace version"),description:_().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:I(_()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:q(_(),_().nullable()).optional().catch(void 0).describe("Append-only map of old plugin name → current name (or null when removed). The loader follows this on plugin-not-found and migrates user settings to the new name.")})),U9=L(()=>_().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")),mHe=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,hHe=L(()=>oe([_().regex(mHe,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),w({name:_().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:_().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),gHe=L(()=>w({version:_().describe("Currently installed version"),installedAt:_().describe("ISO 8601 timestamp of installation"),lastUpdated:_().optional().describe("ISO 8601 timestamp of last update"),installPath:_().describe("Absolute path to the installed plugin directory"),gitCommitSha:_().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:_().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:C().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)."),...k9()})),WAt=L(()=>w({version:N(1).describe("Schema version 1"),plugins:q(U9(),gHe()).describe("Map of plugin IDs to their installation metadata")})),_He=L(()=>G(["managed","user","project","local"])),yHe=L(()=>w({scope:_He().describe("Installation scope"),projectPath:_().optional().describe("Project path (required for project/local scopes)"),installPath:_().describe("Absolute path to the versioned plugin directory"),version:_().optional().describe("Currently installed version"),installedAt:_().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:_().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:_().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:_().optional().describe("Tag-derived semver this install resolved to"),auto:C().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep."),...k9()})),VAt=L(()=>w({version:N(2).describe("Schema version 2"),plugins:q(U9(),I(yHe())).describe("Map of plugin IDs to arrays of installation entries")})),bHe=L(()=>w({source:zf().describe("Where to fetch the marketplace from"),installLocation:_().describe("Local cache path where marketplace manifest is stored"),lastUpdated:_().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:C().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),ZAt=L(()=>q(_(),bHe()));var SHe=["autoMode","deepLink","voice","briefView","screenReader"],kR={},Ny={autoMode:{buildGate:()=>!1,shape:()=>kR,permissionsShape:()=>kR,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:G(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!0,shape:()=>({voiceEnabled:C().optional().describe("Enable voice mode (hold-to-talk dictation)")})},briefView:{buildGate:()=>!0,shape:()=>({defaultView:G(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>kR}};function CR(){return SHe.filter((e)=>Ny[e].buildGate())}function z9(e){let t={};for(let n of e)t={...t,...Ny[n].shape()};return t}function F9(e){let t={};for(let n of e)t={...t,...Ny[n].permissionsShape?.()};return t}function j9(e){let t=[];for(let n of e)t.push(...Ny[n].permissionModes?.()??[]);return t}function RR(e){let t=e.split("__"),[n,r,...o]=t;if(n!=="mcp"||!r)return null;let s=o.length>0?o.join("__"):void 0;return{serverName:r,toolName:s}}var $9={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool",ReadMcpResourceDir:"ReadMcpResourceDirTool"};function ru(e){return Object.hasOwn($9,e)?$9[e]:e}var B9="workspace",skt=`mcp__${B9}__bash`,ikt=`mcp__${B9}__web_fetch`;function OR(e){return e.includes("*")}function xHe(e){return e.replaceAll("\\","\\\\").replaceAll("(","\\(").replaceAll(")","\\)")}function EHe(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function H9(e){let t=vHe(e,"(");if(t===-1)return{toolName:ru(e)};let n=wHe(e,")");if(n===-1||n<=t)return{toolName:ru(e)};if(n!==e.length-1)return{toolName:ru(e)};let r=e.substring(0,t),o=e.substring(t+1,n);if(!r)return{toolName:ru(e)};if(o===""||o==="*")return{toolName:ru(r)};let s=EHe(o);return{toolName:ru(r),ruleContent:s}}function PR(e){if(!e.ruleContent)return e.toolName;let t=xHe(e.ruleContent);return`${e.toolName}(${t})`}function vHe(e,t){for(let n=0;n<e.length;n++)if(e[n]===t){let r=0,o=n-1;while(o>=0&&e[o]==="\\")r++,o--;if(r%2===0)return n}return-1}function wHe(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){let r=0,o=n-1;while(o>=0&&e[o]==="\\")r++,o--;if(r%2===0)return n}return-1}var Uy={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit","Cd"],bashPrefixTools:["Bash"],customValidation:{WebSearch:(e)=>{if(e.includes("*")||e.includes("?"))return{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]};return{valid:!0}},WebFetch:(e)=>{if(e.includes("://")||e.startsWith("http"))return{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]};if(!e.startsWith("domain:"))return{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]};return{valid:!0}}}};function K9(e){return Uy.filePatternTools.includes(e)}function q9(e){return Uy.bashPrefixTools.includes(e)}function G9(e){return Object.hasOwn(Uy.customValidation,e)?Uy.customValidation[e]:void 0}function V9(e,t){let n=0,r=t-1;while(r>=0&&e[r]==="\\")n++,r--;return n%2!==0}function IR(e,t){let n=0;for(let r=0;r<e.length;r++)if(e[r]===t&&!V9(e,r))n++;return n}function THe(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!V9(e,t))return!0}return!1}function W9(e){if(!OR(e))return null;let t=RR(e);if(t&&!OR(t.serverName))return null;return{valid:!1,error:`Wildcard tool name "${e}" is not supported in allow rules`,suggestion:"An allow pattern must name the scope it widens — globs are permitted only in the tool position after a literal mcp__<server>__ prefix. Deny and ask rules accept wildcards anywhere",examples:["mcp__puppeteer__*","mcp__github__get_*"]}}function DR(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=IR(e,"("),r=IR(e,")");if(n!==r)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(THe(e)){let a=e.substring(0,e.indexOf("("));if(!a)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}}let o=H9(e),s=RR(o.toolName);if(s){if(o.ruleContent!==void 0||IR(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${o.toolName}" without parentheses, or use "mcp__${s.serverName}__*" for all tools`,examples:[`mcp__${s.serverName}`,`mcp__${s.serverName}__*`,s.toolName&&s.toolName!=="*"?`mcp__${s.serverName}__${s.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let a=W9(o.toolName);if(a)return a}return{valid:!0}}if(!o.toolName||o.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let a=W9(o.toolName);if(a)return a}if(!o.toolName.includes("_")&&o.toolName[0]!==o.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${du(String(o.toolName))}"`};let i=G9(o.toolName);if(i&&o.ruleContent!==void 0){let a=i(o.ruleContent);if(!a.valid)return a}if(q9(o.toolName)&&o.ruleContent!==void 0){let a=o.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(K9(o.toolName)&&o.ruleContent!==void 0){if(o.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${o.toolName}(*.ts) - matches .ts files`,`${o.toolName}(src/**) - matches all files in src`,`${o.toolName}(**/*.test.ts) - matches test files`]}}if(o.ruleContent!==void 0){let a=o.toolName==="Write"||o.toolName==="NotebookEdit"||o.toolName==="MultiEdit"?"Edit":o.toolName==="Glob"?"Read":void 0;if(a!==void 0&&!o.ruleContent.includes(":*"))return{valid:!0,warning:`${PR(o)} is not matched by file permission checks — only ${a}(path) rules are. Use ${PR({toolName:a,ruleContent:o.ruleContent})} instead (${a} rules cover all file-${a==="Edit"?"editing":"reading"} tools).`}}return{valid:!0}}var LR=L(()=>Y9()),Z9=L(()=>Y9("allow"));function Y9(e){return _().superRefine((t,n)=>{let r=DR(t,e);if(!r.valid){let o=r.error;if(r.suggestion)o+=`. ${r.suggestion}`;if(r.examples&&r.examples.length>0)o+=`. Examples: ${r.examples.join(", ")}`;n.addIssue({code:hr.custom,message:o,params:{received:t}})}})}var AHe=L(()=>q(_(),Sm.string()));function tZ(e){return w({allow:I(Z9()).optional().describe("List of permission rules for allowed operations"),deny:I(LR()).optional().describe("List of permission rules for denied operations"),ask:I(LR()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:xt(Nf,G([...Mf,...j9(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:G(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...F9(e),additionalDirectories:I(_()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var Akt=L(()=>tZ(CR())),NR=L(()=>w({source:zf().describe("Where to fetch the marketplace from"),installLocation:_().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:C().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),Fy=L(()=>w({serverName:_().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:I(_()).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:_().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>np([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"'})),jy=L(()=>w({serverName:_().min(1,"Server name must be non-empty").refine((e)=>e.trim().length>0,{message:"Server name must not be whitespace-only"}).refine((e)=>e===e.trim(),{message:"Server name has leading or trailing whitespace and will never match (names are compared verbatim)"}).optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:I(_()).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:_().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>np([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=L(()=>w({path:_().describe("Absolute path to the helper executable"),timeoutMs:j().int().min(1000).optional(),refreshIntervalMs:oe([N(0),j().int().min(60000)]).optional()})),MR=["macos","linux","windows","wsl"],kHe=L(()=>w(Object.fromEntries(MR.map((e)=>[e,zy().optional()])))),J9=["skills","agents","hooks","mcp"],X9=Object.freeze({type:"invalid-entry-stripped"}),CHe=L(()=>oe([w({type:N("regex").describe('Config variant. This client understands "regex": matches turn output and builds a URL from named capture groups. Entries with other variants are preserved but skipped at runtime.'),pattern:_().describe("Regex matched against turn output (tool results and assistant text)"),url:_().describe("Link target. {name} placeholders are filled from named regex capture groups, e.g. (?<id>...) -> {id}. Values are URL-encoded; the origin must be literal in the template. The scheme must be https, http, or a recognized editor or workspace deep-link scheme: vscode, vscode-insiders, cursor, windsurf, zed, jetbrains, idea, slack, linear, notion, figma."),label:_().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),w({type:_().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function nZ(e){return w({$schema:_().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:_().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:_().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:_().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:_().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:_().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),processWrapper:_().optional().describe("Corporate launcher argv prefix for the background-agent supervisor, the sessions and workers it hosts, and the other covered background processes listed in the Claude Code corporate-launcher documentation. Equivalent to the CLAUDE_CODE_PROCESS_WRAPPER environment variable, which takes precedence when set. Honored from managed settings, a --settings/SDK-supplied settings file, and user settings, in that precedence order; project and local settings are ignored."),policyHelper:zy().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),policyHelpers:kHe().optional().describe("Per-OS variant of policyHelper, keyed by platform: macos, linux, windows, wsl. The entry for the current platform wins over policyHelper; a platform with no entry falls back to policyHelper (wsl falls back to the linux entry first). Honored only from admin-controlled policy sources."),...xn.CLAUDE_CODE_ENABLE_XAA&&{xaaIdp:w({issuer:_().url().describe("IdP issuer URL for OIDC discovery"),clientId:_().describe("Claude Code's client_id registered at the IdP"),callbackPort:j().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:w({type:N("command"),command:_()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:C().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:w({enabled:C().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:j().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:j().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:_().optional().describe("Custom reminder text. Leave unset for a rotating set of friendly nudges.")}).optional().describe("@internal Opt-in break reminder. When enabled, shows a dismissible nudge after sustained continuous use. Never blocks — just a friendly heads-up."),quietHours:w({enabled:C().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:_().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "22:00")').optional().describe('Start of the quiet-hours window, 24-hour local time "HH:MM".'),end:_().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "07:00")').optional().describe('End of the quiet-hours window, 24-hour local time "HH:MM". May be earlier than start for an overnight range.')}).optional().describe("@internal Opt-in quiet hours. When enabled, shows a single soft nudge per session while inside the configured local-time window. Never blocks."),cleanupPeriodDays:j().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:j().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:j().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:C().optional().describe("When set to true in either admin-only Windows source — the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json — 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:AHe().optional().describe("Environment variables to set for Claude Code sessions"),attribution:w({commit:_().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:_().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:C().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link."),...!1}).passthrough().optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:C().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,includeGitInstructions:C().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:tZ(e).optional().describe("Tool usage permissions configuration"),model:_().optional().describe("Override the default model used by Claude Code"),fallbackModel:I(_()).optional().describe('Fallback model(s) tried in order when the primary model is overloaded or unavailable. Each element accepts a model name or alias; "default" expands to the default model. CLI --fallback-model takes precedence.'),availableModels:I(_()).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.'),enforceAvailableModels:C().optional().describe("When true and availableModels is a non-empty array, the Default model selection is also constrained: if the default model for the user tier is not in availableModels, Default resolves to the first allowed availableModels entry instead. Has no effect when availableModels is unset or an empty array. Typically set in managed settings by enterprise administrators."),modelOverrides:q(_(),_()).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:C().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:I(_()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:I(_()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:C().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected. "+"Only gates auto-fetched connectors — a claudeai-proxy server passed explicitly "+"(e.g. via --mcp-config or the SDK mcpServers option) still follows the normal MCP config trust flow. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:q(_(),G(["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.'),disableBundledSkills:C().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:I(Fy()).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:I(jy()).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:ma().optional().describe("Custom commands to run before/after tool executions"),worktree:w({symlinkDirectories:I(_()).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:I(_()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos — only the listed paths are written to disk."),baseRef:G(["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."),bgIsolation:G(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:C().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:C().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:C().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."),disableWorkflows:C().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:C().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableArtifact:C().optional().describe("Enable or disable the Artifact tool for this user. Unset defaults to enabled once the feature is available."),enableWorkflows:C().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowSizeGuideline:G(["unrestricted","small","medium","large"]).optional().describe('Advisory size guideline for the dynamic workflows Claude writes: "small" aims for fewer than 5 agents, "medium" (the default) fewer than 15, "large" fewer than 50, and "unrestricted" sends no guideline. A value here — including from managed settings — takes precedence over the "Dynamic workflow size" choice in /config, and that /config row is hidden while a settings file provides the key. This is a guideline, not an enforced limit.'),workflowKeywordTriggerEnabled:C().optional().describe('Enable the "ultracode" keyword trigger: including the keyword in a prompt opts that turn into the Workflow tool. Set to false to disable the trigger. Default: true.'),disableSkillShellExecution:C().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:G(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:C().optional().describe("Whether Claude responds after an input-box ! bash command runs. Set to false to add the command output to context without a response. Default: true."),allowManagedHooksOnly:C().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:I(_()).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:I(_()).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:C().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:C().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."),allowAllClaudeAiMcps:C().optional().describe("When true (and set in managed settings), claude.ai cloud MCP connectors load alongside managed-mcp.json instead of being suppressed by its exclusive-control lockdown. Default off preserves the lockdown. Read from managed settings only."),strictPluginOnlyCustomization:xt((t)=>Array.isArray(t)?t.filter((n)=>J9.includes(n)):t,oe([C(),I(G(J9))])).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 — plugins gated by "+"marketplace allowlist, everything else blocked here."),statusLine:w({type:N("command"),command:_(),padding:j().optional(),refreshInterval:j().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:C().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:_().optional().describe('URL template for PR links in the footer link badges and inline messages. The detected git PR is rendered as the first footer-link badge. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),footerLinksRegexes:I(CHe().catch(X9)).transform((t)=>t.filter((n)=>n!==X9)).optional().catch(void 0).describe("Extra clickable footer badges that appear when a regex matches turn output (tool results and assistant responses). Read from user, flag, and managed settings only; ignored in project .claude/settings.json and local .claude/settings.local.json. At most 5 badges render; the oldest is displaced by newer matches and /clear removes them. Use to surface IDs printed by project CLIs as session links."),subagentStatusLine:w({type:N("command"),command:_()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:q(_(),oe([I(_()),C(),_x()])).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 — setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:q(_(),NR()).check((t)=>{for(let[n,r]of Object.entries(t.value))if(r.source.source==="settings"&&r.source.name!==n)t.issues.push({code:"custom",input:r.source.name,path:[n,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${n}" but source.name "${r.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:I(zf()).optional().describe('Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these sources can be added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to allow every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem. '+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:I(zf()).optional().describe('Enterprise blocklist of marketplace sources. When set in managed settings, these sources are blocked from being added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to block every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem.'),disableCommandPluginSources:C().optional().describe("Controls the `command` plugin source, whose plugin directory is produced by running a marketplace-declared command on this machine. true: command-sourced plugins are never installed, updated, or re-resolved (the command never runs). false: explicitly allowed. "+"Unset: follows allowManagedHooksOnly — an org that restricts hook execution to managed "+"settings gets command sources disabled too. Only honored from managed settings."),disableSideloadFlags:C().optional().describe("When true (and set in managed settings), rejects the --plugin-dir, --plugin-url, --agents, and non-sdk --mcp-config CLI flags at startup. Closes the CLI-flag bypass of strictKnownMarketplaces. Pair with allowedMcpServers for per-server MCP control; this setting does not gate other MCP entry points (SDK setMcpServers, claude mcp add, .mcp.json). Also blocks surfaces that spawn the CLI with these flags internally (see settings documentation). Only honored from managed settings; ignored in user/project/local settings."),pluginSuggestionMarketplaces:I(_()).optional().describe("Marketplace names whose plugins may surface as contextual install suggestions (relevance-based tips). No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Only honored when set in managed settings (policy scope); the key is ignored in user, project, and local settings. A name only takes effect when the marketplace is registered on the machine AND its registered source is also declared in managed settings, either as the extraKnownMarketplaces entry for that name or as an entry of strictKnownMarketplaces. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source."),forceLoginMethod:G(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:_().url().optional().catch(void 0).describe('Cloud gateway URL to pre-fill and auto-connect to during login, alongside forceLoginMethod: "gateway". Honored only from admin-controlled managed settings (MDM / managed-settings.json / policy helper); ignored in user, project, and remote-delivered settings.'),parentSettingsBehavior:G(["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 — 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:oe([_(),I(_())]).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:C().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:_().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:_().optional().describe("Controls the output style for assistant responses"),viewMode:G(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:_().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:C().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:yR().optional(),feedbackSurveyRate:j().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),feedbackDrafts:G(["notify","quiet","off"]).optional().describe('Model-drafted feedback (the SendFeedback tool). "notify" (default) shows a one-line notice when a draft is queued; "quiet" shows only the footer counter; "off" disables the tool entirely so drafts are never queued.'),spinnerTipsEnabled:C().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:w({mode:G(["append","replace"]),verbs:I(_())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:w({excludeDefault:C().optional(),tips:I(_())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:C().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:C().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:C().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:G(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:C().optional().catch(void 0).describe("Enable ultracode for the session: xhigh effort plus standing dynamic-workflow orchestration. "+"Session-scoped — typically provided via --settings or the apply_flag_settings control request; "+"interactive toggles never persist it. Requires workflows to be enabled and an xhigh-capable model."),autoCompactWindow:j().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:_().optional().describe("Advisor model for the server-side advisor tool."),fastMode:C().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:C().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:C().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),emojiCompletionEnabled:C().optional().describe("When false, the :emoji: shortcode typeahead (the suggestion popup and the :name: inline replacement) is disabled. When absent or true, it is enabled."),awaySummaryEnabled:C().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:C().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:G(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers "+"selected so far. Defaults to never — auto-continue only runs "+"when explicitly set to 60s/5m/10m."),dialogExpiry:G(["60s","5m","10m","never"]).optional().catch(void 0).describe('Max time a permission/user dialog forwarded to a remote client stays parked awaiting an answer, and how long a HELD cross-session message awaits approval, before either resolves to its safe no-action default (cancelled / dropped-with-denial). Defaults to 5m to match the long-standing remote-dialog deadline; "never" disables the deadline. Local-only permission prompts (no remote client) are unaffected. The CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS env var, when set, overrides this. Read from trusted sources only (never a checked-in repo settings file).'),agent:_().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."),modelProposedGoals:G(p9).optional().catch(void 0).describe("@internal Controls the ProposeGoal tool (model-proposed session goals). 'auto' (the default when absent) lets the model choose per proposal whether to ask for approval via its ask_user parameter; 'alwaysAsk' routes every model-proposed goal through the approval dialog; 'disabled' turns the tool off. A typed /goal is unaffected. Consent-affecting, so it is read "+"from trusted sources only (user/policy/flag) — "+"workspace-resident project and local settings are ignored."),companyAnnouncements:I(_()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:q(_(),w({mcpServers:q(_(),q(_(),oe([_(),j(),C(),I(_())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:q(_(),oe([_(),j(),C(),I(_())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(_x())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:w({defaultEnvironmentId:_().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:G(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:_().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:_().optional().describe("Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup with instructions to update. Only enforced from managed (policy) settings."),requiredMaximumVersion:_().optional().describe("Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. Only enforced from managed (policy) settings."),plansDirectory:_().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:G(["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.'),...!1,voice:w({enabled:C().optional(),mode:G(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:C().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:C().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:I(w({marketplace:_(),plugin:_()})).optional().describe("Managed-org allowlist of channel plugins. When set, "+"replaces the default Anthropic allowlist — admins decide which "+"plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:C().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:C().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."),totalTokensReminder:G(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn "+"is on — task-budget semantics). Defaults to off. Env var "+"CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:j().int().positive().optional().describe("@internal Starting budget (tokens) for totalTokensReminder 'padded-countdown' mode. Defaults to 15000000. Server-controlled via GrowthBook; env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_BUDGET overrides."),totalTokensReminderAfterUserTurn:C().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:C().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:_().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:C().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:C().optional().describe("Request API-side thinking summaries and show them in the conversation and in the transcript view (ctrl+o). Set explicitly to override the default for your install."),skipDangerousModePermissionPrompt:C().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:C().optional().describe("@internal Whether the user has accepted the multi-agent workflow usage warning. Until set, auto permission mode prompts before running a workflow."),disableAutoMode:G(["disable"]).optional().describe("Disable auto mode"),sshConfigs:I(w({id:_().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:_().describe("Display name for the SSH connection"),sshHost:_().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:j().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:_().optional().describe("Path to SSH identity file (private key)"),startDirectory:_().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:_().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:I(_()).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:_().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:oe([G(d9),_().startsWith("custom:").transform((t)=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:G(l9).optional().catch(void 0).describe("Key binding mode for the prompt input"),vimInsertModeRemaps:q(_(),Se()).optional().catch(void 0).describe('Vim INSERT-mode key-sequence remaps, e.g. {"jj": "<Esc>"}. Each key is exactly two printable characters typed in sequence; "<Esc>" (return to NORMAL mode) is the only supported target. Applies when editorMode is "vim".'),verbose:C().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:G(c9).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:C().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:C().optional().describe("Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:C().optional().describe("When safeguards flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:C().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:C().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:C().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:C().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:C().optional().describe("Stamp each message with its arrival time"),terminalProgressBarEnabled:C().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:C().optional().describe("Enable the todo / task tracking panel"),teammateMode:G(u9).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:C().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:C().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:G(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),crossSessionInbound:G(["accept","hold","refuse"]).optional().catch(void 0).describe("Inbound cross-session peer messages (SendMessage from your other sessions): 'accept' delivers them, 'hold' parks them for your review without letting Claude act, 'refuse' opts this session out. An explicit value always wins. Unset (mode parity): a message auto-delivers only when the sending session's permission-mode class matches yours (bypass↔bypass or prompting↔prompting); a mismatched sender's message is held for your approval; a sender that asserts no class is held only while this session bypasses permission prompts."),autoUploadSessions:C().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:C().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:C().optional().describe("Allow Claude to push proactive mobile notifications"),...z9(e)}).passthrough()}var ga=L(()=>nZ(CR())),Q9=Object.freeze({serverName:"invalid-entry-stripped"});function eZ(e,t,n){return I(t.catch((r)=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${r.issues[0]?.message??"failed validation"}`}),Q9))).transform((r)=>r.filter((o)=>o!==Q9)).optional()}function UR(e,t){let n=ga(),r={};for(let[h,g]of Object.entries(n.shape))r[h]=g.catch((y)=>{e({path:h,message:`${y.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});r.allowedMcpServers=eZ("allowedMcpServers",Fy(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[])),r.deniedMcpServers=eZ("deniedMcpServers",jy(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return}),r.allowManagedHooksOnly=n.shape.allowManagedHooksOnly.catch(()=>(e({path:"allowManagedHooksOnly",message:'"allowManagedHooksOnly" was present but invalid; treating it as true (only managed hooks run; command-sourced plugins disabled) until it is fixed.'}),!0)),r.disableCommandPluginSources=n.shape.disableCommandPluginSources.catch(()=>(e({path:"disableCommandPluginSources",message:'"disableCommandPluginSources" was present but invalid; treating it as true (command-sourced plugins disabled) until it is fixed.'}),!0)),r.allowManagedMcpServersOnly=n.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),r.enforceAvailableModels=n.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),r.availableModels=I(Se()).transform((h,g)=>{let y=[];for(let b of h)if(typeof b==="string")y.push(b);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(b)}); the entry was ignored.`});return y}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),r.forceLoginOrgUUID=n.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[])),r.policyHelper=xt((h)=>h===null?void 0:h,zy().optional()).catch((h)=>{e({path:"policyHelper",message:`${h.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});let o=(h)=>xt((g)=>g===null?void 0:g,zy().optional()).catch((g)=>{e({path:`policyHelpers.${h}`,message:`Invalid entry was ignored: ${g.issues[0]?.message??"failed validation"}. No policy helper runs on ${h} from this entry.`,statusOnly:!0});return});r.policyHelpers=xt((h)=>h===null?void 0:h,w(Object.fromEntries(MR.map((h)=>[h,o(h)]))).transform((h)=>{for(let g of Object.keys(h))if(h[g]===void 0)delete h[g];return h}).optional().catch((h)=>(e({path:"policyHelpers",message:`"policyHelpers" could not be parsed: expected an object mapping OS keys (${MR.join(", ")}) to helper entries (${h.issues[0]?.message??"failed schema validation"}). When delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0}),{})));let s=Object.freeze({mode:"deny"}),i=Object.freeze({accessKeyIdVar:"_STRIPPED_",secretAccessKeyVar:"_STRIPPED_2_"}),a=0,c=[],l=t===void 0?"":`${[...t].reduce((h,g)=>Math.imul(h^g.charCodeAt(0),16777619)>>>0,2166136261).toString(16).toUpperCase().padStart(8,"0")}_`,u=(h,g)=>{if(typeof h!=="object"||h===null)return;let y=(ye)=>g.some((Ve)=>Ve.path?.includes(ye)),b=(ye)=>{let Ve=h[ye];if(typeof Ve==="string")return Ve;return y(ye)?"":void 0},x=b("accessKeyIdVar"),E=b("secretAccessKeyVar"),k=b("sessionTokenVar"),R=Ql;if(![x,E,k].some((ye)=>ye!==void 0&&R.includes(ye)))return;let V=(ye)=>ye!==void 0&&Xl().safeParse(ye).success;a+=1;let K=(ye)=>`${_R}${ye}_${l}${a}_`,Q=V(x)?x:K("ACCESS_KEY_ID"),X=V(E)&&E!==Q?E:K("SECRET_ACCESS_KEY"),me=k===void 0?void 0:V(k)&&k!==Q&&k!==X?k:K("SESSION_TOKEN"),Ce=(ye)=>ye.startsWith(_R);if(!Ce(Q)&&!Ce(X)){let ye=R.includes(X)?X:void 0;if(X=K("SECRET_ACCESS_KEY"),ye!==void 0){let Ve=u({accessKeyIdVar:ye},[]);if(Ve!==void 0)c.push(Ve)}}let tt=Iy().safeParse({accessKeyIdVar:Q,secretAccessKeyVar:X,...me!==void 0&&{sessionTokenVar:me}});return tt.success?tt.data:void 0},p=(h,g,y)=>I(g.catch((b)=>{let x=y(b.value);if(x!==void 0)return e({path:`sandbox.credentials.${h}[]`,message:`Invalid entry was degraded to mode "deny": ${b.issues[0]?.message??"failed validation"}. The credential stays blocked (not masked) until the entry is fixed.${h==="files"?" Under sandbox.filesystem.disabled, file read-denies are not enforced.":""}`}),x;return e({path:`sandbox.credentials.${h}[]`,message:`Invalid entry was ignored: ${b.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),s})).transform((b)=>b.filter((x)=>x!==s)).optional().catch((b)=>{if(typeof b.value==="object"&&b.value!==null&&!Array.isArray(b.value)){let x=g.safeParse(b.value);if(x.success)return e({path:`sandbox.credentials.${h}`,message:`"${h}" must be an array; a lone entry object was accepted as a one-element list. Wrap it in [ ] to silence this warning.`}),[x.data];let E=y(b.value);if(E!==void 0)return e({path:`sandbox.credentials.${h}`,message:`"${h}" must be an array; its lone entry object was invalid and was degraded to mode "deny". The credential stays blocked (not masked) until it is fixed.`}),[E]}return e({path:`sandbox.credentials.${h}`,message:`${b.issues[0]?.message??"Invalid value"}. "${h}" was ignored; these credential entries are NOT protected until it is fixed.`}),[]}),f=w({files:p("files",Oy(),(h)=>{if(typeof h!=="object"||h===null||!("mode"in h)||h.mode!=="mask"&&h.mode!=="deny"||!("path"in h)||typeof h.path!=="string")return;let g=Oy().safeParse({path:h.path,mode:"deny"});return g.success?g.data:void 0}),envVars:p("envVars",Py(),(h)=>{if(typeof h!=="object"||h===null||!("mode"in h)||h.mode!=="mask"&&h.mode!=="deny"||!("name"in h)||typeof h.name!=="string")return;let g=Py().safeParse({name:h.name,mode:"deny"});return g.success?g.data:void 0}),allowPlaintextInject:C().optional().catch((h)=>(e({path:"sandbox.credentials.allowPlaintextInject",message:`${h.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was degraded to an explicit false; plaintext credential injection stays disabled (lower-precedence values cannot enable it) until it is fixed.`}),!1)),awsPairs:I(Iy().catch((h)=>{let g=u(h.value,h.issues);if(g!==void 0)return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was degraded to a non-functional suppressor: ${h.issues[0]?.message??"failed validation"}. It keeps implicit AWS auto-pairing suppressed but re-signs nothing until it is fixed.`}),g;return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was ignored: ${h.issues[0]?.message??"failed validation"}. SigV4 re-signing stays unconfigured for this pair until it is fixed.`}),i})).transform((h)=>{let g=h.filter((y)=>y!==i);if(c.length>0)g.push(...c),c.length=0;return g}).optional().catch((h)=>{let g=typeof h.value==="object"&&h.value!==null?u(h.value,[]):void 0,y=typeof h.value==="object"&&h.value!==null&&(("accessKeyIdVar"in h.value)||("secretAccessKeyVar"in h.value)||("sessionTokenVar"in h.value));if(g===void 0&&y)return c.length=0,e({path:"sandbox.credentials.awsPairs",message:`${h.issues[0]?.message??"Invalid value"}. "awsPairs" must be an array; its lone pair-shaped entry claimed no conventional AWS name and was ignored. SigV4 re-signing stays unconfigured until it is fixed.`}),[];let b=g!==void 0?[g]:Ql.flatMap((x)=>{let E=u({accessKeyIdVar:x},[]);return E!==void 0?[E]:[]});if(c.length>0)b.push(...c),c.length=0;return e({path:"sandbox.credentials.awsPairs",message:`${h.issues[0]?.message??"Invalid value"}. "awsPairs" was degraded to non-functional suppressor pair(s); implicit AWS auto-pairing stays suppressed but nothing re-signs until it is fixed.`}),b}),sigv4:w(Object.fromEntries(["streaming","presigned","sigv4a"].map((h)=>[h,G(["deny","passthrough"]).optional().catch((g)=>(e({path:`sandbox.credentials.sigv4.${h}`,message:`${g.issues[0]?.message??"Invalid value"}. "${h}" was degraded to an explicit deny; this SigV4 request shape stays denied until it is fixed.`}),"deny"))]))).optional().catch((h)=>(e({path:"sandbox.credentials.sigv4",message:`${h.issues[0]?.message??"Invalid value"}. "sigv4" was degraded to an all-deny block (all shapes stay denied, and lower-precedence sigv4 values cannot take effect) until it is fixed.`}),{streaming:"deny",presigned:"deny",sigv4a:"deny"}))}).optional().catch((h)=>{e({path:"sandbox.credentials",message:`${h.issues[0]?.message??"Failed schema validation"}. The credentials block was degraded to a fail-closed skeleton (all-deny sigv4, implicit AWS auto-pairing suppressed, no masking) until it is fixed.`});let g=Ql.flatMap((y)=>{let b=u({accessKeyIdVar:y},[]);return b!==void 0?[b]:[]});return c.length=0,{allowPlaintextInject:!1,awsPairs:g,sigv4:{streaming:"deny",presigned:"deny",sigv4a:"deny"}}});return r.sandbox=yR().extend({credentials:f}).optional().catch((h)=>{e({path:"sandbox",message:`${h.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});let g=h.value;if(typeof g==="object"&&g!==null&&"credentials"in g){let y=f.safeParse(g.credentials);if(y.success&&y.data!==void 0)return e({path:"sandbox.credentials",message:"The credentials block was salvaged from the invalid sandbox value and stays enforced; every other sandbox field was ignored."}),{credentials:y.data}}return}),w(r).passthrough().transform((h)=>{for(let g of Object.keys(h))if(h[g]===void 0)delete h[g];return h})}var es="https://code.claude.com/docs/en",RHe=[{matches:(e)=>e.path==="permissions.defaultMode"&&e.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:`${es}/iam#permission-modes`}},{matches:(e)=>e.path==="apiKeyHelper"&&e.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:(e)=>e.path==="cleanupPeriodDays"&&e.code==="too_small",tip:{suggestion:'cleanupPeriodDays must be at least 1. To keep transcripts for a long time, set a large number (e.g. 3650 for ~10 years). To disable transcript writes entirely, remove this setting and use the --no-session-persistence CLI flag or the SDK persistSession:false option instead. (0 is rejected because it previously silently disabled all transcript writes, which users setting it to mean "never clean up" did not expect.)'}},{matches:(e)=>e.path.startsWith("env.")&&e.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:`${es}/settings#environment-variables`}},{matches:(e)=>(e.path==="permissions.allow"||e.path==="permissions.deny")&&e.code==="invalid_type"&&e.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:(e)=>e.path.startsWith("hooks.")&&e.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${es}/hooks`}},{matches:(e)=>/\.hooks\.\d+\.command$/.test(e.path)&&e.code==="invalid_type"&&e.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${es}/hooks#exec-form-and-shell-form`}},{matches:(e)=>e.path.includes("hooks")&&e.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:(e)=>e.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:`${es}/settings`}},{matches:(e)=>e.code==="invalid_value"&&e.enumValues!==void 0,tip:{suggestion:void 0}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="object"&&e.received===null&&e.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:(e)=>e.path==="permissions.additionalDirectories"&&e.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:`${es}/iam#working-directories`}}],OHe={permissions:`${es}/iam#configuring-permissions`,env:`${es}/settings#environment-variables`,hooks:`${es}/hooks`};function rZ(e){let t=RHe.find((r)=>r.matches(e));if(!t)return null;let n={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!n.suggestion)n.suggestion=`Valid values: ${e.enumValues.map((r)=>`"${r}"`).join(", ")}`;if(!n.docLink&&e.path)n.docLink=OHe[nb(e.path,".")];return n}var Gkt=L(()=>ga().strict());function oZ(e){return e.code==="invalid_type"}function sZ(e){return e.code==="invalid_value"}function PHe(e){return e.code==="unrecognized_keys"}function iZ(e){return e.code==="too_small"}function _a(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function aZ(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function jf(e,t){return e.issues.map((n)=>{let r=n.path.map(String).join("."),o=n.message,s,i,a,c,l;if(sZ(n))i=n.values.map((p)=>String(p)),a=i.join(" | "),c=void 0,l=void 0;else if(oZ(n)){a=n.expected;let p=aZ(n.message);c=p??_a(n.input),l=p??_a(n.input)}else if(iZ(n))a=String(n.minimum);else if(n.code==="custom"&&"params"in n)c=n.params.received,l=c;let u=rZ({path:r,code:n.code,expected:a,received:c,enumValues:i,message:n.message,value:c});if(sZ(n))s=i?.map((p)=>`"${p}"`).join(", "),o=`Invalid value. Expected one of: ${s}`;else if(oZ(n)){let p=aZ(n.message)??_a(n.input);if(n.expected==="object"&&p==="null"&&r==="")o="Invalid or malformed JSON";else o=`Expected ${n.expected}, but received ${p}`}else if(PHe(n)){let p=n.keys.join(", ");o=`Unrecognized ${wO(n.keys.length,"field")}: ${p}`}else if(iZ(n))o=`Number must be greater than or equal to ${n.minimum}`,s=String(n.minimum);return{file:t,path:r,message:o,expected:s,invalidValue:l,suggestion:u?.suggestion,docLink:u?.docLink}})}function IHe(e,t){if(!e||typeof e!=="object")return[];let n=e;if(!n.permissions||typeof n.permissions!=="object")return[];let r=n.permissions,o=[];for(let s of["allow","deny","ask"]){let i=r[s];if(!Array.isArray(i))continue;r[s]=i.filter((a)=>{if(typeof a!=="string")return o.push({file:t,path:`permissions.${s}`,message:`Non-string value in ${s} array was removed`,severity:"warning",invalidValue:a}),!1;let c=DR(a,s);if(!c.valid){let l=`Invalid permission rule "${a}" was skipped: ${c.error}`;if(c.suggestion)l+=`. ${c.suggestion}`;return o.push({file:t,path:`permissions.${s}`,message:l,severity:"warning",invalidValue:a}),!1}return!0})}return o}var DHe=new Set(wa);function LHe(e,t){if(!e||typeof e!=="object")return[];let n=e;if(!("hooks"in n))return[];if(n.hooks===null||typeof n.hooks!=="object"||Array.isArray(n.hooks)){let s=_a(n.hooks);return delete n.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${s}. This field was ignored.`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"}]}let r=n.hooks,o=[];for(let s of Object.keys(r)){if(!DHe.has(s)){delete r[s],o.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${wa.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(r[s])){let i=_a(r[s]);delete r[s],o.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${i}. This entry was ignored.`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"})}}if(o.length>0&&Object.keys(r).length===0)delete n.hooks;return o}var MHe=[{key:"allowedMcpServers",schema:Fy},{key:"deniedMcpServers",schema:jy}];function NHe(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of MHe){if(!(s in r))continue;if(!Array.isArray(r[s])){if(n?.keepWholeFieldInvalid)continue;let l=r[s];delete r[s],o.push({file:t,path:s,message:`"${s}" must be an array; received ${_a(l)}. This field was ignored.`,severity:"warning",invalidValue:l});continue}let a=r[s],c=[];for(let l=0;l<a.length;l++){let u=i().safeParse(a[l]);if(u.success)c.push(a[l]);else o.push({file:t,path:`${s}[${l}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:a[l]})}if(c.length<a.length)r[s]=c}return o}function UHe(e){if(!e||typeof e!=="object")return;let t=e.source;if(!t||typeof t!=="object")return;let n=t.source;return typeof n==="string"?n:void 0}function zHe(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.plugins;return Array.isArray(n)&&n.some(AR)}function FHe(e,t){if(!e||typeof e!=="object")return[];let n=e,r="extraKnownMarketplaces";if(!(r in n))return[];let o=n[r];if(!o||typeof o!=="object"||Array.isArray(o)){let a=_a(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object mapping marketplace names to declarations; received ${a}. This field was ignored.`,severity:"warning",invalidValue:a}]}let s=o,i=[];for(let a of Object.keys(s)){let c=NR().safeParse(s[a]),l;if(!c.success){let u=UHe(s[a]);if(u!==void 0&&!M9.has(u)||zHe(s[a]))continue;l=My(c.error.issues)}else if(c.data.source.source==="settings"&&c.data.source.name!==a)l=`key "${nu(a)}" must match the settings source name "${nu(c.data.source.name)}"`;if(l!==void 0)i.push({file:t,path:`${r}.${nu(a)}`,message:`Invalid marketplace entry was ignored: ${l}`,severity:"warning"}),delete s[a]}return i}function ya(e,t,n){return[...IHe(e,t),...LHe(e,t),...FHe(e,t),...n?.skipMcpServerEntryFilter?[]:NHe(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly})]}function jR(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),Q3.filter((n)=>t.has(n))}function BHe(){return ao(pa(),"managed-settings.json")}function uZ(e){if(Bo()==="wsl"&&e.wslInherits?.()){let t=zR(eu,e.store);if(t.settings)return t;let n=zR(pa(),e.store);return{settings:n.settings,errors:[...t.errors,...n.errors]}}return zR(pa(),e.store)}function zR(e,t){let n=[],r={},o=!1,{settings:s,errors:i}=ou(ao(e,"managed-settings.json"),t,void 0,!0);if(n.push(...i),s&&Object.keys(s).length>0)r=io(r,s,ko),o=!0;let a=ao(e,"managed-settings.d");try{let u=We().readdirSync(a).filter((p)=>(p.isFile()||p.isSymbolicLink())&&p.name.endsWith(".json")&&!p.name.startsWith(".")).map((p)=>p.name).sort();for(let p of u){let{settings:f,errors:m}=ou(ao(a,p),t,void 0,!0);if(n.push(...m),f&&Object.keys(f).length>0)r=io(r,f,ko),o=!0}}catch(u){let p=Me(u);if(p!=="ENOENT"&&p!=="ENOTDIR")ce(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:c,...l}=r;return{settings:o&&Object.keys(l).length>0?r:null,errors:n}}function HHe(e,t){if(rr(e))ce(`Broken symlink or missing file encountered for settings.json at path: ${t}`);else ce(`settings file read failed at ${t}: ${e}`,{level:"error"})}function ou(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{settings:s.settings?Ds(s.settings):null,errors:s.errors};let i=GHe(e,n,r);return t.parsedFiles.set(o,i),{settings:i.settings?Ds(i.settings):null,errors:i.errors}}function dZ(e){if(!e.mdm)return{settings:null,errors:[]};let t=e.mdm();return{settings:Object.keys(t.settings).length>0?t.settings:null,errors:t.errors}}function By(e,t){let n=Ds(e),r=ya(n,t,{skipMcpServerEntryFilter:!0}),o=[],s=UR(pZ(t,o),t).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...jf(s.error,t)]};return{settings:Object.keys(s.data).length>0?s.data:null,errors:[...r,...o]}}function pZ(e,t){return(n)=>{if(t.push({file:e,path:n.path,message:n.message,severity:"warning",...n.statusOnly&&{statusOnly:n.statusOnly},...n.startupFatal&&{startupFatal:n.startupFatal}}),n.statusOnly||n.startupFatal)ce(`${e}: ${n.path}: ${n.message}`,{level:n.startupFatal?"error":"warn"})}}function fZ(e){let t=e?.remote?e.remote():W3();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return By(t,"remote managed settings")}function KHe(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return By(t,"parent managed settings")}function mZ(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=Ds(t),r=ya(n,"SDK inline settings"),o=ga().safeParse(n);if(!o.success)return{settings:null,errors:[...r,...jf(o.error,"SDK inline settings")]};return{settings:o.data,errors:r}}var qHe=2097152;function GHe(e,t,n){try{let r;if(t!==void 0)r=t;else{let{resolvedPath:o}=ap(We(),e);r=Kl(o,qHe)}return WHe(r,e,n)}catch(r){return VHe(r,e)}}function WHe(e,t,n){if(e.trim()==="")return{settings:{},errors:[]};let r=Ds(Wl(e,!1));if(n){let i=ya(r,t,{skipMcpServerEntryFilter:!0}),a=[],c=UR(pZ(t,a),t).safeParse(r);if(!c.success)return{settings:null,errors:[...i,...jf(c.error,t)]};return{settings:c.data,errors:[...i,...a]}}let o=ya(r,t),s=ga().safeParse(r);if(!s.success){let i=jf(s.error,t);return{settings:null,errors:[...o,...i]}}return{settings:s.data,errors:o}}function VHe(e,t){if(HHe(e,t),rr(e))return{settings:null,errors:[]};return{settings:null,errors:[{file:t,path:"",message:`Settings file could not be read: ${e instanceof Error?e.message:String(e)}`,severity:"fatal"}]}}function cZ(e,t){switch(e){case"userSettings":return Or(qt());case"policySettings":case"projectSettings":return Or(t.cwd);case"localSettings":return hZ(t.cwd,t.canonicalGitRoot);case"flagSettings":return t.flagPath?$He(Or(t.flagPath)):Or(t.cwd)}}function hZ(e,t){let n=t?.(e);if(!n)return Or(e);let r=Or(n),o=Or(e);if(r===o)return r;let s;try{s=XHe()}catch{return o}if(r===s)return o;if(!JHe(r))return o;return r}function ZHe(e){return _Z.canonicalRootOwnerUids(e)}class gZ{ownerUidsByRoot=new Map;realHomeDir=void 0;canonicalRootOwnerUids(e){let t=this.ownerUidsByRoot.get(e);if(t!==void 0)return t;let n=YHe(e);return this.ownerUidsByRoot.set(e,n),n}hasCanonicalRootOwnerUids(e){return this.ownerUidsByRoot.has(e)}clearCanonicalRootOwnerUids(){this.ownerUidsByRoot.clear()}normalizedRealHomeDir(){return this.realHomeDir??=QHe(),this.realHomeDir}clearNormalizedRealHomeDir(){this.realHomeDir=void 0}reset(){this.ownerUidsByRoot.clear(),this.realHomeDir=void 0}}var _Z=new gZ;function YHe(e){let t=We(),n=null;try{n=t.lstatSync(ao(e,".claude")).uid}catch(r){if(!rr(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:t.lstatSync(ao(e,".git")).uid,claudeEntryUid:n}}function JHe(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return ce(`localSettings: not canonicalizing the consent store to ${e} — this platform has no uid semantics to verify directory ownership with, so the store stays at the session cwd (canonicalization is POSIX-only)`,{level:"warn"}),!1;let t=typeof process.geteuid==="function"?process.geteuid():process.getuid?.();try{let{rootUid:n,gitEntryUid:r,claudeEntryUid:o}=ZHe(e);if(n===t&&r===t&&(o===null||o===t))return!0;return ce(`localSettings: not canonicalizing the consent store to ${e} — it (uid ${n}), its .git entry (uid ${r}), or its .claude entry (uid ${o??"absent"}) is not owned by the current user (uid ${t}); the store stays at the session cwd (the pre-canonicalization behavior). If you own this repo, chown it (including .git and .claude) or run from a directory you own.`,{level:"warn"}),!1}catch(n){return ce(`localSettings: not canonicalizing the consent store to ${e} — its ownership could not be verified (${n instanceof Error?n.message:String(n)}); the store stays at the session cwd`,{level:"warn"}),!1}}function XHe(){return _Z.normalizedRealHomeDir()}function QHe(){let e=eb(jHe());if(e===null)throw Error("home directory realpath unavailable");return kt(e)}function e2e(e){if(e.coworkPlugins||xn.CLAUDE_CODE_USE_COWORK_PLUGINS)return"cowork_settings.json";return"settings.json"}function $f(e,t){switch(e){case"userSettings":return ao(cZ(e,t),e2e(t));case"projectSettings":case"localSettings":return ao(cZ(e,t),yZ(e));case"policySettings":return BHe();case"flagSettings":return t.flagPath}}function yZ(e){switch(e){case"projectSettings":return ao(".claude","settings.json");case"localSettings":return ao(".claude","settings.local.json")}}function bZ(e){if(hZ(e.cwd,e.canonicalGitRoot)===Or(e.cwd))return;return ao(Or(e.cwd),yZ("localSettings"))}function SZ(e,t){let n=t.store.perSource.get(e);if(n!==void 0)return n;let r=u2e(e,t);return t.store.perSource.set(e,r),r}function t2e(e){return!e||e.parentSettingsBehavior==="merge"}function n2e(e,t){let n={};if(e.allowManagedHooksOnly===!0)n.allowManagedHooksOnly=!0;if(e.disableCommandPluginSources===!0)n.disableCommandPluginSources=!0;if(e.allowManagedMcpServersOnly===!0)n.allowManagedMcpServersOnly=!0;if(e.disableClaudeAiConnectors===!0)n.disableClaudeAiConnectors=!0;if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(e9(e.attribution,e.includeCoAuthoredBy)==="disabled")n.attribution={...n.attribution,commitTrailers:!1};if(e.attribution?.sessionUrl===!1)n.attribution={...n.attribution,sessionUrl:!1};let r=e.strictPluginOnlyCustomization;if(r===!0||Array.isArray(r)&&r.length>0)n.strictPluginOnlyCustomization=r;if(e.deniedMcpServers)n.deniedMcpServers=e.deniedMcpServers;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)n.forceLoginOrgUUID=e.forceLoginOrgUUID;if(t.allowedMcpServers===void 0&&e.allowedMcpServers)n.allowedMcpServers=e.allowedMcpServers;if(t.availableModels===void 0&&e.availableModels)n.availableModels=e.availableModels;if(e.enforceAvailableModels===!0)n.enforceAvailableModels=!0;if(e.permissions){let o=Ry(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable")o.disableBypassPermissionsMode="disable";if(t.allowManagedPermissionRulesOnly!==!0){let{allow:s,additionalDirectories:i}=e.permissions;if(s&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)o.allow=s;if(i)o.additionalDirectories=i}if(Object.keys(o).length>0)n.permissions=o}if(e.sandbox){let{network:o,filesystem:s,credentials:i}=e.sandbox,a={};if(e.sandbox.enabled===!0)a.enabled=!0;if(e.sandbox.failIfUnavailable===!0)a.failIfUnavailable=!0;if(e.sandbox.allowUnsandboxedCommands===!1)a.allowUnsandboxedCommands=!1;if(e.sandbox.autoAllowBashIfSandboxed===!1)a.autoAllowBashIfSandboxed=!1;if(o){let c=Ry(o,["deniedDomains"]);if(o.allowManagedDomainsOnly===!0)c.allowManagedDomainsOnly=!0;if(o.strictAllowlist===!0)c.strictAllowlist=!0;if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&o.allowedDomains)c.allowedDomains=o.allowedDomains;if(Object.keys(c).length>0)a.network=c}if(s){let c=Ry(s,["denyRead","denyWrite"]);if(s.allowManagedReadPathsOnly===!0)c.allowManagedReadPathsOnly=!0;if(s.disabled===!1)c.disabled=!1;if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&s.allowRead)c.allowRead=s.allowRead;if(Object.keys(c).length>0)a.filesystem=c}if(i){let c=(i.files??[]).map((p)=>p.mode==="deny"?{path:p.path,mode:"deny"}:{path:p.path,mode:"mask",injectHosts:[]}),l=(i.envVars??[]).filter((p)=>p.mode==="deny").map((p)=>({name:p.name,mode:"deny"})),u={...c.length>0&&{files:c},...l.length>0&&{envVars:l}};if(i.allowPlaintextInject===!1)u.allowPlaintextInject=!1;if(i.sigv4){let p={};for(let f of["streaming","presigned","sigv4a"])if(i.sigv4[f]==="deny")p[f]="deny";u.sigv4=p}{let p=Ql,f=Ni((i.awsPairs??[]).flatMap((m)=>[m.accessKeyIdVar,m.secretAccessKeyVar,...m.sessionTokenVar!==void 0?[m.sessionTokenVar]:[]]).filter((m)=>p.includes(m)));if(f.length>0)u.awsPairs=f.map((m,h)=>({accessKeyIdVar:m,secretAccessKeyVar:`${X3}${h+1}_`}))}if(Object.keys(u).length>0)a.credentials=u}if(Object.keys(a).length>0)n.sandbox=a}return n}var r2e=new Set([...[...mR].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...hR,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL"]);function o2e(e,t){if(!t||!e)return null;let n={};if(e.model!==void 0)n.model=e.model;if(e.availableModels!==void 0)n.availableModels=e.availableModels;if(e.enforceAvailableModels!==void 0)n.enforceAvailableModels=e.enforceAvailableModels;if(e.fallbackModel!==void 0)n.fallbackModel=e.fallbackModel;return Object.keys(n).length>0?n:null}function $y(e){if(delete e.model,delete e.fallbackModel,delete e.modelOverrides,e.env){let t={};for(let[n,r]of Object.entries(e.env))if(!r2e.has(n.toUpperCase()))t[n]=r;e.env=t}}function xZ(e){if(e.helper?.())return"helper";if(fZ(e).settings)return"remote";if(dZ(e).settings)return Bo()==="macos"?"plist":"hklm";if((e.file?.()??uZ(e)).settings)return"file";let t=FR(e);if(t.parentSlice||t.hostModelOverlay)return"parent";let n=e.hkcu?.();return n&&Object.keys(n.settings).length>0?"hkcu":null}function FR(e){let t=[],{settings:n,errors:r}=fZ(e);t.push(...r);let{settings:o,errors:s}=dZ(e);t.push(...s);let{settings:i,errors:a}=e.file?.()??uZ(e);t.push(...a);let{settings:c,errors:l}=KHe(e);t.push(...l);let u=[n,o,i].filter((b)=>b!==null),p=u[0]??null,f={remote:n!==null,mdm:o!==null,file:i!==null},m={allowManagedPermissionRulesOnly:u.some((b)=>b.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:u[0]?.forceLoginOrgUUID,allowedMcpServers:u[0]?.allowedMcpServers,availableModels:u[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:u.some((b)=>b.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:u.some((b)=>b.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},h=c&&t2e(p)?n2e(c,m):null,g=h&&Object.keys(h).length>0?h:null,y=o2e(c,e.hostManagedProvider);return{tiers:u,admin:p,parentSlice:g,hostModelOverlay:y,errors:t,present:f}}var s2e=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];function i2e(e){return K3.some((t)=>e.startsWith(t))||H3.includes(e)}function a2e(e,t,n){let r=new Map,o=new Map,s=!1;for(let[i,a]of e.entries()){let c=new Set,l=t?.[i]===!0;for(let[u,p]of Object.entries(a??{})){let f=u.toUpperCase(),m=i2e(f);if(m&&p.trim()==="")continue;if(m&&s)continue;if(m&&i>0&&t?.[i]===!0)continue;let h=r.get(f);if(h!==void 0){if(c.has(f))o.set(u,p);else if(!o.has(u))o.set(u,h);continue}if(i>0&&n?.[i]?.has(f))continue;if(o.set(u,p),c.add(f),r.set(f,p),m)l=!0}if(l)s=!0}return Object.fromEntries(o)}var c2e="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function lZ(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==c2e)t[n]=r;return t}function l2e(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function EZ(e){let t=e.helper?.(),n=e.helperWarnings?.()??[];if(t){e.store.lastPolicyEnvComposition=null;let h=e.hostManagedProvider?{...t}:t;if(e.hostManagedProvider)$y(h);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&t.availableModels!==void 0?t.modelOverrides:void 0};let g=e.store.policy.helperBaseStatusNotices??=FR(e).errors.filter((y)=>y.statusOnly);return{settings:h,errors:[...g,...n]}}let{tiers:r,admin:o,parentSlice:s,hostModelOverlay:i,errors:a,present:c}=FR(e);if(a.push(...n),!o&&!s){e.store.lastPolicyEnvComposition=null,e.store.policy.pairedModelOverrides={value:void 0};let h=e.hkcu?.();if(h&&Object.keys(h.settings).length>0){let g=e.hostManagedProvider?{...h.settings}:h.settings;if(e.hostManagedProvider){if($y(g),i)Object.assign(g,i)}return{settings:g,errors:[...a,...h.errors]}}if(i)return{settings:{...i},errors:[...a,...h?.errors??[]]};return{settings:null,errors:[...a,...h?.errors??[]]}}let l=io({},s??{},o??{},ko);if(r.some((h)=>h.forceRemoteSettingsRefresh===!0))l.forceRemoteSettingsRefresh=!0;let u=xn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,p=l.env;if(!u){let h=a2e(r.map((g)=>g.env),r.map((g)=>(g.otelHeadersHelper??"").trim()!==""),r.map((g)=>{let y=new Set;for(let b of s2e){let x=g[b];if(typeof x==="string"&&x.trim()!=="")for(let E of q3[b])y.add(E)}return y.size>0?y:void 0}));if(Object.keys(h).length>0)l.env=h;else delete l.env}if(l.env){let h=lZ(l.env);if(h&&Object.keys(h).length>0)l.env=h;else delete l.env}if(e.hostManagedProvider){if($y(l),i)Object.assign(l,i)}let f={env:lZ(p)};if(e.hostManagedProvider)$y(f);let m=!u&&!l2e(l.env,f.env);return e.store.lastPolicyEnvComposition={unionOptedOut:u,unionChangedEnv:m,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:np(r,(h)=>Object.keys(h.env??{}).length>0)},e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&o?.availableModels!==void 0&&o.modelOverrides!==void 0&&i?.availableModels===void 0?o.modelOverrides:void 0},{settings:l,errors:a}}function u2e(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return EZ(t).settings;let r=$f(e,t),{settings:o}=r?ou(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=mZ(t);if(s)return io(o||{},s,ko)}if(e==="localSettings"&&n){let s=bZ(t);if(s){let{settings:i}=ou(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),io(i,o||{},ko)}}return o}function d2e(e,t){return{...e,...t}}function ko(e,t,n){if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Ni([...e,...t])}if(n==="extraKnownMarketplaces"&&fa(e)&&fa(t))return d2e(e,t);return}function p2e(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();Cf("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=io(r,n,ko);let o=[],s=new Set,i=new Set,a=(l)=>{for(let u of l){let p=`${u.file}:${u.path}:${u.message}`;if(!s.has(p))s.add(p),o.push(u)}},c=null;for(let l of jR(e)){if(l==="policySettings"){let{settings:p,errors:f}=EZ(e);if(c=p,p)r=io(r,p,ko);a(f);continue}if(l==="localSettings"){let p=bZ(e);if(p&&!i.has(Or(p))){i.add(Or(p));let{settings:f,errors:m}=ou(p,e.store);if(a(m),f)e.onLegacyLocalSettingsRead?.("cascade"),r=io(r,f,ko)}}let u=$f(l,e);if(u){let p=Or(u),f=l==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(p)||f){i.add(p);let{settings:m,errors:h}=ou(u,e.store,l==="flagSettings"?e.flagExpectedContent:void 0);if(a(h),m)r=io(r,m,ko)}}if(l==="flagSettings"){let{settings:p,errors:f}=mZ(e);if(a(f),p)r=io(r,p,ko)}}if(c){if(c.availableModels!==void 0)r.availableModels=[...c.availableModels];if(c.enforceAvailableModels!==void 0)r.enforceAvailableModels=c.enforceAvailableModels}return Cf("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:i.size,error_count:o.length}),{settings:r,errors:o}}finally{e.store.isLoadingFromDisk=!1}}function f2e(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=p2e(e);return e.store.mergedSettings=n,n}function m2e(e){let{settings:t}=f2e(e);return t||{}}function vZ(e){e.store.invalidateAll();let t=[];for(let n of jR(e)){let r=SZ(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:m2e(e),sources:t}}function wZ(e,t){let n=jR(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(SZ(o,t)?.[e]!==void 0)return o}return null}import{execFile as h2e}from"child_process";import{existsSync as g2e}from"fs";class TZ{promise=null;start(){if(this.promise)return;this.promise=$R()}reset(){this.promise=null}}var _2e=new TZ;function Bf(e,t){return new Promise((n)=>{try{h2e(e,t,{encoding:"utf-8",timeout:o9,windowsHide:!0},(r,o)=>{n({stdout:o??"",code:r?1:0})})}catch{n({stdout:"",code:1})}})}function $R(){return(async()=>{if(process.platform==="darwin"){let e=s9(),n=(await Promise.all(e.map(async({path:r,label:o})=>{if(!g2e(r))return{stdout:"",label:o,ok:!1};let{stdout:s,code:i}=await Bf(n9,[...r9,r]);return{stdout:s,label:o,ok:i===0&&!!s}}))).find((r)=>r.ok);return{plistStdouts:n?[{stdout:n.stdout,label:n.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[n,r]=await Promise.all([Bf(t,["query",Df,"/v",ni]),Bf(t,["query",Lf,"/v",ni])]);return{plistStdouts:null,hklmStdout:n.code===0?n.stdout:null,hkcuStdout:r.code===0?r.stdout:null}}if(Dy()){let[e,t]=await Promise.all([Bf(bR,["query",Df,"/v",ni]),Bf(bR,["query",Lf,"/v",ni])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function AZ(){return _2e.promise}var oi=Object.freeze({settings:{},errors:[]});class OZ{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),n=AZ()??$R(),{mdm:r,hkcu:o,wslInherits:s}=await b2e(await n,e);this.replace(r,o,s);let i=Date.now()-t;if(ce(`MDM settings load completed in ${i}ms`),Object.keys(r.settings).length>0){ce(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{Cf("info","mdm_settings_loaded",{duration_ms:i,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})()}replace(e,t,n){this.mdm=e,this.hkcu=t,this.wslInherits=n}reset(){this.mdm=null,this.hkcu=null,this.wslInherits=!1,this.loadPromise=null}}var iu=new OZ;function y2e(e){iu.startLoad(e)}async function PZ(){if(!iu.loadPromise)y2e();await iu.loadPromise}function IZ(){return iu.mdm??oi}function DZ(){return iu.hkcu??oi}function LZ(){return iu.wslInherits}function BR(e,t){let n=Wl(e,!1);if(!n||typeof n!=="object")return{settings:{},errors:[]};let{settings:r,errors:o}=By(n,t);return{settings:r??{},errors:o}}function kZ(e,t="Settings"){let n=e.split(/\r?\n/),r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^\\s+${r}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let s of n){let i=s.match(o);if(i&&i[1])return i[1].trimEnd()}return null}async function b2e(e,t){let n=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:a,label:c}=e.plistStdouts[0],l=BR(a,c),{wslInheritsWindowsSettings:u,...p}=l.settings;if(Object.keys(p).length>0)return{mdm:l,hkcu:oi,wslInherits:!1};n.push(...l.errors)}let r=null;if(e.hklmStdout){let a=kZ(e.hklmStdout);if(a)r=BR(a,`Registry: ${Df}\\${ni}`)}if(r)n.push(...r.errors);let o=n.length>0?{settings:{},errors:n}:oi,s=Dy(),i=!1;if(s){if(i=r?.settings.wslInheritsWindowsSettings===!0||await x2e(t),!i)return{mdm:o,hkcu:oi,wslInherits:!1}}if(r){let{wslInheritsWindowsSettings:a,...c}=r.settings;if(Object.keys(c).length>0)return{mdm:r,hkcu:oi,wslInherits:i}}if(await S2e(i,t))return{mdm:o,hkcu:oi,wslInherits:i};if(e.hkcuStdout){let a=kZ(e.hkcuStdout);if(a){let c=BR(a,`Registry: ${Lf}\\${ni}`);if(!s||c.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:l,...u}=c.settings;return{mdm:o,hkcu:{settings:u,errors:c.errors},wslInherits:i}}if(c.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:c.errors},wslInherits:i}}}return{mdm:o,hkcu:oi,wslInherits:i}}async function MZ(e,t){if(t!==void 0)return(await N6(e)).content;return Kl(e)}async function NZ(e,t){if(t!==void 0)return await We().readdir(e);return We().readdirSync(e)}async function S2e(e,t){if(e&&await RZ(eu,t))return!0;return RZ(pa(),t)}async function CZ(e,t){let n=Ds(Wl(await MZ(e,t),!1));if(!n||typeof n!=="object")return!1;ya(n,e);let{wslInheritsWindowsSettings:r,...o}=n;return Object.keys(o).length>0}async function x2e(e){async function t(n){try{let r=Wl(await MZ(n,e),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(await t(su(eu,"managed-settings.json")))return!0;try{let n=su(eu,"managed-settings.d");for(let r of await NZ(n,e))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&await t(su(n,r.name)))return!0}catch{}return!1}async function RZ(e,t){try{if(await CZ(su(e,"managed-settings.json"),t))return!0}catch{}try{let n=su(e,"managed-settings.d"),r=await NZ(n,t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(await CZ(su(n,o.name),t))return!0}catch{}}}catch{}return!1}var v2e={user:"userSettings",project:"projectSettings",local:"localSettings"},UZ={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},w2e=["user","project","local"],T2e=new Set(["bypassPermissions","auto","acceptEdits"]),A2e=new Set(["project"]);function k2e(e){let t=e.effective.permissions?.defaultMode;if(!t||!T2e.has(t))return e.effective;for(let n=e.sources.length-1;n>=0;n--){let r=e.sources[n];if(r.settings.permissions?.defaultMode!==void 0){if(A2e.has(r.source)){let{defaultMode:o,...s}=e.effective.permissions??{};return{...e.effective,permissions:s}}return e.effective}}return e.effective}async function zZ(e={}){await PZ();let t={store:new Qh,cwd:E2e(e.cwd??We().cwd()),allowedSources:(e.settingSources??w2e).map((a)=>v2e[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:IZ,hkcu:DZ,wslInherits:LZ,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=vZ(t),o=xZ(t)??void 0,s=r.map(({source:a,settings:c})=>({source:UZ[a],settings:c,path:a==="policySettings"?void 0:$f(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let c=wZ(a,t);if(c)i[a]={source:UZ[c],path:c==="policySettings"?void 0:$f(c,t),...c==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function CRt(e){return zZ(e)}var U2e=["enabledPlugins","extraKnownMarketplaces"];function FZ(e){let t;try{t=pt(ml(e.toString("utf8")))}catch{return e}if(!jZ(t))return e;let n=!1;for(let o of U2e)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(jZ(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?xe(t):e}function jZ(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function z2e(e,t){if(!e)return;let n=e;try{let r=pt(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=xe(r)}catch{}await KZ(t,n,{mode:384})}function F2e(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=DK(IK);return new Promise((t)=>{C2e("security",["find-generic-password","-a",LK(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function WZ(e,t,n,r,o=60000,s){if(!Xe(t))return;let i=Pr(n),a=await fr(e.load({projectKey:i,sessionId:t}),o,`SessionStore.load() timed out after ${o}ms for session ${t}`);if(!a||a.length===0)return;let c=on(L2e(),`claude-resume-${WR()}`);try{let l=on(c,"projects",i);await HR(l,{recursive:!0,mode:448});let u=on(l,`${t}.jsonl`);await Bp(u,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??on(KR(),".claude"),m;try{m=await HZ(on(f,".credentials.json"),"utf-8")}catch(b){if(!rr(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await F2e()??m;await z2e(m,on(c,".credentials.json"));let h=PK(xn.CLAUDE_CONFIG_DIR),g=on(p??KR(),".claude.json");await u_(g,on(c,".claude.json"),void 0,wk(s,g,h.globalConfig,jn.globalConfig()));let y=on(f,"settings.json");if(await u_(y,on(c,"settings.json"),FZ,wk(s,y,h.userSettings,jn.userSettings())),await u_(on(f,"cowork_settings.json"),on(c,"cowork_settings.json"),FZ),e.listSubkeys)await j2e(e,{projectKey:i,sessionId:t},on(l,t),o);return c}catch(l){throw await Hy(c),l}}async function j2e(e,t,n,r){let o=await fr(e.listSubkeys({projectKey:t.projectKey,sessionId:t.sessionId}),r,`SessionStore.listSubkeys() timed out after ${r}ms for session ${t.sessionId}`);for(let s of o){let i=Hf(n,s+".jsonl");if(!s||qZ(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+VR)){ce(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await fr(e.load({projectKey:t.projectKey,sessionId:t.sessionId,subpath:s}),r,`SessionStore.load() timed out after ${r}ms for session ${t.sessionId} subpath ${s}`);if(!a||a.length===0)continue;let c=[],l=[];for(let u of a)if(GR(u))c.push(u);else l.push(u);if(l.length>0)await HR(qR(i),{recursive:!0}),await Bp(i,l);if(c.length>0){let u=c.at(-1),p=Hf(n,s+".meta.json");await HR(qR(p),{recursive:!0});let{type:f,...m}=u;await KZ(p,xe(m),{mode:384})}}}function ZR(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o}=t,{systemPrompt:s,settings:i,managedSettings:a,settingSources:c,sandbox:l,...u}=e??{},p,f,m;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.231";let{abortController:h=lu(),additionalDirectories:g=[],agent:y,agents:b,allowedTools:x=[],betas:E,canUseTool:k,continue:R,cwd:V,debug:K,debugFile:Q,disallowedTools:X=[],tools:me,env:Ce,executable:tt=Ta()?"bun":"node",executableArgs:ye=[],extraArgs:Ve={},fallbackModel:fn,enableFileCheckpointing:Z,toolConfig:pr,forkSession:mn,hooks:lt,includeHookEvents:Gn,includePartialMessages:yt,forwardSubagentText:te,onElicitation:Y,onUserDialog:J,supportedDialogKinds:Le,persistSession:be,sessionStore:Ze,sessionStoreFlush:Wn,thinking:Qe,effort:Ir,maxThinkingTokens:Co,maxTurns:Ot,maxBudgetUsd:Kf,taskBudget:e5,mcpServers:JR,model:t5,outputFormat:XR,permissionMode:n5,allowDangerouslySkipPermissions:r5=!1,permissionPromptToolName:o5,plugins:s5,getOAuthToken:QR,getHostAuthToken:eO,workload:tO,resume:nO,resumeSessionAt:i5,resumeDropsTurn:a5,sessionId:c5,skills:rO,stderr:l5,strictMcpConfig:u5}=u,oO=n5??(e?.resolvePermissionModeInCli?void 0:"default");if(Ze&&be===!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(Le!==void 0&&Le.length>0&&!J)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if(Ze&&R&&!nO&&!Ze.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(Ze&&Z)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(Ze&&u.spawnClaudeCodeProcess)ce("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"});MK(!!k,oO??"default",x);let qy=u.pathToClaudeCodeExecutable;if(!qy){let Vn=N2e(import.meta.url),Dr=D2e(Vn),si=s1((ba)=>Dr.resolve(ba));if(!si)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.`);qy=si}let sO=XR?.type==="json_schema"?XR.schema:void 0,hn=Ce?{...Ce}:{...process.env};if(!hn.CLAUDE_CODE_ENTRYPOINT)hn.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!hn.CLAUDE_AGENT_SDK_VERSION)hn.CLAUDE_AGENT_SDK_VERSION="0.3.231";if(Z)hn.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(QR)hn.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(eO)hn.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(pr?.askUserQuestion?.previewFormat)hn.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=pr.askUserQuestion.previewFormat;let Gy={};if(Ky.propagation.inject(Ky.context.active(),Gy),"traceparent"in Gy){for(let Vn of["TRACEPARENT","TRACESTATE"])if(!(Vn in(Ce??{})))delete hn[Vn]}for(let[Vn,Dr]of Object.entries(Gy)){let si=Vn.toUpperCase();if(!(si in(Ce??{})))hn[si]=Dr}let iO={},aO=new Map;if(JR)for(let[Vn,Dr]of Object.entries(JR))if(Dr.type==="sdk"&&Dr.instance)aO.set(Vn,Dr.instance);else iO[Vn]=Dr;let au;if(Qe)switch(Qe.type){case"adaptive":au={type:"adaptive",display:Qe.display};break;case"enabled":au={type:"enabled",budgetTokens:Qe.budgetTokens,display:Qe.display};break;case"disabled":au={type:"disabled"};break}else if(Co!==void 0)au=Co===0?{type:"disabled"}:{type:"enabled",budgetTokens:Co};if(r){if(hn.CLAUDE_CONFIG_DIR=r,process.platform==="win32")hn.CLAUDE_SECURESTORAGE_CONFIG_DIR=Ce?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??Ce?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let cO=new fA({abortController:h,additionalDirectories:g,agent:y,betas:E,cwd:V,debug:K,debugFile:Q,executable:tt,executableArgs:ye,extraArgs:tO?{...Ve,workload:tO}:Ve,pathToClaudeCodeExecutable:qy,env:hn,forkSession:mn,stderr:l5,thinkingConfig:au,effort:Ir,maxTurns:Ot,maxBudgetUsd:Kf,taskBudget:e5,model:t5,fallbackModel:fn,jsonSchema:sO,permissionMode:oO,allowDangerouslySkipPermissions:r5,permissionPromptToolName:o5,continueConversation:Ze?void 0:R,resume:nO,resumeSessionAt:i5,resumeDropsTurn:a5,sessionId:c5,settings:typeof i==="object"?xe(i):i,managedSettings:a?xe(a):void 0,settingSources:c,skills:rO,allowedTools:x,disallowedTools:X,tools:me,mcpServers:iO,strictMcpConfig:u5,canUseTool:!!k,hooks:!!lt,includeHookEvents:Gn,includePartialMessages:yt,persistSession:be,sessionMirror:!!Ze,plugins:s5,sandbox:l,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),d5={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:b,title:u.title,skills:rO,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:te,supportedDialogKinds:Le},Wy=new jg(cO,n,k,lt,h,aO,sO,d5,Y,QR,eO,J);if(Ze){let Vn=()=>on(hn.CLAUDE_CONFIG_DIR??on(KR(),".claude"),"projects"),Dr=Wn==="eager",si=new _A(async(ba,Vy)=>{let cu=BZ(ba,Vn());if(cu)await Ze.append(cu,Vy);else ce(`[SessionStore] dropping mirror frame: filePath ${ba} is not under ${Vn()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(ba,Vy)=>{let cu=BZ(ba,Vn());if(cu)Wy.reportMirrorError(cu,Vy.message)},maxPendingEntries:Dr?0:$g,maxPendingBytes:Dr?0:ll});Wy.setTranscriptMirrorBatcher(si)}return{queryInstance:Wy,transport:cO,abortController:h,processEnv:hn}}function YR(e,t,n,r){if(typeof n==="string")t.write(xe({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
152
152
  `);else e.streamInput(n).catch((o)=>r.abort(o))}var $2e=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function Hy(e){for(let t=0;;t++)try{return await I2e(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!$2e.has(Me(n)??""))return;await Oo((t+1)*100)}}function B2e(e,t){e.waitForExit().catch(()=>{}).finally(()=>Hy(t))}function RRt({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return H2e(e,t);let{queryInstance:n,transport:r,abortController:o}=ZR(t,{isSingleUserTurn:typeof e==="string"});return YR(n,r,e,o),n}function H2e(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s}=ZR({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),i=Hf(t.cwd??"."),a=t.sessionStore,c=t.loadTimeoutMs??60000,l=t.resume;return(async()=>{if(!l)l=(await fr(a.listSessions(Pr(i)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((f,m)=>m.mtime-f.mtime)[0]?.sessionId;if(!l)return;return WZ(a,l,i,t.env,t.loadTimeoutMs)})().then((p)=>{if(p){r.updateResume(l);let f={CLAUDE_CONFIG_DIR:p};if(process.platform==="win32"){let m=t.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??t.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";f.CLAUDE_SECURESTORAGE_CONFIG_DIR=m,s.CLAUDE_SECURESTORAGE_CONFIG_DIR=m}r.updateEnv(f),s.CLAUDE_CONFIG_DIR=p,n.addCleanupCallback(()=>B2e(r,p))}if(!n.isClosed())r.spawn()}).catch((p)=>{let f=Er(p);r.spawnAbort(f),n.setError(f)}),YR(n,r,e,o),n}async function ORt({options:e,initializeTimeoutMs:t=60000}={}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=Hf(e.cwd??".");if(!r){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let c=e.loadTimeoutMs??60000;r=(await fr(e.sessionStore.listSessions(Pr(a)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((u,p)=>p.mtime-u.mtime)[0]?.sessionId}if(r)n=await WZ(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let m=function(){if(f)return;f=!0,u.close()},a=ZR(n&&r&&r!==e?.resume?{...e,resume:r}:e,{isSingleUserTurn:!1,resumeConfigDir:n});o=a.queryInstance;let{transport:c,abortController:l}=a;s=c;let u=a.queryInstance;if(n){let h=n;u.addCleanupCallback(()=>{i=c.waitForExit().catch(()=>{}).then(()=>Hy(h))})}let p=`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`;await fr(u.initializationResult(),t,p).catch((h)=>{throw HL(h,p)?cn(h,{telemetryMessage:`Subprocess initialization did not complete within ${t}ms`,errorClass:"initialize_timeout"}):h});let f=!1;return{query(h){if(f)throw Error("WarmQuery.query() can only be called once");f=!0;try{YR(u,c,h,l)}catch(g){throw u.close(),g}if(typeof h==="string")u.setIsSingleUserTurn(!0);return u},close:m,async[Symbol.asyncDispose](){f=!0,u.close(),await i}}}catch(a){if(o?.close(),n&&!i){let c=s;i=(c?c.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>Hy(n))}throw await i,a}}async function PRt(e,t){if(t?.sessionStore)return V2e(t.sessionStore,e,t);return J2(e,t)}async function IRt(e){if(e?.sessionStore)return q2e(e.sessionStore,e);return tK(e)}async function DRt(e,t){if(t?.sessionStore)return Z2e(t.sessionStore,e,t);return nK(e,t)}async function LRt(e,t,n){if(n?.sessionStore)return Y2e(n.sessionStore,e,t,n.dir);return aK(e,t,n)}async function MRt(e,t,n){if(n?.sessionStore)return J2e(n.sessionStore,e,t,n.dir);return cK(e,t,n)}async function NRt(e,t){if(!Xe(e))throw new qe(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=Pr(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return lK(e,t)}async function URt(e,t){if(t?.sessionStore)return X2e(t.sessionStore,e,t);return fK(e,t)}async function zRt(e,t,n,r){if(!Xe(e))throw new qe(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=await js(e,n?.dir,$n(r));if(!o)throw Error(`Session ${e} not found`);let s=Pr(n?.dir),i=n?.batchSize&&n.batchSize>0?n.batchSize:$g,a=r===void 0?void 0:bl(qR(o.filePath),zn),c=r!==void 0&&a!==void 0?{backend:r,projectKey:a}:void 0;if(c!==void 0)await Ek(c.backend,jn.transcript(c.projectKey,e),{projectKey:s,sessionId:e},t,i);else await $Z(o.filePath,{projectKey:s,sessionId:e},t,i);if(n?.includeSubagents===!1)return;if(c!==void 0){let p=await AK(c.backend,c.projectKey,e),f=await kK(c.backend,c.projectKey,e,p);for(let m of p){let h={projectKey:s,sessionId:e,subpath:l_(m)};await Ek(c.backend,m.kind==="agent"?jn.transcript(c.projectKey,e,m.agentId,m.agentRelPath):jn.journal(c.projectKey,e,m.agentRelPath),h,t,i);let g=f.get(h.subpath),y;if(g!==void 0)try{y=pt(g)}catch(b){ce(`importSessionToStore: skipping unreadable sidecar for ${h.subpath}: ${b}`)}if(y!==void 0)await t.append(h,[{type:"agent_metadata",...y}])}return}let l=o.filePath.replace(/\.jsonl$/,""),u=on(l,"subagents");for(let p of await K2e(u)){let f=GZ(l,p).split(VR);f[f.length-1]=f.at(-1).replace(/\.jsonl$/,"");let m={projectKey:s,sessionId:e,subpath:f.join("/")};await $Z(p,m,t,i);let h=p.replace(/\.jsonl$/,".meta.json"),g;try{g=pt(await HZ(h,"utf8"))}catch(y){if(!rr(y))ce(`importSessionToStore: skipping unreadable sidecar ${h}: ${y}`)}if(g!==void 0)await t.append(m,[{type:"agent_metadata",...g}])}}async function $Z(e,t,n,r){let o=M2e({input:R2e(e,{encoding:"utf8"}),crlfDelay:1/0}),s=[],i=0;for await(let a of o){if(!a)continue;try{s.push(pt(a))}catch(c){ce(`importSessionToStore: skipping unparseable line in ${e}: ${c}`);continue}if(i+=a.length,s.length>=r||i>=ll)await n.append(t,s),s=[],i=0}if(s.length>0)await n.append(t,s)}async function K2e(e){let t=[];async function n(r){let o;try{o=await P2e(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=on(r,s.name);if(s.isDirectory())await n(i);else if(s.isFile()&&s.name.endsWith(".jsonl"))t.push(i)}}return await n(e),t}async function FRt(e,t){if(t?.sessionStore)return Q2e(t.sessionStore,e,t.dir);return EK(e,t)}async function jRt(e,t,n){if(n?.sessionStore)return eKe(n.sessionStore,e,t,n);return vK(e,t,n)}function VZ(e){let t=Hf(e??"."),n;try{n=O2e(t)}catch{n=t}return kt(n)}function Pr(e){return Zo(VZ(e))}function ZZ(e){return e.map((t)=>xe(t)).join(`
153
153
  `)+`
154
154
  `}function YZ(e,t,n){if(t!==void 0&&t>0)return e.slice(n,n+t);if(n>0)return e.slice(n);return e}function GR(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}async function q2e(e,t){let n=VZ(t.dir),r=Zo(n),o=t.offset??0,s=t.limit;if(e.listSessionSummaries)return G2e(e,r,n,t.dir,s,o);if(!e.listSessions)throw Error("sessionStore.listSessions is not implemented -- cannot list sessions. Provide a store with a listSessions() method.");let a=(await e.listSessions(r)).slice().sort((l,u)=>u.mtime-l.mtime),c=YZ(a,s,o);return JZ(e,c,t.dir,n)}async function G2e(e,t,n,r,o,s){let i=await e.listSessionSummaries(t),a=e.listSessions?new Map((await e.listSessions(t)).map((p)=>[p.sessionId,p])):void 0,c=[];for(let p of i){let f=a?.get(p.sessionId);if(a&&!f)continue;let m=f!==void 0&&p.mtime<f.mtime;c.push({sessionId:p.sessionId,mtime:m?f.mtime:p.mtime,info:m?void 0:CO(p,n)})}if(a){let p=new Set(i.map((f)=>f.sessionId));for(let[f,m]of a)if(!p.has(f))c.push({sessionId:f,mtime:m.mtime})}else ce("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");c.sort((p,f)=>f.mtime-p.mtime);let l=YZ(c,o,s),u=l.filter((p)=>p.info===void 0);if(u.length>0){let p=await JZ(e,u,r,n),f=new Map(p.map((m)=>[m.sessionId,m]));for(let m of l)if(m.info===void 0)m.info=f.get(m.sessionId)??null}return l.flatMap((p)=>p.info?[p.info]:[])}async function JZ(e,t,n,r){return(await Promise.allSettled(t.map(async(s)=>{let i=await QZ(e,s.sessionId,n);if(!i)return null;let a=vl(s.sessionId,XZ(i,s.mtime),r);return a?{...a,lastModified:s.mtime}:null}))).flatMap((s,i)=>{let a=t[i];if(s.status==="fulfilled")return s.value?[s.value]:[];return[{sessionId:a.sessionId,summary:"",lastModified:a.mtime}]})}function XZ(e,t){let n=Buffer.from(e,"utf-8"),r=n.length,o=n.subarray(0,lr).toString("utf-8"),s=r>lr?n.subarray(r-lr).toString("utf-8"):o;return{mtime:t,size:r,head:o,tail:s}}function W2e(e){let t=e.trimEnd(),n=t.slice(t.lastIndexOf(`