@anthropic-ai/claude-agent-sdk 0.3.248 → 0.3.250

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.248
4
+ // Version: 0.3.250
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -158,7 +158,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
158
158
  `+"\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
159
159
  `+"\t".repeat(t))}};var IJ;(function(e){e.DEFAULT={allowTrailingComma:!1}})(IJ||(IJ={}));var DJ;(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"})(DJ||(DJ={}));var LJ;(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"})(LJ||(LJ={}));var MJ;(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"})(MJ||(MJ={}));var Ju=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,UJ=new Set,yI=typeof process==="object"&&!!process?process:{},FJ=(e,t,n,r)=>{typeof yI.emitWarning==="function"?yI.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},SS=globalThis.AbortController,NJ=globalThis.AbortSignal;if(typeof SS>"u"){NJ=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},SS=class{constructor(){t()}signal=new NJ;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=yI.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{if(!e)return;e=!1,FJ("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 O3e=(e)=>!UJ.has(e),$Ft=Symbol("type"),Ki=(e)=>e&&e===Math.floor(e)&&e>0&&isFinite(e),jJ=(e)=>!Ki(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?Jm:null;class Jm extends Array{constructor(e){super(e);this.fill(0)}}class Xu{heap;length;static#e=!1;static create(e){let t=jJ(e);if(!t)return[];Xu.#e=!0;let n=new Xu(e,t);return Xu.#e=!1,n}constructor(e,t){if(!Xu.#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 ES{#e;#t;#n;#r;#i;#c;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#l;#u;#a;#s;#p;#d;#f;#h;#g;#m;#S;#E;#_;#x;#w;#b;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#_,sizes:e.#S,keyMap:e.#u,keyList:e.#a,valList:e.#s,next:e.#p,prev:e.#d,get head(){return e.#f},get tail(){return e.#h},free:e.#g,isBackgroundFetch:(t)=>e.#y(t),backgroundFetch:(t,n,r,o)=>e.#U(t,n,r,o),moveToTail:(t)=>e.#L(t),indexes:(t)=>e.#R(t),rindexes:(t)=>e.#O(t),isStale:(t)=>e.#v(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#l}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#c}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:S,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:v,ignoreFetchAbort:A}=e;if(t!==0&&!Ki(t))throw TypeError("max option must be a nonnegative integer");let U=t?jJ(t):Array;if(!U)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.#c=y,g!==void 0&&typeof g!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#i=g,this.#w=!!g,this.#u=new Map,this.#a=Array(t).fill(void 0),this.#s=Array(t).fill(void 0),this.#p=new U(t),this.#d=new U(t),this.#f=0,this.#h=0,this.#g=Xu.create(t),this.#o=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.#x=!!this.#n,this.#b=!!this.#r,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!v,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#t!==0){if(!Ki(this.#t))throw TypeError("maxSize must be a positive integer if specified")}if(!Ki(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#D()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!i,this.ttlResolution=Ki(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Ki(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#A()}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(O3e("LRU_CACHE_UNBOUNDED"))UJ.add("LRU_CACHE_UNBOUNDED"),FJ("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",ES)}}getRemainingTTL(e){return this.#u.has(e)?1/0:0}#A(){let e=new Jm(this.#e),t=new Jm(this.#e);this.#_=e,this.#E=t,this.#I=(o,s,i=Ju.now())=>{if(t[o]=s!==0?i:0,e[o]=s,s!==0&&this.ttlAutopurge){let a=setTimeout(()=>{if(this.#v(o))this.#P(this.#a[o],"expire")},s+1);if(a.unref)a.unref()}},this.#C=(o)=>{t[o]=e[o]!==0?Ju.now():0},this.#T=(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=Ju.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.#v=(o)=>{let s=t[o],i=e[o];return!!i&&!!s&&(n||r())-s>i}}#C=()=>{};#T=()=>{};#I=()=>{};#v=()=>!1;#D(){let e=new Jm(this.#e);this.#l=0,this.#S=e,this.#k=(t)=>{this.#l-=e[t],e[t]=0},this.#F=(t,n,r,o)=>{if(this.#y(n))return 0;if(!Ki(r))if(o){if(typeof o!=="function")throw TypeError("sizeCalculation must be a function");if(r=o(n,t),!Ki(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.#M=(t,n,r)=>{if(e[t]=n,this.#t){let o=this.#t-e[t];while(this.#l>o)this.#N(!0)}if(this.#l+=e[t],r)r.entrySize=n,r.totalCalculatedSize=this.#l}}#k=(e)=>{};#M=(e,t,n)=>{};#F=(e,t,n,r)=>{if(n||r)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#h;;){if(!this.#j(t))break;if(e||!this.#v(t))yield t;if(t===this.#f)break;else t=this.#d[t]}}*#O({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#f;;){if(!this.#j(t))break;if(e||!this.#v(t))yield t;if(t===this.#h)break;else t=this.#p[t]}}#j(e){return e!==void 0&&this.#u.get(this.#a[e])===e}*entries(){for(let e of this.#R())if(this.#s[e]!==void 0&&this.#a[e]!==void 0&&!this.#y(this.#s[e]))yield[this.#a[e],this.#s[e]]}*rentries(){for(let e of this.#O())if(this.#s[e]!==void 0&&this.#a[e]!==void 0&&!this.#y(this.#s[e]))yield[this.#a[e],this.#s[e]]}*keys(){for(let e of this.#R()){let t=this.#a[e];if(t!==void 0&&!this.#y(this.#s[e]))yield t}}*rkeys(){for(let e of this.#O()){let t=this.#a[e];if(t!==void 0&&!this.#y(this.#s[e]))yield t}}*values(){for(let e of this.#R())if(this.#s[e]!==void 0&&!this.#y(this.#s[e]))yield this.#s[e]}*rvalues(){for(let e of this.#O())if(this.#s[e]!==void 0&&!this.#y(this.#s[e]))yield this.#s[e]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#R()){let r=this.#s[n],o=this.#y(r)?r.__staleWhileFetching:r;if(o===void 0)continue;if(e(o,this.#a[n],this))return this.get(this.#a[n],t)}}forEach(e,t=this){for(let n of this.#R()){let r=this.#s[n],o=this.#y(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#a[n],this)}}rforEach(e,t=this){for(let n of this.#O()){let r=this.#s[n],o=this.#y(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#a[n],this)}}purgeStale(){let e=!1;for(let t of this.#O({allowStale:!0}))if(this.#v(t))this.#P(this.#a[t],"expire"),e=!0;return e}info(e){let t=this.#u.get(e);if(t===void 0)return;let n=this.#s[t],r=this.#y(n)?n.__staleWhileFetching:n;if(r===void 0)return;let o={value:r};if(this.#_&&this.#E){let s=this.#_[t],i=this.#E[t];if(s&&i){let a=s-(Ju.now()-i);o.ttl=a,o.start=Date.now()}}if(this.#S)o.size=this.#S[t];return o}dump(){let e=[];for(let t of this.#R({allowStale:!0})){let n=this.#a[t],r=this.#s[t],o=this.#y(r)?r.__staleWhileFetching:r;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#_&&this.#E){s.ttl=this.#_[t];let i=Ju.now()-this.#E[t];s.start=Math.floor(Date.now()-i)}if(this.#S)s.size=this.#S[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=Ju.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.#F(e,t,n.size||0,i);if(this.maxEntrySize&&l>this.maxEntrySize){if(a)a.set="miss",a.maxEntrySizeExceeded=!0;return this.#P(e,"set"),this}let u=this.#o===0?void 0:this.#u.get(e);if(u===void 0){if(u=this.#o===0?this.#h:this.#g.length!==0?this.#g.pop():this.#o===this.#e?this.#N(!1):this.#o,this.#a[u]=e,this.#s[u]=t,this.#u.set(e,u),this.#p[this.#h]=u,this.#d[u]=this.#h,this.#h=u,this.#o++,this.#M(u,l,a),a)a.set="add";c=!1}else{this.#L(u);let p=this.#s[u];if(t!==p){if(this.#w&&this.#y(p)){p.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=p;if(f!==void 0&&!s){if(this.#x)this.#n?.(f,e,"set");if(this.#b)this.#m?.push([f,e,"set"])}}else if(!s){if(this.#x)this.#n?.(p,e,"set");if(this.#b)this.#m?.push([p,e,"set"])}if(this.#k(u),this.#M(u,l,a),this.#s[u]=t,a){a.set="replace";let f=p&&this.#y(p)?p.__staleWhileFetching:p;if(f!==void 0)a.oldValue=f}}else if(a)a.set="update"}if(r!==0&&!this.#_)this.#A();if(this.#_){if(!c)this.#I(u,r,o);if(a)this.#T(a,u)}if(!s&&this.#b&&this.#m){let p=this.#m,f;while(f=p?.shift())this.#r?.(...f)}return this}pop(){try{while(this.#o){let e=this.#s[this.#f];if(this.#N(!0),this.#y(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#b&&this.#m){let e=this.#m,t;while(t=e?.shift())this.#r?.(...t)}}}#N(e){let t=this.#f,n=this.#a[t],r=this.#s[t];if(this.#w&&this.#y(r))r.__abortController.abort(Error("evicted"));else if(this.#x||this.#b){if(this.#x)this.#n?.(r,n,"evict");if(this.#b)this.#m?.push([r,n,"evict"])}if(this.#k(t),e)this.#a[t]=void 0,this.#s[t]=void 0,this.#g.push(t);if(this.#o===1)this.#f=this.#h=0,this.#g.length=0;else this.#f=this.#p[t];return this.#u.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,o=this.#u.get(e);if(o!==void 0){let s=this.#s[o];if(this.#y(s)&&s.__staleWhileFetching===void 0)return!1;if(!this.#v(o)){if(n)this.#C(o);if(r)r.has="hit",this.#T(r,o);return!0}else if(r)r.has="stale",this.#T(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.#v(r))return;let o=this.#s[r];return this.#y(o)?o.__staleWhileFetching:o}#U(e,t,n,r){let o=t===void 0?void 0:this.#s[t];if(this.#y(o))return o;let s=new SS,{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,S=n.ignoreFetchAbort&&h!==void 0;if(n.status)if(y&&!g){if(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,S)n.status.fetchAbortIgnored=!0}else n.status.fetchResolved=!0;if(y&&!S&&!g)return u(s.signal.reason);let b=f;if(this.#s[t]===f)if(h===void 0)if(b.__staleWhileFetching)this.#s[t]=b.__staleWhileFetching;else this.#P(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,S=y||n.allowStaleOnFetchRejection,b=S||n.noDeleteOnFetchRejection,x=f;if(this.#s[t]===f){if(!b||x.__staleWhileFetching===void 0)this.#P(e,"fetch");else if(!y)this.#s[t]=x.__staleWhileFetching}if(S){if(n.status&&x.__staleWhileFetching!==void 0)n.status.returnedStale=!0;return x.__staleWhileFetching}else if(x.__returned===x)throw h},p=(h,g)=>{let y=this.#i?.(e,o,a);if(y&&y instanceof Promise)y.then((S)=>h(S===void 0?void 0:S),g);s.signal.addEventListener("abort",()=>{if(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort){if(h(void 0),n.allowStaleOnFetchAbort)h=(S)=>c(S,!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.#s[t]=m;return m}#y(e){if(!this.#w)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof SS}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:S}=t;if(!this.#w){if(y)y.fetch="get";return this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:y})}let b={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:S},x=this.#u.get(e);if(x===void 0){if(y)y.fetch="miss";let v=this.#U(e,x,b,h);return v.__returned=v}else{let v=this.#s[x];if(this.#y(v)){let K=n&&v.__staleWhileFetching!==void 0;if(y){if(y.fetch="inflight",K)y.returnedStale=!0}return K?v.__staleWhileFetching:v.__returned=v}let A=this.#v(x);if(!g&&!A){if(y)y.fetch="hit";if(this.#L(x),r)this.#C(x);if(y)this.#T(y,x);return v}let U=this.#U(e,x,b,h),F=U.__staleWhileFetching!==void 0&&n;if(y){if(y.fetch=A?"stale":"refresh",F&&A)y.returnedStale=!0}return F?U.__staleWhileFetching:U.__returned=U}}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.#c;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.#s[i],c=this.#y(a);if(s)this.#T(s,i);if(this.#v(i)){if(s)s.get="stale";if(!c){if(!o)this.#P(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.#L(i),r)this.#C(i);return a}}else if(s)s.get="miss"}#$(e,t){this.#d[t]=e,this.#p[e]=t}#L(e){if(e!==this.#h){if(e===this.#f)this.#f=this.#p[e];else this.#$(this.#d[e],this.#p[e]);this.#$(this.#h,e),this.#h=e}}delete(e){return this.#P(e,"delete")}#P(e,t){let n=!1;if(this.#o!==0){let r=this.#u.get(e);if(r!==void 0)if(n=!0,this.#o===1)this.#z(t);else{this.#k(r);let o=this.#s[r];if(this.#y(o))o.__abortController.abort(Error("deleted"));else if(this.#x||this.#b){if(this.#x)this.#n?.(o,e,t);if(this.#b)this.#m?.push([o,e,t])}if(this.#u.delete(e),this.#a[r]=void 0,this.#s[r]=void 0,r===this.#h)this.#h=this.#d[r];else if(r===this.#f)this.#f=this.#p[r];else{let s=this.#d[r];this.#p[s]=this.#p[r];let i=this.#p[r];this.#d[i]=this.#d[r]}this.#o--,this.#g.push(r)}}if(this.#b&&this.#m?.length){let r=this.#m,o;while(o=r?.shift())this.#r?.(...o)}return n}clear(){return this.#z("delete")}#z(e){for(let t of this.#O({allowStale:!0})){let n=this.#s[t];if(this.#y(n))n.__abortController.abort(Error("deleted"));else{let r=this.#a[t];if(this.#x)this.#n?.(n,r,e);if(this.#b)this.#m?.push([n,r,e])}}if(this.#u.clear(),this.#s.fill(void 0),this.#a.fill(void 0),this.#_&&this.#E)this.#_.fill(0),this.#E.fill(0);if(this.#S)this.#S.fill(0);if(this.#f=0,this.#h=0,this.#g.length=0,this.#l=0,this.#o=0,this.#b&&this.#m){let t=this.#m,n;while(n=t?.shift())this.#r?.(...n)}}}function $J(e,t,n=100){let r=new ES({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),set:(s,i)=>void r.set(s,i)},o}var P3e=8192;function HJ(e,t){try{return{ok:!0,value:JSON.parse(bu(e))}}catch(n){if(t)f_($N(n,`safeParseJSON: invalid JSON (${n instanceof Error?n.constructor.name:typeof n}, ${e.length} bytes)`));return{ok:!1}}}class BJ{cached=$J(HJ,(e)=>e,50);cache=this.cached.cache;parse(e,t){return this.cached(e,t)}}var zJ=new BJ;var uc=Object.assign(function(t,n=!0){if(!t)return null;let r=t.length>P3e?HJ(t,n):zJ.parse(t,n);return r.ok?r.value:null},{cache:zJ.cache});import{join as I3e}from"path";class KJ{managedFilePath=void 0;dropInDir=void 0;getManagedFilePath(){return this.managedFilePath??=L3e(),this.managedFilePath}getDropInDir(){return this.dropInDir??=I3e(dc(),"managed-settings.d"),this.dropInDir}clearDropInDir(){this.dropInDir=void 0}reset(){this.managedFilePath=void 0,this.dropInDir=void 0}}var D3e=new KJ;function dc(){return D3e.getManagedFilePath()}function L3e(){let e=M3e();if(e!==void 0)return e;switch($r()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}function M3e(){return}function N3e(e,t,n){if(n!==void 0&&!Uo(e[t],n)||n===void 0&&!(t in e))ci(e,t,n)}var Xm=N3e;var vS={};rn(vS,{default:()=>Qm});var VJ=typeof vS=="object"&&vS&&!vS.nodeType&&vS,GJ=VJ&&typeof xS=="object"&&xS&&!xS.nodeType&&xS,U3e=GJ&&GJ.exports===VJ,WJ=U3e?Kt.Buffer:void 0,qJ=WJ?WJ.allocUnsafe:void 0;function F3e(e,t){if(t)return e.slice();var n=e.length,r=qJ?qJ(n):new e.constructor(n);return e.copy(r),r}var Qm=F3e;function j3e(e){var t=new e.constructor(e.byteLength);return new cl(t).set(new cl(e)),t}var Qu=j3e;function $3e(e,t){var n=t?Qu(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}var wS=$3e;function z3e(e,t){var n=-1,r=e.length;t||(t=Array(r));while(++n<r)t[n]=e[n];return t}var AS=z3e;var ZJ=Object.create,H3e=function(){function e(){}return function(t){if(!zt(t))return{};if(ZJ)return ZJ(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}(),YJ=H3e;var B3e=Gg(Object.getPrototypeOf,Object),ed=B3e;function K3e(e){return typeof e.constructor=="function"&&!ml(e)?YJ(ed(e)):{}}var TS=K3e;function G3e(e){return Xt(e)&&ai(e)}var JJ=G3e;var W3e="[object Object]",q3e=Function.prototype,V3e=Object.prototype,XJ=q3e.toString,Z3e=V3e.hasOwnProperty,Y3e=XJ.call(Object);function J3e(e){if(!Xt(e)||mr(e)!=W3e)return!1;var t=ed(e);if(t===null)return!0;var n=Z3e.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&XJ.call(n)==Y3e}var CS=J3e;function X3e(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var eh=X3e;var Q3e=Object.prototype,e9e=Q3e.hasOwnProperty;function t9e(e,t,n){var r=e[t];if(!(e9e.call(e,t)&&Uo(r,n))||n===void 0&&!(t in e))ci(e,t,n)}var td=t9e;function n9e(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)ci(n,a,c);else td(n,a,c)}return n}var Jr=n9e;function r9e(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var QJ=r9e;var o9e=Object.prototype,s9e=o9e.hasOwnProperty;function i9e(e){if(!zt(e))return QJ(e);var t=ml(e),n=[];for(var r in e)if(!(r=="constructor"&&(t||!s9e.call(e,r))))n.push(r);return n}var e8=i9e;function a9e(e){return ai(e)?Kg(e,!0):e8(e)}var os=a9e;function c9e(e){return Jr(e,os(e))}var t8=c9e;function l9e(e,t,n,r,o,s,i){var a=eh(e,n),c=eh(t,n),l=i.get(c);if(l){Xm(e,n,l);return}var u=s?s(a,c,n+"",e,t,i):void 0,p=u===void 0;if(p){var f=_t(c),m=!f&&Go(c),h=!f&&!m&&fl(c);if(u=c,f||m||h)if(_t(a))u=a;else if(JJ(a))u=AS(a);else if(m)p=!1,u=Qm(c,!0);else if(h)p=!1,u=wS(c,!0);else u=[];else if(CS(c)||gs(c)){if(u=a,gs(a))u=t8(a);else if(!zt(a)||Ac(a))u=TS(c)}else p=!1}if(p)i.set(c,u),o(u,c,r,s,i),i.delete(c);Xm(e,n,u)}var n8=l9e;function r8(e,t,n,r,o){if(e===t)return;Xg(t,function(s,i){if(o||(o=new Ko),zt(s))n8(e,t,i,n,r8,r,o);else{var a=r?r(eh(e,i),s,i+"",e,t,o):void 0;if(a===void 0)a=s;Xm(e,i,a)}},os)}var o8=r8;function u9e(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 s8=u9e;var i8=Math.max;function d9e(e,t,n){return t=i8(t===void 0?e.length-1:t,0),function(){var r=arguments,o=-1,s=i8(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),s8(e,this,a)}}var kS=d9e;function p9e(e){return function(){return e}}var a8=p9e;var f9e=!_l?El:function(e,t){return _l(e,"toString",{configurable:!0,enumerable:!1,value:a8(t),writable:!0})},c8=f9e;var m9e=800,h9e=16,g9e=Date.now;function _9e(e){var t=0,n=0;return function(){var r=g9e(),o=h9e-(r-n);if(n=r,o>0){if(++t>=m9e)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var l8=_9e;var y9e=l8(c8),RS=y9e;function b9e(e,t){return RS(kS(e,t,El),e+"")}var u8=b9e;function S9e(e,t,n){if(!zt(n))return!1;var r=typeof t;if(r=="number"?ai(n)&&ii(t,n.length):r=="string"&&(t in n))return Uo(n[t],e);return!1}var d8=S9e;function E9e(e){return u8(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&&d8(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 p8=E9e;var x9e=p8(function(e,t,n,r){o8(e,t,n,r)}),Hn=x9e;function v9e(e,t){var n=-1,r=e==null?0:e.length;while(++n<r)if(t(e[n],n,e)===!1)break;return e}var f8=v9e;function w9e(e,t){return e&&Jr(t,qo(t),e)}var m8=w9e;function A9e(e,t){return e&&Jr(t,os(t),e)}var h8=A9e;function T9e(e,t){return Jr(e,ul(e),t)}var g8=T9e;var C9e=Object.getOwnPropertySymbols,k9e=!C9e?jg:function(e){var t=[];while(e)ll(t,ul(e)),e=ed(e);return t},OS=k9e;function R9e(e,t){return Jr(e,OS(e),t)}var _8=R9e;function O9e(e){return Fg(e,os,OS)}var nd=O9e;var P9e=Object.prototype,I9e=P9e.hasOwnProperty;function D9e(e){var t=e.length,n=new e.constructor(t);if(t&&typeof e[0]=="string"&&I9e.call(e,"index"))n.index=e.index,n.input=e.input;return n}var y8=D9e;function L9e(e,t){var n=t?Qu(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var b8=L9e;var M9e=/\w*$/;function N9e(e){var t=new e.constructor(e.source,M9e.exec(e));return t.lastIndex=e.lastIndex,t}var S8=N9e;var E8=on?on.prototype:void 0,x8=E8?E8.valueOf:void 0;function U9e(e){return x8?Object(x8.call(e)):{}}var v8=U9e;var F9e="[object Boolean]",j9e="[object Date]",$9e="[object Map]",z9e="[object Number]",H9e="[object RegExp]",B9e="[object Set]",K9e="[object String]",G9e="[object Symbol]",W9e="[object ArrayBuffer]",q9e="[object DataView]",V9e="[object Float32Array]",Z9e="[object Float64Array]",Y9e="[object Int8Array]",J9e="[object Int16Array]",X9e="[object Int32Array]",Q9e="[object Uint8Array]",eZe="[object Uint8ClampedArray]",tZe="[object Uint16Array]",nZe="[object Uint32Array]";function rZe(e,t,n){var r=e.constructor;switch(t){case W9e:return Qu(e);case F9e:case j9e:return new r(+e);case q9e:return b8(e,n);case V9e:case Z9e:case Y9e:case J9e:case X9e:case Q9e:case eZe:case tZe:case nZe:return wS(e,n);case $9e:return new r;case z9e:case K9e:return new r(e);case H9e:return S8(e);case B9e:return new r;case G9e:return v8(e)}}var w8=rZe;var oZe="[object Map]";function sZe(e){return Xt(e)&&_s(e)==oZe}var A8=sZe;var T8=Wo&&Wo.isMap,iZe=T8?pl(T8):A8,C8=iZe;var aZe="[object Set]";function cZe(e){return Xt(e)&&_s(e)==aZe}var k8=cZe;var R8=Wo&&Wo.isSet,lZe=R8?pl(R8):k8,O8=lZe;var uZe=1,dZe=2,pZe=4,P8="[object Arguments]",fZe="[object Array]",mZe="[object Boolean]",hZe="[object Date]",gZe="[object Error]",I8="[object Function]",_Ze="[object GeneratorFunction]",yZe="[object Map]",bZe="[object Number]",D8="[object Object]",SZe="[object RegExp]",EZe="[object Set]",xZe="[object String]",vZe="[object Symbol]",wZe="[object WeakMap]",AZe="[object ArrayBuffer]",TZe="[object DataView]",CZe="[object Float32Array]",kZe="[object Float64Array]",RZe="[object Int8Array]",OZe="[object Int16Array]",PZe="[object Int32Array]",IZe="[object Uint8Array]",DZe="[object Uint8ClampedArray]",LZe="[object Uint16Array]",MZe="[object Uint32Array]",dt={};dt[P8]=dt[fZe]=dt[AZe]=dt[TZe]=dt[mZe]=dt[hZe]=dt[CZe]=dt[kZe]=dt[RZe]=dt[OZe]=dt[PZe]=dt[yZe]=dt[bZe]=dt[D8]=dt[SZe]=dt[EZe]=dt[xZe]=dt[vZe]=dt[IZe]=dt[DZe]=dt[LZe]=dt[MZe]=!0;dt[gZe]=dt[I8]=dt[wZe]=!1;function PS(e,t,n,r,o,s){var i,a=t&uZe,c=t&dZe,l=t&pZe;if(n)i=o?n(e,r,o,s):n(e);if(i!==void 0)return i;if(!zt(e))return e;var u=_t(e);if(u){if(i=y8(e),!a)return AS(e,i)}else{var p=_s(e),f=p==I8||p==_Ze;if(Go(e))return Qm(e,a);if(p==D8||p==P8||f&&!o){if(i=c||f?{}:TS(e),!a)return c?_8(e,h8(i,e)):g8(e,m8(i,e))}else{if(!dt[p])return o?e:{};i=w8(e,p,a)}}s||(s=new Ko);var m=s.get(e);if(m)return m;if(s.set(e,i),O8(e))e.forEach(function(y){i.add(PS(y,t,n,y,e,s))});else if(C8(e))e.forEach(function(y,S){i.set(S,PS(y,t,n,S,e,s))});var h=l?c?nd:Vp:c?os:qo,g=u?void 0:h(e);return f8(g||e,function(y,S){if(g)S=y,y=e[S];td(i,S,PS(y,t,n,S,e,s))}),i}var L8=PS;function NZe(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}var M8=NZe;function UZe(e,t,n){var r=-1,o=e.length;if(t<0)t=-t>o?0:o+t;if(n=n>o?o:n,n<0)n+=o;o=t>n?0:n-t>>>0,t>>>=0;var s=Array(o);while(++r<o)s[r]=e[r+t];return s}var N8=UZe;function FZe(e,t){return t.length<2?e:li(e,N8(t,0,-1))}var U8=FZe;var jZe=Object.prototype,$Ze=jZe.hasOwnProperty;function zZe(e,t){t=jr(t,e);var n=-1,r=t.length;if(!r)return!0;while(++n<r){var o=xr(t[n]);if(o==="__proto__"&&!$Ze.call(e,"__proto__"))return!1;if((o==="constructor"||o==="prototype")&&n<r-1)return!1}var s=U8(e,t);return s==null||delete s[xr(M8(t))]}var F8=zZe;function HZe(e){return CS(e)?void 0:e}var j8=HZe;var $8=on?on.isConcatSpreadable:void 0;function BZe(e){return _t(e)||gs(e)||!!($8&&e&&e[$8])}var z8=BZe;function H8(e,t,n,r,o){var s=-1,i=e.length;n||(n=z8),o||(o=[]);while(++s<i){var a=e[s];if(t>0&&n(a))if(t>1)H8(a,t-1,n,r,o);else ll(o,a);else if(!r)o[o.length]=a}return o}var B8=H8;function KZe(e){var t=e==null?0:e.length;return t?B8(e,1):[]}var K8=KZe;function GZe(e){return RS(kS(e,void 0,K8),e+"")}var IS=GZe;var WZe=1,qZe=2,VZe=4,ZZe=IS(function(e,t){var n={};if(e==null)return n;var r=!1;if(t=Sl(t,function(s){return s=jr(s,e),r||(r=s.length>1),s}),Jr(e,nd(e),n),r)n=L8(n,WZe|qZe|VZe,j8);var o=t.length;while(o--)F8(n,t[o]);return n}),bI=ZZe;function YZe(e,t,n,r){if(!zt(e))return e;t=jr(t,e);var o=-1,s=t.length,i=s-1,a=e;while(a!=null&&++o<s){var c=xr(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=zt(u)?u:ii(t[o+1])?[]:{}}td(a,c,l),a=a[c]}return e}var G8=YZe;function JZe(e,t,n){var r=-1,o=t.length,s={};while(++r<o){var i=t[r],a=li(e,i);if(n(a,i))G8(s,jr(i,e),a)}return s}var DS=JZe;function XZe(e,t){return DS(e,t,function(n,r){return t_(e,r)})}var W8=XZe;var QZe=IS(function(e,t){return e==null?{}:W8(e,t)}),LS=QZe;import{homedir as u8e}from"os";import{dirname as d8e,join as Mo,resolve as Qr}from"path";wc();var eYe="Expected a function";function tYe(e){if(typeof e!="function")throw TypeError(eYe);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 q8=tYe;function nYe(e,t){if(e==null)return{};var n=Sl(nd(e),function(r){return[r]});return t=ui(t),DS(e,n,function(r,o){return t(r,o[0])})}var V8=nYe;function rYe(e,t){return V8(e,q8(ui(t)))}var th=rYe;function pn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var nh=[{alias:"additionalMarketplaces",canonical:"extraKnownMarketplaces"},{alias:"allowedMarketplaces",canonical:"strictKnownMarketplaces"}];function Z8(e,t){if(!pn(e))return[];let n=[];for(let{alias:r,canonical:o}of nh){if(!(r in e))continue;if(o in e&&e[o]!==null)n.push({file:t,path:r,message:`"${r}" is an alias for "${o}" and this file sets both; the "${r}" value was ignored. Use only "${o}".`,severity:"warning",alias:r,canonical:o});else e[o]=e[r];delete e[r]}return n}import{join as E7}from"path";var SI=["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"],Y8=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE"];var J8="OTEL_EXPORTER_OTLP_",X8=["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"],Q8=[J8,`ANT_${J8}`],eX={apiKeyHelper:["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],awsAuthRefresh:[...Y8,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],awsCredentialExport:[...Y8,"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"]},oYe=["CLAUDE_CODE_MEMORY_API_BASE_URL","CLAUDE_CODE_MEMORY_API_TOKEN"];var EI=["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_SYNC_BASE_URL","CLAUDE_CODE_ARTIFACT_VIEWER_BASE_URL",...oYe];var xI=["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"],sYe=["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"],vI=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_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"],wI=["ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES"],iYe=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],AI=[...iYe,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var TI=["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_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN"],CI=["GCE_METADATA_HOST","GCE_METADATA_IP","METADATA_SERVER_DETECTION"],vHt=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...SI,...EI,...xI,...sYe,"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",...AI,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT",...CI,...TI,"AWS_REGION","AWS_DEFAULT_REGION",...vI,"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",...wI]);var tX=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","fileSuggestion","gcpAuthRefresh","otelHeadersHelper","processWrapper","policyHelpers","proxyAuthHelper","statusLine","subagentStatusLine"],nX=["bwrapPath","ripgrep","socatPath"],aYe=new Set(["ANTHROPIC_BEDROCK_REGION_PREFIX","ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_MODEL","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_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","ANTHROPIC_SMALL_FAST_MODEL","AWS_DEFAULT_REGION","AWS_PROFILE","AWS_REGION","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_ENABLE_AUTO_MODE","CLAUDE_CODE_ENABLE_DESIGN_SYNC","CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL","CLAUDE_CODE_ENABLE_TELEMETRY","CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","CLAUDE_CODE_USE_GATEWAY","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_POWERSHELL_TOOL","CLAUDE_CODE_USE_VERTEX","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_FEEDBACK_COMMAND","DISABLE_GROWTHBOOK","DISABLE_INSTALLATION_CHECKS","DISABLE_UPDATES","ENABLE_TOOL_SEARCH","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_CONNECT_TIMEOUT_MS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","OTEL_EXPORTER_OTLP_COMPRESSION","OTEL_EXPORTER_OTLP_HEADERS","OTEL_EXPORTER_OTLP_LOGS_COMPRESSION","OTEL_EXPORTER_OTLP_LOGS_HEADERS","OTEL_EXPORTER_OTLP_LOGS_PROTOCOL","OTEL_EXPORTER_OTLP_METRICS_COMPRESSION","OTEL_EXPORTER_OTLP_METRICS_HEADERS","OTEL_EXPORTER_OTLP_METRICS_PROTOCOL","OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE","OTEL_EXPORTER_OTLP_PROTOCOL","OTEL_EXPORTER_OTLP_TRACES_COMPRESSION","OTEL_EXPORTER_OTLP_TRACES_HEADERS","OTEL_EXPORTER_OTLP_TRACES_PROTOCOL","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_USER_PROMPTS","OTEL_LOGS_EXPORT_INTERVAL","OTEL_LOGS_EXPORTER","OTEL_METRIC_EXPORT_INTERVAL","OTEL_METRICS_EXPORTER","OTEL_METRICS_INCLUDE_ACCOUNT_UUID","OTEL_METRICS_INCLUDE_ENTRYPOINT","OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES","OTEL_METRICS_INCLUDE_SESSION_ID","OTEL_METRICS_INCLUDE_VERSION","OTEL_RESOURCE_ATTRIBUTES","OTEL_SERVICE_NAME","OTEL_TRACES_EXPORT_INTERVAL","OTEL_TRACES_EXPORTER","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_5_SONNET","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS","VERTEX_REGION_CLAUDE_4_5_OPUS","VERTEX_REGION_CLAUDE_4_6_OPUS","VERTEX_REGION_CLAUDE_4_7_OPUS","VERTEX_REGION_CLAUDE_4_8_OPUS","VERTEX_REGION_CLAUDE_5_OPUS","VERTEX_REGION_CLAUDE_FABLE_5","VERTEX_REGION_CLAUDE_4_5_SONNET","VERTEX_REGION_CLAUDE_4_6_SONNET","VERTEX_REGION_CLAUDE_5_SONNET","VERTEX_REGION_CLAUDE_HAIKU_4_5","CLAUDE_AUTOCOMPACT_PCT_OVERRIDE","CLAUDE_CODE_AUTO_COMPACT_WINDOW","CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT","CLAUDE_CODE_MAX_CONTEXT_TOKENS","DISABLE_AUTO_COMPACT","DISABLE_COMPACT","CLAUDE_CODE_ALWAYS_ENABLE_EFFORT","CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING","CLAUDE_CODE_DISABLE_FAST_MODE","CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP","CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK","CLAUDE_CODE_DISABLE_THINKING","CLAUDE_CODE_EFFORT_LEVEL","CLAUDE_CODE_PROMPT_CACHE_TTL","CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL","DISABLE_INTERLEAVED_THINKING","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_FABLE","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","ENABLE_PROMPT_CACHING_1H","ENABLE_PROMPT_CACHING_1H_BEDROCK","FALLBACK_FOR_ALL_PRIMARY_MODELS","FORCE_PROMPT_CACHING_5M","CLAUDE_AUTO_BACKGROUND_TASKS","CLAUDE_CODE_DISABLE_ADVISOR_TOOL","CLAUDE_CODE_DISABLE_AGENT_VIEW","CLAUDE_CODE_DISABLE_ARTIFACT","CLAUDE_CODE_DISABLE_BACKGROUND_TASKS","CLAUDE_CODE_DISABLE_BUNDLED_SKILLS","CLAUDE_CODE_DISABLE_CRON","CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS","CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY","CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING","CLAUDE_CODE_DISABLE_MEMORY_RO_UNSAVED_NOTICE","CLAUDE_CODE_DISABLE_WORKFLOWS","CLAUDE_CODE_ENABLE_AWAY_SUMMARY","CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING","CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION","CLAUDE_CODE_ENABLE_TASKS","CLAUDE_CODE_FORK_SUBAGENT","CLAUDE_CODE_PLAN_MODE_REQUIRED","DISABLE_DOCTOR_COMMAND","DISABLE_EXTRA_USAGE_COMMAND","DISABLE_INSTALL_GITHUB_APP_COMMAND","DISABLE_LOGIN_COMMAND","DISABLE_LOGOUT_COMMAND","DISABLE_UPGRADE_COMMAND","CLAUDE_AX_SCREEN_READER","CLAUDE_CODE_ACCESSIBILITY","CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN","CLAUDE_CODE_DISABLE_MOUSE","CLAUDE_CODE_DISABLE_MOUSE_CLICKS","CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL","CLAUDE_CODE_FORCE_STRIKETHROUGH","CLAUDE_CODE_HIDE_CWD","CLAUDE_CODE_NATIVE_CURSOR","CLAUDE_CODE_NO_FLICKER","CLAUDE_CODE_SCROLL_SPEED","CLAUDE_CODE_SYNTAX_HIGHLIGHT","API_TIMEOUT_MS","CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS","CLAUDE_CODE_COORDINATOR_WORKER_CHECKIN_SECONDS","CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS","CLAUDE_CODE_GLOB_TIMEOUT_SECONDS","CLAUDE_CODE_MAX_RETRIES","CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION","CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY","CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION","CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS","CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT","CLAUDE_CODE_TEAM_TEARDOWN_PARK_TIMEOUT_MS","CLAUDE_STREAM_IDLE_TIMEOUT_MS","MAX_STRUCTURED_OUTPUT_RETRIES","MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE","MCP_SERVER_CONNECTION_BATCH_SIZE","SLASH_COMMAND_TOOL_CHAR_BUDGET","TASK_MAX_OUTPUT_LENGTH","MCP_CONNECTION_NONBLOCKING","CLAUDE_ENABLE_BYTE_WATCHDOG","CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK","CLAUDE_ENABLE_STREAM_WATCHDOG"]),cYe=new Set(["API_FORCE_IDLE_TIMEOUT","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","DISABLE_ERROR_REPORTING","DISABLE_TELEMETRY","DO_NOT_TRACK"]);function rX(e,t){let n=e.toUpperCase();return aYe.has(n)||cYe.has(n)&&Ie(t)}function pc(){return Zv.of(Ct().host)}function oX(e){pc().invalidateAll(e)}import{createHash as g7}from"crypto";import{posix as l7,win32 as u7}from"path";import{isAbsolute as sX}from"path";var uYe=L(()=>C({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:R().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:R().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:R().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:R().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:Q().optional(),socksProxyPort:Q().optional(),tlsTerminate:C({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()),dYe=L(()=>C({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:R().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used."),disabled:R().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 iX(e,t,n){if(e.length===0||e.some((r)=>r.length===0))n.addIssue({code:Gr.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:Gr.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 aX(e,t){let n;try{n=new RegExp(e)}catch(o){t.addIssue({code:Gr.custom,path:["extract"],message:`extract is not a valid regular expression: ${co(o)}`});return}if(new RegExp(n.source+"|").exec("").length-1<1)t.addIssue({code:Gr.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 cX(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 MS=L(()=>ot(cX,C({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:q(["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:q(["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:q(["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:R().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:Gr.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)aX(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)iX(e.maskClaims,e.decode,t)}))),rd=()=>_().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"),NS=L(()=>ot(cX,C({name:rd().describe("Environment variable name."),mode:q(["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:q(["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:q(["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)aX(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)iX(e.maskClaims,e.decode,t);if(e.mode==="mask"&&e.decode!==void 0&&e.extract!==void 0)t.addIssue({code:Gr.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:Gr.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)."})}))),od=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"];var kI="_INVALID_PAIR_",lX="_PARENT_PAIR_SUPPRESSOR_";var US=L(()=>C({accessKeyIdVar:rd().describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:rd().describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:rd().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:Gr.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)}})),pYe=L(()=>{let e=q(["deny","passthrough"]);return C({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`.")})}),fYe=L(()=>C({files:I(MS()).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(NS()).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:R().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(US()).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:pYe().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:Gr.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()),RI=L(()=>C({enabled:R().optional(),failIfUnavailable:R().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:R().optional(),allowUnsandboxedCommands:R().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:uYe(),filesystem:dYe(),credentials:fYe(),ignoreViolations:X(_(),I(_())).optional(),enableWeakerNestedSandbox:R().optional(),enableWeakerNetworkIsolation:R().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:R().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:C({command:_(),args:I(_()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored."),bwrapPath:ot((e)=>typeof e==="string"&&sX(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:ot((e)=>typeof e==="string"&&sX(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());var sd=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],mYe=[...sd],uX=mYe;function rh(e){return e==="manual"?"default":e}var zHt=`Cannot set permission mode: must be one of ${sd.join(", ")}`,HHt={dangerousRemoval:{bypassImmune:!0,classifierRouted:!0},backgroundOperator:{bypassImmune:!1,classifierRouted:!0},suspiciousWindowsPath:{bypassImmune:!1,classifierRouted:!0},isolatePeerMachines:{bypassImmune:!0,classifierRouted:!1},restrictedMode:{bypassImmune:!0,classifierRouted:!1},...{}};var dX=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"];var pX=["normal","vim"],fX=["classic","readline"];var mX=["auto","tmux","iterm2","in-process"],hYe=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],hX=["auto",...hYe],gX=["auto","alwaysAsk","disabled"];var qHt=$r()==="macos"?"⏺":"●";var tBt=L(()=>ot(rh,q(uX))),nBt=L(()=>ot(rh,q(sd)));import{posix as kYe,win32 as RYe}from"path";import{isIPv4 as OYe,isIPv6 as PYe}from"net";var _X=["bash","powershell"];var oh=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 gYe(){let e=C({type:j("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:oh(),shell:q(_X).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:Q().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:_().optional().describe("Custom status message to display in spinner while hook runs"),once:R().optional().describe("If true, hook runs once and is removed after execution"),async:R().optional().describe("If true, hook runs in background without blocking"),asyncRewake:R().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".'),cloud:q(["device","skip"]).optional().catch("skip").describe("@internal Where this hook may run when a cloud session is driven from this machine. 'device': offer it to the cloud session and run it here even when its script sits where the cloud session can write on this machine or cannot be pinned — the author accepts that the session may have changed files this hook executes. 'skip': never offer it to cloud sessions. Omit for the default: a command hook whose script could be read and pinned and lies outside everything the cloud session can write here is offered; other command hooks are not. Applies to this entry only: the same hook written in another settings scope keeps its own setting. An unrecognised value reads as 'skip' (the file still loads; the hook stays on this machine).")}),t=C({type:j("prompt").describe("LLM prompt hook type"),prompt:_().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:oh(),timeout:Q().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:R().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:R().optional().describe("If true, hook runs once and is removed after execution")}),n=C({type:j("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:X(_(),Te()).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:oh(),timeout:Q().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:R().optional().describe("If true, hook runs once and is removed after execution")}),r=C({type:j("http").describe("HTTP hook type"),url:_().url().describe("URL to POST the hook input JSON to"),if:oh(),timeout:Q().positive().optional().describe("Timeout in seconds for this specific request"),headers:X(_(),_()).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:R().optional().describe("If true, hook runs once and is removed after execution"),cloud:q(["device","skip"]).optional().catch("skip").describe("@internal Where this hook may run when a cloud session is driven from this machine. 'skip': never offer it to cloud sessions; 'device' or omitted: offered (an HTTP hook has no script to pin). Applies to this entry only. An unrecognised value reads as 'skip' (the file still loads).")}),o=C({type:j("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:oh(),timeout:Q().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:R().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:r,AgentHookSchema:o,McpToolHookSchema:n}}var yX=L(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:r,McpToolHookSchema:o}=gYe();return Qa("type",[e,t,n,r,o])}),bX=L(()=>C({matcher:_().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:I(yX()).describe("List of hooks to execute when the matcher matches")})),fc=L(()=>D4(q(xc),I(bX())));var uBt=L(()=>q(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),dBt=L(()=>q(["stdio","sse","sse-ide","http","ws","sdk"])),id=L(()=>j("comms").optional().catch(void 0)),Gi=L(()=>Q().int().positive()),_Ye=300000,SX=L(()=>Q().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function EX({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,_Ye)}}}var yYe=L(()=>C({type:j("stdio").optional(),command:_().min(1,"Command cannot be empty"),args:I(_()).default([]),env:X(_(),_()).optional(),timeout:Gi().optional(),alwaysLoad:R().optional(),role:id()})),bYe=L(()=>R()),xX=L(()=>C({clientId:_().optional(),callbackPort:Q().int().positive().optional(),authServerMetadataUrl:_().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:_().min(1).optional(),xaa:bYe().optional()})),vX=L(()=>C({name:_(),permission_policy:q(["always_allow","always_ask","always_deny"]).optional()})),SYe=L(()=>C({type:j("sse"),url:_(),headers:X(_(),_()).optional(),headersHelper:_().optional(),oauth:xX().optional(),timeout:Gi().optional(),request_timeout_ms:SX(),tools:I(vX()).optional(),alwaysLoad:R().optional(),discoveryCache:R().optional(),role:id(),toolPermissions:X(_(),OI()).optional()}).transform(EX)),EYe=L(()=>C({type:j("sse-ide"),url:_(),ideName:_(),ideRunningInWindows:R().optional(),timeout:Gi().optional(),alwaysLoad:R().optional(),role:id()})),xYe=L(()=>C({type:j("ws-ide"),url:_(),ideName:_(),authToken:_().optional(),ideRunningInWindows:R().optional(),timeout:Gi().optional(),alwaysLoad:R().optional(),role:id()})),vYe=L(()=>C({type:q(["http","streamable-http"]).transform(()=>"http"),url:_(),headers:X(_(),_()).optional(),headersHelper:_().optional(),oauth:xX().optional(),timeout:Gi().optional(),request_timeout_ms:SX(),tools:I(vX()).optional(),alwaysLoad:R().optional(),discoveryCache:R().optional(),role:id(),toolPermissions:X(_(),OI()).optional()}).transform(EX)),wYe=L(()=>C({type:j("ws"),url:_(),headers:X(_(),_()).optional(),headersHelper:_().optional(),timeout:Gi().optional(),alwaysLoad:R().optional(),role:id()})),AYe=L(()=>C({type:j("sdk"),name:_(),timeout:Gi().optional(),alwaysLoad:R().optional()})),OI=L(()=>q(["allow","ask","blocked"])),TYe=L(()=>C({type:j("claudeai-proxy"),url:_(),id:_(),displayName:_().optional(),iconUrl:_().optional(),timeout:Gi().optional(),alwaysLoad:R().optional(),toolPermissions:X(_(),OI()).optional(),stateless:R().optional(),cachedInitResponse:X(_(),Te()).nullish(),discoverSupport:q(["supported","legacy","unknown"]).optional().catch(void 0),cachedDiscoverResponse:X(_(),Te()).nullish(),eligible:R().nullish(),ineligibleReason:_().nullish(),enterpriseManaged:R().optional()})),FS=L(()=>le([yYe(),SYe(),EYe(),xYe(),vYe(),wYe(),AYe(),TYe()]));var pBt=L(()=>C({mcpServers:X(_(),FS())}));function CYe(e){return xy(e).replace(/ {2,}/g," ").trim()}function PI(e,t=160){let n=CYe(e);return n.length>t?`${Sd(n,t)}…`:n}var NI=500,IYe=32;function OX(){return{sourceCommand:_().max(NI+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(wX,{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(Te()).transform((e)=>e.filter((t)=>typeof t==="string"&&t.length<=4096&&wX(t)).slice(-IYe)).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 wX(e){return kYe.isAbsolute(e)||RYe.isAbsolute(e)}var PX=/[^\x20-\x7E]| {4,}/;function UI(){return _().max(NI,{message:"headersHelper must not be longer than the install consent UI can display"}).refine((e)=>!PX.test(e),{message:"headersHelper must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"})}var DYe=new Set(["claude-community","claude-plugins-community","healthcare"]),LYe=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"]),IX=new Set([...LYe,...DYe]);var MYe=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,NYe=/[^\u0020-\u007E]/;function UYe(e){if(IX.has(e.toLowerCase()))return!1;if(NYe.test(e))return!0;return MYe.test(e)}var ss=L(()=>_().startsWith("./")),mc=L(()=>ss().endsWith(".json")),AX=L(()=>le([j("."),ss()])),TX=L(()=>le([ss().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")])),DI=L(()=>ss().endsWith(".md")),LI=L(()=>le([DI(),ss()])),DX={inline:"--plugin-dir session plugins",builtin:"built-in plugins","skills-dir":"plugins auto-loaded from .claude/skills/",synced:"plugins synced from your claude.ai account"};function FYe(e){return Object.hasOwn(DX,e)}var LX=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)=>!KX.test(e),{message:"Marketplace name cannot contain control or bidirectional-formatting characters"}).refine((e)=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((e)=>!UYe(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).superRefine((e,t)=>{let n=e.toLowerCase();if(!FYe(n))return;t.addIssue({code:"custom",message:`Marketplace name "${n}" is reserved for ${DX[n]}`})})),jS=L(()=>_().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).refine((e)=>!KX.test(e),{message:"Plugin name cannot contain control or bidirectional-formatting characters"})),FI=L(()=>C({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")})),jYe=L(()=>C({$schema:_().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:jS().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:FI().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:R().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(N5e()).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:ot((e)=>pn(e)?e:void 0,X(_(),Te()).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.")})),$Ye=1,PBt=L(()=>C({description:_().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:tb(()=>fc()).optional().describe("The hooks provided by the plugin, in the same format as the one used for settings"),modules:I(_()).max($Ye,{message:"hooks.json `modules` names one hooks module per plugin; a second entry is refused"}).optional().describe("The hooks module: one path, relative to this hooks.json, of a module exporting register(on). What it hooks and calls is read from its source before it loads; `claude plugin validate` shows the result.")}).refine((e)=>e.hooks!==void 0||(e.modules?.length??0)>0,{message:"hooks.json must have `hooks` (the hook matchers) or `modules` (hooks modules), or both"})),zYe=L(()=>C({hooks:le([mc().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),tb(()=>fc()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),I(le([mc().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),tb(()=>fc()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),HYe=L(()=>C({source:LI().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'})),BYe=L(()=>C({commands:le([LI().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(LI().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."),X(_(),HYe()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),KYe=L(()=>C({agents:le([DI().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(DI().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.")])})),GYe=L(()=>C({skills:le([AX().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(AX().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).")])})),WYe=L(()=>le([_(),I(_())])),MX=L(()=>C({outputStyles:le([ss().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(ss().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.")])})),qYe=L(()=>_().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),VYe=16,ZYe=L(()=>C({id:qYe(),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()),YYe=L(()=>C({syntaxHighlighting:C({hljsLanguages:I(ZYe()).max(VYe)}).strict()})),NX=L(()=>C({themes:le([ss().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(ss().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.")])})),JYe=L(()=>C({})),CX=L(()=>_().min(1)),XYe=L(()=>_().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),QYe=L(()=>C({mcpServers:le([mc().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),TX().describe("Path or URL to MCPB file containing MCP server configuration"),X(_(),FS()).describe("MCP server configurations keyed by server name"),I(le([mc().describe("Path to MCP servers configuration file"),TX().describe("Path or URL to MCPB file"),X(_(),FS()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),UX=L(()=>C({type:q(["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:R().optional().describe("If true, validation fails when this field is empty"),default:le([_(),Q(),R(),I(_())]).optional().describe("Default value used when the user provides nothing"),multiple:R().optional().describe("For string type: allow an array of strings"),sensitive:R().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:Q().optional().describe("Minimum value (number type only)"),max:Q().optional().describe("Maximum value (number type only)")}).strict()),e5e=L(()=>C({userConfig:X(_().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"),UX()).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.")})),t5e=L(()=>C({channels:I(C({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:X(_(),UX()).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.")})),kX=L(()=>TO({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(CX()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:X(XYe(),CX()).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:q(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:X(_(),_()).optional().describe("Environment variables to set when starting the server"),initializationOptions:Te().optional().describe("Initialization options passed to the server during initialization"),settings:Te().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:_().optional().describe("Workspace folder path to use for the server"),startupTimeout:Q().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:Q().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:R().optional().describe("Whether to restart the server if it crashes"),maxRestarts:Q().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:R().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.")})),n5e=L(()=>TO({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:le([j("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).')})),r5e=L(()=>I(n5e()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),FX=L(()=>C({monitors:le([mc().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),r5e()]).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.")})),o5e=L(()=>C({lspServers:le([mc().describe("Path to .lsp.json configuration file relative to plugin root"),X(_(),kX()).describe("LSP server configurations keyed by server name"),I(le([mc().describe("Path to LSP configuration file"),X(_(),kX()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),jX=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")),s5e=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,i5e=/^[0-9a-f]{64}$/;var a5e=64;var c5e=L(()=>C({sha256:_().regex(i5e)}));function l5e(e){let t=X(_(),Te()).safeParse(e);if(!t.success)return;let n=Object.create(null),r=0;for(let[o,s]of Object.entries(t.data)){if(r>=a5e)break;let i=c5e().safeParse(s);if(s5e.test(o)&&i.success)n[o]=i.data,r++}return r>0?n:void 0}var u5e=L(()=>C({binaries:Te().transform(l5e).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),d5e=L(()=>C({settings:X(_(),Te()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),p5e=L(()=>C({experimental:ot((e)=>pn(e)?e:void 0,C({...NX().partial().shape,...YYe().partial().shape,...FX().partial().shape,...MX().partial().shape,evals:WYe().optional().describe("Directory of eval cases for the plugin evaluation harness, relative to the plugin root (default: evals/). A list is accepted; its first entry is the case directory.")}).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 f5e=L(()=>C({...jYe().shape,...zYe().partial().shape,...BYe().partial().shape,...KYe().partial().shape,...GYe().partial().shape,...MX().partial().shape,...NX().partial().shape,...JYe().shape,...t5e().partial().shape,...QYe().partial().shape,...o5e().partial().shape,...FX().partial().shape,...d5e().partial().shape,...e5e().partial().shape,...u5e().partial().shape,...p5e().partial().shape})),$X=new Set(["url","github","git","npm","file","directory","skills-dir","hostPattern","pathPattern","settings"]),ad=L(()=>Qa("source",[C({source:j("url"),url:_().url().describe("Direct URL to marketplace.json file"),headers:X(_(),_()).optional().describe("Custom HTTP headers (e.g., for authentication)"),headersHelper:UI().optional().describe("Command that prints a JSON object of HTTP headers (e.g. a short-lived auth token). Its output overrides `headers` and, like `headers`, is inherited by same-origin archive downloads from this marketplace. Runs from a fixed directory (the Claude config home, never the session's), so give a bare command found via PATH or an absolute path; it is re-run on later refreshes of this marketplace.")}),C({source:j("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:R().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.")}),C({source:j("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:R().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.")}),C({source:j("npm"),package:jX().describe("NPM package containing marketplace.json")}),C({source:j("file"),path:_().describe("Local file path to marketplace.json")}),C({source:j("directory"),path:_().describe("Local directory containing .claude-plugin/marketplace.json")}),C({source:j("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."),C({source:j("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$").')}),C({source:j("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.')}),C({source:j("settings"),name:LX().refine((e)=>!IX.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(y5e()).describe("Plugin entries declared inline in settings.json"),owner:FI().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).")])),II=L(()=>_().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),m5e=L(()=>_().regex(/^[0-9a-fA-F]{64}$/,"Must be a 64-character hex SHA-256 digest"));function MI(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(OYe(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(!PYe(t))return!1;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);if(n?.[1])return MI(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 MI(`${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 h5e="Archive URLs must use https:// and must not point at a loopback, link-local, or cloud-metadata host";function g5e(e){try{let t=new URL(e);return t.protocol==="https:"&&!MI(t.hostname)}catch{return!1}}var _5e=L(()=>C({source:j("archive"),url:_().url().refine(g5e,{message:h5e}).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:m5e().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: the entry's own `headers` / `headersHelper` (bound to this URL), overlaid on the enclosing url-source marketplace's headers (static or `headersHelper`-minted) when the archive shares its origin.")),zX=L(()=>le([ot((e)=>e==="."?"./":e,ss()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),C({source:j("npm"),package:jX().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"),C({source:j("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:II().optional().describe("Specific commit SHA to use")}),C({source:j("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:II().optional().describe("Specific commit SHA to use")}),C({source:j("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:II().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."),_5e(),C({source:j("command"),command:_().min(1).max(NI,{message:"command must not be longer than the install consent UI can display"}).refine((e)=>!PX.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:Q().int().positive().max(600).optional().describe("Seconds to wait for the command before giving up (default: 60)"),mode:q(["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."),C({source:j("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.")])),y5e=L(()=>C({name:jS().describe("Plugin name as it appears in the target repository"),source:zX().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:R().optional(),headers:X(_(),_()).optional().describe("HTTP headers sent when downloading this entry's `archive` source."),headersHelper:UI().optional().describe("Command that prints a JSON object of HTTP headers for downloading this entry's `archive` source. Runs only when a user explicitly installs or updates this plugin. Unlike a catalog entry, an entry written here does not need `strict: false`: it is declared in a settings file, which has no manifest fields to inline. A declaration in project settings is not operator-authored, so request-routing and client-identity header names are still filtered there. Use an absolute path.")}).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 b5e=L(()=>C({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(C({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.`)})),S5e=L(()=>C({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:b5e().optional().describe("Matchers that determine when the plugin is relevant.")})),E5e=L(()=>f5e().partial().extend({name:jS().describe("Unique identifier matching the plugin name"),source:zX().describe("Where to fetch the plugin from"),headers:X(_(),_()).optional().describe("Custom HTTP headers for fetching this plugin's archive; overrides the marketplace's"),headersHelper:UI().optional().describe("Command that prints a JSON object of HTTP headers for fetching this plugin's archive (e.g. a short-lived auth token); overrides this entry's `headers` and the marketplace's. Runs only when the user installs or updates this plugin, never during catalog browse. An entry that sets it must be `strict: false` with its manifest inlined here, so consent is informed from the entry alone before the command runs."),category:_().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:I(_()).optional().describe("Tags for searchability and discovery"),strict:R().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:ot((e)=>pn(e)?e:void 0,S5e().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.`)})),x5e=L(()=>C({name:jS()}));function v5e(e){let t=E5e();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=x5e().safeParse(n).data?.name,i=o.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(s){ae(`Stubbing unparseable marketplace plugin entry (${s}): ${i}`,{level:"warn"});let a=HX(pn(n)?n.source:void 0)?O5e:jI(n)?void 0:A5e(o.error.issues)??$S(o.error.issues);return[{name:s,source:{source:"unsupported",...a&&{error:a}},strict:!0}]}return ae(`Dropping unparseable marketplace plugin entry (index ${r}): ${i}`,{level:"warn"}),[]})}var w5e=new Set(["npm","url","github","git-subdir","archive","command","unsupported"]);function jI(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"&&!w5e.has(n)}function A5e(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 $S(n.map((r)=>({...r,path:["source",...r.path]})))}var T5e=/^[A-Za-z0-9_$.-]{1,40}$/;function Wi(e){return T5e.test(e)?e:"<key>"}var C5e=3,k5e=160;function $S(e){let t=e.slice(0,C5e).map((r)=>{let o=r.path.map(String).map((i)=>Wi(i)).join("."),s=r.code==="unrecognized_keys"?`Unrecognized ${r.keys.length===1?"field":"fields"}: ${r.keys.map(Wi).join(", ")}`:PI(r.message,k5e);return o?`${o}: ${s}`:s}),n=e.length-t.length;return n>0?`${t.join(", ")} (+${n} more)`:t.join(", ")}var R5e=/^[A-Za-z0-9][-A-Za-z0-9._]*$/,O5e='Bare source names resolve under metadata.pluginRoot, which this marketplace does not set (or sets to a path outside the marketplace root). Use a "./relative/path" source, or set metadata.pluginRoot to allow bare names.';function HX(e){return typeof e==="string"&&R5e.test(e)&&!e.includes("..")}function P5e(e){if(typeof e!=="string"||e===""||e.startsWith("/")||e.includes("\\")||e.includes(":"))return;let t=e.replace(/^\.\//,"").replace(/\/+$/,"");if(t===""||t===".")return".";if(t.split("/").some((n)=>n===""||n==="."||n===".."))return;return t}function I5e(e,t){if(t===void 0||!pn(e)||!HX(e.source))return e;let n=t==="."?`./${e.source}`:`./${t}/${e.source}`;return{...e,source:n}}function D5e(e){if(!pn(e)||!Array.isArray(e.plugins))return e;let t=pn(e.metadata)?P5e(e.metadata.pluginRoot):void 0;if(t===void 0)return e;return{...e,plugins:e.plugins.map((n)=>I5e(n,t))}}var L5e=L(()=>C({$schema:_().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:LX(),version:_().optional().describe("Marketplace manifest version"),description:_().optional().describe("Human-readable description of this marketplace"),owner:FI().describe("Marketplace maintainer or curator information"),plugins:I(Te()).transform(v5e).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:R().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:C({pluginRoot:_().optional().describe('Base directory for bare plugin source names, relative to the marketplace root (e.g. "./plugins" resolves "source": "formatter" as ./plugins/formatter). Sources that already start with "./" are unaffected.'),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:X(_(),_().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.")})),IBt=L(()=>ot(D5e,L5e())),RX="[A-Za-z0-9][-A-Za-z0-9._]*",BX=L(()=>_().regex(new RegExp(`^${RX}@${RX}$`),"Plugin ID must be in format: plugin@marketplace")),DBt=new RegExp(`[@:\\s/\\\\${yu}]`,"u"),LBt=new RegExp(`[${yu}]`,"u"),KX=/[\p{Cc}\u200E\u200F\u202A-\u202E\u2066-\u2069]/u,M5e=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,N5e=L(()=>le([_().regex(M5e,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),C({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)])),U5e=L(()=>C({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:R().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)."),...OX()})),MBt=L(()=>C({version:j(1).describe("Schema version 1"),plugins:X(BX(),U5e()).describe("Map of plugin IDs to their installation metadata")})),F5e=L(()=>q(["managed","user","project","local"])),j5e=L(()=>C({scope:F5e().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:R().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep."),...OX()})),NBt=L(()=>C({version:j(2).describe("Schema version 2"),plugins:X(BX(),I(j5e())).describe("Map of plugin IDs to arrays of installation entries")})),$5e=L(()=>C({source:ad().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:R().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),UBt=L(()=>X(_(),$5e()));var zS=["aspell","hunspell","ispell"];var z5e=["autoMode","deepLink","voice","briefView","screenReader"],$I={},HS={autoMode:{buildGate:()=>!1,shape:()=>$I,permissionsShape:()=>$I,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:q(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!0,shape:()=>({voiceEnabled:R().optional().describe("Enable voice mode (hold-to-talk dictation)")})},briefView:{buildGate:()=>!0,shape:()=>({defaultView:q(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>$I}};function ih(){return z5e.filter((e)=>HS[e].buildGate())}function GX(e){let t={};for(let n of e)t={...t,...HS[n].shape()};return t}function WX(e){let t={};for(let n of e)t={...t,...HS[n].permissionsShape?.()};return t}function qX(e){let t=[];for(let n of e)t.push(...HS[n].permissionModes?.()??[]);return t}var VX={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 cd(e){return Object.hasOwn(VX,e)?VX[e]:e}var ZX="workspace",KBt=`mcp__${ZX}__bash`,GBt=`mcp__${ZX}__web_fetch`;function BS(e){return e.includes("*")}function H5e(e){return e.replaceAll("\\","\\\\").replaceAll("(","\\(").replaceAll(")","\\)")}function B5e(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function YX(e){let t=K5e(e,"(");if(t===-1)return{toolName:cd(e)};let n=G5e(e,")");if(n===-1||n<=t)return{toolName:cd(e)};if(n!==e.length-1)return{toolName:cd(e)};let r=e.substring(0,t),o=e.substring(t+1,n);if(!r)return{toolName:cd(e)};if(o===""||o==="*")return{toolName:cd(r)};let s=B5e(o);return{toolName:cd(r),ruleContent:s}}function KS(e){if(!e.ruleContent)return e.toolName;let t=H5e(e.ruleContent);return`${e.toolName}(${t})`}function K5e(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 G5e(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}function zI(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 GS={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 JX(e){return GS.filePatternTools.includes(e)}function XX(e){return GS.bashPrefixTools.includes(e)}function QX(e){return Object.hasOwn(GS.customValidation,e)?GS.customValidation[e]:void 0}function BI(e,t){let n=0,r=t-1;while(r>=0&&e[r]==="\\")n++,r--;return n%2!==0}function HI(e,t){let n=0;for(let r=0;r<e.length;r++)if(e[r]===t&&!BI(e,r))n++;return n}function W5e(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!BI(e,t))return!0}return!1}var q5e=/^(?:[|&;<>]|\d+[<>])/;function V5e(e){return q5e.test(e)}function e7(e){for(let t=0;t<e.length;t++)if(e[t]==="*"&&!BI(e,t))return!0;return!1}function Z5e(e){if(e.endsWith(":*"))return;let t=e.trim().split(/\s+/).filter(Boolean),n=t[0];if(t.length<3||n===void 0||e7(n))return;let r=!1;for(let o of t.slice(1)){if(V5e(o))return;if(e7(o)){r=!0;continue}if(o.startsWith("-"))continue;return r?n:void 0}return}function t7(e){if(!BS(e))return null;let t=zI(e);if(t&&!BS(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 KI(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=HI(e,"("),r=HI(e,")");if(n!==r)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(W5e(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=YX(e),s=zI(o.toolName);if(s){if(o.ruleContent!==void 0||HI(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=t7(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=t7(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 "${bd(String(o.toolName))}"`};let i=QX(o.toolName);if(i&&o.ruleContent!==void 0){let a=i(o.ruleContent);if(!a.valid)return a}if(XX(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(t==="allow"){let c=Z5e(a);if(c!==void 0){let l=c==="git",u=l?" For git, options such as -c and --exec-path can run arbitrary commands.":"",p=l?" (for example Bash(git status *))":"";return{valid:!0,warning:`${KS(o)} has a wildcard before the rest of the command, so it also matches any options inserted at that position and approves them without a prompt.${u} Replace that * with the exact value you mean, or only use * after the subcommand${p}.`}}}}if(JX(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:`${KS(o)} is not matched by file permission checks — only ${a}(path) rules are. Use ${KS({toolName:a,ruleContent:o.ruleContent})} instead (${a} rules cover all file-${a==="Edit"?"editing":"reading"} tools).`}}return{valid:!0}}var GI=L(()=>r7()),n7=L(()=>r7("allow"));function r7(e){return _().superRefine((t,n)=>{let r=KI(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:Gr.custom,message:o,params:{received:t}})}})}var ah=["accept","hold","refuse"],Y5e=L(()=>X(_(),nb.string()));function d7(e){return C({allow:I(n7()).optional().describe("List of permission rules for allowed operations"),deny:I(GI()).optional().describe("List of permission rules for denied operations"),ask:I(GI()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:ot(rh,q([...sd,...qX(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:q(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...WX(e),additionalDirectories:I(_()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var A2t=L(()=>d7(ih())),J5e=L(()=>le([_(),C({}).passthrough().describe('{ id: stable id (letters, digits, ".", "_", "-"; max 64), text: the tip (max 500 characters, one line), cooldownSessions?: sessions to wait before showing it again (default 0), priority?: tie-break weight among never-shown tips (default 0) }')])),X5e=L(()=>ot((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"||!!t&&typeof t==="object"&&!Array.isArray(t)):[],I(J5e()))),VI=L(()=>C({source:ad().describe("Where to fetch the marketplace from"),installLocation:_().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:R().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),ZI=L(()=>{let e=()=>Q().min(0).max(1e4);return C({input:e(),output:e(),cacheRead:e(),cacheWrite:e()})}),YI=L(()=>Q().gt(0).lte(1).optional()),JI=L(()=>C({model:_().describe('Model to select, taken verbatim: an alias ("opus"), an Anthropic model ID, or a provider-format ID (Vertex, Bedrock, gateway). Same values --model accepts.'),label:_().optional().describe("Row title. Defaults to the model name."),description:_().optional().describe("Row subtitle. Defaults to a generic description.")})),VS=L(()=>C({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)=>rf([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"'})),ZS=L(()=>C({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)=>rf([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"'})),Q5e=/[\x00-\x1f\x7f-\x9f\u2028\u2029]|\p{DI}/u;function eJe(e){let t=e.replaceAll("/","\\");if(Sc(t))return!1;return/^\\{2}[^\\]/.test(t)}function tJe(e){return $s(e)||/^\/network\/servers(\/|$)/i.test(e)}function nJe(e){return/^\/(proc|dev\/(fd|stdin|stdout|stderr))(\/|$)/i.test(e)}function rJe(e,t,n={}){if(t==="win32"){let r=e.replaceAll("/","\\");if(Sc(r))return!1;let o=eJe(r);if(n.rejectUnc&&o)return!1;if(n.rejectDriveRelative){if(!/^[A-Za-z]:\\/.test(r)&&!o&&/^(\\|[A-Za-z]:)/.test(r))return!1}if(u7.normalize(r)!==r)return!1;let s=r.split("\\");if(s.some((a)=>a==="."||a===".."))return!1;if(s.some((a,c)=>/[. ]$/.test(a)||a.includes(":")&&!(c===0&&/^[A-Za-z]:$/.test(a))))return!1;let i=r.startsWith("\\\\")?r.slice(2):r;if(/\\{2}/.test(i))return!1;return!r.endsWith("\\")||/^([A-Za-z]:)?\\$/.test(r)}if(n.rejectNetworkRoot&&tJe(e))return!1;if(n.rejectMagicLinkRoot&&nJe(e))return!1;if(l7.normalize(e)!==e)return!1;if(e.split("/").some((r)=>r==="."||r===".."))return!1;if(/\/{2}/.test(e))return!1;return!e.endsWith("/")||e==="/"}var oJe=/\.(exe|ps1)$/i;function sJe(e){return/\.ps1$/i.test(e)}function iJe(e){return sJe(e)&&/[[\]`*?]/.test(e)}var aJe='a .ps1 path must not contain "[", "]", "`", "*", or "?" on Windows (PowerShell resolves them as wildcard syntax)',cJe=()=>_().describe("Absolute path to the helper executable"),ld=(e)=>ot((t)=>t===null?void 0:t,e.optional()).optional(),o7=["path","script","defaultSettings"];function p7(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;return o7.some((n)=>t[n]===null)&&o7.every((n)=>t[n]===null||t[n]===void 0)}var qS=L(()=>C({path:cJe(),timeoutMs:ld(Q().int().min(1000)),refreshIntervalMs:ld(le([j(0),Q().int().min(60000)]))})),f7=()=>q(["replace","merge"]).describe("How the helper's managedSettings compose with the settings of the source that delivered this entry: 'replace' (default) — the output is the policy; 'merge' — the output is deep-merged over that source's own settings (helper keys win, arrays replace), so a failed helper costs only the delta"),lJe=(e)=>(e==="windows"?j("pwsh",{message:"interpreter must be 'pwsh' on windows ('sh' is not supported there)"}):j("sh",{message:"interpreter must be 'sh' on macos/linux/wsl"})).describe("Fixed interpreter for `script`: 'sh' (/bin/sh) on macos/linux/wsl entries; 'pwsh' (PowerShell at its fixed install locations, never PATH) on the windows entry"),uJe="exactly one of path/script must be configured",dJe='"script" and "interpreter" must be configured together',pJe="script must be ASCII-only on Windows (PowerShell decodes stdin with the console OEM code page); spell non-ASCII characters as escapes, e.g. [char]0x00E9",fJe=(e)=>_({message:"script must be a string"}).min(1,{message:"script must not be empty"}).max(65536,{message:"script must be at most 65536 characters"}).refine((t)=>!t.includes("\x00"),{message:"script must not contain NUL bytes"}).refine((t)=>Ah(t),{message:"script must be valid UTF-8 (no lone surrogates)"}).refine((t)=>e!=="windows"||!/[\u0080-\uffff]/.test(t),{message:pJe}).describe("Inline helper script, delivered to the fixed interpreter over stdin (never written to disk)");var is=["macos","linux","windows","wsl"];function mJe(e){return e==="windows"?"win32":"posix"}function hJe(e){return{rejectDriveRelative:e==="windows",rejectUnc:e==="windows",rejectNetworkRoot:e!=="windows",rejectMagicLinkRoot:e!=="windows",requireWin32ExecutableSuffix:e==="windows"}}function gJe(e){let t=mJe(e),n=hJe(e);return _().max(1024,{message:"path must be at most 1024 characters"}).refine((r)=>!Q5e.test(r),{message:"path must not contain control, line/paragraph-separator, or invisible (default-ignorable) characters"}).refine((r)=>(t==="win32"?u7:l7).isAbsolute(r),{message:"path must be absolute"}).refine((r)=>!(t==="win32"&&n.requireWin32ExecutableSuffix)||oJe.test(r),{message:"path must end in .exe or .ps1 on Windows"}).refine((r)=>t!=="win32"||!iJe(r),{message:aJe}).refine((r)=>rJe(r,t,n),{message:t==="win32"?'path must be in normalized form: no "." or ".." segments, no doubled or trailing separators, no component ending in "." or a space, no ":" outside the drive letter, no device-namespace (\\\\?\\) prefix, no drive-relative (\\dir or C:name) or UNC (\\\\server\\share) form':'path must be in normalized form: no "." or ".." segments, no doubled or trailing separators, and not under a network automount root (/net/<host>, /Network/Servers) or a kernel magic-link root (/proc, /dev/fd)'}).describe("Absolute path to the helper executable")}var XI=[...is,"default"],WI=["path","script","interpreter","outputBehavior","timeoutMs","refreshIntervalMs","defaultSettings"],WS=["managedSettings","appendSystemPrompt"],hc=L(()=>X(_(),Te()).superRefine((e,t)=>{for(let n of["policyHelper","policyHelpers"])if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — the default payload is applied as managed settings and cannot configure further policy helpers`});for(let n of WI)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is a managed-settings object, not a policyHelpers entry; entry fields (${WI.join("/")}) belong on the per-OS entries (policyHelpers.${is.join("/")})`});for(let n of WS)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is the managedSettings SUBTREE, not the helper's stdout envelope; paste the object your helper emits UNDER "managedSettings", not the envelope around it`});for(let n of XI)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is the VALUE of a policyHelpers key (a managed-settings object), never another policyHelpers map; don't paste the map or its "${n}" line inside the slot`})})),_Je='Entry must carry "path" (a helper executable) or "script" + "interpreter" (an inline helper), and/or "defaultSettings" (a static settings payload)';function yJe(e){let{path:t,script:n,interpreter:r,defaultSettings:o}=e;if(t!==void 0&&n!==void 0)return uJe;if(n===void 0!==(r===void 0))return dJe;if(t===void 0&&n===void 0&&o===void 0)return _Je;return null}function m7(e,t){return qS().omit({path:!0}).extend({path:ld(gJe(e)),script:ld(fJe(e)),interpreter:ld(lJe(e)),outputBehavior:ld(f7()),defaultSettings:ot((n)=>n===null?void 0:n,t.optional()).optional()}).check((n)=>{if(n.issues.length>0)return;let r=yJe(n.value);if(r!==null)n.issues.push({code:"custom",message:r,input:n.value})})}var T2t=L(()=>m7("linux",hc()));function qI(e,t=hc()){return e==="default"?hc():m7(e,t)}var bJe=L(()=>C(Object.fromEntries(XI.map((e)=>[e,ot((t)=>{if(t===null)return;if(e!=="default"&&p7(t))return;return t},qI(e).optional()).optional()])))),s7=["skills","agents","hooks","mcp"],i7=Object.freeze({type:"invalid-entry-stripped"}),SJe=L(()=>le([C({type:j("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(),C({type:_().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function YS(e,{strictPolicyHelperKeys:t=!1}={}){function n(o){return X(_(),VI()).check((s)=>{for(let[i,a]of Object.entries(s.value))if(a.source.source==="settings"&&a.source.name!==i)s.issues.push({code:"custom",input:a.source.name,path:[i,"source","name"],message:`Settings-sourced marketplace name must match its ${o} key (got key "${i}" but source.name "${a.source.name}")`})})}let r=(o,s)=>t?ot((i)=>{if(i===null)return;return s?s(i):i},o):o.catch(void 0);return C({$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:r(qS().optional(),(o)=>o&&typeof o==="object"&&!Array.isArray(o)&&o.path===null?void 0:o).describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),policyHelpers:r(bJe().optional()).describe(`@internal Per-OS variant of policyHelper, keyed by platform: macos, linux, windows, wsl, plus an optional "default" entry that is a STATIC settings payload (a JSON object of managed settings, not a helper). Each per-OS entry carries a helper — a "path", or an inline "script" + "interpreter" delivered to a fixed interpreter over stdin, either with timeoutMs/refreshIntervalMs — its own static "defaultSettings" payload, or both; an entry may be payload-only. Selection for a platform walks its chain (the platform's own entry; on wsl the linux entry next): the first helper on the chain wins over policyHelper; if no helper is configured — or the selected helper fails at startup or refresh — the first payload applies (the chain's "defaultSettings" in platform-specific-first order, then the top-level "default", applied with no process spawned; unrecognized platforms reach only "default"); with no payload either, policyHelper. Honored only from admin-controlled policy sources.`),...Nn.CLAUDE_CODE_ENABLE_XAA&&{xaaIdp:C({issuer:_().url().describe("IdP issuer URL for OIDC discovery"),clientId:_().describe("Claude Code's client_id registered at the IdP"),callbackPort:Q().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:C({type:j("command"),command:_()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:R().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:C({enabled:R().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:Q().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:Q().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:C({enabled:R().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:Q().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."),desktopSessionCleanupPeriodDays:Q().int().nonnegative().optional().describe("Retention ceiling in days for session transcripts created or last written by a desktop-host surface (Claude Desktop, Cowork), which are otherwise exempt from the cleanupPeriodDays sweep. 0 (the default) means no ceiling: such transcripts are kept until deleted another way. Unlike cleanupPeriodDays, 0 is allowed because this setting never disables writes — it only bounds an exemption from deletion. The ceiling is a hard cap: it also bounds an active archive grace, so the grace window of a release marker never keeps files past the ceiling. Ignored when cleanupPeriodDays is managed by org policy. A ceiling at or below cleanupPeriodDays effectively disables the exemption: those transcripts age out on the regular cleanupPeriodDays schedule, so the effective retention is whichever of the two periods is longer."),syncClaudeAiSkills:R().optional().describe("Set to false to turn off syncing of the skills you have enabled on claude.ai. In your user settings (or managed settings): nothing more is downloaded, previously synced skills (~/.claude/skills/synced) can no longer be run, are hidden from every session started afterwards, and are moved to ~/.claude/skills/.trash at the next launch (deleted after cleanupPeriodDays; re-downloaded, not restored, if you re-enable). In .claude/settings.local.json or --settings: downloads stop and synced skills are blocked and hidden for sessions in that workspace or invocation only (nothing is moved). Not read from project settings (.claude/settings.json). Only false is honored — the feature is enabled server-side for your account, so setting true does not turn it on early. While it is on, synced skills are available in every session, re-synced every 10 minutes, and removed when you disable them on claude.ai. Only applies when signed in with your Claude account."),syncClaudeAiPlugins:R().optional().describe("Set to false to turn off syncing of the plugins you have enabled on claude.ai. In your user settings (or managed settings): nothing more is downloaded, previously synced plugins (~/.claude/plugins/synced) are hidden from every session started afterwards and moved to ~/.claude/plugins/.trash at the next launch (deleted after cleanupPeriodDays; re-downloaded, not restored, if you re-enable). In .claude/settings.local.json or --settings: downloads stop and synced plugins are hidden for sessions in that workspace or invocation only (nothing is moved). Not read from project settings (.claude/settings.json). Only false is honored — the feature is enabled server-side for your account, so setting true does not turn it on early. While it is on, synced plugins load in every session like plugins you installed yourself (a plugin you installed with the same name takes precedence), are re-synced at each launch, and are removed when you disable them on claude.ai. Only applies when signed in with your Claude account."),skillListingMaxDescChars:Q().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:Q().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:R().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:Y5e().optional().describe("Environment variables to set for Claude Code sessions"),attribution:C({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:R().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:R().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,...!1,includeGitInstructions:R().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:d7(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:R().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:X(_(),_()).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.'),modelPicker:C({options:I(JI()).describe("Rows to show in the /model picker, in order."),replaceBuiltInOptions:R().optional().describe("When true, the picker shows only the Default row and these options — the built-in "+"lineup, gateway-discovered models and ANTHROPIC_CUSTOM_MODEL_OPTION are hidden. When false or unset, these options are added after the built-in lineup.")}).optional().describe("Curate the /model picker: an ordered list of models with your own labels, independent of the built-in lineup and of Claude Code releases. availableModels still applies to these rows. Honored from managed, --settings/SDK, and user settings only (not from a project checkout); the highest-precedence of those that defines modelPicker wins outright (no merging across sources). Typically set in managed settings by enterprise administrators."),modelPricing:C({multiplier:YI(),overrides:X(_(),ZI()).optional()}).optional().describe("Price usage at your organization's contracted rates instead of list price. "+"Affects every spend figure Claude Code reports — /cost, the status line, the SDK total_cost_usd, "+"--max-budget-usd, and the OpenTelemetry cost metric and events — which remain USD estimates, not an invoice "+'(the per-Mtok price labels in /model stay at list). "overrides" maps a model ID to its USD-per-million-token rates (input, output, cacheRead, '+"cacheWrite — all four required, each 0 to 10000; cacheWrite prices both 5-minute and 1-hour cache writes). "+"A matching row is charged exactly as written; fast-mode and US-data-residency surcharges are not added on top. "+'A key Claude Code itself uses for a built-in model — its ID such as "claude-sonnet-4-6", or its '+"first-party, Bedrock (any or no region prefix), Vertex or Foundry ID — covers every dated and provider form "+"of that model; any other key — a gateway model alias, or a spelling Claude Code does not itself use — "+'matches that model ID only (case-insensitive), and such an exact match wins over a built-in row. On Bedrock an application inference profile is matched by its backing model. An invalid row or multiplier is reported and skipped; the rest still apply. "multiplier" in (0, 1] scales every computed cost, overridden or not (0.85 = 85% of the price). Only honored from managed settings (server-managed, MDM / OS policy, or managed-settings.json), '+"or — when none of those sets it — when supplied by a host application that manages the model "+"provider; ignored in user, project, local and --settings sources."),enableAllProjectMcpServers:R().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:R().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:X(_(),q(["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:R().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(VS()).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(ZS()).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:fc().optional().describe("Custom commands to run before/after tool executions"),worktree:C({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:q(["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:q(["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."),location:_().optional().catch(void 0).describe("Directory under which Claude Code Desktop creates the worktrees of SSH sessions that run on this machine (an absolute path or one starting with ~/), instead of <project>/.claude/worktrees. Read by the desktop app from the SSH host user settings; a location chosen in the desktop app's SSH connection settings takes precedence. The CLI (--worktree, EnterWorktree, agent isolation) does not read it yet.")}).optional().describe("Git worktree configuration: the CLI --worktree flag, EnterWorktree and agent isolation, plus the location Claude Code Desktop uses for SSH-session worktrees on this machine."),disableAllHooks:R().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:R().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:R().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:R().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:R().optional().describe("Deprecated: use enableArtifact: false. Still honored — true disables the Artifact tool; false is ignored."),enableArtifact:R().optional().describe("Turn the Artifact tool on or off. Off in any of managed, --settings, or user settings wins; project and local settings can only turn it off. Unset defaults to on once the feature is available."),enableWorkflows:R().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowSizeGuideline:q(["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:R().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:R().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:q(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:R().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:R().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:R().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:R().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:R().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:ot((o)=>Array.isArray(o)?o.filter((s)=>s7.includes(s)):o,le([R(),I(q(s7))])).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:C({type:j("command"),command:_(),padding:Q().optional(),refreshInterval:Q().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:R().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(SJe().catch(i7)).transform((o)=>o.filter((s)=>s!==i7)).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:C({type:j("command"),command:_()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:X(_(),le([I(_()),R(),vO()])).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:n("extraKnownMarketplaces").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."),additionalMarketplaces:n("additionalMarketplaces").optional().describe("Alias for extraKnownMarketplaces: this key is read exactly as if it were spelled "+"extraKnownMarketplaces. Do not set both in one file — if both appear, this key is ignored "+"with a warning. Claude Code may rewrite this key as extraKnownMarketplaces when it updates the file. Clients older than this alias ignore it, so prefer extraKnownMarketplaces while older Claude Code versions still share the same settings."),strictKnownMarketplaces:I(ad()).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."),allowedMarketplaces:I(ad()).optional().describe("Alias for strictKnownMarketplaces (managed settings only): this key is read exactly as if it "+"were spelled strictKnownMarketplaces. Do not set both in one file — if both appear, this key "+"is ignored with a warning. Clients older than this alias ignore it, so keep using strictKnownMarketplaces when the allowlist must also bind older Claude Code versions."),blockedMarketplaces:I(ad()).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:R().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:R().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:q(["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:q(["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).`),managedSourcesBehavior:q(["first-wins","merge"]).optional().describe('Controls how the managed settings sources compose. "first-wins" (default): the highest-priority source present (server-managed > MDM (managed plist / HKLM) > managed-settings.json) is the managed tier alone. "merge": every present source deep-merges with fixed '+"precedence server-managed > MDM > managed-settings.json — scalars "+"take the highest source's value and arrays union, except fallbackModel and the restriction allowlists allowedMcpServers, availableModels, strictKnownMarketplaces and allowedChannelPlugins (the highest source that sets one owns it whole) and the auth pins forceLoginOrgUUID, forceLoginMethod and forceLoginGatewayUrl (highest source only). Honored only from the highest-priority source present; enable it only when every lower source is admin-controlled, since lower sources then contribute entries such as permissions.allow. HKCU and --managed-settings never take part in the merge."),forceLoginOrgUUID:le([_(),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:R().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:q(["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:R().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:RI().optional(),feedbackSurveyRate:Q().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:q(["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:R().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:C({mode:q(["append","replace"]),verbs:I(_())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:C({excludeDefault:R().optional().catch(void 0),tips:X5e().optional(),tipsFile:_().optional().catch(void 0).describe("Absolute or ~/ local path to a JSON file holding an array of tips (same shapes as `tips`); honored from user, --settings and on-disk managed settings only. Read once per CLI process (restart to pick up edits)."),label:_().optional().catch(void 0).describe('Prefix shown before your tips in the spinner (default "Tip")')}).passthrough().optional().catch(void 0).describe("Add your organization's own tips to the spinner tip rotation. tips: strings or {id, text, cooldownSessions?, priority?} objects; tipsFile: a JSON file of the same; label: prefix shown before your tips; excludeDefault: if true, only show your tips (default: false)."),syntaxHighlightingDisabled:R().optional().describe("Whether to disable syntax highlighting in diffs"),spellcheck:C({enabled:R().optional().catch(void 0).describe("Turn on spell checking of the prompt input (default: false)"),checker:_().optional().catch(void 0).describe(`Which spell checker to run: ${zS.map((o)=>`"${o}"`).join(", ")}, or "auto" (default) for the first of those found on PATH`),language:_().optional().catch(void 0).describe(`Dictionary to use, passed to the checker as-is (aspell --lang, hunspell -d, ispell -d), e.g. "en_GB"; names are checker-specific (letters, digits and _ - . , only). Default: the checker's own default`),color:_().optional().catch(void 0).describe(`Color of misspelled words (they are also underlined): a terminal color name such as "red" or "magenta", "#rrggbb", "rgb(r,g,b)", "ansi256(n)" or "ansi:<name>". Default: the theme's error color`)}).passthrough().optional().catch(void 0).describe(`Underline misspelled words in the prompt input as you type, using an installed ${zS.slice(0,-1).join(", ")} or ${zS.at(-1)} (off unless "enabled" is true; does nothing if none is installed). Read from user, flag and managed settings only (the whole block from the highest-precedence of those applies); ignored in project .claude/settings.json and .claude/settings.local.json.`),terminalTitleFromRename:R().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),promptCacheTtl:q(["5m","1h"]).optional().catch(void 0).describe('Prompt cache TTL for the main conversation (interactive, -p and SDK turns, plus the helpers that run inline with it): "5m" or "1h". Unset = automatic: 1 hour on a Claude subscription within its usage limits, 5 minutes on an API key, Bedrock, Vertex or Foundry. 1-hour cache writes are billed at a higher rate; the cache stays warm across longer breaks. The CLAUDE_CODE_PROMPT_CACHE_TTL environment variable takes precedence.'),subagentPromptCacheTtl:q(["5m","1h"]).optional().catch(void 0).describe("Prompt cache TTL for everything outside the main conversation — subagents, workflows, background and helper requests: "+'"5m" or "1h". Unset = automatic (5 minutes unless ENABLE_PROMPT_CACHING_1H=1). The CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL environment variable takes precedence.'),alwaysThinkingEnabled:R().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:q(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),modelSettings:ot((o)=>typeof o==="object"&&o!==null&&!Array.isArray(o)?th(o,(s,i)=>Object.hasOwn(Object.prototype,i)):o,X(_(),C({effortLevel:q(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for this model.")}).passthrough().optional().catch(void 0))).optional().catch(void 0).describe("Per-model settings keyed by canonical model name."),ultracode:R().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:Q().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:R().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:R().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:R().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),emojiCompletionEnabled:R().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:R().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:R().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:q(["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:q(["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:q(gX).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:X(_(),C({mcpServers:X(_(),X(_(),le([_(),Q(),R(),I(_())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:X(_(),le([_(),Q(),R(),I(_())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(vO())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:C({defaultEnvironmentId:_().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:q(["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:q(["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:C({enabled:R().optional(),mode:q(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:R().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:R().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(C({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:R().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:R().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:q(["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 padded-countdown. "+"Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:Q().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:R().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 on. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:R().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:R().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:R().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:R().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:R().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:q(["disable"]).optional().describe("Disable auto mode"),sshConfigs:I(C({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:Q().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:le([q(hX),_().startsWith("custom:").transform((o)=>o)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:q(pX).optional().catch(void 0).describe("Key binding mode for the prompt input"),keybindingFlavor:q(fX).optional().catch(void 0).describe(`Which conventions the prompt's word-editing keys follow: "readline" matches Bash and other readline programs (Ctrl+W deletes back to the previous whitespace; Alt+F and Alt+D stop at the end of the current word and Ctrl+Y can paste back what Alt+D deleted; for Alt+B, Alt+F, Alt+D, Ctrl/Option+Arrow and Option/Ctrl+Backspace a word is a run of letters and digits, so punctuation separates words); "classic" (default) keeps Claude Code's long-standing behavior (Ctrl+W deletes the previous word; the word keys use Unicode word segmentation, so foo_bar and 3.14 are one word)`),vimInsertModeRemaps:X(_(),Te()).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:R().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:q(dX).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:R().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:R().optional().describe("Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:R().optional().describe("When safeguards flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoContinueAtUsageLimit:R().optional().describe("When a claude.ai usage limit stops your session, wait for the limit to reset and continue the task automatically. When off, the limit dialog offers the wait as a choice instead."),autoScrollEnabled:R().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:R().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:R().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:R().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:R().optional().describe("Stamp each message with its arrival time"),terminalProgressBarEnabled:R().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:R().optional().describe("Enable the todo / task tracking panel"),teammateMode:q(mX).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:R().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:R().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:q(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),crossSessionInbound:q(ah).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:R().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:R().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:R().optional().describe("Allow Claude to push proactive mobile notifications"),...GX(e)}).passthrough()}var ud=L(()=>YS(ih())),a7=Object.freeze({serverName:"invalid-entry-stripped"});function c7(e,t,n){return I(t.catch((r)=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${r.issues[0]?.message??"failed validation"}`}),a7))).transform((r)=>r.filter((o)=>o!==a7)).optional()}function QI(e,t){let n=ud(),r={};for(let[b,x]of Object.entries(n.shape))r[b]=x.catch((v)=>{e({path:b,message:`${v.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});r.allowedMcpServers=c7("allowedMcpServers",VS(),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=c7("deniedMcpServers",ZS(),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.syncClaudeAiSkills=n.shape.syncClaudeAiSkills.catch(()=>(e({path:"syncClaudeAiSkills",message:'"syncClaudeAiSkills" was present but invalid; treating it as false (claude.ai skills sync off) until it is fixed.'}),!1)),r.syncClaudeAiPlugins=n.shape.syncClaudeAiPlugins.catch(()=>(e({path:"syncClaudeAiPlugins",message:'"syncClaudeAiPlugins" was present but invalid; treating it as false (claude.ai plugins sync off) until it is fixed.'}),!1)),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(Te()).transform((b,x)=>{let v=[];for(let A of b)if(typeof A==="string")v.push(A);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(A)}); the entry was ignored.`});return v}).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.'}),[]));let o=!1,s=(b,x)=>{let v=b.safeParse(x);if(v.success)return;return v.error.issues.slice(0,3).map((A)=>A.path.length?`${A.path.join(".")}: ${A.message}`:A.message).join("; ")},i;r.policyHelper=ot((b)=>{if(o=!1,i=b,b&&typeof b==="object"&&!Array.isArray(b)){let x=b;for(let v of["defaultSettings","default",...WS])if(x[v]!==void 0&&x[v]!==null)e({path:"policyHelper",message:`"${v}" on the singular policyHelper is ignored — static fallback payloads belong on the policyHelpers per-OS entries ("defaultSettings") or the map's "default" key. The intended fallback will NOT apply from here.`,statusOnly:!0});for(let v of["policyHelper","policyHelpers"])if(x[v]!==void 0&&x[v]!==null)e({path:"policyHelper",message:`"${v}" inside the singular policyHelper is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; nothing nests inside the singular entry. The nested config will NOT apply from here.`,statusOnly:!0});for(let v of is)if(x[v]!==void 0&&x[v]!==null)e({path:"policyHelper",message:`"${v}" on the singular policyHelper is ignored — per-OS entries live on the policyHelpers MAP ("policyHelpers": {"${v}": ...}), not inside the singular key. The intended per-OS config will NOT apply from here.`,statusOnly:!0});if(x.claudeMd!==void 0&&x.claudeMd!==null)e({path:"policyHelper",message:`"claudeMd" on the singular policyHelper is ignored — "claudeMd" is a managed-settings key: put it at the settings top level or inside a static payload, or emit it from the helper's stdout envelope. The intended instructions will NOT apply from here.`,statusOnly:!0});if(x.outputBehavior!==void 0&&x.outputBehavior!==null)e({path:"policyHelper",message:`"outputBehavior" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${is.join("/")}); this helper's output REPLACES the policy tier whatever the value says.`,statusOnly:!0});if(x.path===null||x.path===void 0)o=!0}return b===null?void 0:b},qS().optional()).catch((b)=>{e({path:"policyHelper",message:`${b.issues[0]?.message??s(qS(),i)??"Failed schema validation"}. This field was ignored.`,...o&&{statusOnly:!0}});return});let a=(b,x)=>{e({path:b,message:`"${b}" is not a valid static settings payload: ${x??"failed 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})},c=(b)=>{let x=!1,v,A=qI(b,hc().optional().catch((U)=>{x=!0,a(`policyHelpers.${b}.defaultSettings`,U.issues[0]?.message??s(hc(),v&&typeof v==="object"&&!Array.isArray(v)?v.defaultSettings:void 0));return}));return ot((U)=>{if(x=!1,v=U,b!=="default"&&U&&typeof U==="object"&&!Array.isArray(U)){let D=U;for(let F of[...WS,"claudeMd"])if(D[F]!==void 0&&D[F]!==null)e({path:`policyHelpers.${b}`,message:`"${F}" on the policyHelpers.${b} entry is ignored — helper output cannot be pre-seeded on an entry; a static fallback payload goes under this entry's "defaultSettings" (a managed-settings object). The intended content will NOT apply from here.`,statusOnly:!0});for(let F of["policyHelper","policyHelpers"])if(D[F]!==void 0&&D[F]!==null)e({path:`policyHelpers.${b}`,message:`"${F}" on the policyHelpers.${b} entry is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; nothing nests inside an entry. The nested config will NOT apply from here.`,statusOnly:!0});for(let F of is)if(D[F]!==void 0&&D[F]!==null)e({path:`policyHelpers.${b}`,message:`"${F}" on the policyHelpers.${b} entry is ignored — per-OS entries are SIBLINGS on the policyHelpers map, not nested inside each other. The intended ${F} config will NOT apply from here.`,statusOnly:!0});if(D.default!==void 0&&D.default!==null)e({path:`policyHelpers.${b}`,message:`"default" on the policyHelpers.${b} entry is ignored — the per-entry static payload field is spelled "defaultSettings"; "default" is the MAP's any-platform catch-all key (a sibling of the OS entries). The intended fallback will NOT apply from here.`,statusOnly:!0});if(p7(U))return}return U===null?void 0:U},A.optional()).catch((U)=>{if(b==="default"){a("policyHelpers.default",U.issues[0]?.message??s(hc(),v));return}if(x)return;let D=s(qI(b),v)??"failed validation",F=v;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F,V=K.defaultSettings;if(V!==void 0&&V!==null){let ne=hc().safeParse(V);if(ne.success){let oe=K.outputBehavior,ge=oe===void 0||oe===null?null:f7().safeParse(oe);if(ge&&!ge.success){e({path:`policyHelpers.${b}`,message:`Invalid entry was ignored: ${D}. Its "defaultSettings" static payload was NOT kept: "outputBehavior" is unrecognized, so whether the payload replaces or merges over this source's settings is unknown. No policy helper runs on ${b} from this entry.`,statusOnly:!0});return}return e({path:`policyHelpers.${b}`,message:`Invalid entry: its helper fields were ignored (${D}), but its "defaultSettings" static payload was kept. No policy helper runs on ${b} from this entry.`,statusOnly:!0}),{defaultSettings:ne.data,...ge&&{outputBehavior:ge.data}}}}}e({path:`policyHelpers.${b}`,message:`Invalid entry was ignored: ${D}. No policy helper runs on ${b} from this entry.`,statusOnly:!0});return})};r.policyHelpers=ot((b)=>{if(b&&typeof b==="object"&&!Array.isArray(b)){let x=b;for(let v of["defaultSettings",...WS,"claudeMd"])if(x[v]!==void 0&&x[v]!==null)e({path:"policyHelpers",message:`"${v}" directly on the policyHelpers map is ignored — static fallback payloads go on a per-OS entry's "defaultSettings" or the map's "default" key (a managed-settings object), and helper-output keys come from the helper's stdout. The intended content will NOT apply from here.`,statusOnly:!0});for(let v of["policyHelper","policyHelpers"])if(x[v]!==void 0&&x[v]!==null)e({path:"policyHelpers",message:`"${v}" inside the policyHelpers map is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; the map's keys are the per-OS entries and "default". The nested config will NOT apply from here.`,statusOnly:!0});for(let v of WI.filter((A)=>A!=="defaultSettings"))if(x[v]!==void 0&&x[v]!==null){let A=v==="script"||v==="interpreter"?"; inline scripts are per-OS only (the singular policyHelper key takes a path)":v==="outputBehavior"?"":", or on the singular policyHelper key";e({path:"policyHelpers",message:`"${v}" directly on the policyHelpers map is ignored — helper configs go on a per-OS entry (policyHelpers.${is.join("/")})${A}. No helper runs from this field here.`,statusOnly:!0})}}return b===null?void 0:b},C(Object.fromEntries(XI.map((b)=>[b,c(b)]))).transform((b)=>{for(let x of Object.keys(b))if(b[x]===void 0)delete b[x];return b}).optional().catch((b)=>(e({path:"policyHelpers",message:`"policyHelpers" could not be parsed: expected an object mapping OS keys (${is.join(", ")}) to helper entries, plus an optional "default" settings payload (${b.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 l=Object.freeze({mode:"deny"}),u=Object.freeze({accessKeyIdVar:"_STRIPPED_",secretAccessKeyVar:"_STRIPPED_2_"}),p=0,f=[],m=t===void 0?"":`${[...t].reduce((b,x)=>Math.imul(b^x.charCodeAt(0),16777619)>>>0,2166136261).toString(16).toUpperCase().padStart(8,"0")}_`,h=(b,x)=>{if(typeof b!=="object"||b===null)return;let v=(Je)=>x.some((wt)=>wt.path?.includes(Je)),A=(Je)=>{let wt=b[Je];if(typeof wt==="string")return wt;return v(Je)?"":void 0},U=A("accessKeyIdVar"),D=A("secretAccessKeyVar"),F=A("sessionTokenVar"),K=od;if(![U,D,F].some((Je)=>Je!==void 0&&K.includes(Je)))return;let V=(Je)=>Je!==void 0&&rd().safeParse(Je).success;p+=1;let ne=(Je)=>`${kI}${Je}_${m}${p}_`,oe=V(U)?U:ne("ACCESS_KEY_ID"),ge=V(D)&&D!==oe?D:ne("SECRET_ACCESS_KEY"),ke=F===void 0?void 0:V(F)&&F!==oe&&F!==ge?F:ne("SESSION_TOKEN"),vt=(Je)=>Je.startsWith(kI);if(!vt(oe)&&!vt(ge)){let Je=K.includes(ge)?ge:void 0;if(ge=ne("SECRET_ACCESS_KEY"),Je!==void 0){let wt=h({accessKeyIdVar:Je},[]);if(wt!==void 0)f.push(wt)}}let Z=US().safeParse({accessKeyIdVar:oe,secretAccessKeyVar:ge,...ke!==void 0&&{sessionTokenVar:ke}});return Z.success?Z.data:void 0},g=(b,x,v)=>I(x.catch((A)=>{let U=v(A.value);if(U!==void 0)return e({path:`sandbox.credentials.${b}[]`,message:`Invalid entry was degraded to mode "deny": ${A.issues[0]?.message??"failed validation"}. The credential stays blocked (not masked) until the entry is fixed.${b==="files"?" Under sandbox.filesystem.disabled, file read-denies are not enforced.":""}`}),U;return e({path:`sandbox.credentials.${b}[]`,message:`Invalid entry was ignored: ${A.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),l})).transform((A)=>A.filter((U)=>U!==l)).optional().catch((A)=>{if(typeof A.value==="object"&&A.value!==null&&!Array.isArray(A.value)){let U=x.safeParse(A.value);if(U.success)return e({path:`sandbox.credentials.${b}`,message:`"${b}" must be an array; a lone entry object was accepted as a one-element list. Wrap it in [ ] to silence this warning.`}),[U.data];let D=v(A.value);if(D!==void 0)return e({path:`sandbox.credentials.${b}`,message:`"${b}" 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.`}),[D]}return e({path:`sandbox.credentials.${b}`,message:`${A.issues[0]?.message??"Invalid value"}. "${b}" was ignored; these credential entries are NOT protected until it is fixed.`}),[]}),y=C({files:g("files",MS(),(b)=>{if(typeof b!=="object"||b===null||!("mode"in b)||b.mode!=="mask"&&b.mode!=="deny"||!("path"in b)||typeof b.path!=="string")return;let x=MS().safeParse({path:b.path,mode:"deny"});return x.success?x.data:void 0}),envVars:g("envVars",NS(),(b)=>{if(typeof b!=="object"||b===null||!("mode"in b)||b.mode!=="mask"&&b.mode!=="deny"||!("name"in b)||typeof b.name!=="string")return;let x=NS().safeParse({name:b.name,mode:"deny"});return x.success?x.data:void 0}),allowPlaintextInject:R().optional().catch((b)=>(e({path:"sandbox.credentials.allowPlaintextInject",message:`${b.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(US().catch((b)=>{let x=h(b.value,b.issues);if(x!==void 0)return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was degraded to a non-functional suppressor: ${b.issues[0]?.message??"failed validation"}. It keeps implicit AWS auto-pairing suppressed but re-signs nothing until it is fixed.`}),x;return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was ignored: ${b.issues[0]?.message??"failed validation"}. SigV4 re-signing stays unconfigured for this pair until it is fixed.`}),u})).transform((b)=>{let x=b.filter((v)=>v!==u);if(f.length>0)x.push(...f),f.length=0;return x}).optional().catch((b)=>{let x=typeof b.value==="object"&&b.value!==null?h(b.value,[]):void 0,v=typeof b.value==="object"&&b.value!==null&&(("accessKeyIdVar"in b.value)||("secretAccessKeyVar"in b.value)||("sessionTokenVar"in b.value));if(x===void 0&&v)return f.length=0,e({path:"sandbox.credentials.awsPairs",message:`${b.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 A=x!==void 0?[x]:od.flatMap((U)=>{let D=h({accessKeyIdVar:U},[]);return D!==void 0?[D]:[]});if(f.length>0)A.push(...f),f.length=0;return e({path:"sandbox.credentials.awsPairs",message:`${b.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.`}),A}),sigv4:C(Object.fromEntries(["streaming","presigned","sigv4a"].map((b)=>[b,q(["deny","passthrough"]).optional().catch((x)=>(e({path:`sandbox.credentials.sigv4.${b}`,message:`${x.issues[0]?.message??"Invalid value"}. "${b}" was degraded to an explicit deny; this SigV4 request shape stays denied until it is fixed.`}),"deny"))]))).optional().catch((b)=>(e({path:"sandbox.credentials.sigv4",message:`${b.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((b)=>{e({path:"sandbox.credentials",message:`${b.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 x=od.flatMap((v)=>{let A=h({accessKeyIdVar:v},[]);return A!==void 0?[A]:[]});return f.length=0,{allowPlaintextInject:!1,awsPairs:x,sigv4:{streaming:"deny",presigned:"deny",sigv4a:"deny"}}});return r.sandbox=RI().extend({credentials:y}).optional().catch((b)=>{e({path:"sandbox",message:`${b.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});let x=b.value;if(typeof x==="object"&&x!==null&&"credentials"in x){let v=y.safeParse(x.credentials);if(v.success&&v.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:v.data}}return}),C(r).passthrough().transform((b)=>{for(let x of Object.keys(b))if(b[x]===void 0)delete b[x];return b})}function JS(e){if(Array.isArray(e))return e.map(JS);if(e!==null&&typeof e==="object"){let t={};for(let n of Object.keys(e).sort())t[n]=JS(e[n]);return t}return e}function _7(e){if(!e)return{shellSettings:{},envVars:{},hasHooks:!1,hasClaudeMd:!1};let t={},n;for(let c of tX){let l=e[c];if(c==="policyHelpers"){if(l!==null&&typeof l==="object")for(let p of is){let f=vJe(l[p]);if(f){if(t[`policyHelpers.${p}`]=f.command,f.scriptSize)n??={},n[`policyHelpers.${p}`]=f.scriptSize}}continue}let u;if(typeof l==="string")u=l;else if(l!==null&&typeof l==="object"&&"command"in l&&typeof l.command==="string")u=l.command;if(u!==void 0&&u.length>0)t[c]=u}let r=kJe(e);if(r&&typeof r==="object")for(let[c,l]of Object.entries(r)){let u=l?.source;if(!u||typeof u!=="object")continue;if(u.source==="url"&&typeof u.headersHelper==="string"&&u.headersHelper.length>0)t[`extraKnownMarketplaces[${fe(c)}].source.headersHelper`]=h7(u.headersHelper,"url",u.url);if(u.source==="settings"&&Array.isArray(u.plugins)){let p=new Map;for(let f of u.plugins){let m=fe(f?.name),h=p.get(m)??0;p.set(m,h+1);let g=f?.source;if(g!==null&&typeof g==="object"&&"source"in g&&g.source==="command"&&"command"in g&&typeof g.command==="string"&&g.command.length>0)t[`extraKnownMarketplaces[${fe(c)}].plugins[${fe(f.name)}][${h}].source.command`]=g.command;if(typeof f?.headersHelper==="string"&&f.headersHelper.length>0){let y=f.source,S=y!==null&&typeof y==="object";t[`extraKnownMarketplaces[${fe(c)}].plugins[${fe(f.name)}][${h}].headersHelper`]=h7(f.headersHelper,S&&"source"in y?y.source:void 0,S&&"url"in y?y.url:void 0)}}}}let o=e.sandbox;if(o!==null&&typeof o==="object")for(let c of nX){let l=TJe(o[c]);if(l)t[`sandbox.${c}`]=l}let s={};if(e.env&&typeof e.env==="object")for(let[c,l]of Object.entries(e.env)){if(l===void 0)continue;let u=String(l);if(u.length>0&&!rX(c,u))s[c]=u}let i=e.hooks!==void 0&&e.hooks!==null&&typeof e.hooks==="object"&&Object.keys(e.hooks).length>0,a=typeof e.claudeMd==="string"&&e.claudeMd.length>0;return{shellSettings:t,inlineHelperScriptSizes:n,envVars:s,hasHooks:i,hooks:i?e.hooks:void 0,hasClaudeMd:a,claudeMd:a?e.claudeMd:void 0}}function EJe(e){return Object.keys(e.shellSettings).some((t)=>t.startsWith("policyHelpers."))}function y7(e){return EJe(e)||Object.keys(e.shellSettings).some((t)=>t.startsWith("extraKnownMarketplaces["))}function xJe(e){return e==="sh"||e==="pwsh"}function vJe(e){if(e===null||typeof e!=="object")return;let{path:t,script:n,interpreter:r,timeoutMs:o,refreshIntervalMs:s}=e,i,a;if(typeof t==="string"&&t)i=t;else if(typeof n==="string"&&n&&xJe(r))i={interpreter:r,script:AJe(n)},a=wJe(n);else return;return{command:fe([i,o??null,s??null]),scriptSize:a}}function wJe(e){return{bytes:Buffer.byteLength(e,"utf8"),lines:ZD(e,`
160
160
  `)+(e.endsWith(`
161
- `)?0:1)}}function AJe(e){return g7("sha256").update(fe(e)).digest("hex")}function TJe(e){if(typeof e==="string")return e||void 0;if(e===null||typeof e!=="object"||!("command"in e)||typeof e.command!=="string"||!e.command)return;let t="args"in e&&Array.isArray(e.args)?e.args.map(String):[];return fe([e.command,...t])}function CJe(e){return fe(JS({shellSettings:e.shellSettings,envVars:e.envVars,hooks:e.hooks,claudeMd:e.claudeMd}))}function b7(e){return g7("sha256").update(CJe(e)).digest("hex")}function h7(e,t,n){return fe([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}function S7(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function kJe(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of nh){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var RJe="remote-settings.json";var x7="remote-settings-helper-consent";function OJe(){return E7(Gt(),x7)}function PJe(e){if(e.policyHelpers===void 0&&e.extraKnownMarketplaces===void 0&&!nh.some(({alias:n,canonical:r})=>r==="extraKnownMarketplaces"&&e[n]!==void 0))return;let t=_7(e);return y7(t)?b7(t):void 0}function IJe(e){return th(e,(t,n)=>n.startsWith("$")&&n!=="$schema")}class v7{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;ineligibleReason=void 0;lastLoadStatus=void 0;lastLoadStatusChanged=At();policySettingsNotified=!1;verifiedPayload=null;unverifiedView=null;consentedPayload=null;resetEpoch=0;backendView=void 0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified)this.verifiedPayload=e}seedFromDisk(e){this.sessionCache=e;let t=PJe(e);if(t===void 0||t===UJe())this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}markPolicySettingsNotified(){this.policySettingsNotified=!0}recordEligibility(e,t){if(this.eligible=e,t.memoize)this.eligibilityMemo=e,this.ineligibleReason=e?void 0:t.ineligibleReason}resetListener=null;registerResetListener(e){if(this.resetListener!==null)throw Error("registerSyncCacheResetListener: a listener is already registered; a second one would unhook the first");this.resetListener=e}reset(){this.sessionCache=null,this.eligible=void 0,this.eligibilityMemo=void 0,this.ineligibleReason=void 0,this.lastLoadStatus=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,this.unverifiedView=null,this.consentedPayload=null,this.resetEpoch++,this.emitLoadStatusChanged(void 0)}emitLoadStatusChanged(e){try{this.lastLoadStatusChanged.emit(e)}catch(t){ae(`Remote settings: load-status listener threw: ${co(t)}`,{level:"error"})}}}var DJe=new tt(()=>new v7);function eD(){return DJe.of(Ct().host)}function XS(){return}function LJe(){return XS()??E7(Gt(),RJe)}var w7=8388608;function MJe(){try{let e=FJe();if(e===null)return null;let t=yt(bu(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return IJe(t)}catch(e){if(TJ(e))ae(`Remote settings: Disk cache exceeds ${w7} bytes; ignoring it as if absent`);return null}}var NJe=4096;function UJe(){let e=tD();if(e!==void 0)return e.attestation;try{return lc(OJe(),NJe).trim()||void 0}catch{return}}function FJe(){let e=tD();if(e!==void 0)return e.content;return lc(LJe(),w7)}function tD(){let e=eD().backendView;if(!ye()||e===void 0||!e.ready||e.stoodDown||XS()!==void 0)return;if(!t0(e.configHome)){e.standDown("config home changed");return}return e}var dKt=en.state("remote-settings"),pKt=en.state(x7);var jJe=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",...SI,...EI,"AWS_ENDPOINT_URL_STS","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_SSO","AWS_ENDPOINT_URL_SSO_OIDC","AWS_ENDPOINT_URL_BEDROCK","AWS_ENDPOINT_URL_BEDROCK_RUNTIME",...AI,...TI,...CI,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...xI,"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","CLAUDE_CODE_FEDERATION_CACHE_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 $Je(e){if(!e?.env)return e;let t=th(e.env,(n,r)=>jJe.has(r.toUpperCase()));return{...e,env:t}}function zJe(){let e=eD();if(!XS()&&e.eligible!==!0)return null;if(e.sessionCache)return e.sessionCache;let t=tD()!==void 0,n=MJe();if(n){if(e.seedFromDisk(n),t)pc().invalidatePolicyLayer();else oX();return n}return null}function A7(){let e=zJe(),t=eD();if(e===t.verifiedPayload||XS())return e;if(e===null)return null;if(t.unverifiedView?.raw!==e)t.unverifiedView={raw:e,view:$Je(e)};return t.unverifiedView.view}var T7=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];function HJe(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function C7(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&HJe(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{userInfo as BJe}from"os";var k7="com.anthropic.claudecode",ch="HKLM\\SOFTWARE\\Policies\\ClaudeCode",lh="HKCU\\SOFTWARE\\Policies\\ClaudeCode",qi="Settings",R7="/usr/bin/plutil",O7=["-convert","json","-o","-","--"],P7=5000,nD="/mnt/c/Windows/System32/reg.exe",dd="/mnt/c/Program Files/ClaudeCode";function uh(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Ee("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function I7(){let e="";try{e=BJe().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${k7}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${k7}.plist`,label:"device-level managed preferences"}),t}var D7=512;function L7(e){return e.map(KJe)}function KJe(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,mcpErrorMetadata:i,path:a,message:c,expected:l,suggestion:u,invalidValue:p,...f}=e,m=f;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,mcpErrorMetadata:i,path:dh(a),message:dh(c),expected:l===void 0?void 0:dh(l),suggestion:u===void 0?void 0:dh(u),invalidValue:typeof p==="string"?dh(p):void 0}}function dh(e){let t=S7(e.replace(/\s+/gu," "));return t.length>D7?`${t.slice(0,D7-1)}…`:t}var js="https://code.claude.com/docs/en",GJe=[{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:`${js}/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:`${js}/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:`${js}/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:`${js}/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:`${js}/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:`${js}/iam#working-directories`}}],WJe={permissions:`${js}/iam#configuring-permissions`,env:`${js}/settings#environment-variables`,hooks:`${js}/hooks`};function M7(e){let t=GJe.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=WJe[bE(e.path,".")];return n}var YKt=L(()=>YS(ih(),{strictPolicyHelperKeys:!0}).strict());function N7(e){return e.code==="invalid_type"}function U7(e){return e.code==="invalid_value"}function qJe(e){return e.code==="unrecognized_keys"}function F7(e){return e.code==="too_small"}function lr(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function j7(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function ph(e,t){return e.issues.map((n)=>{let r=n.path.map(String).join("."),o=n.message,s,i,a,c,l;if(U7(n))i=n.values.map((p)=>String(p)),a=i.join(" | "),c=void 0,l=void 0;else if(N7(n)){a=n.expected;let p=j7(n.message);c=p??lr(n.input),l=p??lr(n.input)}else if(F7(n))a=String(n.minimum);else if(n.code==="custom"&&"params"in n)c=n.params.received,l=c;let u=M7({path:r,code:n.code,expected:a,received:c,enumValues:i,message:n.message,value:c});if(U7(n))s=i?.map((p)=>`"${p}"`).join(", "),o=`Invalid value. Expected one of: ${s}`;else if(N7(n)){let p=j7(n.message)??lr(n.input);if(n.expected==="object"&&p==="null"&&r==="")o="Invalid or malformed JSON";else o=`Expected ${n.expected}, but received ${p}`}else if(qJe(n)){let p=n.keys.join(", ");o=`Unrecognized ${gE(n.keys.length,"field")}: ${p}`}else if(F7(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 VJe(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=KI(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 ZJe=new Set(xc);function YJe(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=lr(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(!ZJe.has(s)){delete r[s],o.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${xc.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(r[s])){let i=lr(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 JJe=[{key:"allowedMcpServers",schema:VS},{key:"deniedMcpServers",schema:ZS}];function XJe(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of JJe){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 ${lr(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 QJe(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 e8e(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(jI)}function t8e(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=lr(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=VI().safeParse(s[a]),l;if(!c.success){let u=QJe(s[a]);if(u!==void 0&&!$X.has(u)||e8e(s[a]))continue;l=$S(c.error.issues)}else if(c.data.source.source==="settings"&&c.data.source.name!==a)l=`key "${Wi(a)}" must match the settings source name "${Wi(c.data.source.name)}"`;if(l!==void 0)i.push({file:t,path:`${r}.${Wi(a)}`,message:`Invalid marketplace entry was ignored: ${l}`,severity:"warning"}),delete s[a]}return i}function n8e(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!pn(o)||!Array.isArray(o.options)){let c=pn(o)?`options: ${lr(o.options)}`:lr(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object with an "options" array of { model, label?, description? } rows; received ${c}. This field was ignored.`,severity:"warning",invalidValue:c}]}let s=[];if("replaceBuiltInOptions"in o&&typeof o.replaceBuiltInOptions!=="boolean"){let c=lr(o.replaceBuiltInOptions);delete o.replaceBuiltInOptions,s.push({file:t,path:`${r}.replaceBuiltInOptions`,message:`"replaceBuiltInOptions" must be true or false; received ${c}. This entry was ignored (the rows are added to the built-in lineup).`,severity:"warning",invalidValue:c})}let i=o.options,a=[];for(let c=0;c<i.length;c++){let l=JI().safeParse(i[c]);if(l.success){a.push(i[c]);continue}s.push({file:t,path:`${r}.options.${c}`,message:`${o8e(l.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:lr(i[c])})}if(a.length!==i.length)o.options=a;return s}function r8e(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let n=e;if(!("modelPricing"in n)||n.modelPricing===void 0)return[];let r=n.modelPricing;if(!r||typeof r!=="object"||Array.isArray(r))return delete n.modelPricing,[{file:t,path:"modelPricing",message:`"modelPricing" must be an object; received ${lr(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!YI().safeParse(o.multiplier).success)s.push({file:t,path:"modelPricing.multiplier",message:'"multiplier" must be a number in (0, 1]. It was ignored.',severity:"warning",invalidValue:o.multiplier}),delete o.multiplier;if(o.overrides!==void 0){let i=o.overrides;if(!i||typeof i!=="object"||Array.isArray(i))s.push({file:t,path:"modelPricing.overrides",message:`"overrides" must be an object mapping model ID to rates; received ${lr(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let c of Object.keys(a)){let l=ZI().safeParse(a[c]);if(l.success&&c!=="constructor"&&c!=="__proto__")continue;let u=l.success?void 0:l.error.issues[0];s.push({file:t,path:`modelPricing.overrides.${Wi(c)}`,message:`Invalid pricing row was ignored (${u?`${u.path.join(".")||"row"}: ${u.message}`:"not a model ID"}).`,severity:"warning",invalidValue:a[c]}),delete a[c]}}}return s}function o8e(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function s8e(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||i8e(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[l8e(o,t,n?.policySource===!0)]}function i8e(e){return typeof e==="string"&&ah.includes(e)}var a8e="crossSessionInbound";function c8e(e){let t=ah.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${Wi(e).replace(/^<key>$/,"<value>")}"`:lr(e);return`must be one of ${t}; received ${n}`}function l8e(e,t,n=!1){let r=ah.map((s)=>`"${s}"`).join(", "),o=n?'In managed settings an unrecognized value is treated as "refuse" (the most restrictive): cross-session messages to this session are turned away until an administrator fixes it.':"This value was ignored; while it is present, cross-session messages are held for your approval instead of being delivered. Set it to one of the values above.";return{file:t,path:a8e,message:`"crossSessionInbound" ${c8e(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}function gc(e,t,n){return[...Z8(e,t),...VJe(e,t),...YJe(e,t),...t8e(e,t),...n8e(e,t),...r8e(e,t),...s8e(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:XJe(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly})]}function iD(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),T7.filter((n)=>t.has(n))}function p8e(){return Mo(dc(),"managed-settings.json")}function aD(e){if($r()==="wsl"&&e.wslInherits?.()){let t=rD(dd,e.store);if(t.settings)return t;let n=rD(dc(),e.store);return{settings:n.settings,errors:[...t.errors,...n.errors]}}return rD(dc(),e.store)}function f8e(e){return e.endsWith(".json")&&!e.startsWith(".")}function rD(e,t){let n=[],r={},o=!1,{settings:s,errors:i}=fd(Mo(e,"managed-settings.json"),t,void 0,!0);if(n.push(...i),s&&Object.keys(s).length>0)r=Hn(r,s,Xr),o=!0;let a=Mo(e,"managed-settings.d");try{let c=t.folderListingForPolicyWalk(a),l;if(c!==void 0)l=c;else l=Qe().readdirSync(a).filter((u)=>(u.isFile()||u.isSymbolicLink())&&f8e(u.name)).map((u)=>u.name).sort(),t.noteWalkListing(a,l);for(let u of l){let{settings:p,errors:f}=fd(Mo(a,u),t,void 0,!0);if(n.push(...f),p&&Object.keys(p).length>0)r=Hn(r,p,Xr),o=!0}}catch(c){let l=Ue(c);if(l!=="ENOENT"&&l!=="ENOTDIR")ae(`managed-settings.d read failed: ${c}`,{level:"error"}),n.push({file:a,path:"",message:`Managed settings drop-in directory could not be read: ${l??"unknown error"}`,severity:"fatal"})}return{settings:o&&_c(r)?r:null,errors:n}}function m8e(e,t){if(Er(e))E8e(t);else ae(`settings file read failed at ${t}: ${e}`,{level:"error"})}function fd(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{settings:s.settings?ho(s.settings):null,errors:s.errors};let i=b8e(e,n,r);return t.parsedFiles.set(o,i),{settings:i.settings?ho(i.settings):null,errors:i.errors}}function cD(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 eE(e,t){let n=$7.get(e),r=n?.get(t);if(r)return{settings:r.settings&&ho(r.settings),errors:r.errors.map((s)=>({...s}))};let o=h8e(e,t);if(n)n.set(t,o);else $7.set(e,new Map([[t,o]]));return{settings:o.settings&&ho(o.settings),errors:o.errors.map((s)=>({...s}))}}var $7=new WeakMap;function h8e(e,t){let n=ho(e),r=gc(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=QI(G7(t,o),t).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...ph(s.error,t)]};return{settings:Object.keys(s.data).length>0?s.data:null,errors:[...r,...o]}}function G7(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)ae(`${e}: ${n.path}: ${n.message}`,{level:n.startupFatal?"error":"warn"})}}function W7(e){let t=e?.remote?e.remote():A7();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let{settings:n,errors:r}=eE(t,"remote managed settings");return{settings:n,errors:L7(r)}}var g8e="parent managed settings";function _8e(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return eE(t,g8e)}function q7(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=ho(t),r=gc(n,"SDK inline settings"),o=ud().safeParse(n);if(!o.success)return{settings:null,errors:[...r,...ph(o.error,"SDK inline settings")]};return{settings:o.data,errors:r}}var y8e=2097152;function b8e(e,t,n){try{let r;if(t!==void 0)r=t;else{let{resolvedPath:o}=of(Qe(),e);r=lc(o,y8e)}return S8e(r,e,n)}catch(r){return v8e(r,e)}}function S8e(e,t,n){if(e.trim()==="")return{settings:{},errors:[]};let r=ho(uc(e,!1));if(n){let i=gc(r,t,{skipMcpServerEntryFilter:!0,policySource:!0}),a=[],c=QI(G7(t,a),t).safeParse(r);if(!c.success)return{settings:null,errors:[...i,...ph(c.error,t)]};return{settings:c.data,errors:[...i,...a]}}let o=gc(r,t),s=ud().safeParse(r);if(!s.success){let i=ph(s.error,t);return{settings:null,errors:[...o,...i]}}return{settings:s.data,errors:o}}function E8e(e){ae(`Broken symlink or missing file encountered for settings.json at path: ${e}`)}function x8e(){return{settings:null,errors:[]}}function v8e(e,t){if(m8e(e,t),Er(e))return x8e();return{settings:null,errors:[{file:t,path:"",message:`Settings file could not be read: ${e instanceof Error?e.message:String(e)}`,severity:"fatal"}]}}function z7(e,t){switch(e){case"userSettings":return Qr(Gt());case"policySettings":case"projectSettings":return Qr(t.cwd);case"localSettings":return V7(t.cwd,t.canonicalGitRoot);case"flagSettings":return t.flagPath?d8e(Qr(t.flagPath)):Qr(t.cwd)}}function V7(e,t){let n=w8e(e,t);if(n.decided!==void 0)return n.decided;if(!C8e(n.root))return n.cwdResolved;return n.root}function w8e(e,t){let n=t?.(e);if(!n)return{decided:Qr(e)};let r=Qr(n),o=Qr(e);if(r===o)return{decided:r};let s;try{s=k8e()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function A8e(e){return pc().localStoreProbes.canonicalRootOwnerUids(e,T8e)}function T8e(e){let t=Qe(),n=null;try{n=t.lstatSync(Mo(e,".claude")).uid}catch(r){if(!Er(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:t.lstatSync(Mo(e,".git")).uid,claudeEntryUid:n}}function C8e(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return ae(`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}=A8e(e);if(n===t&&r===t&&(o===null||o===t))return!0;return ae(`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 ae(`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 k8e(){return pc().localStoreProbes.normalizedRealHomeDir(R8e)}function R8e(){let e=hE(u8e());if(e===null)throw Error("home directory realpath unavailable");return st(e)}var H7={default:"settings.json",cowork:"cowork_settings.json"};function O8e(e){if(e.coworkPlugins||Nn.CLAUDE_CODE_USE_COWORK_PLUGINS)return H7.cowork;return H7.default}function mh(e,t){switch(e){case"userSettings":return Mo(z7(e,t),O8e(t));case"projectSettings":case"localSettings":return Mo(z7(e,t),Z7(e));case"policySettings":return p8e();case"flagSettings":return t.flagPath}}function Z7(e){switch(e){case"projectSettings":return Mo(".claude","settings.json");case"localSettings":return Mo(".claude","settings.local.json")}}function Y7(e){if(V7(e.cwd,e.canonicalGitRoot)===Qr(e.cwd))return;return Mo(Qr(e.cwd),Z7("localSettings"))}function J7(e,t){let n=t.store.perSource.get(e);if(n!==void 0)return n;let r=Z8e(e,t);return t.store.perSource.set(e,r),r}function P8e(e){return!e||e.parentSettingsBehavior==="merge"}var X7=[{path:["allowManagedPermissionRulesOnly"],restrictive:!0},{path:["allowManagedHooksOnly"],restrictive:!0},{path:["allowManagedMcpServersOnly"],restrictive:!0},{path:["enforceAvailableModels"],restrictive:!0},{path:["disableAllHooks"],restrictive:!0},{path:["disableClaudeAiConnectors"],restrictive:!0},{path:["disableCommandPluginSources"],restrictive:!0},{path:["disableSideloadFlags"],restrictive:!0},{path:["disableSkillShellExecution"],restrictive:!0},{path:["disableRemoteControl"],restrictive:!0},{path:["disableAgentView"],restrictive:!0},{path:["disableWorkflows"],restrictive:!0},{path:["disableArtifact"],restrictive:!0},{path:["disableBundledSkills"],restrictive:!0},{path:["fastModePerSessionOptIn"],restrictive:!0},{path:["isolatePeerMachines"],restrictive:!0},{path:["strictPluginOnlyCustomization"],restrictive:!0},{path:["disableAutoMode"],restrictive:"disable"},{path:["disableDeepLinkRegistration"],restrictive:"disable"},{path:["permissions","disableBypassPermissionsMode"],restrictive:"disable"},{path:["permissions","disableAutoMode"],restrictive:"disable"},{path:["autoMode","classifyAllShell"],restrictive:!0},...[],{path:["worktree","bgIsolation"],restrictive:"worktree"},{path:["enableArtifact"],restrictive:!1},{path:["enableWorkflows"],restrictive:!1},{path:["syncClaudeAiSkills"],restrictive:!1},{path:["syncClaudeAiPlugins"],restrictive:!1},{path:["useAutoModeDuringPlan"],restrictive:!1},{path:["skipDangerousModePermissionPrompt"],restrictive:!1},{path:["skipAutoPermissionPrompt"],restrictive:!1},{path:["enableAllProjectMcpServers"],restrictive:!1},{path:["channelsEnabled"],restrictive:!1},{path:["skipWebFetchPreflight"],restrictive:!1},{path:["skipWorkflowUsageWarning"],restrictive:!1},{path:["autoUploadSessions"],restrictive:!1},{path:["remoteControlAtStartup"],restrictive:!1},{path:["autoContinueAtUsageLimit"],restrictive:!1},...[],{path:["attribution","sessionUrl"],restrictive:!1},{path:["crossSessionInbound"],restrictive:["refuse","hold"]},{path:["modelProposedGoals"],restrictive:["disabled","alwaysAsk"]},{path:["feedbackDrafts"],restrictive:"off"},{path:["askUserQuestionTimeout"],restrictive:"never"},{path:["dialogExpiry"],restrictive:"never"},{path:["sandbox","enabled"],restrictive:!0},{path:["sandbox","failIfUnavailable"],restrictive:!0},{path:["sandbox","autoAllowBashIfSandboxed"],restrictive:!1},{path:["sandbox","allowUnsandboxedCommands"],restrictive:!1},{path:["sandbox","enableWeakerNestedSandbox"],restrictive:!1},{path:["sandbox","enableWeakerNetworkIsolation"],restrictive:!1},{path:["sandbox","allowAppleEvents"],restrictive:!1},{path:["sandbox","network","allowManagedDomainsOnly"],restrictive:!0},{path:["sandbox","network","strictAllowlist"],restrictive:!0},{path:["sandbox","network","allowAllUnixSockets"],restrictive:!1},{path:["sandbox","network","allowLocalBinding"],restrictive:!1},{path:["sandbox","filesystem","allowManagedReadPathsOnly"],restrictive:!0},{path:["sandbox","filesystem","disabled"],restrictive:!1},{path:["sandbox","credentials","allowPlaintextInject"],restrictive:!1},{path:["sandbox","credentials","sigv4","streaming"],restrictive:"deny"},{path:["sandbox","credentials","sigv4","presigned"],restrictive:"deny"},{path:["sandbox","credentials","sigv4","sigv4a"],restrictive:"deny"}];function Q7(e){return Array.isArray(e)?e:[e]}var I8e=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function pd(e,t){let n=e;for(let r of t){if(n===null||typeof n!=="object")return;n=n[r]}return n}function fh(e,t,n){let r=[e],o=e;for(let i of t.slice(0,-1)){let a={...o[i]};o[i]=a,o=a,r.push(o)}let s=t.at(-1);if(n!==void 0){o[s]=n;return}delete o[s];for(let i=r.length-1;i>0;i--){if(Object.keys(r[i]).length>0)break;delete r[i-1][t[i-1]]}}function D8e(e){let t={};for(let{path:n,restrictive:r}of X7){let o=pd(e,n);if(n[0]==="sandbox"&&Q7(r).includes(o))fh(t,n,o)}return t.sandbox??{}}function L8e(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.syncClaudeAiSkills===!1)n.syncClaudeAiSkills=!1;if(e.syncClaudeAiPlugins===!1)n.syncClaudeAiPlugins=!1;if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(C7(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=LS(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={},c=o?LS(o,["deniedDomains"]):{},l=s?LS(s,["denyRead","denyWrite"]):{};if(o){if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&o.allowedDomains)c.allowedDomains=o.allowedDomains}if(Object.keys(c).length>0)a.network=c;if(s){if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&s.allowRead)l.allowRead=s.allowRead}if(Object.keys(l).length>0)a.filesystem=l;if(i){let u=(i.files??[]).map((m)=>m.mode==="deny"?{path:m.path,mode:"deny"}:{path:m.path,mode:"mask",injectHosts:[]}),p=(i.envVars??[]).filter((m)=>m.mode==="deny").map((m)=>({name:m.name,mode:"deny"})),f={...u.length>0&&{files:u},...p.length>0&&{envVars:p}};if(i.sigv4){let m={};for(let h of["streaming","presigned","sigv4a"])if(i.sigv4[h]==="deny")m[h]="deny";f.sigv4=m}{let m=od,h=Es((i.awsPairs??[]).flatMap((g)=>[g.accessKeyIdVar,g.secretAccessKeyVar,...g.sessionTokenVar!==void 0?[g.sessionTokenVar]:[]]).filter((g)=>m.includes(g)));if(h.length>0)f.awsPairs=h.map((g,y)=>({accessKeyIdVar:g,secretAccessKeyVar:`${lX}${y+1}_`}))}if(Object.keys(f).length>0)a.credentials=f}if(Hn(a,D8e(e)),Object.keys(a).length>0)n.sandbox=a}return n}var M8e=new Set([...[...vI].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...wI,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL"]);function N8e(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;if(e.modelPicker!==void 0)n.modelPicker=e.modelPicker;return Object.keys(n).length>0?n:null}function QS(e){if(delete e.model,delete e.fallbackModel,delete e.modelPicker,delete e.modelOverrides,e.env){let t={};for(let[n,r]of Object.entries(e.env))if(!M8e.has(n.toUpperCase()))t[n]=r;e.env=t}}function U8e(){return $r()==="macos"?"plist":"hklm"}function eQ(e){let t=lD(e);if(t.composes==="tier")return"helper";let n=sD(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return U8e();if(n.present.file)return"file";if(n.parentSlice||n.hostModelOverlay)return"parent";let r=e.hkcu?.();return r&&Object.keys(r.settings).length>0?"hkcu":null}function sD(e){let t=[],{settings:n,errors:r}=W7(e);t.push(...r);let o=lD(e),s=o.composes==="remoteSlot"?o.helper:oD(n),{settings:i,errors:a}=cD(e);t.push(...a);let c=oD(i),{settings:l,errors:u}=e.file?.()??aD(e);t.push(...u);let p=oD(l),{settings:f,errors:m}=_8e(e);t.push(...m);let h=[s,c,p].filter((V)=>V!==null),y=(o.composes==="remoteSlot"?o.helper:[n,i,l].find((V)=>V!==null&&(V.managedSourcesBehavior!==void 0||_c(V))))?.managedSourcesBehavior,{admin:S,merged:b}=F8e(h,y),x={remote:s!==null,mdm:c!==null,file:p!==null},v=(V)=>V!==null&&(V===h[0]||Object.keys(bI(V,oQ)).length>0),A={remote:v(s),mdm:v(c),file:v(p)},U={allowManagedPermissionRulesOnly:h.some((V)=>V.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:S?.forceLoginOrgUUID,allowedMcpServers:S?.allowedMcpServers,availableModels:S?.availableModels,sandbox:{network:{allowManagedDomainsOnly:h.some((V)=>V.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:h.some((V)=>V.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},D=f&&P8e(S)?L8e(f,U):null,F=D&&Object.keys(D).length>0?D:null,K=N8e(f,e.hostManagedProvider);return{tiers:h,admin:S,parentSlice:F,hostModelOverlay:K,errors:t,present:x,merged:b,composed:A}}function F8e(e,t){let n=e[0];if(!n)return{admin:null,merged:!1};let{managedSourcesBehavior:r,...o}=n;if(t!=="merge"||e.length<2)return{admin:r===void 0?n:o,merged:!1};let s=e.slice(1).map((a)=>{let c=bI(a,oQ);for(let u of I8e)if(pd(c,u)!==void 0)fh(c,u,void 0);let l=pd(c.sandbox,["enabledPlatforms"]);if(Array.isArray(l)&&l.includes($r()))fh(c,["sandbox","enabledPlatforms"],void 0);else if(l!==void 0)delete c.sandbox;return c}),i={};for(let a of[...s].reverse())Hn(i,a,B7);return Hn(i,o,B7),z8e(i,[n,...s]),j8e(i,[n,...s]),{admin:i,merged:!0}}var tQ=["managedSourcesBehavior","wslInheritsWindowsSettings"];function _c(e){return Object.keys(e).some((t)=>!tQ.includes(t))}function oD(e){return e&&_c(e)?e:null}function j8e(e,t){let n=t.findIndex((o)=>o.availableModels!==void 0),r=t.findIndex((o)=>o.modelOverrides!==void 0);if(r!==-1&&(n===-1||r<=n))e.modelOverrides={...t[r].modelOverrides};else delete e.modelOverrides}var $8e=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins"];function B7(e,t,n){if(n!==void 0&&$8e.includes(n)){if(t===void 0)return e;return Array.isArray(t)?[...t]:t}if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Es([...t,...e]);return Xr(e,t,n)}function z8e(e,t){let n=t[0],r=e;for(let{path:o,restrictive:s}of X7){let i=Q7(s),a=Math.min(...t.map((c)=>i.indexOf(pd(c,o))).filter((c)=>c!==-1));if(Number.isFinite(a))fh(r,o,i[a]);else if(pd(n,o)===void 0&&pd(e,o)!==void 0)fh(r,o,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Es(t.flatMap((s)=>Array.isArray(s.strictPluginOnlyCustomization)?s.strictPluginOnlyCustomization:[]));if(o.length>0)e.strictPluginOnlyCustomization=o;else if(n?.strictPluginOnlyCustomization===void 0)delete e.strictPluginOnlyCustomization}}function lD(e){let t=e.helper?.()??null;if(!t)return{composes:"none"};let n=e.helperArmedFromRemote?.()===!1?"tier":"remoteSlot";if(e.helperMergesOutput?.()!==!0)return{composes:n,helper:t,mergedOver:null};if(!e.store.policy.mergedHelper){let r,o;if(n==="remoteSlot")r=W7(e).settings,o="remote";else if(r=cD(e).settings)o=$r()==="macos"?"plist":"hklm";else r=(e.file?.()??aD(e)).settings,o="file";e.store.policy.mergedHelper={helper:B8e(r,t),mergedOver:Object.keys(nQ(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function nQ(e){let{policyHelper:t,policyHelpers:n,...r}=e??{};return r}function H8e(e,t){let n=new Map;for(let[o,s]of Object.entries(t)){let i=o.toUpperCase();if(!n.has(i))n.set(i,s)}let r={};for(let[o,s]of Object.entries(e))r[o]=n.get(o.toUpperCase())??s;return Object.assign(r,t)}function B8e(e,t){let n=nQ(e),r=Hn({},n,t,(o,s,i)=>Array.isArray(s)?[...s]:Xr(o,s,i));if(n.env&&t.env)r.env=H8e(n.env,t.env);return r}var rQ=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var oQ=[...rQ,"otelHeadersHelper","proxyAuthHelper","forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","parentSettingsBehavior","env","modelPicker",...tQ];function K8e(e){return Q8.some((t)=>e.startsWith(t))||X8.includes(e)}function G8e(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=K8e(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 W8e="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function K7(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==W8e)t[n]=r;return t}function q8e(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function V8e(e){let t=cD(e);return t.settings?t.errors:[...t.errors,...(e.file?.()??aD(e)).errors]}function sQ(e){let t=lD(e),n=e.helperWarnings?.()??[];if(t.composes==="tier"){let{helper:h}=t;e.store.lastPolicyEnvComposition=null;let g=e.hostManagedProvider?{...h}:h;if(e.hostManagedProvider)QS(g);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&h.availableModels!==void 0?h.modelOverrides:void 0};let y=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?V8e(e).filter((S)=>!S.statusOnly):[],...sD(e).errors.filter((S)=>S.statusOnly)];return{settings:g,errors:[...y,...n]}}let{tiers:r,admin:o,parentSlice:s,hostModelOverlay:i,errors:a,present:c}=sD(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(QS(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=Hn({},s??{},o??{},Xr);if(r.some((h)=>h.forceRemoteSettingsRefresh===!0))l.forceRemoteSettingsRefresh=!0;let u=Nn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,p=l.env;if(!u){let h=G8e(r.map((g)=>g.env),r.map((g)=>(g.otelHeadersHelper??"").trim()!==""),r.map((g)=>{let y=new Set;for(let S of rQ){let b=g[S];if(typeof b==="string"&&b.trim()!=="")for(let x of eX[S])y.add(x)}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=K7(l.env);if(h&&Object.keys(h).length>0)l.env=h;else delete l.env}if(e.hostManagedProvider){if(QS(l),i)Object.assign(l,i)}let f={env:K7(p)};if(e.hostManagedProvider)QS(f);let m=!u&&!q8e(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:rf(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 Z8e(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return sQ(t).settings;let r=mh(e,t),{settings:o}=r?fd(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=q7(t);if(s)return Hn(o||{},s,Xr)}if(e==="localSettings"&&n){let s=Y7(t);if(s){let{settings:i}=fd(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),Hn(i,o||{},Xr)}}return o}function Y8e(e,t){return{...e,...t}}function Xr(e,t,n){if(n==="modelPicker"&&t!==void 0)return iQ(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Es([...e,...t])}if(n==="extraKnownMarketplaces"&&pn(e)&&pn(t))return Y8e(e,t);return}function iQ(e){if(!pn(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>pn(n)?{...n}:n)}}}function J8e(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();Ym("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=Hn(r,n,Xr);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 iD(e)){if(l==="policySettings"){let{settings:p,errors:f}=sQ(e);if(c=p,p)r=Hn(r,p,Xr);a(f);continue}if(l==="localSettings"){let p=Y7(e);if(p&&!i.has(Qr(p))){i.add(Qr(p));let{settings:f,errors:m}=fd(p,e.store);if(a(m),f)e.onLegacyLocalSettingsRead?.("cascade"),r=Hn(r,f,Xr)}}let u=mh(l,e);if(u){let p=Qr(u),f=l==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(p)||f){i.add(p);let{settings:m,errors:h}=fd(u,e.store,l==="flagSettings"?e.flagExpectedContent:void 0);if(a(h),m)r=Hn(r,m,Xr)}}if(l==="flagSettings"){let{settings:p,errors:f}=q7(e);if(a(f),p)r=Hn(r,p,Xr)}}if(c){if(c.availableModels!==void 0)r.availableModels=[...c.availableModels];if(c.enforceAvailableModels!==void 0)r.enforceAvailableModels=c.enforceAvailableModels;if(c.modelPicker!==void 0)r.modelPicker=iQ(c.modelPicker)}return Ym("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 X8e(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=J8e(e);return e.store.mergedSettings=n,n}function Q8e(e){let{settings:t}=X8e(e);return t||{}}function aQ(e){e.store.invalidateAll();let t=[];for(let n of iD(e)){let r=J7(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:Q8e(e),sources:t}}function cQ(e,t){let n=iD(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(J7(o,t)?.[e]!==void 0)return o}return null}import{execFile as eXe}from"child_process";import{existsSync as tXe}from"fs";class lQ{promise=null;start(){if(this.promise)return;this.promise=uD()}reset(){this.promise=null}}var nXe=new lQ;function rXe(e){if(!e)return{status:"ok",exitCode:0,errno:null,signal:null};let t=e,n=typeof t.signal==="string"&&t.signal?t.signal:null;if(typeof t.code==="string")return{status:"spawn_error",exitCode:null,errno:t.code,signal:null};if(t.killed===!0)return{status:"timeout",exitCode:null,errno:null,signal:n};if(n)return{status:"killed",exitCode:null,errno:null,signal:n};return{status:"exited",exitCode:typeof t.code==="number"?t.code:null,errno:null,signal:null}}function hh(e,t){let n=Date.now();return new Promise((r)=>{try{eXe(e,t,{encoding:"utf-8",timeout:P7,windowsHide:!0},(o,s)=>{r({stdout:s??"",...rXe(o),durationMs:Date.now()-n})})}catch(o){let s=o.code;r({stdout:"",status:"spawn_error",exitCode:null,errno:typeof s==="string"?s:null,signal:null,durationMs:Date.now()-n})}})}function tE(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function uD(){return(async()=>{if(process.platform==="darwin"){let e=I7(),n=(await Promise.all(e.map(async({path:r,label:o})=>{if(!tXe(r))return{stdout:"",label:o,ok:!1};let{stdout:s,status:i}=await hh(R7,[...O7,r]);return{stdout:s,label:o,ok:i==="ok"&&!!s}}))).find((r)=>r.ok);return{plistStdouts:n?[{stdout:n.stdout,label:n.label}]:[],hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[n,r]=await Promise.all([hh(t,["query",ch,"/v",qi]),hh(t,["query",lh,"/v",qi])]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:tE(n),hkcu:tE(r)}}}if(uh()){let[e,t]=await Promise.all([hh(nD,["query",ch,"/v",qi]),hh(nD,["query",lh,"/v",qi])]);return{plistStdouts:null,hklmStdout:e.status==="ok"?e.stdout:null,hkcuStdout:t.status==="ok"?t.stdout:null,outcomes:{hklm:tE(e),hkcu:tE(t)}}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}function uQ(){return nXe.promise}var Vi=Object.freeze({settings:{},errors:[]});class hQ{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await(uQ()??uD()),{mdm:o,hkcu:s,wslInherits:i}=await dXe(r,e);this.replace(o,s,i);let a=Date.now()-t;ae(`MDM settings load completed in ${a}ms`);try{Ti("tengu_managed_settings_os_read",uXe(r,a))}catch{}if(Object.keys(o.settings).length>0){ae(`MDM settings found: ${Object.keys(o.settings).join(", ")}`);try{Ym("info","mdm_settings_loaded",{duration_ms:a,key_count:Object.keys(o.settings).length,error_count:o.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 oXe=new tt(()=>new hQ);function gh(){return oXe.of(Ct().host)}function sXe(e){gh().startLoad(e)}async function gQ(){let e=gh();if(!e.loadPromise)sXe();await e.loadPromise}function _Q(){return gh().mdm??Vi}function yQ(){return gh().hkcu??Vi}function bQ(){return gh().wslInherits}function dD(e,t){let n=uc(e,!1);if(!n||typeof n!=="object")return{settings:{},errors:[]};let{settings:r,errors:o}=eE(n,t);return{settings:r??{},errors:o}}function dQ(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}var iXe=new Map([["ENOENT",An("ENOENT")],["EACCES",An("EACCES")],["EPERM",An("EPERM")],["ENOEXEC",An("ENOEXEC")],["EAGAIN",An("EAGAIN")],["EMFILE",An("EMFILE")],["ENOMEM",An("ENOMEM")],["ETIMEDOUT",An("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",An("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),aXe=new Map([["SIGTERM",An("SIGTERM")],["SIGKILL",An("SIGKILL")],["SIGINT",An("SIGINT")]]);function cXe(e){if(!e)return;return iXe.get(e)??An("other")}function lXe(e){if(!e)return;return aXe.get(e)??An("other")}function pQ(e,t){if(!t)return{};return{[`${e}_status`]:si(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:cXe(t.errno),[`${e}_signal`]:lXe(t.signal),[`${e}_duration_ms`]:t.durationMs}}function uXe(e,t){return{is_wsl:uh(),await_ms:t,...pQ("hklm",e.outcomes.hklm),...pQ("hkcu",e.outcomes.hkcu)}}async function dXe(e,t){let n=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:a,label:c}=e.plistStdouts[0],l=dD(a,c);if(_c(l.settings))return{mdm:l,hkcu:Vi,wslInherits:!1};n.push(...l.errors)}let r=null;if(e.hklmStdout){let a=dQ(e.hklmStdout);if(a)r=dD(a,`Registry: ${ch}\\${qi}`)}if(r)n.push(...r.errors);let o=n.length>0?{settings:{},errors:n}:Vi,s=uh(),i=!1;if(s){if(i=r?.settings.wslInheritsWindowsSettings===!0||await fXe(t),!i)return{mdm:o,hkcu:Vi,wslInherits:!1}}if(r){if(_c(r.settings))return{mdm:r,hkcu:Vi,wslInherits:i}}if(await pXe(i,t))return{mdm:o,hkcu:Vi,wslInherits:i};if(e.hkcuStdout){let a=dQ(e.hkcuStdout);if(a){let c=dD(a,`Registry: ${lh}\\${qi}`);if(!s||c.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:l,managedSourcesBehavior:u,...p}=c.settings;return{mdm:o,hkcu:{settings:p,errors:c.errors},wslInherits:i}}if(c.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:c.errors},wslInherits:i}}}return{mdm:o,hkcu:Vi,wslInherits:i}}async function SQ(e,t){if(ye()&&t!==void 0)return(await RJ(e)).content;return lc(e)}async function EQ(e,t){if(ye()&&t!==void 0)return await Qe().readdir(e);return Qe().readdirSync(e)}async function pXe(e,t){if(e&&await mQ(dd,t))return!0;return mQ(dc(),t)}async function fQ(e,t){let n=ho(uc(await SQ(e,t),!1));if(!n||typeof n!=="object")return!1;return gc(n,e,{skipMcpServerEntryFilter:!0,policySource:!0}),_c(n)}async function fXe(e){async function t(n){try{let r=uc(await SQ(n,e),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(await t(md(dd,"managed-settings.json")))return!0;try{let n=md(dd,"managed-settings.d");for(let r of await EQ(n,e))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&await t(md(n,r.name)))return!0}catch{}return!1}async function mQ(e,t){try{if(await fQ(md(e,"managed-settings.json"),t))return!0}catch{}try{let n=md(e,"managed-settings.d"),r=await EQ(n,t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(await fQ(md(n,o.name),t))return!0}catch{}}}catch{}return!1}var hXe={user:"userSettings",project:"projectSettings",local:"localSettings"},xQ={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},gXe=["user","project","local"],_Xe=new Set(["bypassPermissions","auto","acceptEdits"]),yXe=new Set(["project"]);function bXe(e){let t=e.effective.permissions?.defaultMode;if(!t||!_Xe.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(yXe.has(r.source)){let{defaultMode:o,...s}=e.effective.permissions??{};return{...e.effective,permissions:s}}return e.effective}}return e.effective}async function vQ(e={}){await gQ();let t={store:new Jg,cwd:mXe(e.cwd??Qe().cwd()),allowedSources:(e.settingSources??gXe).map((a)=>hXe[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:_Q,hkcu:yQ,wslInherits:bQ,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=aQ(t),o=eQ(t)??void 0,s=r.map(({source:a,settings:c})=>({source:xQ[a],settings:c,path:a==="policySettings"?void 0:mh(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let c=cQ(a,t);if(c)i[a]={source:xQ[c],path:c==="policySettings"?void 0:mh(c,t),...c==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function BWt(e){return vQ(e)}var RXe=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function wQ(e){let t;try{t=yt(bu(e.toString("utf8")))}catch{return e}if(!AQ(t))return e;let n=!1;for(let o of RXe)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(AQ(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?fe(t):e}function AQ(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function OXe(e,t){if(!e)return;let n=e;try{let r=yt(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=fe(r)}catch{}await RQ(t,n,{mode:384})}function PXe(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=v6(x6);return new Promise((t)=>{SXe("security",["find-generic-password","-a",w6(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function IQ(e,t,n,r,o=60000,s){if(!rt(t))return;let i=eo(n,r),a=await Pr(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=xn(TXe(),`claude-resume-${gD()}`);try{let l=xn(c,"projects",i);await pD(l,{recursive:!0,mode:448});let u=xn(l,`${t}.jsonl`);await Vf(u,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??xn(fD(),".claude"),m;try{m=await kQ(xn(f,".credentials.json"),"utf-8")}catch(S){if(!Er(S))throw S}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await PXe()??m;await OXe(m,xn(c,".credentials.json"));let h=E6(Nn.CLAUDE_CONFIG_DIR),g=xn(p??fD(),".claude.json");await lb(g,xn(c,".claude.json"),void 0,DO(s,g,h.globalConfig,en.globalConfig()));let y=xn(f,"settings.json");if(await lb(y,xn(c,"settings.json"),wQ,DO(s,y,h.userSettings,en.userSettings())),await lb(xn(f,"cowork_settings.json"),xn(c,"cowork_settings.json"),wQ),e.listSubkeys)await IXe(e,{projectKey:i,sessionId:t},xn(l,t),o);return c}catch(l){throw await nE(c),l}}async function IXe(e,t,n,r){let o=await Pr(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=_h(n,s+".jsonl");if(!s||OQ(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+_D)){ae(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Pr(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(hD(u))c.push(u);else l.push(u);if(l.length>0)await pD(mD(i),{recursive:!0}),await Vf(i,l);if(c.length>0){let u=c.at(-1),p=_h(n,s+".meta.json");await pD(mD(p),{recursive:!0});let{type:f,...m}=u;await RQ(p,fe(m),{mode:384})}}}function yD(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.248";let{abortController:h=_d(),additionalDirectories:g=[],agent:y,agents:S,allowedTools:b=[],betas:x,canUseTool:v,continue:A,cwd:U,debug:D,debugFile:F,disallowedTools:K=[],tools:V,env:ne,executable:oe=vc()?"bun":"node",executableArgs:ge=[],extraArgs:ke={},fallbackModel:vt,enableFileCheckpointing:Z,toolConfig:Je,forkSession:wt,hooks:ht,includeHookEvents:ur,includePartialMessages:Pt,forwardSubagentText:se,onElicitation:ee,onUserDialog:te,supportedDialogKinds:$e,perTaskStopAffordance:Re,persistSession:It,sessionStore:Ft,sessionStoreFlush:gt,thinking:Pn,effort:Zi,maxThinkingTokens:Dt,maxTurns:yh,maxBudgetUsd:jQ,taskBudget:$Q,mcpServers:SD,model:zQ,outputFormat:ED,permissionMode:HQ,allowDangerouslySkipPermissions:BQ=!1,permissionPromptToolName:KQ,plugins:GQ,getOAuthToken:xD,getHostAuthToken:vD,workload:wD,resume:AD,resumeSessionAt:WQ,resumeDropsTurn:qQ,sessionId:VQ,skills:TD,stderr:ZQ,strictMcpConfig:YQ}=u,CD=HQ??(e?.resolvePermissionModeInCli?void 0:"default");if(Ft&&It===!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($e!==void 0&&$e.length>0&&!te)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(Ft&&A&&!AD&&!Ft.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(Ft&&Z)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(Ft&&u.spawnClaudeCodeProcess)ae("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"});T6(!!v,CD??"default",b);let oE=u.pathToClaudeCodeExecutable;if(!oE){let dr=kXe(import.meta.url),to=AXe(dr),Yi=P2((yc)=>to.resolve(yc));if(!Yi)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.`);oE=Yi}let kD=ED?.type==="json_schema"?ED.schema:void 0,In=ne?{...ne}:{...process.env};if(!In.CLAUDE_CODE_ENTRYPOINT)In.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!In.CLAUDE_AGENT_SDK_VERSION)In.CLAUDE_AGENT_SDK_VERSION="0.3.248";if(Z)In.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(xD)In.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(vD)In.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(Je?.askUserQuestion?.previewFormat)In.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=Je.askUserQuestion.previewFormat;let sE={};if(rE.propagation.inject(rE.context.active(),sE),"traceparent"in sE){for(let dr of["TRACEPARENT","TRACESTATE"])if(!(dr in(ne??{})))delete In[dr]}for(let[dr,to]of Object.entries(sE)){let Yi=dr.toUpperCase();if(!(Yi in(ne??{})))In[Yi]=to}let RD={},OD=new Map;if(SD)for(let[dr,to]of Object.entries(SD))if(to.type==="sdk"&&to.instance)OD.set(dr,to);else RD[dr]=to;let hd;if(Pn)switch(Pn.type){case"adaptive":hd={type:"adaptive",display:Pn.display};break;case"enabled":hd={type:"enabled",budgetTokens:Pn.budgetTokens,display:Pn.display};break;case"disabled":hd={type:"disabled"};break}else if(Dt!==void 0)hd=Dt===0?{type:"disabled"}:{type:"enabled",budgetTokens:Dt};if(r){if(In.CLAUDE_CONFIG_DIR=r,process.platform==="win32")In.CLAUDE_SECURESTORAGE_CONFIG_DIR=ne?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??ne?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let PD=new oC({abortController:h,additionalDirectories:g,agent:y,betas:x,cwd:U,debug:D,debugFile:F,executable:oe,executableArgs:ge,extraArgs:wD?{...ke,workload:wD}:ke,pathToClaudeCodeExecutable:oE,env:In,forkSession:wt,stderr:ZQ,thinkingConfig:hd,effort:Zi,maxTurns:yh,maxBudgetUsd:jQ,taskBudget:$Q,model:zQ,fallbackModel:vt,jsonSchema:kD,permissionMode:CD,allowDangerouslySkipPermissions:BQ,permissionPromptToolName:KQ,continueConversation:Ft?void 0:A,resume:AD,resumeSessionAt:WQ,resumeDropsTurn:qQ,sessionId:VQ,settings:typeof i==="object"?fe(i):i,managedSettings:a?fe(a):void 0,settingSources:c,skills:TD,allowedTools:b,disallowedTools:K,tools:V,mcpServers:RD,strictMcpConfig:YQ,canUseTool:!!v,hooks:!!ht,includeHookEvents:ur,includePartialMessages:Pt,persistSession:It,sessionMirror:!!Ft,plugins:GQ,sandbox:l,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),JQ={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:S,title:u.title,skills:TD,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:se,supportedDialogKinds:$e,perTaskStopAffordance:Re},iE=new fy(PD,n,v,ht,h,OD,kD,JQ,ee,xD,vD,te);if(Ft){let dr=()=>xn(In.CLAUDE_CONFIG_DIR??xn(fD(),".claude"),"projects"),to=gt==="eager",Yi=new cC(async(yc,aE)=>{let gd=CQ(yc,dr());if(gd)await Ft.append(gd,aE);else ae(`[SessionStore] dropping mirror frame: filePath ${yc} is not under ${dr()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(yc,aE)=>{let gd=CQ(yc,dr());if(gd)iE.reportMirrorError(gd,aE.message)},maxPendingEntries:to?0:my,maxPendingBytes:to?0:fu});iE.setTranscriptMirrorBatcher(Yi)}return{queryInstance:iE,transport:PD,abortController:h,processEnv:In}}function bD(e,t,n,r){if(typeof n==="string")t.write(fe({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
161
+ `)?0:1)}}function AJe(e){return g7("sha256").update(fe(e)).digest("hex")}function TJe(e){if(typeof e==="string")return e||void 0;if(e===null||typeof e!=="object"||!("command"in e)||typeof e.command!=="string"||!e.command)return;let t="args"in e&&Array.isArray(e.args)?e.args.map(String):[];return fe([e.command,...t])}function CJe(e){return fe(JS({shellSettings:e.shellSettings,envVars:e.envVars,hooks:e.hooks,claudeMd:e.claudeMd}))}function b7(e){return g7("sha256").update(CJe(e)).digest("hex")}function h7(e,t,n){return fe([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}function S7(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function kJe(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of nh){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var RJe="remote-settings.json";var x7="remote-settings-helper-consent";function OJe(){return E7(Gt(),x7)}function PJe(e){if(e.policyHelpers===void 0&&e.extraKnownMarketplaces===void 0&&!nh.some(({alias:n,canonical:r})=>r==="extraKnownMarketplaces"&&e[n]!==void 0))return;let t=_7(e);return y7(t)?b7(t):void 0}function IJe(e){return th(e,(t,n)=>n.startsWith("$")&&n!=="$schema")}class v7{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;ineligibleReason=void 0;lastLoadStatus=void 0;lastLoadStatusChanged=At();policySettingsNotified=!1;verifiedPayload=null;unverifiedView=null;consentedPayload=null;resetEpoch=0;backendView=void 0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified)this.verifiedPayload=e}seedFromDisk(e){this.sessionCache=e;let t=PJe(e);if(t===void 0||t===UJe())this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}markPolicySettingsNotified(){this.policySettingsNotified=!0}recordEligibility(e,t){if(this.eligible=e,t.memoize)this.eligibilityMemo=e,this.ineligibleReason=e?void 0:t.ineligibleReason}resetListener=null;registerResetListener(e){if(this.resetListener!==null)throw Error("registerSyncCacheResetListener: a listener is already registered; a second one would unhook the first");this.resetListener=e}reset(){this.sessionCache=null,this.eligible=void 0,this.eligibilityMemo=void 0,this.ineligibleReason=void 0,this.lastLoadStatus=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,this.unverifiedView=null,this.consentedPayload=null,this.resetEpoch++,this.emitLoadStatusChanged(void 0)}emitLoadStatusChanged(e){try{this.lastLoadStatusChanged.emit(e)}catch(t){ae(`Remote settings: load-status listener threw: ${co(t)}`,{level:"error"})}}}var DJe=new tt(()=>new v7);function eD(){return DJe.of(Ct().host)}function XS(){return}function LJe(){return XS()??E7(Gt(),RJe)}var w7=8388608;function MJe(){try{let e=FJe();if(e===null)return null;let t=yt(bu(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return IJe(t)}catch(e){if(TJ(e))ae(`Remote settings: Disk cache exceeds ${w7} bytes; ignoring it as if absent`);return null}}var NJe=4096;function UJe(){let e=tD();if(e!==void 0)return e.attestation;try{return lc(OJe(),NJe).trim()||void 0}catch{return}}function FJe(){let e=tD();if(e!==void 0)return e.content;return lc(LJe(),w7)}function tD(){let e=eD().backendView;if(!ye()||e===void 0||!e.ready||e.stoodDown||XS()!==void 0)return;if(!t0(e.configHome)){e.standDown("config home changed");return}return e}var dKt=en.state("remote-settings"),pKt=en.state(x7);var jJe=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",...SI,...EI,"AWS_ENDPOINT_URL_STS","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_SSO","AWS_ENDPOINT_URL_SSO_OIDC","AWS_ENDPOINT_URL_BEDROCK","AWS_ENDPOINT_URL_BEDROCK_RUNTIME",...AI,...TI,...CI,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...xI,"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","CLAUDE_CODE_FEDERATION_CACHE_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 $Je(e){if(!e?.env)return e;let t=th(e.env,(n,r)=>jJe.has(r.toUpperCase()));return{...e,env:t}}function zJe(){let e=eD();if(!XS()&&e.eligible!==!0)return null;if(e.sessionCache)return e.sessionCache;let t=tD()!==void 0,n=MJe();if(n){if(e.seedFromDisk(n),t)pc().invalidatePolicyLayer();else oX();return n}return null}function A7(){let e=zJe(),t=eD();if(e===t.verifiedPayload||XS())return e;if(e===null)return null;if(t.unverifiedView?.raw!==e)t.unverifiedView={raw:e,view:$Je(e)};return t.unverifiedView.view}var T7=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];function HJe(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function C7(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&HJe(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{userInfo as BJe}from"os";var k7="com.anthropic.claudecode",ch="HKLM\\SOFTWARE\\Policies\\ClaudeCode",lh="HKCU\\SOFTWARE\\Policies\\ClaudeCode",qi="Settings",R7="/usr/bin/plutil",O7=["-convert","json","-o","-","--"],P7=5000,nD="/mnt/c/Windows/System32/reg.exe",dd="/mnt/c/Program Files/ClaudeCode";function uh(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Ee("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function I7(){let e="";try{e=BJe().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${k7}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${k7}.plist`,label:"device-level managed preferences"}),t}var D7=512;function L7(e){return e.map(KJe)}function KJe(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,mcpErrorMetadata:i,path:a,message:c,expected:l,suggestion:u,invalidValue:p,...f}=e,m=f;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,mcpErrorMetadata:i,path:dh(a),message:dh(c),expected:l===void 0?void 0:dh(l),suggestion:u===void 0?void 0:dh(u),invalidValue:typeof p==="string"?dh(p):void 0}}function dh(e){let t=S7(e.replace(/\s+/gu," "));return t.length>D7?`${t.slice(0,D7-1)}…`:t}var js="https://code.claude.com/docs/en",GJe=[{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:`${js}/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:`${js}/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:`${js}/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:`${js}/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:`${js}/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:`${js}/iam#working-directories`}}],WJe={permissions:`${js}/iam#configuring-permissions`,env:`${js}/settings#environment-variables`,hooks:`${js}/hooks`};function M7(e){let t=GJe.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=WJe[bE(e.path,".")];return n}var YKt=L(()=>YS(ih(),{strictPolicyHelperKeys:!0}).strict());function N7(e){return e.code==="invalid_type"}function U7(e){return e.code==="invalid_value"}function qJe(e){return e.code==="unrecognized_keys"}function F7(e){return e.code==="too_small"}function lr(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function j7(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function ph(e,t){return e.issues.map((n)=>{let r=n.path.map(String).join("."),o=n.message,s,i,a,c,l;if(U7(n))i=n.values.map((p)=>String(p)),a=i.join(" | "),c=void 0,l=void 0;else if(N7(n)){a=n.expected;let p=j7(n.message);c=p??lr(n.input),l=p??lr(n.input)}else if(F7(n))a=String(n.minimum);else if(n.code==="custom"&&"params"in n)c=n.params.received,l=c;let u=M7({path:r,code:n.code,expected:a,received:c,enumValues:i,message:n.message,value:c});if(U7(n))s=i?.map((p)=>`"${p}"`).join(", "),o=`Invalid value. Expected one of: ${s}`;else if(N7(n)){let p=j7(n.message)??lr(n.input);if(n.expected==="object"&&p==="null"&&r==="")o="Invalid or malformed JSON";else o=`Expected ${n.expected}, but received ${p}`}else if(qJe(n)){let p=n.keys.join(", ");o=`Unrecognized ${gE(n.keys.length,"field")}: ${p}`}else if(F7(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 VJe(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=KI(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 ZJe=new Set(xc);function YJe(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=lr(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(!ZJe.has(s)){delete r[s],o.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${xc.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(r[s])){let i=lr(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 JJe=[{key:"allowedMcpServers",schema:VS},{key:"deniedMcpServers",schema:ZS}];function XJe(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of JJe){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 ${lr(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 QJe(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 e8e(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(jI)}function t8e(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=lr(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=VI().safeParse(s[a]),l;if(!c.success){let u=QJe(s[a]);if(u!==void 0&&!$X.has(u)||e8e(s[a]))continue;l=$S(c.error.issues)}else if(c.data.source.source==="settings"&&c.data.source.name!==a)l=`key "${Wi(a)}" must match the settings source name "${Wi(c.data.source.name)}"`;if(l!==void 0)i.push({file:t,path:`${r}.${Wi(a)}`,message:`Invalid marketplace entry was ignored: ${l}`,severity:"warning"}),delete s[a]}return i}function n8e(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!pn(o)||!Array.isArray(o.options)){let c=pn(o)?`options: ${lr(o.options)}`:lr(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object with an "options" array of { model, label?, description? } rows; received ${c}. This field was ignored.`,severity:"warning",invalidValue:c}]}let s=[];if("replaceBuiltInOptions"in o&&typeof o.replaceBuiltInOptions!=="boolean"){let c=lr(o.replaceBuiltInOptions);delete o.replaceBuiltInOptions,s.push({file:t,path:`${r}.replaceBuiltInOptions`,message:`"replaceBuiltInOptions" must be true or false; received ${c}. This entry was ignored (the rows are added to the built-in lineup).`,severity:"warning",invalidValue:c})}let i=o.options,a=[];for(let c=0;c<i.length;c++){let l=JI().safeParse(i[c]);if(l.success){a.push(i[c]);continue}s.push({file:t,path:`${r}.options.${c}`,message:`${o8e(l.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:lr(i[c])})}if(a.length!==i.length)o.options=a;return s}function r8e(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let n=e;if(!("modelPricing"in n)||n.modelPricing===void 0)return[];let r=n.modelPricing;if(!r||typeof r!=="object"||Array.isArray(r))return delete n.modelPricing,[{file:t,path:"modelPricing",message:`"modelPricing" must be an object; received ${lr(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!YI().safeParse(o.multiplier).success)s.push({file:t,path:"modelPricing.multiplier",message:'"multiplier" must be a number in (0, 1]. It was ignored.',severity:"warning",invalidValue:o.multiplier}),delete o.multiplier;if(o.overrides!==void 0){let i=o.overrides;if(!i||typeof i!=="object"||Array.isArray(i))s.push({file:t,path:"modelPricing.overrides",message:`"overrides" must be an object mapping model ID to rates; received ${lr(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let c of Object.keys(a)){let l=ZI().safeParse(a[c]);if(l.success&&c!=="constructor"&&c!=="__proto__")continue;let u=l.success?void 0:l.error.issues[0];s.push({file:t,path:`modelPricing.overrides.${Wi(c)}`,message:`Invalid pricing row was ignored (${u?`${u.path.join(".")||"row"}: ${u.message}`:"not a model ID"}).`,severity:"warning",invalidValue:a[c]}),delete a[c]}}}return s}function o8e(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function s8e(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||i8e(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[l8e(o,t,n?.policySource===!0)]}function i8e(e){return typeof e==="string"&&ah.includes(e)}var a8e="crossSessionInbound";function c8e(e){let t=ah.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${Wi(e).replace(/^<key>$/,"<value>")}"`:lr(e);return`must be one of ${t}; received ${n}`}function l8e(e,t,n=!1){let r=ah.map((s)=>`"${s}"`).join(", "),o=n?'In managed settings an unrecognized value is treated as "refuse" (the most restrictive): cross-session messages to this session are turned away until an administrator fixes it.':"This value was ignored; while it is present, cross-session messages are held for your approval instead of being delivered. Set it to one of the values above.";return{file:t,path:a8e,message:`"crossSessionInbound" ${c8e(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}function gc(e,t,n){return[...Z8(e,t),...VJe(e,t),...YJe(e,t),...t8e(e,t),...n8e(e,t),...r8e(e,t),...s8e(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:XJe(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly})]}function iD(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),T7.filter((n)=>t.has(n))}function p8e(){return Mo(dc(),"managed-settings.json")}function aD(e){if($r()==="wsl"&&e.wslInherits?.()){let t=rD(dd,e.store);if(t.settings)return t;let n=rD(dc(),e.store);return{settings:n.settings,errors:[...t.errors,...n.errors]}}return rD(dc(),e.store)}function f8e(e){return e.endsWith(".json")&&!e.startsWith(".")}function rD(e,t){let n=[],r={},o=!1,{settings:s,errors:i}=fd(Mo(e,"managed-settings.json"),t,void 0,!0);if(n.push(...i),s&&Object.keys(s).length>0)r=Hn(r,s,Xr),o=!0;let a=Mo(e,"managed-settings.d");try{let c=t.folderListingForPolicyWalk(a),l;if(c!==void 0)l=c;else l=Qe().readdirSync(a).filter((u)=>(u.isFile()||u.isSymbolicLink())&&f8e(u.name)).map((u)=>u.name).sort(),t.noteWalkListing(a,l);for(let u of l){let{settings:p,errors:f}=fd(Mo(a,u),t,void 0,!0);if(n.push(...f),p&&Object.keys(p).length>0)r=Hn(r,p,Xr),o=!0}}catch(c){let l=Ue(c);if(l!=="ENOENT"&&l!=="ENOTDIR")ae(`managed-settings.d read failed: ${c}`,{level:"error"}),n.push({file:a,path:"",message:`Managed settings drop-in directory could not be read: ${l??"unknown error"}`,severity:"fatal"})}return{settings:o&&_c(r)?r:null,errors:n}}function m8e(e,t){if(Er(e))E8e(t);else ae(`settings file read failed at ${t}: ${e}`,{level:"error"})}function fd(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{settings:s.settings?ho(s.settings):null,errors:s.errors};let i=b8e(e,n,r);return t.parsedFiles.set(o,i),{settings:i.settings?ho(i.settings):null,errors:i.errors}}function cD(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 eE(e,t){let n=$7.get(e),r=n?.get(t);if(r)return{settings:r.settings&&ho(r.settings),errors:r.errors.map((s)=>({...s}))};let o=h8e(e,t);if(n)n.set(t,o);else $7.set(e,new Map([[t,o]]));return{settings:o.settings&&ho(o.settings),errors:o.errors.map((s)=>({...s}))}}var $7=new WeakMap;function h8e(e,t){let n=ho(e),r=gc(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=QI(G7(t,o),t).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...ph(s.error,t)]};return{settings:Object.keys(s.data).length>0?s.data:null,errors:[...r,...o]}}function G7(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)ae(`${e}: ${n.path}: ${n.message}`,{level:n.startupFatal?"error":"warn"})}}function W7(e){let t=e?.remote?e.remote():A7();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let{settings:n,errors:r}=eE(t,"remote managed settings");return{settings:n,errors:L7(r)}}var g8e="parent managed settings";function _8e(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return eE(t,g8e)}function q7(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=ho(t),r=gc(n,"SDK inline settings"),o=ud().safeParse(n);if(!o.success)return{settings:null,errors:[...r,...ph(o.error,"SDK inline settings")]};return{settings:o.data,errors:r}}var y8e=2097152;function b8e(e,t,n){try{let r;if(t!==void 0)r=t;else{let{resolvedPath:o}=of(Qe(),e);r=lc(o,y8e)}return S8e(r,e,n)}catch(r){return v8e(r,e)}}function S8e(e,t,n){if(e.trim()==="")return{settings:{},errors:[]};let r=ho(uc(e,!1));if(n){let i=gc(r,t,{skipMcpServerEntryFilter:!0,policySource:!0}),a=[],c=QI(G7(t,a),t).safeParse(r);if(!c.success)return{settings:null,errors:[...i,...ph(c.error,t)]};return{settings:c.data,errors:[...i,...a]}}let o=gc(r,t),s=ud().safeParse(r);if(!s.success){let i=ph(s.error,t);return{settings:null,errors:[...o,...i]}}return{settings:s.data,errors:o}}function E8e(e){ae(`Broken symlink or missing file encountered for settings.json at path: ${e}`)}function x8e(){return{settings:null,errors:[]}}function v8e(e,t){if(m8e(e,t),Er(e))return x8e();return{settings:null,errors:[{file:t,path:"",message:`Settings file could not be read: ${e instanceof Error?e.message:String(e)}`,severity:"fatal"}]}}function z7(e,t){switch(e){case"userSettings":return Qr(Gt());case"policySettings":case"projectSettings":return Qr(t.cwd);case"localSettings":return V7(t.cwd,t.canonicalGitRoot);case"flagSettings":return t.flagPath?d8e(Qr(t.flagPath)):Qr(t.cwd)}}function V7(e,t){let n=w8e(e,t);if(n.decided!==void 0)return n.decided;if(!C8e(n.root))return n.cwdResolved;return n.root}function w8e(e,t){let n=t?.(e);if(!n)return{decided:Qr(e)};let r=Qr(n),o=Qr(e);if(r===o)return{decided:r};let s;try{s=k8e()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function A8e(e){return pc().localStoreProbes.canonicalRootOwnerUids(e,T8e)}function T8e(e){let t=Qe(),n=null;try{n=t.lstatSync(Mo(e,".claude")).uid}catch(r){if(!Er(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:t.lstatSync(Mo(e,".git")).uid,claudeEntryUid:n}}function C8e(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return ae(`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}=A8e(e);if(n===t&&r===t&&(o===null||o===t))return!0;return ae(`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 ae(`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 k8e(){return pc().localStoreProbes.normalizedRealHomeDir(R8e)}function R8e(){let e=hE(u8e());if(e===null)throw Error("home directory realpath unavailable");return st(e)}var H7={default:"settings.json",cowork:"cowork_settings.json"};function O8e(e){if(e.coworkPlugins||Nn.CLAUDE_CODE_USE_COWORK_PLUGINS)return H7.cowork;return H7.default}function mh(e,t){switch(e){case"userSettings":return Mo(z7(e,t),O8e(t));case"projectSettings":case"localSettings":return Mo(z7(e,t),Z7(e));case"policySettings":return p8e();case"flagSettings":return t.flagPath}}function Z7(e){switch(e){case"projectSettings":return Mo(".claude","settings.json");case"localSettings":return Mo(".claude","settings.local.json")}}function Y7(e){if(V7(e.cwd,e.canonicalGitRoot)===Qr(e.cwd))return;return Mo(Qr(e.cwd),Z7("localSettings"))}function J7(e,t){let n=t.store.perSource.get(e);if(n!==void 0)return n;let r=Z8e(e,t);return t.store.perSource.set(e,r),r}function P8e(e){return!e||e.parentSettingsBehavior==="merge"}var X7=[{path:["allowManagedPermissionRulesOnly"],restrictive:!0},{path:["allowManagedHooksOnly"],restrictive:!0},{path:["allowManagedMcpServersOnly"],restrictive:!0},{path:["enforceAvailableModels"],restrictive:!0},{path:["disableAllHooks"],restrictive:!0},{path:["disableClaudeAiConnectors"],restrictive:!0},{path:["disableCommandPluginSources"],restrictive:!0},{path:["disableSideloadFlags"],restrictive:!0},{path:["disableSkillShellExecution"],restrictive:!0},{path:["disableRemoteControl"],restrictive:!0},{path:["disableAgentView"],restrictive:!0},{path:["disableWorkflows"],restrictive:!0},{path:["disableArtifact"],restrictive:!0},{path:["disableBundledSkills"],restrictive:!0},{path:["fastModePerSessionOptIn"],restrictive:!0},{path:["isolatePeerMachines"],restrictive:!0},{path:["strictPluginOnlyCustomization"],restrictive:!0},{path:["disableAutoMode"],restrictive:"disable"},{path:["disableDeepLinkRegistration"],restrictive:"disable"},{path:["permissions","disableBypassPermissionsMode"],restrictive:"disable"},{path:["permissions","disableAutoMode"],restrictive:"disable"},{path:["autoMode","classifyAllShell"],restrictive:!0},...[],{path:["worktree","bgIsolation"],restrictive:"worktree"},{path:["enableArtifact"],restrictive:!1},{path:["enableWorkflows"],restrictive:!1},{path:["syncClaudeAiSkills"],restrictive:!1},{path:["syncClaudeAiPlugins"],restrictive:!1},{path:["useAutoModeDuringPlan"],restrictive:!1},{path:["skipDangerousModePermissionPrompt"],restrictive:!1},{path:["skipAutoPermissionPrompt"],restrictive:!1},{path:["enableAllProjectMcpServers"],restrictive:!1},{path:["channelsEnabled"],restrictive:!1},{path:["skipWebFetchPreflight"],restrictive:!1},{path:["skipWorkflowUsageWarning"],restrictive:!1},{path:["autoUploadSessions"],restrictive:!1},{path:["remoteControlAtStartup"],restrictive:!1},{path:["autoContinueAtUsageLimit"],restrictive:!1},...[],{path:["attribution","sessionUrl"],restrictive:!1},{path:["crossSessionInbound"],restrictive:["refuse","hold"]},{path:["modelProposedGoals"],restrictive:["disabled","alwaysAsk"]},{path:["feedbackDrafts"],restrictive:"off"},{path:["askUserQuestionTimeout"],restrictive:"never"},{path:["dialogExpiry"],restrictive:"never"},{path:["sandbox","enabled"],restrictive:!0},{path:["sandbox","failIfUnavailable"],restrictive:!0},{path:["sandbox","autoAllowBashIfSandboxed"],restrictive:!1},{path:["sandbox","allowUnsandboxedCommands"],restrictive:!1},{path:["sandbox","enableWeakerNestedSandbox"],restrictive:!1},{path:["sandbox","enableWeakerNetworkIsolation"],restrictive:!1},{path:["sandbox","allowAppleEvents"],restrictive:!1},{path:["sandbox","network","allowManagedDomainsOnly"],restrictive:!0},{path:["sandbox","network","strictAllowlist"],restrictive:!0},{path:["sandbox","network","allowAllUnixSockets"],restrictive:!1},{path:["sandbox","network","allowLocalBinding"],restrictive:!1},{path:["sandbox","filesystem","allowManagedReadPathsOnly"],restrictive:!0},{path:["sandbox","filesystem","disabled"],restrictive:!1},{path:["sandbox","credentials","allowPlaintextInject"],restrictive:!1},{path:["sandbox","credentials","sigv4","streaming"],restrictive:"deny"},{path:["sandbox","credentials","sigv4","presigned"],restrictive:"deny"},{path:["sandbox","credentials","sigv4","sigv4a"],restrictive:"deny"}];function Q7(e){return Array.isArray(e)?e:[e]}var I8e=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function pd(e,t){let n=e;for(let r of t){if(n===null||typeof n!=="object")return;n=n[r]}return n}function fh(e,t,n){let r=[e],o=e;for(let i of t.slice(0,-1)){let a={...o[i]};o[i]=a,o=a,r.push(o)}let s=t.at(-1);if(n!==void 0){o[s]=n;return}delete o[s];for(let i=r.length-1;i>0;i--){if(Object.keys(r[i]).length>0)break;delete r[i-1][t[i-1]]}}function D8e(e){let t={};for(let{path:n,restrictive:r}of X7){let o=pd(e,n);if(n[0]==="sandbox"&&Q7(r).includes(o))fh(t,n,o)}return t.sandbox??{}}function L8e(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.syncClaudeAiSkills===!1)n.syncClaudeAiSkills=!1;if(e.syncClaudeAiPlugins===!1)n.syncClaudeAiPlugins=!1;if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(C7(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=LS(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={},c=o?LS(o,["deniedDomains"]):{},l=s?LS(s,["denyRead","denyWrite"]):{};if(o){if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&o.allowedDomains)c.allowedDomains=o.allowedDomains}if(Object.keys(c).length>0)a.network=c;if(s){if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&s.allowRead)l.allowRead=s.allowRead}if(Object.keys(l).length>0)a.filesystem=l;if(i){let u=(i.files??[]).map((m)=>m.mode==="deny"?{path:m.path,mode:"deny"}:{path:m.path,mode:"mask",injectHosts:[]}),p=(i.envVars??[]).filter((m)=>m.mode==="deny").map((m)=>({name:m.name,mode:"deny"})),f={...u.length>0&&{files:u},...p.length>0&&{envVars:p}};if(i.sigv4){let m={};for(let h of["streaming","presigned","sigv4a"])if(i.sigv4[h]==="deny")m[h]="deny";f.sigv4=m}{let m=od,h=Es((i.awsPairs??[]).flatMap((g)=>[g.accessKeyIdVar,g.secretAccessKeyVar,...g.sessionTokenVar!==void 0?[g.sessionTokenVar]:[]]).filter((g)=>m.includes(g)));if(h.length>0)f.awsPairs=h.map((g,y)=>({accessKeyIdVar:g,secretAccessKeyVar:`${lX}${y+1}_`}))}if(Object.keys(f).length>0)a.credentials=f}if(Hn(a,D8e(e)),Object.keys(a).length>0)n.sandbox=a}return n}var M8e=new Set([...[...vI].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...wI,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL"]);function N8e(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;if(e.modelPicker!==void 0)n.modelPicker=e.modelPicker;return Object.keys(n).length>0?n:null}function QS(e){if(delete e.model,delete e.fallbackModel,delete e.modelPicker,delete e.modelOverrides,e.env){let t={};for(let[n,r]of Object.entries(e.env))if(!M8e.has(n.toUpperCase()))t[n]=r;e.env=t}}function U8e(){return $r()==="macos"?"plist":"hklm"}function eQ(e){let t=lD(e);if(t.composes==="tier")return"helper";let n=sD(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return U8e();if(n.present.file)return"file";if(n.parentSlice||n.hostModelOverlay)return"parent";let r=e.hkcu?.();return r&&Object.keys(r.settings).length>0?"hkcu":null}function sD(e){let t=[],{settings:n,errors:r}=W7(e);t.push(...r);let o=lD(e),s=o.composes==="remoteSlot"?o.helper:oD(n),{settings:i,errors:a}=cD(e);t.push(...a);let c=oD(i),{settings:l,errors:u}=e.file?.()??aD(e);t.push(...u);let p=oD(l),{settings:f,errors:m}=_8e(e);t.push(...m);let h=[s,c,p].filter((V)=>V!==null),y=(o.composes==="remoteSlot"?o.helper:[n,i,l].find((V)=>V!==null&&(V.managedSourcesBehavior!==void 0||_c(V))))?.managedSourcesBehavior,{admin:S,merged:b}=F8e(h,y),x={remote:s!==null,mdm:c!==null,file:p!==null},v=(V)=>V!==null&&(V===h[0]||Object.keys(bI(V,oQ)).length>0),A={remote:v(s),mdm:v(c),file:v(p)},U={allowManagedPermissionRulesOnly:h.some((V)=>V.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:S?.forceLoginOrgUUID,allowedMcpServers:S?.allowedMcpServers,availableModels:S?.availableModels,sandbox:{network:{allowManagedDomainsOnly:h.some((V)=>V.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:h.some((V)=>V.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},D=f&&P8e(S)?L8e(f,U):null,F=D&&Object.keys(D).length>0?D:null,K=N8e(f,e.hostManagedProvider);return{tiers:h,admin:S,parentSlice:F,hostModelOverlay:K,errors:t,present:x,merged:b,composed:A}}function F8e(e,t){let n=e[0];if(!n)return{admin:null,merged:!1};let{managedSourcesBehavior:r,...o}=n;if(t!=="merge"||e.length<2)return{admin:r===void 0?n:o,merged:!1};let s=e.slice(1).map((a)=>{let c=bI(a,oQ);for(let u of I8e)if(pd(c,u)!==void 0)fh(c,u,void 0);let l=pd(c.sandbox,["enabledPlatforms"]);if(Array.isArray(l)&&l.includes($r()))fh(c,["sandbox","enabledPlatforms"],void 0);else if(l!==void 0)delete c.sandbox;return c}),i={};for(let a of[...s].reverse())Hn(i,a,B7);return Hn(i,o,B7),z8e(i,[n,...s]),j8e(i,[n,...s]),{admin:i,merged:!0}}var tQ=["managedSourcesBehavior","wslInheritsWindowsSettings"];function _c(e){return Object.keys(e).some((t)=>!tQ.includes(t))}function oD(e){return e&&_c(e)?e:null}function j8e(e,t){let n=t.findIndex((o)=>o.availableModels!==void 0),r=t.findIndex((o)=>o.modelOverrides!==void 0);if(r!==-1&&(n===-1||r<=n))e.modelOverrides={...t[r].modelOverrides};else delete e.modelOverrides}var $8e=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins"];function B7(e,t,n){if(n!==void 0&&$8e.includes(n)){if(t===void 0)return e;return Array.isArray(t)?[...t]:t}if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Es([...t,...e]);return Xr(e,t,n)}function z8e(e,t){let n=t[0],r=e;for(let{path:o,restrictive:s}of X7){let i=Q7(s),a=Math.min(...t.map((c)=>i.indexOf(pd(c,o))).filter((c)=>c!==-1));if(Number.isFinite(a))fh(r,o,i[a]);else if(pd(n,o)===void 0&&pd(e,o)!==void 0)fh(r,o,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Es(t.flatMap((s)=>Array.isArray(s.strictPluginOnlyCustomization)?s.strictPluginOnlyCustomization:[]));if(o.length>0)e.strictPluginOnlyCustomization=o;else if(n?.strictPluginOnlyCustomization===void 0)delete e.strictPluginOnlyCustomization}}function lD(e){let t=e.helper?.()??null;if(!t)return{composes:"none"};let n=e.helperArmedFromRemote?.()===!1?"tier":"remoteSlot";if(e.helperMergesOutput?.()!==!0)return{composes:n,helper:t,mergedOver:null};if(!e.store.policy.mergedHelper){let r,o;if(n==="remoteSlot")r=W7(e).settings,o="remote";else if(r=cD(e).settings)o=$r()==="macos"?"plist":"hklm";else r=(e.file?.()??aD(e)).settings,o="file";e.store.policy.mergedHelper={helper:B8e(r,t),mergedOver:Object.keys(nQ(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function nQ(e){let{policyHelper:t,policyHelpers:n,...r}=e??{};return r}function H8e(e,t){let n=new Map;for(let[o,s]of Object.entries(t)){let i=o.toUpperCase();if(!n.has(i))n.set(i,s)}let r={};for(let[o,s]of Object.entries(e))r[o]=n.get(o.toUpperCase())??s;return Object.assign(r,t)}function B8e(e,t){let n=nQ(e),r=Hn({},n,t,(o,s,i)=>Array.isArray(s)?[...s]:Xr(o,s,i));if(n.env&&t.env)r.env=H8e(n.env,t.env);return r}var rQ=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var oQ=[...rQ,"otelHeadersHelper","proxyAuthHelper","forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","parentSettingsBehavior","env","modelPicker",...tQ];function K8e(e){return Q8.some((t)=>e.startsWith(t))||X8.includes(e)}function G8e(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=K8e(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 W8e="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function K7(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==W8e)t[n]=r;return t}function q8e(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function V8e(e){let t=cD(e);return t.settings?t.errors:[...t.errors,...(e.file?.()??aD(e)).errors]}function sQ(e){let t=lD(e),n=e.helperWarnings?.()??[];if(t.composes==="tier"){let{helper:h}=t;e.store.lastPolicyEnvComposition=null;let g=e.hostManagedProvider?{...h}:h;if(e.hostManagedProvider)QS(g);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&h.availableModels!==void 0?h.modelOverrides:void 0};let y=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?V8e(e).filter((S)=>!S.statusOnly):[],...sD(e).errors.filter((S)=>S.statusOnly)];return{settings:g,errors:[...y,...n]}}let{tiers:r,admin:o,parentSlice:s,hostModelOverlay:i,errors:a,present:c}=sD(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(QS(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=Hn({},s??{},o??{},Xr);if(r.some((h)=>h.forceRemoteSettingsRefresh===!0))l.forceRemoteSettingsRefresh=!0;let u=Nn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,p=l.env;if(!u){let h=G8e(r.map((g)=>g.env),r.map((g)=>(g.otelHeadersHelper??"").trim()!==""),r.map((g)=>{let y=new Set;for(let S of rQ){let b=g[S];if(typeof b==="string"&&b.trim()!=="")for(let x of eX[S])y.add(x)}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=K7(l.env);if(h&&Object.keys(h).length>0)l.env=h;else delete l.env}if(e.hostManagedProvider){if(QS(l),i)Object.assign(l,i)}let f={env:K7(p)};if(e.hostManagedProvider)QS(f);let m=!u&&!q8e(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:rf(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 Z8e(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return sQ(t).settings;let r=mh(e,t),{settings:o}=r?fd(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=q7(t);if(s)return Hn(o||{},s,Xr)}if(e==="localSettings"&&n){let s=Y7(t);if(s){let{settings:i}=fd(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),Hn(i,o||{},Xr)}}return o}function Y8e(e,t){return{...e,...t}}function Xr(e,t,n){if(n==="modelPicker"&&t!==void 0)return iQ(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Es([...e,...t])}if(n==="extraKnownMarketplaces"&&pn(e)&&pn(t))return Y8e(e,t);return}function iQ(e){if(!pn(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>pn(n)?{...n}:n)}}}function J8e(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();Ym("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=Hn(r,n,Xr);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 iD(e)){if(l==="policySettings"){let{settings:p,errors:f}=sQ(e);if(c=p,p)r=Hn(r,p,Xr);a(f);continue}if(l==="localSettings"){let p=Y7(e);if(p&&!i.has(Qr(p))){i.add(Qr(p));let{settings:f,errors:m}=fd(p,e.store);if(a(m),f)e.onLegacyLocalSettingsRead?.("cascade"),r=Hn(r,f,Xr)}}let u=mh(l,e);if(u){let p=Qr(u),f=l==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(p)||f){i.add(p);let{settings:m,errors:h}=fd(u,e.store,l==="flagSettings"?e.flagExpectedContent:void 0);if(a(h),m)r=Hn(r,m,Xr)}}if(l==="flagSettings"){let{settings:p,errors:f}=q7(e);if(a(f),p)r=Hn(r,p,Xr)}}if(c){if(c.availableModels!==void 0)r.availableModels=[...c.availableModels];if(c.enforceAvailableModels!==void 0)r.enforceAvailableModels=c.enforceAvailableModels;if(c.modelPicker!==void 0)r.modelPicker=iQ(c.modelPicker)}return Ym("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 X8e(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=J8e(e);return e.store.mergedSettings=n,n}function Q8e(e){let{settings:t}=X8e(e);return t||{}}function aQ(e){e.store.invalidateAll();let t=[];for(let n of iD(e)){let r=J7(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:Q8e(e),sources:t}}function cQ(e,t){let n=iD(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(J7(o,t)?.[e]!==void 0)return o}return null}import{execFile as eXe}from"child_process";import{existsSync as tXe}from"fs";class lQ{promise=null;start(){if(this.promise)return;this.promise=uD()}reset(){this.promise=null}}var nXe=new lQ;function rXe(e){if(!e)return{status:"ok",exitCode:0,errno:null,signal:null};let t=e,n=typeof t.signal==="string"&&t.signal?t.signal:null;if(typeof t.code==="string")return{status:"spawn_error",exitCode:null,errno:t.code,signal:null};if(t.killed===!0)return{status:"timeout",exitCode:null,errno:null,signal:n};if(n)return{status:"killed",exitCode:null,errno:null,signal:n};return{status:"exited",exitCode:typeof t.code==="number"?t.code:null,errno:null,signal:null}}function hh(e,t){let n=Date.now();return new Promise((r)=>{try{eXe(e,t,{encoding:"utf-8",timeout:P7,windowsHide:!0},(o,s)=>{r({stdout:s??"",...rXe(o),durationMs:Date.now()-n})})}catch(o){let s=o.code;r({stdout:"",status:"spawn_error",exitCode:null,errno:typeof s==="string"?s:null,signal:null,durationMs:Date.now()-n})}})}function tE(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function uD(){return(async()=>{if(process.platform==="darwin"){let e=I7(),n=(await Promise.all(e.map(async({path:r,label:o})=>{if(!tXe(r))return{stdout:"",label:o,ok:!1};let{stdout:s,status:i}=await hh(R7,[...O7,r]);return{stdout:s,label:o,ok:i==="ok"&&!!s}}))).find((r)=>r.ok);return{plistStdouts:n?[{stdout:n.stdout,label:n.label}]:[],hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[n,r]=await Promise.all([hh(t,["query",ch,"/v",qi]),hh(t,["query",lh,"/v",qi])]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:tE(n),hkcu:tE(r)}}}if(uh()){let[e,t]=await Promise.all([hh(nD,["query",ch,"/v",qi]),hh(nD,["query",lh,"/v",qi])]);return{plistStdouts:null,hklmStdout:e.status==="ok"?e.stdout:null,hkcuStdout:t.status==="ok"?t.stdout:null,outcomes:{hklm:tE(e),hkcu:tE(t)}}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}function uQ(){return nXe.promise}var Vi=Object.freeze({settings:{},errors:[]});class hQ{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await(uQ()??uD()),{mdm:o,hkcu:s,wslInherits:i}=await dXe(r,e);this.replace(o,s,i);let a=Date.now()-t;ae(`MDM settings load completed in ${a}ms`);try{Ti("tengu_managed_settings_os_read",uXe(r,a))}catch{}if(Object.keys(o.settings).length>0){ae(`MDM settings found: ${Object.keys(o.settings).join(", ")}`);try{Ym("info","mdm_settings_loaded",{duration_ms:a,key_count:Object.keys(o.settings).length,error_count:o.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 oXe=new tt(()=>new hQ);function gh(){return oXe.of(Ct().host)}function sXe(e){gh().startLoad(e)}async function gQ(){let e=gh();if(!e.loadPromise)sXe();await e.loadPromise}function _Q(){return gh().mdm??Vi}function yQ(){return gh().hkcu??Vi}function bQ(){return gh().wslInherits}function dD(e,t){let n=uc(e,!1);if(!n||typeof n!=="object")return{settings:{},errors:[]};let{settings:r,errors:o}=eE(n,t);return{settings:r??{},errors:o}}function dQ(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}var iXe=new Map([["ENOENT",An("ENOENT")],["EACCES",An("EACCES")],["EPERM",An("EPERM")],["ENOEXEC",An("ENOEXEC")],["EAGAIN",An("EAGAIN")],["EMFILE",An("EMFILE")],["ENOMEM",An("ENOMEM")],["ETIMEDOUT",An("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",An("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),aXe=new Map([["SIGTERM",An("SIGTERM")],["SIGKILL",An("SIGKILL")],["SIGINT",An("SIGINT")]]);function cXe(e){if(!e)return;return iXe.get(e)??An("other")}function lXe(e){if(!e)return;return aXe.get(e)??An("other")}function pQ(e,t){if(!t)return{};return{[`${e}_status`]:si(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:cXe(t.errno),[`${e}_signal`]:lXe(t.signal),[`${e}_duration_ms`]:t.durationMs}}function uXe(e,t){return{is_wsl:uh(),await_ms:t,...pQ("hklm",e.outcomes.hklm),...pQ("hkcu",e.outcomes.hkcu)}}async function dXe(e,t){let n=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:a,label:c}=e.plistStdouts[0],l=dD(a,c);if(_c(l.settings))return{mdm:l,hkcu:Vi,wslInherits:!1};n.push(...l.errors)}let r=null;if(e.hklmStdout){let a=dQ(e.hklmStdout);if(a)r=dD(a,`Registry: ${ch}\\${qi}`)}if(r)n.push(...r.errors);let o=n.length>0?{settings:{},errors:n}:Vi,s=uh(),i=!1;if(s){if(i=r?.settings.wslInheritsWindowsSettings===!0||await fXe(t),!i)return{mdm:o,hkcu:Vi,wslInherits:!1}}if(r){if(_c(r.settings))return{mdm:r,hkcu:Vi,wslInherits:i}}if(await pXe(i,t))return{mdm:o,hkcu:Vi,wslInherits:i};if(e.hkcuStdout){let a=dQ(e.hkcuStdout);if(a){let c=dD(a,`Registry: ${lh}\\${qi}`);if(!s||c.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:l,managedSourcesBehavior:u,...p}=c.settings;return{mdm:o,hkcu:{settings:p,errors:c.errors},wslInherits:i}}if(c.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:c.errors},wslInherits:i}}}return{mdm:o,hkcu:Vi,wslInherits:i}}async function SQ(e,t){if(ye()&&t!==void 0)return(await RJ(e)).content;return lc(e)}async function EQ(e,t){if(ye()&&t!==void 0)return await Qe().readdir(e);return Qe().readdirSync(e)}async function pXe(e,t){if(e&&await mQ(dd,t))return!0;return mQ(dc(),t)}async function fQ(e,t){let n=ho(uc(await SQ(e,t),!1));if(!n||typeof n!=="object")return!1;return gc(n,e,{skipMcpServerEntryFilter:!0,policySource:!0}),_c(n)}async function fXe(e){async function t(n){try{let r=uc(await SQ(n,e),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(await t(md(dd,"managed-settings.json")))return!0;try{let n=md(dd,"managed-settings.d");for(let r of await EQ(n,e))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&await t(md(n,r.name)))return!0}catch{}return!1}async function mQ(e,t){try{if(await fQ(md(e,"managed-settings.json"),t))return!0}catch{}try{let n=md(e,"managed-settings.d"),r=await EQ(n,t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(await fQ(md(n,o.name),t))return!0}catch{}}}catch{}return!1}var hXe={user:"userSettings",project:"projectSettings",local:"localSettings"},xQ={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},gXe=["user","project","local"],_Xe=new Set(["bypassPermissions","auto","acceptEdits"]),yXe=new Set(["project"]);function bXe(e){let t=e.effective.permissions?.defaultMode;if(!t||!_Xe.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(yXe.has(r.source)){let{defaultMode:o,...s}=e.effective.permissions??{};return{...e.effective,permissions:s}}return e.effective}}return e.effective}async function vQ(e={}){await gQ();let t={store:new Jg,cwd:mXe(e.cwd??Qe().cwd()),allowedSources:(e.settingSources??gXe).map((a)=>hXe[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:_Q,hkcu:yQ,wslInherits:bQ,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=aQ(t),o=eQ(t)??void 0,s=r.map(({source:a,settings:c})=>({source:xQ[a],settings:c,path:a==="policySettings"?void 0:mh(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let c=cQ(a,t);if(c)i[a]={source:xQ[c],path:c==="policySettings"?void 0:mh(c,t),...c==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function BWt(e){return vQ(e)}var RXe=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function wQ(e){let t;try{t=yt(bu(e.toString("utf8")))}catch{return e}if(!AQ(t))return e;let n=!1;for(let o of RXe)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(AQ(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?fe(t):e}function AQ(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function OXe(e,t){if(!e)return;let n=e;try{let r=yt(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=fe(r)}catch{}await RQ(t,n,{mode:384})}function PXe(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=v6(x6);return new Promise((t)=>{SXe("security",["find-generic-password","-a",w6(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function IQ(e,t,n,r,o=60000,s){if(!rt(t))return;let i=eo(n,r),a=await Pr(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=xn(TXe(),`claude-resume-${gD()}`);try{let l=xn(c,"projects",i);await pD(l,{recursive:!0,mode:448});let u=xn(l,`${t}.jsonl`);await Vf(u,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??xn(fD(),".claude"),m;try{m=await kQ(xn(f,".credentials.json"),"utf-8")}catch(S){if(!Er(S))throw S}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await PXe()??m;await OXe(m,xn(c,".credentials.json"));let h=E6(Nn.CLAUDE_CONFIG_DIR),g=xn(p??fD(),".claude.json");await lb(g,xn(c,".claude.json"),void 0,DO(s,g,h.globalConfig,en.globalConfig()));let y=xn(f,"settings.json");if(await lb(y,xn(c,"settings.json"),wQ,DO(s,y,h.userSettings,en.userSettings())),await lb(xn(f,"cowork_settings.json"),xn(c,"cowork_settings.json"),wQ),e.listSubkeys)await IXe(e,{projectKey:i,sessionId:t},xn(l,t),o);return c}catch(l){throw await nE(c),l}}async function IXe(e,t,n,r){let o=await Pr(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=_h(n,s+".jsonl");if(!s||OQ(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+_D)){ae(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Pr(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(hD(u))c.push(u);else l.push(u);if(l.length>0)await pD(mD(i),{recursive:!0}),await Vf(i,l);if(c.length>0){let u=c.at(-1),p=_h(n,s+".meta.json");await pD(mD(p),{recursive:!0});let{type:f,...m}=u;await RQ(p,fe(m),{mode:384})}}}function yD(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.250";let{abortController:h=_d(),additionalDirectories:g=[],agent:y,agents:S,allowedTools:b=[],betas:x,canUseTool:v,continue:A,cwd:U,debug:D,debugFile:F,disallowedTools:K=[],tools:V,env:ne,executable:oe=vc()?"bun":"node",executableArgs:ge=[],extraArgs:ke={},fallbackModel:vt,enableFileCheckpointing:Z,toolConfig:Je,forkSession:wt,hooks:ht,includeHookEvents:ur,includePartialMessages:Pt,forwardSubagentText:se,onElicitation:ee,onUserDialog:te,supportedDialogKinds:$e,perTaskStopAffordance:Re,persistSession:It,sessionStore:Ft,sessionStoreFlush:gt,thinking:Pn,effort:Zi,maxThinkingTokens:Dt,maxTurns:yh,maxBudgetUsd:jQ,taskBudget:$Q,mcpServers:SD,model:zQ,outputFormat:ED,permissionMode:HQ,allowDangerouslySkipPermissions:BQ=!1,permissionPromptToolName:KQ,plugins:GQ,getOAuthToken:xD,getHostAuthToken:vD,workload:wD,resume:AD,resumeSessionAt:WQ,resumeDropsTurn:qQ,sessionId:VQ,skills:TD,stderr:ZQ,strictMcpConfig:YQ}=u,CD=HQ??(e?.resolvePermissionModeInCli?void 0:"default");if(Ft&&It===!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($e!==void 0&&$e.length>0&&!te)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(Ft&&A&&!AD&&!Ft.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(Ft&&Z)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(Ft&&u.spawnClaudeCodeProcess)ae("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"});T6(!!v,CD??"default",b);let oE=u.pathToClaudeCodeExecutable;if(!oE){let dr=kXe(import.meta.url),to=AXe(dr),Yi=P2((yc)=>to.resolve(yc));if(!Yi)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.`);oE=Yi}let kD=ED?.type==="json_schema"?ED.schema:void 0,In=ne?{...ne}:{...process.env};if(!In.CLAUDE_CODE_ENTRYPOINT)In.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!In.CLAUDE_AGENT_SDK_VERSION)In.CLAUDE_AGENT_SDK_VERSION="0.3.250";if(Z)In.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(xD)In.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(vD)In.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(Je?.askUserQuestion?.previewFormat)In.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=Je.askUserQuestion.previewFormat;let sE={};if(rE.propagation.inject(rE.context.active(),sE),"traceparent"in sE){for(let dr of["TRACEPARENT","TRACESTATE"])if(!(dr in(ne??{})))delete In[dr]}for(let[dr,to]of Object.entries(sE)){let Yi=dr.toUpperCase();if(!(Yi in(ne??{})))In[Yi]=to}let RD={},OD=new Map;if(SD)for(let[dr,to]of Object.entries(SD))if(to.type==="sdk"&&to.instance)OD.set(dr,to);else RD[dr]=to;let hd;if(Pn)switch(Pn.type){case"adaptive":hd={type:"adaptive",display:Pn.display};break;case"enabled":hd={type:"enabled",budgetTokens:Pn.budgetTokens,display:Pn.display};break;case"disabled":hd={type:"disabled"};break}else if(Dt!==void 0)hd=Dt===0?{type:"disabled"}:{type:"enabled",budgetTokens:Dt};if(r){if(In.CLAUDE_CONFIG_DIR=r,process.platform==="win32")In.CLAUDE_SECURESTORAGE_CONFIG_DIR=ne?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??ne?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let PD=new oC({abortController:h,additionalDirectories:g,agent:y,betas:x,cwd:U,debug:D,debugFile:F,executable:oe,executableArgs:ge,extraArgs:wD?{...ke,workload:wD}:ke,pathToClaudeCodeExecutable:oE,env:In,forkSession:wt,stderr:ZQ,thinkingConfig:hd,effort:Zi,maxTurns:yh,maxBudgetUsd:jQ,taskBudget:$Q,model:zQ,fallbackModel:vt,jsonSchema:kD,permissionMode:CD,allowDangerouslySkipPermissions:BQ,permissionPromptToolName:KQ,continueConversation:Ft?void 0:A,resume:AD,resumeSessionAt:WQ,resumeDropsTurn:qQ,sessionId:VQ,settings:typeof i==="object"?fe(i):i,managedSettings:a?fe(a):void 0,settingSources:c,skills:TD,allowedTools:b,disallowedTools:K,tools:V,mcpServers:RD,strictMcpConfig:YQ,canUseTool:!!v,hooks:!!ht,includeHookEvents:ur,includePartialMessages:Pt,persistSession:It,sessionMirror:!!Ft,plugins:GQ,sandbox:l,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),JQ={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:S,title:u.title,skills:TD,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:se,supportedDialogKinds:$e,perTaskStopAffordance:Re},iE=new fy(PD,n,v,ht,h,OD,kD,JQ,ee,xD,vD,te);if(Ft){let dr=()=>xn(In.CLAUDE_CONFIG_DIR??xn(fD(),".claude"),"projects"),to=gt==="eager",Yi=new cC(async(yc,aE)=>{let gd=CQ(yc,dr());if(gd)await Ft.append(gd,aE);else ae(`[SessionStore] dropping mirror frame: filePath ${yc} is not under ${dr()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(yc,aE)=>{let gd=CQ(yc,dr());if(gd)iE.reportMirrorError(gd,aE.message)},maxPendingEntries:to?0:my,maxPendingBytes:to?0:fu});iE.setTranscriptMirrorBatcher(Yi)}return{queryInstance:iE,transport:PD,abortController:h,processEnv:In}}function bD(e,t,n,r){if(typeof n==="string")t.write(fe({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
162
162
  `);else e.streamInput(n).catch((o)=>r.abort(o))}var DXe=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function nE(e){for(let t=0;;t++)try{return await wXe(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!DXe.has(Ue(n)??""))return;await no((t+1)*100)}}function LXe(e,t){e.waitForExit().catch(()=>{}).finally(()=>nE(t))}function KWt({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return MXe(e,t);let{queryInstance:n,transport:r,abortController:o}=yD(t,{isSingleUserTurn:typeof e==="string"});return bD(n,r,e,o),n}function MXe(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s}=yD({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),i=_h(t.cwd??"."),a=t.sessionStore,c=t.loadTimeoutMs??60000,l=t.resume;return(async()=>{if(!l)l=(await Pr(a.listSessions(eo(i,t.env)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((f,m)=>m.mtime-f.mtime)[0]?.sessionId;if(!l)return;return IQ(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(()=>LXe(r,p))}if(!n.isClosed())r.spawn()}).catch((p)=>{let f=Fr(p);r.spawnAbort(f),n.setError(f)}),bD(n,r,e,o),n}async function GWt({options:e,initializeTimeoutMs:t=60000}={}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=_h(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 Pr(e.sessionStore.listSessions(eo(a,e.env)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((u,p)=>p.mtime-u.mtime)[0]?.sessionId}if(r)n=await IQ(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let m=function(){if(f)return;f=!0,u.close()},a=yD(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(()=>nE(h))})}let p=`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`;await Pr(u.initializationResult(),t,p).catch((h)=>{throw HN(h,p)?Tn(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{bD(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(()=>nE(n))}throw await i,a}}async function WWt(e,t){if(t?.sessionStore)return $Xe(t.sessionStore,e,t);return jq(e,t)}async function qWt(e){if(e?.sessionStore)return UXe(e.sessionStore,e);return G4(e)}async function VWt(e,t){if(t?.sessionStore)return zXe(t.sessionStore,e,t);return W4(e,t)}async function ZWt(e,t,n){if(n?.sessionStore)return HXe(n.sessionStore,e,t,n.dir);return J4(e,t,n)}async function YWt(e,t,n){if(n?.sessionStore)return BXe(n.sessionStore,e,t,n.dir);return X4(e,t,n)}async function JWt(e,t){if(!rt(e))throw new qe(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=eo(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return Q4(e,t)}async function XWt(e,t){if(t?.sessionStore)return KXe(t.sessionStore,e,t);return r6(e,t)}async function QWt(e,t,n,r){if(!rt(e))throw new qe(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=ye(),s=o?r:void 0,i=await Ci(e,n?.dir,nr(s),o);if(!i)throw Error(`Session ${e} not found`);let a=eo(n?.dir),c=n?.batchSize&&n.batchSize>0?n.batchSize:my,l=s===void 0?void 0:qa(mD(i.filePath),dn),u=s!==void 0&&l!==void 0?{backend:s,projectKey:l}:void 0;if(u!==void 0)await PO(u.backend,en.transcript(u.projectKey,e),{projectKey:a,sessionId:e},t,c);else await TQ(i.filePath,{projectKey:a,sessionId:e},t,c);if(n?.includeSubagents===!1)return;if(u!==void 0){let m=await g6(u.backend,u.projectKey,e),h=await _6(u.backend,u.projectKey,e,m);for(let g of m){let y={projectKey:a,sessionId:e,subpath:cb(g)};await PO(u.backend,g.kind==="agent"?en.transcript(u.projectKey,e,g.agentId,g.agentRelPath):en.journal(u.projectKey,e,g.agentRelPath),y,t,c);let S=h.get(y.subpath),b;if(S!==void 0)try{b=yt(S)}catch(x){ae(`importSessionToStore: skipping unreadable sidecar for ${y.subpath}: ${x}`)}if(b!==void 0)await t.append(y,[{type:"agent_metadata",...b}])}return}let p=i.filePath.replace(/\.jsonl$/,""),f=xn(p,"subagents");for(let m of await NXe(f)){let h=PQ(p,m).split(_D);h[h.length-1]=h.at(-1).replace(/\.jsonl$/,"");let g={projectKey:a,sessionId:e,subpath:h.join("/")};await TQ(m,g,t,c);let y=m.replace(/\.jsonl$/,".meta.json"),S;try{S=yt(await kQ(y,"utf8"))}catch(b){if(!Er(b))ae(`importSessionToStore: skipping unreadable sidecar ${y}: ${b}`)}if(S!==void 0)await t.append(g,[{type:"agent_metadata",...S}])}}async function TQ(e,t,n,r){let o=CXe({input:EXe(e,{encoding:"utf8"}),crlfDelay:1/0}),s=[],i=0;for await(let a of o){if(!a)continue;try{s.push(yt(a))}catch(c){ae(`importSessionToStore: skipping unparseable line in ${e}: ${c}`);continue}if(i+=a.length,s.length>=r||i>=fu)await n.append(t,s),s=[],i=0}if(s.length>0)await n.append(t,s)}async function NXe(e){let t=[];async function n(r){let o;try{o=await vXe(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=xn(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 eqt(e,t){if(t?.sessionStore)return GXe(t.sessionStore,e,t.dir);return p6(e,t)}async function tqt(e,t,n){if(n?.sessionStore)return WXe(n.sessionStore,e,t,n);return f6(e,t,n)}function DQ(e){let t=_h(e??"."),n;try{n=xXe(t)}catch{n=t}return st(n)}function eo(e,t){let n=DQ(e);if(t===void 0)return Rs(n);return(t.CLAUDE_CONFIG_DIR?jE(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??Yf(n)}function LQ(e){return e.map((t)=>fe(t)).join(`
163
163
  `)+`
164
164
  `}function MQ(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 hD(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}async function UXe(e,t){let n=DQ(t.dir),r=Rs(n),o=t.offset??0,s=t.limit;if(e.listSessionSummaries)return FXe(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=MQ(a,s,o);return NQ(e,c,t.dir,n)}async function FXe(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:YD(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 ae("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");c.sort((p,f)=>f.mtime-p.mtime);let l=MQ(c,o,s),u=l.filter((p)=>p.info===void 0);if(u.length>0){let p=await NQ(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 NQ(e,t,n,r){return(await Promise.allSettled(t.map(async(s)=>{let i=await FQ(e,s.sessionId,n);if(!i)return null;let a=Pu(s.sessionId,UQ(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 UQ(e,t){let n=Buffer.from(e,"utf-8"),r=n.length,o=n.subarray(0,Rr).toString("utf-8"),s=r>Rr?n.subarray(r-Rr).toString("utf-8"):o;return{mtime:t,size:r,head:o,tail:s}}function jXe(e){let t=e.trimEnd(),n=t.slice(t.lastIndexOf(`