@anthropic-ai/claude-agent-sdk 0.3.269 → 0.3.270
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/bridge.mjs +2 -2
- package/browser-sdk.js +1 -1
- package/manifest.json +21 -21
- package/manifest.zst.json +25 -25
- package/package.json +10 -10
- package/sdk.mjs +2 -2
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.
|
|
4
|
+
// Version: 0.3.270
|
|
5
5
|
|
|
6
6
|
// Want to see the unminified source? We're hiring!
|
|
7
7
|
// https://job-boards.greenhouse.io/anthropic/jobs/4816199008
|
|
@@ -218,7 +218,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
218
218
|
`+"\t".repeat(t))}};var a7;(function(e){e.DEFAULT={allowTrailingComma:!1}})(a7||(a7={}));var c7;(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"})(c7||(c7={}));var l7;(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"})(l7||(l7={}));var u7;(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"})(u7||(u7={}));var rd=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,p7=new Set,$D=typeof process==="object"&&!!process?process:{},f7=(e,t,n,r)=>{typeof $D.emitWarning==="function"?$D.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},{AbortController:cE,AbortSignal:d7}=globalThis;if(typeof cE>"u"){d7=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},cE=class{constructor(){t()}signal=new d7;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=$D.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{if(!e)return;e=!1,f7("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 d5e=(e)=>!p7.has(e),hGt=Symbol("type"),Vi=(e)=>e&&e===Math.floor(e)&&e>0&&isFinite(e),m7=(e)=>!Vi(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?dh:null;class dh extends Array{constructor(e){super(e);this.fill(0)}}class od{heap;length;static#e=!1;static create(e){let t=m7(e);if(!t)return[];od.#e=!0;let n=new od(e,t);return od.#e=!1,n}constructor(e,t){if(!od.#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 lE{#e;#t;#n;#r;#i;#u;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#l;#a;#o;#s;#f;#d;#p;#m;#_;#h;#S;#b;#y;#E;#v;#x;static unsafeExposeInternals(e){return{starts:e.#b,ttls:e.#y,sizes:e.#S,keyMap:e.#a,keyList:e.#o,valList:e.#s,next:e.#f,prev:e.#d,get head(){return e.#p},get tail(){return e.#m},free:e.#_,isBackgroundFetch:(t)=>e.#g(t),backgroundFetch:(t,n,r,o)=>e.#D(t,n,r,o),moveToTail:(t)=>e.#$(t),indexes:(t)=>e.#T(t),rindexes:(t)=>e.#R(t),isStale:(t)=>e.#w(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#l}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#u}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:_,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:x,ignoreFetchAbort:w}=e;if(t!==0&&!Vi(t))throw TypeError("max option must be a nonnegative integer");let N=t?m7(t):Array;if(!N)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.#u=y,_!==void 0&&typeof _!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#i=_,this.#v=!!_,this.#a=new Map,this.#o=Array(t).fill(void 0),this.#s=Array(t).fill(void 0),this.#f=new N(t),this.#d=new N(t),this.#p=0,this.#m=0,this.#_=od.create(t),this.#c=0,this.#l=0,typeof c==="function")this.#n=c;if(typeof l==="function")this.#r=l,this.#h=[];else this.#r=void 0,this.#h=void 0;if(this.#E=!!this.#n,this.#x=!!this.#r,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!x,this.ignoreFetchAbort=!!w,this.maxEntrySize!==0){if(this.#t!==0){if(!Vi(this.#t))throw TypeError("maxSize must be a positive integer if specified")}if(!Vi(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!i,this.ttlResolution=Vi(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Vi(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(d5e("LRU_CACHE_UNBOUNDED"))p7.add("LRU_CACHE_UNBOUNDED"),f7("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",lE)}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#A(){let e=new dh(this.#e),t=new dh(this.#e);this.#y=e,this.#b=t,this.#N=(o,s,i=rd.now())=>{if(t[o]=s!==0?i:0,e[o]=s,s!==0&&this.ttlAutopurge){let a=setTimeout(()=>{if(this.#w(o))this.#L(this.#o[o],"expire")},s+1);if(a.unref)a.unref()}},this.#C=(o)=>{t[o]=e[o]!==0?rd.now():0},this.#k=(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=rd.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.#a.get(o);if(s===void 0)return 0;let i=e[s],a=t[s];if(!i||!a)return 1/0;let c=(n||r())-a;return i-c},this.#w=(o)=>{let s=t[o],i=e[o];return!!i&&!!s&&(n||r())-s>i}}#C=()=>{};#k=()=>{};#N=()=>{};#w=()=>!1;#F(){let e=new dh(this.#e);this.#l=0,this.#S=e,this.#O=(t)=>{this.#l-=e[t],e[t]=0},this.#M=(t,n,r,o)=>{if(this.#g(n))return 0;if(!Vi(r))if(o){if(typeof o!=="function")throw TypeError("sizeCalculation must be a function");if(r=o(n,t),!Vi(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.#P=(t,n,r)=>{if(e[t]=n,this.#t){let o=this.#t-e[t];while(this.#l>o)this.#I(!0)}if(this.#l+=e[t],r)r.entrySize=n,r.totalCalculatedSize=this.#l}}#O=(e)=>{};#P=(e,t,n)=>{};#M=(e,t,n,r)=>{if(n||r)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;;){if(!this.#U(t))break;if(e||!this.#w(t))yield t;if(t===this.#p)break;else t=this.#d[t]}}*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;;){if(!this.#U(t))break;if(e||!this.#w(t))yield t;if(t===this.#m)break;else t=this.#f[t]}}#U(e){return e!==void 0&&this.#a.get(this.#o[e])===e}*entries(){for(let e of this.#T())if(this.#s[e]!==void 0&&this.#o[e]!==void 0&&!this.#g(this.#s[e]))yield[this.#o[e],this.#s[e]]}*rentries(){for(let e of this.#R())if(this.#s[e]!==void 0&&this.#o[e]!==void 0&&!this.#g(this.#s[e]))yield[this.#o[e],this.#s[e]]}*keys(){for(let e of this.#T()){let t=this.#o[e];if(t!==void 0&&!this.#g(this.#s[e]))yield t}}*rkeys(){for(let e of this.#R()){let t=this.#o[e];if(t!==void 0&&!this.#g(this.#s[e]))yield t}}*values(){for(let e of this.#T())if(this.#s[e]!==void 0&&!this.#g(this.#s[e]))yield this.#s[e]}*rvalues(){for(let e of this.#R())if(this.#s[e]!==void 0&&!this.#g(this.#s[e]))yield this.#s[e]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#T()){let r=this.#s[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;if(e(o,this.#o[n],this))return this.get(this.#o[n],t)}}forEach(e,t=this){for(let n of this.#T()){let r=this.#s[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#o[n],this)}}rforEach(e,t=this){for(let n of this.#R()){let r=this.#s[n],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0)continue;e.call(t,o,this.#o[n],this)}}purgeStale(){let e=!1;for(let t of this.#R({allowStale:!0}))if(this.#w(t))this.#L(this.#o[t],"expire"),e=!0;return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let n=this.#s[t],r=this.#g(n)?n.__staleWhileFetching:n;if(r===void 0)return;let o={value:r};if(this.#y&&this.#b){let s=this.#y[t],i=this.#b[t];if(s&&i){let a=s-(rd.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.#T({allowStale:!0})){let n=this.#o[t],r=this.#s[t],o=this.#g(r)?r.__staleWhileFetching:r;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#y&&this.#b){s.ttl=this.#y[t];let i=rd.now()-this.#b[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=rd.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.#M(e,t,n.size||0,i);if(this.maxEntrySize&&l>this.maxEntrySize){if(a)a.set="miss",a.maxEntrySizeExceeded=!0;return this.#L(e,"set"),this}let u=this.#c===0?void 0:this.#a.get(e);if(u===void 0){if(u=this.#c===0?this.#m:this.#_.length!==0?this.#_.pop():this.#c===this.#e?this.#I(!1):this.#c,this.#o[u]=e,this.#s[u]=t,this.#a.set(e,u),this.#f[this.#m]=u,this.#d[u]=this.#m,this.#m=u,this.#c++,this.#P(u,l,a),a)a.set="add";c=!1}else{this.#$(u);let p=this.#s[u];if(t!==p){if(this.#v&&this.#g(p)){p.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=p;if(f!==void 0&&!s){if(this.#E)this.#n?.(f,e,"set");if(this.#x)this.#h?.push([f,e,"set"])}}else if(!s){if(this.#E)this.#n?.(p,e,"set");if(this.#x)this.#h?.push([p,e,"set"])}if(this.#O(u),this.#P(u,l,a),this.#s[u]=t,a){a.set="replace";let f=p&&this.#g(p)?p.__staleWhileFetching:p;if(f!==void 0)a.oldValue=f}}else if(a)a.set="update"}if(r!==0&&!this.#y)this.#A();if(this.#y){if(!c)this.#N(u,r,o);if(a)this.#k(a,u)}if(!s&&this.#x&&this.#h){let p=this.#h,f;while(f=p?.shift())this.#r?.(...f)}return this}pop(){try{while(this.#c){let e=this.#s[this.#p];if(this.#I(!0),this.#g(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#x&&this.#h){let e=this.#h,t;while(t=e?.shift())this.#r?.(...t)}}}#I(e){let t=this.#p,n=this.#o[t],r=this.#s[t];if(this.#v&&this.#g(r))r.__abortController.abort(Error("evicted"));else if(this.#E||this.#x){if(this.#E)this.#n?.(r,n,"evict");if(this.#x)this.#h?.push([r,n,"evict"])}if(this.#O(t),e)this.#o[t]=void 0,this.#s[t]=void 0,this.#_.push(t);if(this.#c===1)this.#p=this.#m=0,this.#_.length=0;else this.#p=this.#f[t];return this.#a.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,o=this.#a.get(e);if(o!==void 0){let s=this.#s[o];if(this.#g(s)&&s.__staleWhileFetching===void 0)return!1;if(!this.#w(o)){if(n)this.#C(o);if(r)r.has="hit",this.#k(r,o);return!0}else if(r)r.has="stale",this.#k(r,o)}else if(r)r.has="miss";return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#a.get(e);if(r===void 0||!n&&this.#w(r))return;let o=this.#s[r];return this.#g(o)?o.__staleWhileFetching:o}#D(e,t,n,r){let o=t===void 0?void 0:this.#s[t];if(this.#g(o))return o;let s=new cE,{signal:i}=n;i?.addEventListener("abort",()=>s.abort(i.reason),{signal:s.signal});let a={signal:s.signal,options:n,context:r},c=(h,_=!1)=>{let{aborted:y}=s.signal,b=n.ignoreFetchAbort&&h!==void 0;if(n.status)if(y&&!_){if(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,b)n.status.fetchAbortIgnored=!0}else n.status.fetchResolved=!0;if(y&&!b&&!_)return u(s.signal.reason);let v=f;if(this.#s[t]===f)if(h===void 0)if(v.__staleWhileFetching)this.#s[t]=v.__staleWhileFetching;else this.#L(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:_}=s.signal,y=_&&n.allowStaleOnFetchAbort,b=y||n.allowStaleOnFetchRejection,v=b||n.noDeleteOnFetchRejection,S=f;if(this.#s[t]===f){if(!v||S.__staleWhileFetching===void 0)this.#L(e,"fetch");else if(!y)this.#s[t]=S.__staleWhileFetching}if(b){if(n.status&&S.__staleWhileFetching!==void 0)n.status.returnedStale=!0;return S.__staleWhileFetching}else if(S.__returned===S)throw h},p=(h,_)=>{let y=this.#i?.(e,o,a);if(y&&y instanceof Promise)y.then((b)=>h(b===void 0?void 0:b),_);s.signal.addEventListener("abort",()=>{if(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort){if(h(void 0),n.allowStaleOnFetchAbort)h=(b)=>c(b,!0)}})};if(n.status)n.status.fetchDispatched=!0;let f=new Promise(p).then(c,l),m=Object.assign(f,{__abortController:s,__staleWhileFetching:o,__returned:void 0});if(t===void 0)this.set(e,m,{...a.options,status:void 0}),t=this.#a.get(e);else this.#s[t]=m;return m}#g(e){if(!this.#v)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof cE}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:_=!1,status:y,signal:b}=t;if(!this.#v){if(y)y.fetch="get";return this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:y})}let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:i,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:y,signal:b},S=this.#a.get(e);if(S===void 0){if(y)y.fetch="miss";let x=this.#D(e,S,v,h);return x.__returned=x}else{let x=this.#s[S];if(this.#g(x)){let z=n&&x.__staleWhileFetching!==void 0;if(y){if(y.fetch="inflight",z)y.returnedStale=!0}return z?x.__staleWhileFetching:x.__returned=x}let w=this.#w(S);if(!_&&!w){if(y)y.fetch="hit";if(this.#$(S),r)this.#C(S);if(y)this.#k(y,S);return x}let N=this.#D(e,S,v,h),F=N.__staleWhileFetching!==void 0&&n;if(y){if(y.fetch=w?"stale":"refresh",F&&w)y.returnedStale=!0}return F?N.__staleWhileFetching:N.__returned=N}}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.#u;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.#a.get(e);if(i!==void 0){let a=this.#s[i],c=this.#g(a);if(s)this.#k(s,i);if(this.#w(i)){if(s)s.get="stale";if(!c){if(!o)this.#L(e,"expire");if(s&&n)s.returnedStale=!0;return n?a:void 0}else{if(s&&n&&a.__staleWhileFetching!==void 0)s.returnedStale=!0;return n?a.__staleWhileFetching:void 0}}else{if(s)s.get="hit";if(c)return a.__staleWhileFetching;if(this.#$(i),r)this.#C(i);return a}}else if(s)s.get="miss"}#z(e,t){this.#d[t]=e,this.#f[e]=t}#$(e){if(e!==this.#m){if(e===this.#p)this.#p=this.#f[e];else this.#z(this.#d[e],this.#f[e]);this.#z(this.#m,e),this.#m=e}}delete(e){return this.#L(e,"delete")}#L(e,t){let n=!1;if(this.#c!==0){let r=this.#a.get(e);if(r!==void 0)if(n=!0,this.#c===1)this.#j(t);else{this.#O(r);let o=this.#s[r];if(this.#g(o))o.__abortController.abort(Error("deleted"));else if(this.#E||this.#x){if(this.#E)this.#n?.(o,e,t);if(this.#x)this.#h?.push([o,e,t])}if(this.#a.delete(e),this.#o[r]=void 0,this.#s[r]=void 0,r===this.#m)this.#m=this.#d[r];else if(r===this.#p)this.#p=this.#f[r];else{let s=this.#d[r];this.#f[s]=this.#f[r];let i=this.#f[r];this.#d[i]=this.#d[r]}this.#c--,this.#_.push(r)}}if(this.#x&&this.#h?.length){let r=this.#h,o;while(o=r?.shift())this.#r?.(...o)}return n}clear(){return this.#j("delete")}#j(e){for(let t of this.#R({allowStale:!0})){let n=this.#s[t];if(this.#g(n))n.__abortController.abort(Error("deleted"));else{let r=this.#o[t];if(this.#E)this.#n?.(n,r,e);if(this.#x)this.#h?.push([n,r,e])}}if(this.#a.clear(),this.#s.fill(void 0),this.#o.fill(void 0),this.#y&&this.#b)this.#y.fill(0),this.#b.fill(0);if(this.#S)this.#S.fill(0);if(this.#p=0,this.#m=0,this.#_.length=0,this.#l=0,this.#c=0,this.#x&&this.#h){let t=this.#h,n;while(n=t?.shift())this.#r?.(...n)}}}function uE(e,t,n=100){let r=new lE({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 p5e=8192;function g7(e,t){try{return{ok:!0,value:JSON.parse(vu(e))}}catch(n){if(t)W_(GF(n,`safeParseJSON: invalid JSON (${n instanceof Error?n.constructor.name:typeof n}, ${e.length} bytes)`));return{ok:!1}}}class _7{cached=uE(g7,(e)=>e,50);cache=this.cached.cache;parse(e,t){return this.cached(e,t)}}var h7=new _7;var mc=Object.assign(function(t,n=!0){if(!t)return null;let r=t.length>p5e?g7(t,n):h7.parse(t,n);return r.ok?r.value:null},{cache:h7.cache});import{join as f5e}from"path";class y7{managedFilePath=void 0;dropInDir=void 0;getManagedFilePath(){return this.managedFilePath??=h5e(),this.managedFilePath}getDropInDir(){return this.dropInDir??=f5e(hc(),"managed-settings.d"),this.dropInDir}clearDropInDir(){this.dropInDir=void 0}reset(){this.managedFilePath=void 0,this.dropInDir=void 0}}var m5e=new y7;function hc(){return m5e.getManagedFilePath()}function h5e(){let e=g5e();if(e!==void 0)return e;switch(In()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}function g5e(){return}var ph=["low","medium","high","xhigh","max"];var fh=[{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:["permissions","blockReadsOutsideWorkingDirectories"],restrictive:!0},{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:["remoteTools","allowUnattendedServing"],restrictive:!1},{path:["autoContinueAtUsageLimit"],restrictive:!1},...[],{path:["attribution","sessionUrl"],restrictive:!1},{path:["crossSessionInbound"],restrictive:["refuse","hold"]},{path:["remoteControl","shareHostProfile"],restrictive:["off","basic"]},{path:["modelProposedGoals"],restrictive:["disabled","alwaysAsk"]},{path:["maxEffortLevel"],restrictive:ph},{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 mh(e){return Array.isArray(e)?e:[e]}function js(e,t){let n=e;for(let r of t){if(n===null||typeof n!=="object")return;n=n[r]}return n}function qi(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 _5e(e,t,n){if(n!==void 0&&!Uo(e[t],n)||n===void 0&&!(t in e))Ys(e,t,n)}var hh=_5e;var pE={};Lr(pE,{default:()=>gh});var x7=typeof pE=="object"&&pE&&!pE.nodeType&&pE,S7=x7&&typeof dE=="object"&&dE&&!dE.nodeType&&dE,y5e=S7&&S7.exports===x7,b7=y5e?Gt.Buffer:void 0,E7=b7?b7.allocUnsafe:void 0;function S5e(e,t){if(t)return e.slice();var n=e.length,r=E7?E7(n):new e.constructor(n);return e.copy(r),r}var gh=S5e;function b5e(e){var t=new e.constructor(e.byteLength);return new Ic(t).set(new Ic(e)),t}var sd=b5e;function E5e(e,t){var n=t?sd(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}var fE=E5e;function x5e(e,t){var n=-1,r=e.length;t||(t=Array(r));while(++n<r)t[n]=e[n];return t}var mE=x5e;var v7=Object.create,v5e=function(){function e(){}return function(t){if(!Ht(t))return{};if(v7)return v7(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}(),w7=v5e;function w5e(e){return typeof e.constructor=="function"&&!Fc(e)?w7(td(e)):{}}var hE=w5e;function A5e(e){return Zt(e)&&Zs(e)}var A7=A5e;var C5e="[object Object]",T5e=Function.prototype,R5e=Object.prototype,C7=T5e.toString,k5e=R5e.hasOwnProperty,O5e=C7.call(Object);function P5e(e){if(!Zt(e)||hr(e)!=C5e)return!1;var t=td(e);if(t===null)return!0;var n=k5e.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&C7.call(n)==O5e}var gE=P5e;function I5e(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var _h=I5e;function D5e(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)Ys(n,a,c);else ed(n,a,c)}return n}var eo=D5e;function L5e(e){return eo(e,os(e))}var T7=L5e;function N5e(e,t,n,r,o,s,i){var a=_h(e,n),c=_h(t,n),l=i.get(c);if(l){hh(e,n,l);return}var u=s?s(a,c,n+"",e,t,i):void 0,p=u===void 0;if(p){var f=Ct(c),m=!f&&$o(c),h=!f&&!m&&Uc(c);if(u=c,f||m||h)if(Ct(a))u=a;else if(A7(a))u=mE(a);else if(m)p=!1,u=gh(c,!0);else if(h)p=!1,u=fE(c,!0);else u=[];else if(gE(c)||us(c)){if(u=a,us(a))u=T7(a);else if(!Ht(a)||Rc(a))u=hE(c)}else p=!1}if(p)i.set(c,u),o(u,c,r,s,i),i.delete(c);hh(e,n,u)}var R7=N5e;function k7(e,t,n,r,o){if(e===t)return;og(t,function(s,i){if(o||(o=new Fo),Ht(s))R7(e,t,i,n,k7,r,o);else{var a=r?r(_h(e,i),s,i+"",e,t,o):void 0;if(a===void 0)a=s;hh(e,i,a)}},os)}var O7=k7;function M5e(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 P7=M5e;var I7=Math.max;function U5e(e,t,n){return t=I7(t===void 0?e.length-1:t,0),function(){var r=arguments,o=-1,s=I7(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),P7(e,this,a)}}var _E=U5e;function F5e(e){return function(){return e}}var D7=F5e;var $5e=!Hc?Wc:function(e,t){return Hc(e,"toString",{configurable:!0,enumerable:!1,value:D7(t),writable:!0})},L7=$5e;var z5e=800,j5e=16,H5e=Date.now;function B5e(e){var t=0,n=0;return function(){var r=H5e(),o=j5e-(r-n);if(n=r,o>0){if(++t>=z5e)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var N7=B5e;var K5e=N7(L7),yE=K5e;function G5e(e,t){return yE(_E(e,t,Wc),e+"")}var M7=G5e;function W5e(e,t,n){if(!Ht(n))return!1;var r=typeof t;if(r=="number"?Zs(n)&&qs(t,n.length):r=="string"&&(t in n))return Uo(n[t],e);return!1}var U7=W5e;function V5e(e){return M7(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&&U7(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 F7=V5e;var q5e=F7(function(e,t,n,r){O7(e,t,n,r)}),Gn=q5e;function Z5e(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 $7=Z5e;function Y5e(e,t){return e&&eo(t,jo(t),e)}var z7=Y5e;function J5e(e,t){return e&&eo(t,os(t),e)}var j7=J5e;function X5e(e,t){return eo(e,Lc(e),t)}var H7=X5e;function Q5e(e,t){return eo(e,iE(e),t)}var B7=Q5e;var e8e=Object.prototype,t8e=e8e.hasOwnProperty;function n8e(e){var t=e.length,n=new e.constructor(t);if(t&&typeof e[0]=="string"&&t8e.call(e,"index"))n.index=e.index,n.input=e.input;return n}var K7=n8e;function r8e(e,t){var n=t?sd(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var G7=r8e;var o8e=/\w*$/;function s8e(e){var t=new e.constructor(e.source,o8e.exec(e));return t.lastIndex=e.lastIndex,t}var W7=s8e;var V7=an?an.prototype:void 0,q7=V7?V7.valueOf:void 0;function i8e(e){return q7?Object(q7.call(e)):{}}var Z7=i8e;var a8e="[object Boolean]",c8e="[object Date]",l8e="[object Map]",u8e="[object Number]",d8e="[object RegExp]",p8e="[object Set]",f8e="[object String]",m8e="[object Symbol]",h8e="[object ArrayBuffer]",g8e="[object DataView]",_8e="[object Float32Array]",y8e="[object Float64Array]",S8e="[object Int8Array]",b8e="[object Int16Array]",E8e="[object Int32Array]",x8e="[object Uint8Array]",v8e="[object Uint8ClampedArray]",w8e="[object Uint16Array]",A8e="[object Uint32Array]";function C8e(e,t,n){var r=e.constructor;switch(t){case h8e:return sd(e);case a8e:case c8e:return new r(+e);case g8e:return G7(e,n);case _8e:case y8e:case S8e:case b8e:case E8e:case x8e:case v8e:case w8e:case A8e:return fE(e,n);case l8e:return new r;case u8e:case f8e:return new r(e);case d8e:return W7(e);case p8e:return new r;case m8e:return Z7(e)}}var Y7=C8e;var T8e="[object Map]";function R8e(e){return Zt(e)&&ds(e)==T8e}var J7=R8e;var X7=zo&&zo.isMap,k8e=X7?Mc(X7):J7,Q7=k8e;var O8e="[object Set]";function P8e(e){return Zt(e)&&ds(e)==O8e}var eQ=P8e;var tQ=zo&&zo.isSet,I8e=tQ?Mc(tQ):eQ,nQ=I8e;var D8e=1,L8e=2,N8e=4,rQ="[object Arguments]",M8e="[object Array]",U8e="[object Boolean]",F8e="[object Date]",$8e="[object Error]",oQ="[object Function]",z8e="[object GeneratorFunction]",j8e="[object Map]",H8e="[object Number]",sQ="[object Object]",B8e="[object RegExp]",K8e="[object Set]",G8e="[object String]",W8e="[object Symbol]",V8e="[object WeakMap]",q8e="[object ArrayBuffer]",Z8e="[object DataView]",Y8e="[object Float32Array]",J8e="[object Float64Array]",X8e="[object Int8Array]",Q8e="[object Int16Array]",eXe="[object Int32Array]",tXe="[object Uint8Array]",nXe="[object Uint8ClampedArray]",rXe="[object Uint16Array]",oXe="[object Uint32Array]",Et={};Et[rQ]=Et[M8e]=Et[q8e]=Et[Z8e]=Et[U8e]=Et[F8e]=Et[Y8e]=Et[J8e]=Et[X8e]=Et[Q8e]=Et[eXe]=Et[j8e]=Et[H8e]=Et[sQ]=Et[B8e]=Et[K8e]=Et[G8e]=Et[W8e]=Et[tXe]=Et[nXe]=Et[rXe]=Et[oXe]=!0;Et[$8e]=Et[oQ]=Et[V8e]=!1;function SE(e,t,n,r,o,s){var i,a=t&D8e,c=t&L8e,l=t&N8e;if(n)i=o?n(e,r,o,s):n(e);if(i!==void 0)return i;if(!Ht(e))return e;var u=Ct(e);if(u){if(i=K7(e),!a)return mE(e,i)}else{var p=ds(e),f=p==oQ||p==z8e;if($o(e))return gh(e,a);if(p==sQ||p==rQ||f&&!o){if(i=c||f?{}:hE(e),!a)return c?B7(e,j7(i,e)):H7(e,z7(i,e))}else{if(!Et[p])return o?e:{};i=Y7(e,p,a)}}s||(s=new Fo);var m=s.get(e);if(m)return m;if(s.set(e,i),nQ(e))e.forEach(function(y){i.add(SE(y,t,n,y,e,s))});else if(Q7(e))e.forEach(function(y,b){i.set(b,SE(y,t,n,b,e,s))});var h=l?c?nd:Ed:c?os:jo,_=u?void 0:h(e);return $7(_||e,function(y,b){if(_)b=y,y=e[b];ed(i,b,SE(y,t,n,b,e,s))}),i}var iQ=SE;function sXe(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}var aQ=sXe;function iXe(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 cQ=iXe;function aXe(e,t){return t.length<2?e:Js(e,cQ(t,0,-1))}var lQ=aXe;var cXe=Object.prototype,lXe=cXe.hasOwnProperty;function uXe(e,t){t=Nr(t,e);var n=-1,r=t.length;if(!r)return!0;while(++n<r){var o=gr(t[n]);if(o==="__proto__"&&!lXe.call(e,"__proto__"))return!1;if((o==="constructor"||o==="prototype")&&n<r-1)return!1}var s=lQ(e,t);return s==null||delete s[gr(aQ(t))]}var uQ=uXe;function dXe(e){return gE(e)?void 0:e}var dQ=dXe;var pQ=an?an.isConcatSpreadable:void 0;function pXe(e){return Ct(e)||us(e)||!!(pQ&&e&&e[pQ])}var fQ=pXe;function mQ(e,t,n,r,o){var s=-1,i=e.length;n||(n=fQ),o||(o=[]);while(++s<i){var a=e[s];if(t>0&&n(a))if(t>1)mQ(a,t-1,n,r,o);else Dc(o,a);else if(!r)o[o.length]=a}return o}var hQ=mQ;function fXe(e){var t=e==null?0:e.length;return t?hQ(e,1):[]}var gQ=fXe;function mXe(e){return yE(_E(e,void 0,gQ),e+"")}var bE=mXe;var hXe=1,gXe=2,_Xe=4,yXe=bE(function(e,t){var n={};if(e==null)return n;var r=!1;if(t=Gc(t,function(s){return s=Nr(s,e),r||(r=s.length>1),s}),eo(e,nd(e),n),r)n=iQ(n,hXe|gXe|_Xe,dQ);var o=t.length;while(o--)uQ(n,t[o]);return n}),yh=yXe;function SXe(e,t){return sE(e,t,function(n,r){return ag(e,r)})}var _Q=SXe;var bXe=bE(function(e,t){return e==null?{}:_Q(e,t)}),Sh=bXe;import{homedir as Dtt}from"os";import{dirname as Ltt,join as No,resolve as to}from"path";jc();var EXe="Expected a function";function xXe(e){if(typeof e!="function")throw TypeError(EXe);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 yQ=xXe;function vXe(e,t){return aE(e,yQ(Xs(t)))}var bh=vXe;import{join as wte}from"path";import{isAbsolute as SQ}from"path";var wXe=L(()=>C({allowedDomains:I(g()).optional(),deniedDomains:I(g()).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:k().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:k().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(g()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:k().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:k().optional(),allowMachLookup:I(g().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:X().optional(),socksProxyPort:X().optional(),tlsTerminate:C({caCertPath:g().min(1).optional(),caKeyPath:g().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()),AXe=L(()=>C({allowWrite:I(g()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:I(g()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:I(g()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:I(g()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:k().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used."),disabled:k().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 bQ(e,t,n){if(e.length===0||e.some((r)=>r.length===0))n.addIssue({code:qr.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:qr.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 EQ(e,t){let n;try{n=new RegExp(e)}catch(o){t.addIssue({code:qr.custom,path:["extract"],message:`extract is not a valid regular expression: ${Kr(o)}`});return}if(new RegExp(n.source+"|").exec("").length-1<1)t.addIssue({code:qr.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 xQ(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 EE=L(()=>Qe(xQ,C({path:g().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:V(["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:g().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:V(["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:V(["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(g()).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:k().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(g()).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:qr.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)EQ(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)bQ(e.maskClaims,e.decode,t)}))),id=()=>g().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"),xE=L(()=>Qe(xQ,C({name:id().describe("Environment variable name."),mode:V(["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:g().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:V(["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:V(["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(g()).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(g()).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)EQ(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)bQ(e.maskClaims,e.decode,t);if(e.mode==="mask"&&e.decode!==void 0&&e.extract!==void 0)t.addIssue({code:qr.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:qr.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)."})}))),Zi=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"];var zD="_INVALID_PAIR_",vE="_PARENT_PAIR_SUPPRESSOR_";var wE=L(()=>C({accessKeyIdVar:id().describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:id().describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:id().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:qr.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)}})),CXe=L(()=>{let e=V(["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`.")})}),TXe=L(()=>C({files:I(EE()).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(xE()).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:k().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(wE()).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:CXe().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:qr.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()),jD=L(()=>C({enabled:k().optional(),failIfUnavailable:k().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:k().optional(),allowUnsandboxedCommands:k().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:wXe(),filesystem:AXe(),credentials:TXe(),ignoreViolations:Z(g(),I(g())).optional(),enableWeakerNestedSandbox:k().optional(),enableWeakerNetworkIsolation:k().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:k().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(g()).optional(),ripgrep:C({command:g(),args:I(g()).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:Qe((e)=>typeof e==="string"&&SQ(e)?e:void 0,g()).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:Qe((e)=>typeof e==="string"&&SQ(e)?e:void 0,g()).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 vQ=new Set(["disableAllHooks"]);function wQ(e){let t={};for(let{path:u,restrictive:p}of fh){if(vQ.has(u[0]))continue;let f=js(e,u);if((typeof f==="boolean"||typeof f==="string")&&mh(p).includes(f))qi(t,u,f)}let n=AE(e.permissions,["deny","ask","disableBypassPermissionsMode","disableAutoMode"]);if(n)t.permissions={...t.permissions,...n};for(let u of RXe)if(e[u]!==void 0)t[u]=e[u];for(let[u,p]of Object.entries(e))if((u.startsWith("disable")&&(p===!0||p==="disable")||u.startsWith("enable")&&p===!1)&&!vQ.has(u))t[u]=p;if(e.disableAllHooks===!0)t.allowManagedHooksOnly=!0;if(Array.isArray(e.httpHookAllowedEnvVars)&&e.httpHookAllowedEnvVars.length===0)t.httpHookAllowedEnvVars=[];let r=AE(e.sandbox?.filesystem,["denyRead","denyWrite","allowManagedReadPathsOnly"]),o=AE(e.sandbox?.network,["deniedDomains","strictAllowlist","allowManagedDomainsOnly"]),s=AE(e.sandbox?.credentials,["files","envVars"])??{},i=(e.sandbox?.credentials?.awsPairs??[]).flatMap((u)=>[u.accessKeyIdVar,u.secretAccessKeyVar,u.sessionTokenVar]),a=Zi.filter((u)=>i.includes(u));if(a.length>0)s.awsPairs=a.map((u,p)=>({accessKeyIdVar:u,secretAccessKeyVar:`${vE}${p+1}_`}));let c=e.sandbox?.credentials?.sigv4;if(c){let u={};for(let[p,f]of Object.entries(c))if(f==="deny")u[p]="deny";if(Object.keys(u).length>0)s.sigv4=u}let l=Object.keys(s).length>0;if(r||o||l){let u=t.sandbox??{};t.sandbox={...u,...r&&{filesystem:{...u.filesystem,...r}},...o&&{network:{...u.network,...o}},...l&&{credentials:{...u.credentials,...s}}}}return Object.keys(t).length>0?t:null}function AE(e,t){if(!e)return;let n={};for(let r of t)if(e[r]!==void 0)n[r]=e[r];return Object.keys(n).length>0?n:void 0}var RXe=["allowedMcpServers","deniedMcpServers","allowManagedMcpServersOnly","disabledMcpjsonServers","allowManagedHooksOnly","allowedHttpHookUrls","strictKnownMarketplaces","allowedMarketplaces","blockedMarketplaces","strictPluginOnlyCustomization","availableModels","enforceAvailableModels"];function CQ(e){let t=0,n=e.length;while(t<n&&AQ(e.charCodeAt(t)))t++;while(n>t&&AQ(e.charCodeAt(n-1)))n--;let r=kXe(e.slice(t,n));if(r!==-1)return{kind:"line_break",index:HD(e,t+r)};for(let o=t;o<n;o++){let s=e.charCodeAt(o);if(s===0)return{kind:"nul",index:HD(e,o)};if(s>255)return{kind:"non_ascii",index:HD(e,o),codePoint:OXe(e,o)}}return null}function kXe(e){let t=e.indexOf(`
|
|
219
219
|
`),n=e.indexOf("\r");if(t===-1)return n;return n===-1?t:Math.min(t,n)}function AQ(e){return e===9||e===32||e===10||e===13}function OXe(e,t){return e.codePointAt(t)??e.charCodeAt(t)}function HD(e,t){let n=0;for(let r=0;r<t;r++){let o=e.charCodeAt(r);if(o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320)r++;n++}return n}var BD=["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"],TQ=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE"];var RQ="OTEL_EXPORTER_OTLP_",kQ=["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"],OQ=[RQ,`ANT_${RQ}`],PQ={apiKeyHelper:["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],awsAuthRefresh:[...TQ,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],awsCredentialExport:[...TQ,"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"]},PXe=["CLAUDE_CODE_MEMORY_API_BASE_URL","CLAUDE_CODE_MEMORY_API_TOKEN"];var KD=["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",...PXe],IXe=[{endpoint:"ANTHROPIC_BASE_URL",companions:["_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_BEDROCK_BASE_URL",selection:"CLAUDE_CODE_USE_BEDROCK",companions:["CLAUDE_CODE_SKIP_BEDROCK_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_VERTEX_BASE_URL",selection:"CLAUDE_CODE_USE_VERTEX",companions:["CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_FOUNDRY_BASE_URL",selection:"CLAUDE_CODE_USE_FOUNDRY",companions:["CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_AWS_BASE_URL",selection:"CLAUDE_CODE_USE_ANTHROPIC_AWS",companions:["CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_GOOGLE_CLOUD_BASE_URL",selection:"CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",companions:["CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_BEDROCK_MANTLE_BASE_URL",selection:"CLAUDE_CODE_USE_MANTLE",companions:["CLAUDE_CODE_SKIP_MANTLE_AUTH","ANTHROPIC_CUSTOM_HEADERS"]}],A4t=Tr(IXe.flatMap((e)=>[e.endpoint,...e.companions])),GD=["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"],DXe=["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"],WD=["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"],VD=["ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES"],LXe=["CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR","CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR","CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR","CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR"],C4t=["CLAUDE_CODE_OAUTH_TOKEN",...LXe,"CLAUDE_CODE_ARTIFACTS_API_TOKEN","CLAUDE_CODE_SLACK_TAG_TOKEN","CLAUDE_CODE_HFI_BEARER_TOKEN","CLAUDE_BRIDGE_OAUTH_TOKEN","CLAUDE_TRUSTED_DEVICE_TOKEN","AGENT_PROXY_AUTH_TOKEN","CLAUDE_CODE_MCP_SERVE_AUTH_TOKEN","CLAUDE_BG_AUTH_SNAPSHOT_PATH","CLAUDE_BG_SOCKET_TOKENS_PATH","CLAUDE_BG_RV_AUTH","CLAUDE_BG_PTY_AUTH","CLAUDE_BG_CLAIM_AUTH"],NXe=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],qD=[...NXe,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var ZD=["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"],YD=["GCE_METADATA_HOST","GCE_METADATA_ROOT","GCE_METADATA_IP","METADATA_SERVER_DETECTION"],T4t=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...BD,...KD,...GD,...DXe,"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",...qD,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT",...YD,...ZD,"AWS_REGION","AWS_DEFAULT_REGION",...WD,"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","CLAUDE_CODE_SUBAGENT_MODEL_FORCE",...VD]);var IQ=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","fileSuggestion","gcpAuthRefresh","otelHeadersHelper","processWrapper","policyHelpers","proxyAuthHelper","statusLine","subagentStatusLine"],JD=["bwrapPath","ripgrep","socatPath"],DQ=["allowAppleEvents","credentials","enableWeakerNestedSandbox","enableWeakerNetworkIsolation","filesystem.disabled","network.allowAllUnixSockets","network.allowMachLookup","network.allowUnixSockets","network.httpProxyPort","network.socksProxyPort","network.tlsTerminate"],MXe=new Set(["ANTHROPIC_BEDROCK_REGION_PREFIX","ANTHROPIC_BEDROCK_SERVICE_TIER","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_REPOSITORY","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_FABLE_5_1","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_MCP_TASK_BACKGROUND","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_FUNCTION_HOOKS","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_FIRST_BYTE_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"]),UXe=new Set(["API_FORCE_IDLE_TIMEOUT","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","DISABLE_ERROR_REPORTING","DISABLE_TELEMETRY","DO_NOT_TRACK"]),FXe=new Set(["ENABLE_BETA_TRACING_DETAILED","OTEL_LOG_RAW_API_BODIES"]),$Xe=/auth|key|token|cookie|secret|credential|session|signature|passw|jwt|assertion|cert|oidc|org|tenant|account|project|workspace|user|email|identity|principal|consumer|client|host|url|base|target|upstream|endpoint|proxy|forward|route|fallback|override|apigw|x-goog-|l5d-|bypass|guardrail|amz|x-ms-|azureml|extra-parameters|envoy|helicone|litellm|cf-aig|cf-access|beta|version/;function zXe(e){if(/\r(?!\n)/.test(e))return!0;return e.split(/\n|\r\n/).some((t)=>{let n=t.indexOf(":");if(n===-1)return!1;let r=t.slice(0,n).trim();return!jXe.test(r)||CQ(t.slice(n+1))!==null||$Xe.test(r.toLowerCase())})}var jXe=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function LQ(e,t){let n=e.toUpperCase();return MXe.has(n)||UXe.has(n)&&Oe(t)||FXe.has(n)&&ea(t)||n==="ANTHROPIC_CUSTOM_HEADERS"&&!zXe(t)}import{posix as Xee,win32 as Qee}from"path";var ad=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],BXe=[...ad],NQ=BXe;function Eh(e){return e==="manual"?"default":e}var k4t=`Cannot set permission mode: must be one of ${ad.join(", ")}`,O4t={dangerousRemoval:{bypassImmune:!0,classifierRouted:!0,hostPersonOnly:!1,localProjectionOnly:!1},backgroundOperator:{bypassImmune:!1,classifierRouted:!0,hostPersonOnly:!1,localProjectionOnly:!1},suspiciousWindowsPath:{bypassImmune:!1,classifierRouted:!0,hostPersonOnly:!1,localProjectionOnly:!1},isolatePeerMachines:{bypassImmune:!0,classifierRouted:!1,hostPersonOnly:!1,localProjectionOnly:!1},restrictedMode:{bypassImmune:!0,classifierRouted:!1,hostPersonOnly:!1,localProjectionOnly:!1},outsideReadsBlocked:{bypassImmune:!0,classifierRouted:!1,hostPersonOnly:!1,localProjectionOnly:!1},claudeSettingsFile:{bypassImmune:!1,classifierRouted:!1,hostPersonOnly:!0,localProjectionOnly:!1},denyRulesUnjudged:{bypassImmune:!0,classifierRouted:!1,hostPersonOnly:!1,localProjectionOnly:!1},...{},...{}};var MQ=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"];var UQ=["normal","vim"];var FQ=["auto","12-hour","24-hour","24-hour-utc"],$Q=["auto","tmux","iterm2","in-process"],KXe=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],zQ=["auto",...KXe],jQ=["auto","alwaysAsk","disabled"],HQ=1e5,BQ=1e6;var GXe=String.raw`\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}`;function KQ(e){return new RegExp(GXe).test(e)}var M4t=L(()=>V(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),U4t=L(()=>V(["stdio","sse","sse-ide","http","ws","sdk"])),cd=L(()=>j("comms").optional().catch(void 0)),Yi=L(()=>X().int().positive()),WXe=300000,GQ=L(()=>X().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function WQ({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,WXe)}}}var VXe=L(()=>C({type:j("stdio").optional(),command:g().min(1,"Command cannot be empty"),args:I(g()).default([]),env:Z(g(),g()).optional(),timeout:Yi().optional(),alwaysLoad:k().optional(),role:cd()})),qXe=L(()=>k()),VQ=L(()=>C({clientId:g().optional(),callbackPort:X().int().positive().optional(),authServerMetadataUrl:g().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:g().min(1).optional(),xaa:qXe().optional()})),qQ=L(()=>C({name:g(),permission_policy:V(["always_allow","always_ask","always_deny"]).optional()})),ZQ=L(()=>C({type:j("sse"),url:g(),headers:Z(g(),g()).optional(),headersHelper:g().optional(),oauth:VQ().optional(),timeout:Yi().optional(),request_timeout_ms:GQ(),tools:I(qQ()).optional(),alwaysLoad:k().optional(),discoveryCache:k().optional(),role:cd(),toolPermissions:Z(g(),tL()).optional()}).transform(WQ)),ZXe=L(()=>C({type:j("sse-ide"),url:g(),ideName:g(),ideRunningInWindows:k().optional(),timeout:Yi().optional(),alwaysLoad:k().optional(),role:cd()})),YXe=L(()=>C({type:j("ws-ide"),url:g(),ideName:g(),authToken:g().optional(),ideRunningInWindows:k().optional(),timeout:Yi().optional(),alwaysLoad:k().optional(),role:cd()})),YQ=L(()=>C({type:V(["http","streamable-http"]).transform(()=>"http"),url:g(),headers:Z(g(),g()).optional(),headersHelper:g().optional(),oauth:VQ().optional(),timeout:Yi().optional(),request_timeout_ms:GQ(),tools:I(qQ()).optional(),alwaysLoad:k().optional(),discoveryCache:k().optional(),role:cd(),toolPermissions:Z(g(),tL()).optional()}).transform(WQ)),JXe=["command","args","env","headersHelper"],XXe=new Set(["http","streamable-http","sse"]),QXe=/[\p{Cc}\p{Cf}\u2028\u2029]/u,e7e=/[\p{Cc}\p{Cf}\u2028\u2029]/gu;function XD(e){return/^[A-Za-z0-9_-]+$/.test(e)&&e!=="__proto__"&&e!=="constructor"&&e!=="prototype"}function t7e(e){try{let t=new URL(e);return t.protocol==="https:"&&t.hostname!==""}catch{return!1}}function JQ(e,t="",n=0){if(typeof e==="string")return[[t,e,!1]];if(n>4||e===null||typeof e!=="object")return[];return Object.entries(e).flatMap(([r,o])=>{let s=r.replace(e7e,(a)=>`\\u${a.codePointAt(0).toString(16).padStart(4,"0")}`),i=t?`${t}.${s}`:s;return[[i,r,!0],...JQ(o,i,n+1)]})}var QD=L(()=>Z(g(),xe()).check((e)=>{let t=(r,o)=>{e.issues.push({code:"custom",path:r,message:o,input:e.value})};for(let r of JXe)if(Object.hasOwn(e.value,r))t([r],`"${r}" is not allowed in managed settings: only http/sse URL servers can be delivered this way, and a managed settings document must not name a program to run`);if(!XXe.has(e.value.type))t(["type"],'managed settings can only deliver "http" or "sse" servers');let n=e.value.url;if(typeof n==="string"&&!t7e(n))t(["url"],"managed settings servers must use a valid https:// url");for(let[r,o,s]of JQ(e.value))if(QXe.test(o))t(r.split("."),"contains control or invisible format characters (in a key or a value); a managed settings document must not be able to print escape sequences");else if(!s&&KQ(o))t(r.split("."),"${VAR} references are not expanded in managed settings; use a literal value (a managed settings document must not read the user's environment)")}).pipe(ue([YQ(),ZQ()]))),eL=`"managedMcpServers" must be an object keyed by server name (the .mcp.json mcpServers shape; Claude Desktop's array form of its same-named key is not accepted here: use the server name as the key and "type" instead of "transport"). No managed MCP servers are installed from it until it is fixed.`;function CE(e,t){if(e===void 0)return;if(e===null||typeof e!=="object"||Array.isArray(e)){t("",eL);return}let n=Object.create(null);for(let[r,o]of Object.entries(e)){if(!XD(r)){t("<invalid name>","server names may only contain letters, numbers, hyphens and underscores");continue}let s=QD().safeParse(o);if(s.success){n[r]=s.data;continue}let i=s.error.issues[0];t(r,i?[i.path.join("."),i.message].filter(Boolean).join(": "):"failed validation")}return n}var n7e=L(()=>C({type:j("ws"),url:g(),headers:Z(g(),g()).optional(),headersHelper:g().optional(),timeout:Yi().optional(),alwaysLoad:k().optional(),role:cd()})),r7e=L(()=>C({type:j("sdk"),name:g(),timeout:Yi().optional(),alwaysLoad:k().optional()})),tL=L(()=>V(["allow","ask","blocked"])),o7e=L(()=>C({type:j("claudeai-proxy"),url:g(),id:g(),displayName:g().optional(),iconUrl:g().optional(),timeout:Yi().optional(),alwaysLoad:k().optional(),toolPermissions:Z(g(),tL()).optional(),stateless:k().optional(),cachedInitResponse:Z(g(),xe()).nullish(),discoverSupport:V(["supported","legacy","unknown"]).optional().catch(void 0),cachedDiscoverResponse:Z(g(),xe()).nullish(),eligible:k().nullish(),ineligibleReason:g().nullish(),enterpriseManaged:k().optional()})),TE=L(()=>ue([VXe(),ZQ(),ZXe(),YXe(),YQ(),n7e(),r7e(),o7e()]));var F4t=L(()=>C({mcpServers:Z(g(),TE())}));var H4t=In()==="macos"?"⏺":"●";var a7e=new Set(["Claude Preview","Claude Browser"]),c7e=new Set(["claude-in-chrome","Claude in Chrome"]),V4t=new Set([...c7e,...a7e]);var l7e=["Claude_Browser__"],u7e=["claude-in-chrome__","Claude_in_Chrome__"],q4t=[...l7e,...u7e];var o6t=L(()=>Qe(Eh,V(NQ))),s6t=L(()=>Qe(Eh,V(ad)));import{posix as O7e,win32 as P7e}from"path";import{isIPv4 as d7e,isIPv6 as p7e}from"net";var f7e=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal","ip6-localhost","ip6-loopback","localhost.localdomain","localhost4","localhost4.localdomain4","localhost6","localhost6.localdomain6"]),XQ=new Set(["100.100.100.200","168.63.129.16","192.0.0.192"]);function QQ(e,t,n,r){return e===127||e===169&&t===254||e===0}function m7e(e){let t=e.indexOf("%"),r=(t>=0?e.slice(0,t):e).toLowerCase().split("::");if(r.length>2)return;let o=r[0]?r[0].split(":"):[],s=r.length===2&&r[1]?r[1].split(":"):[],i=r.length===2?s:o,a=[],c=i.at(-1);if(c!==void 0&&c.includes(".")){let m=c.split(".").map(Number);if(m.length!==4||m.some((h)=>!Number.isInteger(h)||h<0||h>255))return;a=m,i.pop()}let l=(m)=>{let h=[];for(let _ of m){if(!/^[0-9a-f]{1,4}$/.test(_))return;let y=parseInt(_,16);h.push(y>>8,y&255)}return h},u=l(r.length===2?o:[]),p=l(i);if(u===void 0||p===void 0)return;let f=u.length+p.length+a.length;if(f>16||r.length===1&&f!==16)return;return[...u,...Array(16-f).fill(0),...p,...a]}function h7e(e){return eee(e)&&e[4]===0&&e[5]===1}function eee(e){return e[0]===0&&e[1]===100&&e[2]===255&&e[3]===155}function g7e(e){let t=[];if(e[0]===32&&e[1]===2)t.push(e.slice(2,6));let n=e.slice(0,10).every((a)=>a===0),r=n&&e[10]===255&&e[11]===255,o=n&&e[10]===0&&e[11]===0,s=eee(e)&&e.slice(4,12).every((a)=>a===0),i=(e[8]===0||e[8]===2)&&e[9]===0&&e[10]===94&&e[11]===254;if(r||o||s||i)t.push(e.slice(12,16));return t}function tee(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(f7e.has(t))return!0;if(t.startsWith("instance-data.")&&t.endsWith(".compute.internal"))return!0;if(d7e(t)){if(XQ.has(t))return!0;let[r=0,o=0,s=0,i=0]=t.split(".").map(Number);return QQ(r,o,s,i)}if(!p7e(t))return!1;let n=m7e(t);if(n===void 0)return!0;if(h7e(n))return!0;if(n.every((r)=>r===0))return!0;if(n.slice(0,15).every((r)=>r===0)&&n[15]===1)return!0;if(t==="fd00:ec2::254")return!0;if(n[0]===254&&(n[1]??0)>=128&&(n[1]??0)<=191)return!0;return g7e(n).some((r)=>{let[o=0,s=0,i=0,a=0]=r;return QQ(o,s,i,a)||XQ.has(`${o}.${s}.${i}.${a}`)})}var nee=["bash","powershell"];var xh=L(()=>g().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 _7e(){let e=C({type:j("command").describe("Shell command hook type"),command:g().describe("Shell command to execute"),args:I(g()).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:xh(),shell:V(nee).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:X().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:g().optional().describe("Custom status message to display in spinner while hook runs"),once:k().optional().describe("If true, hook runs once and is removed after execution"),async:k().optional().describe("If true, hook runs in background without blocking"),asyncRewake:k().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:g().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:g().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:V(["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:g().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:xh(),timeout:X().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:g().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:k().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:g().optional().describe("Custom status message to display in spinner while hook runs"),once:k().optional().describe("If true, hook runs once and is removed after execution")}),n=C({type:j("mcp_tool").describe("MCP tool hook type"),server:g().describe("Name of an already-configured MCP server to invoke"),tool:g().describe("Name of the tool on that server to call"),input:Z(g(),xe()).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:xh(),timeout:X().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:g().optional().describe("Custom status message to display in spinner while hook runs"),once:k().optional().describe("If true, hook runs once and is removed after execution")}),r=C({type:j("http").describe("HTTP hook type"),url:g().url().describe("URL to POST the hook input JSON to"),if:xh(),timeout:X().positive().optional().describe("Timeout in seconds for this specific request"),headers:Z(g(),g()).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(g()).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:g().optional().describe("Custom status message to display in spinner while hook runs"),once:k().optional().describe("If true, hook runs once and is removed after execution"),cloud:V(["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:g().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:xh(),timeout:X().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:g().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:g().optional().describe("Custom status message to display in spinner while hook runs"),once:k().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:r,AgentHookSchema:o,McpToolHookSchema:n}}var RE=L(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:r,McpToolHookSchema:o}=_7e();return nc("type",[...[e,t,n,r,o]])}),nL=L(()=>C({matcher:g().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:I(RE()).describe("List of hooks to execute when the matcher matches")})),yc=L(()=>q3(V(fs),I(nL())));function kE(){return new Set(RE().options.map((e)=>e.shape.type.value))}function y7e(e,t){if(!e||typeof e!=="object"||Array.isArray(e)){let o=gc(e);return{problem:`Hook entry must be an object; received ${o}`,received:o,aboutType:!1}}let n=e.type;if(typeof n!=="string"){let o=gc(n);return{problem:n===void 0?'Hook entry has no "type"':`Hook entry "type" must be a string; received ${o}`,received:o,aboutType:!0}}if(!t.has(n)){let o=bg(n);return{problem:`Unknown hook type "${o}"`,received:o,aboutType:!0}}let r=RE().safeParse(e);if(!r.success)return{problem:`Invalid ${n} hook (${ree(r.error)})`,received:n,aboutType:!1};return}function ree(e){return e.issues.map((t)=>t.path.length>0?`${t.path.join(".")}: ${t.message}`:t.message).join("; ")}function OE(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;if(!("matcher"in e)&&Object.keys(e).some((n)=>fs.includes(n)))return!1;let t=e.hooks;if(Array.isArray(t))return t.length>0;return!!t&&typeof t==="object"&&(("matcher"in e)||typeof t.type==="string")}function _c(e,t=3,{matchersCount:n=!0,unscannedKeys:r=S7e,inHooksList:o=!1}={}){if(iee(e))return!0;if(n&&OE(e))return!0;if(t===0||!e||typeof e!=="object")return!1;if(Array.isArray(e))return e.some((s)=>_c(s,t-1,{matchersCount:n,unscannedKeys:r,inHooksList:o}));if(o&&typeof e.type==="string")return!1;return Object.entries(e).some(([s,i])=>!r.has(s)&&_c(i,t-1,{unscannedKeys:r,matchersCount:n&&!fs.includes(s),inHooksList:s==="hooks"&&Array.isArray(i)}))}function oee(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return!1;return iee(e)||Object.entries(e).some(([n,r])=>n!=="hooks"&&!t.has(n)&&_c(r,3,{unscannedKeys:t,matchersCount:!fs.includes(n)}))}var S7e=new Set,see=new Set(["mcpServers","managedMcpServers","lspServers","pluginConfigs","enabledPlugins","extraKnownMarketplaces","env","skillOverrides","modelSettings"]),b7e=new Set(["metadata","mcpServers","lspServers"]),h6t=new Set([...b7e,"experimental"]);function iee(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;return Object.entries(e).some(([t,n])=>vh.has(t)&&n!==null&&n!==void 0&&!(Array.isArray(n)&&n.length===0))}function rL(e){if(OE(e))return!0;if(Array.isArray(e))return e.some(rL);if(!e||typeof e!=="object")return!1;return Object.entries(e).some(([t,n])=>vh.has(t)&&n!==null&&n!==void 0&&!(Array.isArray(n)&&n.length===0))}var vh=new Set(["PreToolUse","PermissionRequest"]);function aee(e,t){if(!Array.isArray(e))return{stripped:[],unloadableGuards:[]};let n=vh.has(t),r=kE(),o=nL(),s=[],i=[];for(let a=e.length-1;a>=0;a--){let c=e[a],l=(m,h)=>{if(!n)e.splice(a,1);s.push({matcherIndex:a,hookIndex:void 0,path:`${a}`,problem:m,received:h,aboutType:!1})};if(_c(c,3,{matchersCount:!1})){(n?s:i).push({matcherIndex:a,hookIndex:void 0,path:`${a}`,problem:"holds PreToolUse/PermissionRequest hooks where a matcher was expected",received:gc(c),aboutType:!1});continue}if(!c||typeof c!=="object"||Array.isArray(c)){l(`Hook matcher must be an object; received ${gc(c)}`,gc(c));continue}let u=c.hooks;if(!Array.isArray(u)){l(`Hook matcher "hooks" must be an array of hook entries; received ${gc(u)}`,gc(u));continue}let p=[];for(let m=u.length-1;m>=0;m--){let h=y7e(u[m],r);if(h!==void 0){if(!n)u.splice(m,1);p.push({matcherIndex:a,hookIndex:m,path:`${a}.hooks.${m}`,...h})}}let f=o.safeParse(n?{...c,hooks:[]}:c);if(!f.success){l(`Invalid hook matcher (${ree(f.error)})`,"matcher");continue}s.push(...p)}return s.reverse(),i.reverse(),n?{stripped:[],unloadableGuards:s}:{stripped:s,unloadableGuards:i}}var Sc="a PreToolUse/PermissionRequest hook that cannot be loaded may be what guards the permissions declared beside it, so nothing it sits in is applied until the entry is fixed or removed";function gc(e){if(e===null||e===void 0)return String(e);if(Array.isArray(e))return"an array";let t=typeof e;return`${t==="object"?"an":"a"} ${t}`}var ld="github.com",y6t=[`git@${ld}:`,`ssh://git@${ld}/`],S6t=[`https://${ld}`,`https://${ld}/`,ld],b6t=`users.noreply.${ld}`;var E7e=/[:/\\?#@\s]/;function x7e(e){let t=cee(e.replace(/[\t\n\r]/g,"").toLowerCase());if(t===""||E7e.test(t))return t;try{let n=new URL(`https://${t}`);if(n.username!==""||n.password!==""||n.port!==""||n.pathname!=="/"||n.search!==""||n.hash!=="")return t;return cee(n.hostname)}catch{return t}}var E6t=uE(function(t){let n=x7e(t);while(n.startsWith("www."))n=n.slice(4);return n},(e)=>e,50);function cee(e){let t=e.length;while(t>0&&e[t-1]===".")t--;return e.slice(0,t)}function v7e(e){return tS(C7e(Sg(e))).replace(/ {2,}/g," ").trim()}var w7e=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/g,A7e=4;function C7e(e){let t=e;for(let n=0;n<A7e;n++){let r=t.replace(w7e,"");if(r===t)break;t=r}return t}function oL(e,t=160){return T7e(v7e(R7e(e,t)).normalize("NFC").replace(/[`\uff40\u02cb\u1fef\u2035]/g,"'").replace(k7e,""),t)}function T7e(e,t=2000){return e.length>t?`${Qc(e,t)}…`:e}function R7e(e,t){let n=Qc(e,t*8);if(n.length===e.length)return n;let r=/\x1b(?:[\]PX^_][^\x1b\x07]*\x1b?|\[[\x30-\x3f]*[\x20-\x2f]*)$/.exec(n);if(r===null)return n;let o=e.slice(r.index);return(o[1]==="["?/^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/.test(o):/^\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/.test(o))?n.slice(0,r.index):n}var k7e=/(?<![^\s\p{P}])\p{M}+/gu;var lL=500,I7e=32;function mee(){return{claudeaiPluginId:g().max(128).optional().catch(void 0),archiveSha256:Cee().optional().catch(void 0)}}function hee(){return{sourceCommand:g().max(lL+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:g().max(4096).refine(lee,{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(xe()).transform((e)=>e.filter((t)=>typeof t==="string"&&t.length<=4096&&lee(t)).slice(-I7e)).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 lee(e){return O7e.isAbsolute(e)||P7e.isAbsolute(e)}var gee=/[^\x20-\x7E]| {4,}/;function uL(){return g().max(lL,{message:"headersHelper must not be longer than the install consent UI can display"}).refine((e)=>!gee.test(e),{message:"headersHelper must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"})}var D7e=new Set(["claude-community","claude-plugins-community","healthcare"]),L7e=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","claude-tag-plugins"]),_ee=new Set([...L7e,...D7e]);var N7e=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,M7e=/[^\u0020-\u007E]/;function U7e(e){if(_ee.has(e.toLowerCase()))return!1;if(M7e.test(e))return!0;return N7e.test(e)}var ss=L(()=>g().startsWith("./")),bc=L(()=>ss().endsWith(".json")),uee=L(()=>ue([j("."),ss()])),dee=L(()=>ue([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"),g().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),iL=L(()=>ss().endsWith(".md")),aL=L(()=>ue([iL(),ss()])),yee={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 F7e(e){return Object.hasOwn(yee,e)}var See=L(()=>g().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)=>!kee.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)=>!U7e(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).superRefine((e,t)=>{let n=e.toLowerCase();if(!F7e(n))return;t.addIssue({code:"custom",message:`Marketplace name "${n}" is reserved for ${yee[n]}`})})),PE=L(()=>g().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)=>!kee.test(e),{message:"Plugin name cannot contain control or bidirectional-formatting characters"})),dL=L(()=>C({name:g().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:g().optional().describe("Contact email for support or feedback"),url:g().optional().describe("Website, GitHub profile, or organization URL")})),$7e=L(()=>C({$schema:g().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:PE().describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:g().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:g().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:g().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:dL().optional().describe("Information about the plugin creator or maintainer"),homepage:g().url().optional().describe("Plugin homepage or documentation URL"),repository:g().optional().describe("Source code repository URL"),license:g().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:I(g()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:k().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(NQe()).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:Qe((e)=>Ge(e)?e:void 0,Z(g(),xe()).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.")})),z7e=1,H6t=L(()=>C({description:g().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:zS(()=>yc()).optional().describe("The hooks provided by the plugin, in the same format as the one used for settings"),modules:I(g()).max(z7e,{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."),surface:US({error:'hooks.json `surface` is gone: name the module in the Client element, `Client({ module: "./board.tsx", key })`, a path relative to the file that builds it'}).optional()}).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"})),j7e=L(()=>C({hooks:ue([bc().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),zS(()=>yc()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),I(ue([bc().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),zS(()=>yc()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),H7e=L(()=>C({source:aL().optional().describe("Path to command markdown file, relative to plugin root"),content:g().optional().describe("Inline markdown content for the command"),description:g().optional().describe("Command description override"),argumentHint:g().optional().describe('Hint for command arguments (e.g., "[file]")'),model:g().optional().describe("Default model for this command"),allowedTools:I(g()).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'})),B7e=L(()=>C({commands:ue([aL().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(aL().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."),Z(g(),H7e()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),K7e=L(()=>C({agents:ue([iL().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(iL().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.")])})),G7e=L(()=>C({skills:ue([uee().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(uee().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).")])})),W7e=L(()=>ue([g(),I(g())])),bee=L(()=>C({outputStyles:ue([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.")])})),V7e=L(()=>g().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),q7e=16,Z7e=L(()=>C({id:V7e(),remote:g().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:g().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),Y7e=L(()=>C({syntaxHighlighting:C({hljsLanguages:I(Z7e()).max(q7e)}).strict()})),Eee=L(()=>C({themes:ue([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.")])})),J7e=L(()=>C({})),pee=L(()=>g().min(1)),X7e=L(()=>g().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),Q7e=L(()=>C({mcpServers:ue([bc().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),dee().describe("Path or URL to MCPB file containing MCP server configuration"),Z(g(),TE()).describe("MCP server configurations keyed by server name"),I(ue([bc().describe("Path to MCP servers configuration file"),dee().describe("Path or URL to MCPB file"),Z(g(),TE()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),xee=L(()=>C({type:V(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:g().describe("Human-readable label shown in the config dialog"),description:g().describe("Help text shown beneath the field in the config dialog"),required:k().optional().describe("If true, validation fails when this field is empty"),default:ue([g(),X(),k(),I(g())]).optional().describe("Default value used when the user provides nothing"),multiple:k().optional().describe("For string type: allow an array of strings"),sensitive:k().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:X().optional().describe("Minimum value (number type only)"),max:X().optional().describe("Maximum value (number type only)")}).strict()),eQe=L(()=>C({userConfig:Z(g().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"),xee()).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.")})),tQe=L(()=>C({channels:I(C({server:g().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:g().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:Z(g(),xee()).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.")})),fee=L(()=>VP({command:g().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(pee()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:Z(X7e(),pee()).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:V(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:Z(g(),g()).optional().describe("Environment variables to set when starting the server"),initializationOptions:xe().optional().describe("Initialization options passed to the server during initialization"),settings:xe().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:g().optional().describe("Workspace folder path to use for the server"),startupTimeout:X().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:X().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:k().optional().describe("Whether to restart the server if it crashes"),maxRestarts:X().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:k().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.")})),nQe=L(()=>VP({name:g().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:g().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:g().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:ue([j("always"),g().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).')})),rQe=L(()=>I(nQe()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),vee=L(()=>C({monitors:ue([bc().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),rQe()]).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.")})),oQe=L(()=>C({lspServers:ue([bc().describe("Path to .lsp.json configuration file relative to plugin root"),Z(g(),fee()).describe("LSP server configurations keyed by server name"),I(ue([bc().describe("Path to LSP configuration file"),Z(g(),fee()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),wee=L(()=>g().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")),sQe=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,iQe=/^[0-9a-f]{64}$/;var aQe=64;var cQe=L(()=>C({sha256:g().regex(iQe)}));function lQe(e){let t=Z(g(),xe()).safeParse(e);if(!t.success)return;let n=Object.create(null),r=0;for(let[o,s]of Object.entries(t.data)){if(r>=aQe)break;let i=cQe().safeParse(s);if(sQe.test(o)&&i.success)n[o]=i.data,r++}return r>0?n:void 0}var uQe=L(()=>C({binaries:xe().transform(lQe).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),dQe=L(()=>C({settings:Z(g(),xe()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),pQe=L(()=>C({experimental:Qe((e)=>Ge(e)?e:void 0,C({...Eee().partial().shape,...Y7e().partial().shape,...vee().partial().shape,...bee().partial().shape,evals:W7e().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 fQe=L(()=>C({...$7e().shape,...j7e().partial().shape,...B7e().partial().shape,...K7e().partial().shape,...G7e().partial().shape,...bee().partial().shape,...Eee().partial().shape,...J7e().shape,...tQe().partial().shape,...Q7e().partial().shape,...oQe().partial().shape,...vee().partial().shape,...dQe().partial().shape,...eQe().partial().shape,...uQe().partial().shape,...pQe().partial().shape})),Aee=new Set(["url","github","git","npm","file","directory","skills-dir","hostPattern","pathPattern","settings"]),ud=L(()=>nc("source",[C({source:j("url"),url:g().url().describe("Direct URL to marketplace.json file"),headers:Z(g(),g()).optional().describe("Custom HTTP headers (e.g., for authentication)"),headersHelper:uL().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:g().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:g().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:g().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:I(g()).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:k().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:g().describe("Full git repository URL"),ref:g().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:g().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:I(g()).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:k().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:wee().describe("NPM package containing marketplace.json")}),C({source:j("file"),path:g().describe("Local file path to marketplace.json")}),C({source:j("directory"),path:g().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:g().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:g().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:See().refine((e)=>!_ee.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(_Qe()).describe("Plugin entries declared inline in settings.json"),owner:dL().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).")])),sL=L(()=>g().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),Cee=L(()=>g().regex(/^[0-9a-fA-F]{64}$/,"Must be a 64-character hex SHA-256 digest")),mQe="Archive URLs must use https:// and must not point at a loopback, link-local, or cloud-metadata host";function hQe(e){try{let t=new URL(e);return t.protocol==="https:"&&!tee(t.hostname)}catch{return!1}}var gQe=L(()=>C({source:j("archive"),url:g().url().refine(hQe,{message:mQe}).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:Cee().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.")),Tee=L(()=>ue([Qe((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:wee().or(g().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:g().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:g().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:g().describe("Full git repository URL (https:// or git@)"),ref:g().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:sL().optional().describe("Specific commit SHA to use")}),C({source:j("github"),repo:g().describe("GitHub repository in owner/repo format"),ref:g().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:sL().optional().describe("Specific commit SHA to use")}),C({source:j("git-subdir"),url:g().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:g().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:g().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:sL().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."),gQe(),C({source:j("command"),command:g().min(1).max(lL,{message:"command must not be longer than the install consent UI can display"}).refine((e)=>!gee.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:X().int().positive().max(600).optional().describe("Seconds to wait for the command before giving up (default: 60)"),mode:V(["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:g().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.")])),_Qe=L(()=>C({name:PE().describe("Plugin name as it appears in the target repository"),source:Tee().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:g().optional(),version:g().optional(),strict:k().optional(),headers:Z(g(),g()).optional().describe("HTTP headers sent when downloading this entry's `archive` source."),headersHelper:uL().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 yQe=L(()=>C({cli:I(g().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:I(g().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(g().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:g().max(256),pattern:g().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(g().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.`)})),SQe=L(()=>C({topic:g().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:yQe().optional().describe("Matchers that determine when the plugin is relevant.")})),bQe=L(()=>fQe().partial().extend({name:PE().describe("Unique identifier matching the plugin name"),source:Tee().describe("Where to fetch the plugin from"),headers:Z(g(),g()).optional().describe("Custom HTTP headers for fetching this plugin's archive; overrides the marketplace's"),headersHelper:uL().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:g().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:I(g()).optional().describe("Tags for searchability and discovery"),strict:k().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:Qe((e)=>Ge(e)?e:void 0,SQe().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.`)})),EQe=L(()=>C({name:PE()}));function xQe(e){let t=bQe();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=EQe().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=Ree(Ge(n)?n.source:void 0)?kQe:pL(n)?void 0:wQe(o.error.issues)??IE(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 vQe=new Set(["npm","url","github","git-subdir","archive","command","unsupported"]);function pL(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"&&!vQe.has(n)}function wQe(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 IE(n.map((r)=>({...r,path:["source",...r.path]})))}var AQe=/^[A-Za-z0-9_$.-]{1,40}$/;function is(e){return AQe.test(e)?e:"<key>"}var CQe=3,TQe=160;function IE(e){let t=e.slice(0,CQe).map((r)=>{let o=r.path.map(String).map((i)=>is(i)).join("."),s=r.code==="unrecognized_keys"?`Unrecognized ${r.keys.length===1?"field":"fields"}: ${r.keys.map(is).join(", ")}`:oL(r.message,TQe);return o?`${o}: ${s}`:s}),n=e.length-t.length;return n>0?`${t.join(", ")} (+${n} more)`:t.join(", ")}var RQe=/^[A-Za-z0-9][-A-Za-z0-9._]*$/,kQe='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 Ree(e){return typeof e==="string"&&RQe.test(e)&&!e.includes("..")}function OQe(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 PQe(e,t){if(t===void 0||!Ge(e)||!Ree(e.source))return e;let n=t==="."?`./${e.source}`:`./${t}/${e.source}`;return{...e,source:n}}function IQe(e){if(!Ge(e)||!Array.isArray(e.plugins))return e;let t=Ge(e.metadata)?OQe(e.metadata.pluginRoot):void 0;if(t===void 0)return e;return{...e,plugins:e.plugins.map((n)=>PQe(n,t))}}var DQe=L(()=>C({$schema:g().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:See(),version:g().optional().describe("Marketplace manifest version"),description:g().optional().describe("Human-readable description of this marketplace"),owner:dL().describe("Marketplace maintainer or curator information"),plugins:I(xe()).transform(xQe).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:k().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:C({pluginRoot:g().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:g().optional().describe("Marketplace version"),description:g().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:I(g()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:Z(g(),g().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.")})),B6t=L(()=>Qe(IQe,DQe())),cL="[A-Za-z0-9][-A-Za-z0-9._]*",K6t=new RegExp(`^${cL}$`);var DE=L(()=>g().regex(new RegExp(`^${cL}@${cL}$`),"Plugin ID must be in format: plugin@marketplace")),G6t=new RegExp(`[@:\\s/\\\\${xu}]`,"u"),W6t=new RegExp(`[${xu}]`,"u"),kee=/[\p{Cc}\u200E\u200F\u202A-\u202E\u2066-\u2069]/u,LQe=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,NQe=L(()=>ue([g().regex(LQe,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),C({name:g().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:g().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),MQe=L(()=>C({version:g().describe("Currently installed version"),installedAt:g().describe("ISO 8601 timestamp of installation"),lastUpdated:g().optional().describe("ISO 8601 timestamp of last update"),installPath:g().describe("Absolute path to the installed plugin directory"),gitCommitSha:g().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:g().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:k().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)."),...mee(),...hee()})),V6t=L(()=>C({version:j(1).describe("Schema version 1"),plugins:Z(DE(),MQe()).describe("Map of plugin IDs to their installation metadata")})),UQe=L(()=>V(["managed","user","project","local"])),FQe=L(()=>C({scope:UQe().describe("Installation scope"),projectPath:g().optional().describe("Project path (required for project/local scopes)"),installPath:g().describe("Absolute path to the versioned plugin directory"),version:g().optional().describe("Currently installed version"),installedAt:g().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:g().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:g().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:g().optional().describe("Tag-derived semver this install resolved to"),auto:k().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep."),...mee(),...hee()})),q6t=L(()=>C({version:j(2).describe("Schema version 2"),plugins:Z(DE(),I(FQe())).describe("Map of plugin IDs to arrays of installation entries")})),$Qe=L(()=>C({source:ud().describe("Where to fetch the marketplace from"),installLocation:g().describe("Local cache path where marketplace manifest is stored"),lastUpdated:g().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:k().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),Z6t=L(()=>Z(g(),$Qe()));var LE=["aspell","hunspell","ispell"];var Oee=2147483647;var zQe=["autoMode","deepLink","voice","briefView","screenReader"],fL={},NE={autoMode:{buildGate:()=>!1,shape:()=>fL,permissionsShape:()=>fL,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:V(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!0,shape:()=>({voiceEnabled:k().optional().describe("Enable voice mode (hold-to-talk dictation)")})},briefView:{buildGate:()=>!0,shape:()=>({defaultView:V(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>fL}};function Ah(){return zQe.filter((e)=>NE[e].buildGate())}function Pee(e){let t={};for(let n of e)t={...t,...NE[n].shape()};return t}function Iee(e){let t={};for(let n of e)t={...t,...NE[n].permissionsShape?.()};return t}function Dee(e){let t=[];for(let n of e)t.push(...NE[n].permissionModes?.()??[]);return t}var Lee={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 mL(e){return Object.hasOwn(Lee,e)?Lee[e]:e}var Nee="workspace",r3t=`mcp__${Nee}__bash`,o3t=`mcp__${Nee}__web_fetch`;function ME(e){return e.includes("*")}function jQe(e){return e.replaceAll("\\","\\\\").replaceAll("(","\\(").replaceAll(")","\\)")}function HQe(e){return BQe(e).replaceAll("\\\\","\\")}function BQe(e){return e.replaceAll("\\(","(").replaceAll("\\)",")")}function hL(e){let t=KQe(e,"("),n=GQe(e,")");if(t===-1&&n===-1)return{kind:"bare"};let r=e.substring(0,t);if(t===-1||n<=t||n!==e.length-1||/[()]/.test(r))return{kind:"malformed"};return{kind:"call",toolName:r,rawContent:e.substring(t+1,n)}}function Mee(e){let t=hL(e);if(t.kind!=="call"||!t.toolName)return{toolName:mL(e)};if(t.rawContent===""||t.rawContent==="*")return{toolName:mL(t.toolName)};let n=HQe(t.rawContent);return{toolName:mL(t.toolName),ruleContent:n}}function UE(e){if(!e.ruleContent)return e.toolName;let t=jQe(e.ruleContent);return`${e.toolName}(${t})`}function KQe(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 GQe(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 gL(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 FE={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 _L(e){return FE.filePatternTools.includes(e)}function Uee(e){return FE.bashPrefixTools.includes(e)}function Fee(e){return Object.hasOwn(FE.customValidation,e)?FE.customValidation[e]:void 0}function Hee(e,t){let n=0,r=t-1;while(r>=0&&e[r]==="\\")n++,r--;return n%2!==0}function $ee(e,t){let n=0;for(let r=0;r<e.length;r++)if(e[r]===t&&!Hee(e,r))n++;return n}var WQe=/(?:^|[^\\])\\[()]/;function VQe(e){return WQe.test(e)&&$ee(e,"(")!==$ee(e,")")}var qQe=/^(?:[|&;<>]|\d+[<>])/;function ZQe(e){return qQe.test(e)}function zee(e){for(let t=0;t<e.length;t++)if(e[t]==="*"&&!Hee(e,t))return!0;return!1}function YQe(e){if(e.endsWith(":*"))return;let t=e.trim().split(/\s+/).filter(Boolean),n=t[0];if(t.length<3||n===void 0||zee(n))return;let r=!1;for(let o of t.slice(1)){if(ZQe(o))return;if(zee(o)){r=!0;continue}if(o.startsWith("-"))continue;return r?n:void 0}return}function jee(e){if(!ME(e))return null;let t=gL(e);if(t&&!ME(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 yL(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=hL(e);if(n.kind==="malformed")return{valid:!1,error:"Malformed Tool(content) rule",suggestion:'Rules take the form Tool or Tool(content) and must end at the closing ")"; parentheses inside the content are literal'};if(n.kind==="call"&&n.rawContent===""){if(!n.toolName)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 "${n.toolName}" without parentheses`,examples:[`${n.toolName}`,`${n.toolName}(some-pattern)`]}}let r=Mee(e),o=gL(r.toolName);if(o){if(n.kind==="call")return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${r.toolName}" without parentheses, or use "mcp__${o.serverName}__*" for all tools`,examples:[`mcp__${o.serverName}`,`mcp__${o.serverName}__*`,o.toolName&&o.toolName!=="*"?`mcp__${o.serverName}__${o.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let i=jee(r.toolName);if(i)return i}return{valid:!0}}if(!r.toolName||r.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let i=jee(r.toolName);if(i)return i}if(!r.toolName.includes("_")&&r.toolName[0]!==r.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${Rd(String(r.toolName))}"`};if(n.kind==="call"&&VQe(n.rawContent)){let i=_L(r.toolName);return{valid:!1,error:'Ambiguous "\\(" or "\\)" beside an unescaped parenthesis',suggestion:i?"Write a Windows path with forward slashes, or spell a literal parenthesis as [(] or [)]":'Double a backslash that is a path separator ("\\\\("), and escape literal parentheses in pairs',examples:i?[`${r.toolName}(C:/Projects/(drafts)/**)`,`${r.toolName}(C:\\Projects\\[(]drafts)\\**)`]:[`${r.toolName}(C:\\tools\\\\(x86)\\run.exe *)`]}}let s=Fee(r.toolName);if(s&&r.ruleContent!==void 0){let i=s(r.ruleContent);if(!i.valid)return i}if(Uee(r.toolName)&&r.ruleContent!==void 0){let i=r.ruleContent;if(i.includes(":*")&&!i.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(i===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]};if(t==="allow"){let a=YQe(i);if(a!==void 0){let c=a==="git",l=c?" For git, options such as -c and --exec-path can run arbitrary commands.":"",u=c?" (for example Bash(git status *))":"";return{valid:!0,warning:`${UE(r)} 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.${l} Replace that * with the exact value you mean, or only use * after the subcommand${u}.`}}}}if(_L(r.toolName)&&r.ruleContent!==void 0){if(r.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${r.toolName}(*.ts) - matches .ts files`,`${r.toolName}(src/**) - matches all files in src`,`${r.toolName}(**/*.test.ts) - matches test files`]}}if(r.ruleContent!==void 0){let i=r.toolName==="Write"||r.toolName==="NotebookEdit"||r.toolName==="MultiEdit"?"Edit":r.toolName==="Glob"?"Read":void 0;if(i!==void 0&&!r.ruleContent.includes(":*"))return{valid:!0,warning:`${UE(r)} is not matched by file permission checks — only ${i}(path) rules are. Use ${UE({toolName:i,ruleContent:r.ruleContent})} instead (${i} rules cover all file-${i==="Edit"?"editing":"reading"} tools).`}}return{valid:!0}}var SL=L(()=>Kee()),Bee=L(()=>Kee("allow"));function Kee(e){return g().superRefine((t,n)=>{let r=yL(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:qr.custom,message:o,params:{received:t}})}})}var Ch=["accept","hold","refuse"],jE=["off","basic","full"],JQe=L(()=>Z(g(),oKe()));function ete(e){return C({allow:I(Bee()).optional().describe("List of permission rules for allowed operations"),deny:I(SL()).optional().describe("List of permission rules for denied operations"),ask:I(SL()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:Qe(Eh,V([...ad,...Dee(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:V(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),blockReadsOutsideWorkingDirectories:k().optional().describe('Refuse file-tool reads (Read, Grep, Glob, LSP) outside the working directories in every permission mode; true in any settings source wins. Also set when the user picks "block" on the one-time auto-mode prompt for a read outside the working directories.'),...Iee(e),additionalDirectories:I(g()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var z3t=L(()=>ete(Ah())),XQe=L(()=>ue([g(),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) }')])),QQe=L(()=>Qe((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"||!!t&&typeof t==="object"&&!Array.isArray(t)):[],I(XQe()))),vL=L(()=>C({source:ud().describe("Where to fetch the marketplace from"),installLocation:g().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:k().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),wL=L(()=>{let e=()=>X().min(0).max(1e4);return C({input:e(),output:e(),cacheRead:e(),cacheWrite:e()})}),AL=L(()=>X().gt(0).lte(1).optional()),CL=L(()=>C({model:g().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:g().optional().describe("Row title. Defaults to the model name."),description:g().optional().describe("Row subtitle. Defaults to a generic description."),behavesAs:g().optional().describe("For a model this version of Claude Code does not know: the ID of a model it does know "+'(e.g. "claude-opus-4-8") whose client-side handling — prompt profile, capability and effort '+"defaults — applies to it. Changes neither the row's label nor the model ID sent. Without it, "+"a model-catalog row for a model this version does not know is not offered until Claude Code is updated.")})),HE=L(()=>C({serverName:g().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(g()).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:g().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>pf([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"'})),BE=L(()=>C({serverName:g().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(g()).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:g().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>pf([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"'})),tte=L(()=>C({marketplace:g(),plugin:g()})),eet=L(()=>Qe((e)=>{if(typeof e!=="string"||!DE().safeParse(e).success)return e;let t=e.indexOf("@");return{marketplace:e.slice(t+1),plugin:e.slice(0,t)}},tte())),tet=/[\x00-\x1f\x7f-\x9f\u2028\u2029]|\p{DI}/u;function net(e){let t=e.replaceAll("/","\\");if(Yc(t))return!1;return/^\\{2}[^\\]/.test(t)}function ret(e){return Qs(e)||/^\/network\/servers(\/|$)/i.test(e)}function oet(e){return/^\/(proc|dev\/(fd|stdin|stdout|stderr))(\/|$)/i.test(e)}function set(e,t,n={}){if(t==="win32"){let r=e.replaceAll("/","\\");if(Yc(r))return!1;let o=net(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(Qee.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&&ret(e))return!1;if(n.rejectMagicLinkRoot&&oet(e))return!1;if(Xee.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 iet=/\.(exe|ps1)$/i;function aet(e){return/\.ps1$/i.test(e)}function cet(e){return aet(e)&&/[[\]`*?]/.test(e)}var uet='a .ps1 path must not contain "[", "]", "`", "*", or "?" on Windows (PowerShell resolves them as wildcard syntax)',det=()=>g().describe("Absolute path to the helper executable"),Ji=(e)=>Qe((t)=>t===null?void 0:t,e.optional()).optional(),pet=Oee,Gee=(e)=>X().int().min(e).transform((t)=>Math.min(t,pet)),Wee=["path","script","defaultSettings"];function nte(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;return Wee.some((n)=>t[n]===null)&&Wee.every((n)=>t[n]===null||t[n]===void 0)}var Vee=64,zE=L(()=>C({path:det(),timeoutMs:Ji(Gee(1000)),refreshIntervalMs:Ji(ue([j(0),Gee(60000)]))})),rte=()=>V(["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 the way merged managed sources compose (helper scalars win, arrays union, objects merge — except fallbackModel, forceLoginOrgUUID, gatewayInternalNetworks, sandbox.filesystem.allowRead, sandbox.credentials.awsPairs, sandbox.ripgrep and the restriction allowlists such as allowedMcpServers, availableModels and allowedHttpHookUrls, which are the helper's whole value when it emits one; tighten a permission with a deny), so a failed helper costs only the delta");function ote(e){return e==="continue"||e==="refuse"}var fet=()=>Qe((e)=>e===void 0||ote(e)?e:"refuse",V(["continue","refuse"]).describe(`What happens when this entry's helper fails at startup (bad path, missing file or interpreter, non-zero exit, timeout, oversize or invalid output) and no static settings payload (this entry's own, the linux entry's on WSL, or the map's "default") applies in its place: 'refuse' — Claude Code does not start, naming the failure; 'continue' — Claude Code starts without the helper's output, on the delivering source's own settings, with a /status notice. Default: 'refuse' when the entry comes from MDM or the managed settings file, 'continue' when it comes from remote managed settings. Any other value is treated as 'refuse', with a /status notice. The install and update commands start no session and are never refused over a remote entry: they report the refusal in /status. An entry whose other fields fail validation runs no helper; from MDM or the managed settings file, any value but 'continue' on it then refuses to start Claude Code until the entry is fixed, unless a static settings payload (the entry's own, kept when it validates, the linux entry's for a wsl one, or the map's "default") serves in its place. From remote, a non-interactive session runs the helper off settings verified this session without the interactive approval, so 'refuse' there too means the helper ran and failed; a launch whose remote settings could not be verified this session (offline, fetch failed) starts without the helper regardless; and a failure first reached after the session has started (settings verified or approved mid-session, which on a machine that only ever runs non-interactively is every launch) ends a session no person watches (non-interactive, a background session no client is attached to, or a teammate session) as the refused start would have, and leaves a watched interactive one (a terminal, with or without remote control, or an attached background session) running under a /status notice with its next start refused. Background refresh failures always keep the last good output whatever this says`)),met=5,het=()=>X().int().min(0).transform((e)=>Math.min(e,met)).describe("How many more times to run this entry's helper when a run fails to execute — it could not be launched, exited non-zero, or was stopped at timeoutMs — before that counts as a failure (a non-negative integer; default 0, a single attempt; above 5 is treated as 5). Attempts are separated by a short randomized backoff (from 250 ms, doubling per attempt, at most 4 s each) and each attempt gets the full timeoutMs, so a start that waits on the helper can wait up to (retries + 1) × timeoutMs plus the backoff. Output the helper did produce and that was refused — oversized, not a JSON object, an invalid envelope, or settings that fail validation — is not retried, and neither is an invalid path. Applies alike at startup and on each background refresh; only once the attempts are used up do the entry's failure rules (a static settings payload in its place, onFailure, the refresh notice) apply, naming the last attempt's failure"),get=(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"),_et="exactly one of path/script must be configured",yet='"script" and "interpreter" must be configured together',bet="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",Eet=(e)=>g({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)=>yg(t),{message:"script must be valid UTF-8 (no lone surrogates)"}).refine((t)=>e!=="windows"||!/[\u0080-\uffff]/.test(t),{message:bet}).describe("Inline helper script, delivered to the fixed interpreter over stdin (never written to disk)");var Wn=["macos","linux","windows","wsl"];function TL(e){return e==="wsl"?["wsl","linux"]:[e]}function xet(e){return e==="windows"?"win32":"posix"}function vet(e){return{rejectDriveRelative:e==="windows",rejectUnc:e==="windows",rejectNetworkRoot:e!=="windows",rejectMagicLinkRoot:e!=="windows",requireWin32ExecutableSuffix:e==="windows"}}function wet(e){let t=xet(e),n=vet(e);return g().max(1024,{message:"path must be at most 1024 characters"}).refine((r)=>!tet.test(r),{message:"path must not contain control, line/paragraph-separator, or invisible (default-ignorable) characters"}).refine((r)=>(t==="win32"?Qee:Xee).isAbsolute(r),{message:"path must be absolute"}).refine((r)=>!(t==="win32"&&n.requireWin32ExecutableSuffix)||iet.test(r),{message:"path must end in .exe or .ps1 on Windows"}).refine((r)=>t!=="win32"||!cet(r),{message:uet}).refine((r)=>set(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 RL=[...Wn,"default"],EL=["path","script","interpreter","outputBehavior","onFailure","retries","timeoutMs","refreshIntervalMs","defaultSettings"],$E=["managedSettings","appendSystemPrompt"],Ec=L(()=>Z(g(),xe()).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 EL)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 (${EL.join("/")}) belong on the per-OS entries (policyHelpers.${Wn.join("/")})`});for(let n of $E)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 RL)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`})})),Aet='Entry must carry "path" (a helper executable) or "script" + "interpreter" (an inline helper), and/or "defaultSettings" (a static settings payload)';function Cet(e){let{path:t,script:n,interpreter:r,defaultSettings:o}=e;if(t!==void 0&&n!==void 0)return _et;if(n===void 0!==(r===void 0))return yet;if(t===void 0&&n===void 0&&o===void 0)return Aet;return null}function ste(e,t){return zE().omit({path:!0}).extend({path:Ji(wet(e)),script:Ji(Eet(e)),interpreter:Ji(get(e)),outputBehavior:Ji(rte()),onFailure:Ji(fet()),retries:Ji(het()),defaultSettings:Qe((n)=>n===null?void 0:n,t.optional()).optional()}).check((n)=>{if(n.issues.length>0)return;let r=Cet(n.value);if(r!==null)n.issues.push({code:"custom",message:r,input:n.value})})}var j3t=L(()=>ste("linux",Ec()));function xL(e,t=Ec()){return e==="default"?Ec():ste(e,t)}var Tet=L(()=>C(Object.fromEntries(RL.map((e)=>[e,Qe((t)=>{if(t===null)return;if(e!=="default"&&nte(t))return;return t},xL(e).optional()).optional()])))),qee=["skills","agents","hooks","mcp"],Zee=Object.freeze({type:"invalid-entry-stripped"}),Ret=L(()=>ue([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:g().describe("Regex matched against turn output (tool results and assistant text)"),url:g().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:g().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),C({type:g().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()])),ket=()=>X().int().min(HQ).max(BQ).optional().catch(void 0);function KE(e,{strictPolicyHelperKeys:t=!1}={}){function n(o){return Z(g(),vL()).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?Qe((i)=>{if(i===null)return;return s?s(i):i},o):o.catch(void 0);return C({$schema:g().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:g().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:g().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:g().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:g().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:g().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),processWrapper:g().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(zE().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(Tet().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 from admin-controlled policy sources, and from remote managed settings — a payload of plain policy as delivered, like any other remote key; a helper, or a payload carrying anything the managed-settings approval dialog lists, only once the settings are verified this session and approved there (policyHelper itself is never honored from remote).`),...yn.CLAUDE_CODE_ENABLE_XAA&&{xaaIdp:C({issuer:g().url().describe("IdP issuer URL for OIDC discovery"),clientId:g().describe("Claude Code's client_id registered at the IdP"),callbackPort:X().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:g()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:k().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:C({enabled:k().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:X().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:X().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:g().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:k().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:g().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:g().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:X().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:X().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:k().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:k().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:X().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:X().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:k().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:JQe().optional().describe("Environment variables to set for Claude Code sessions"),attribution:C({commit:g().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:g().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:k().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:k().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:k().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:ete(e).optional().describe("Tool usage permissions configuration"),model:g().optional().describe("Override the default model used by Claude Code"),fallbackModel:I(g()).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(g()).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:k().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:Z(g(),g()).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(CL()).describe("Rows to show in the /model picker, in order."),replaceBuiltInOptions:k().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:AL(),overrides:Z(g(),wL()).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."),...!1,enableAllProjectMcpServers:k().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:I(g()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:I(g()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:k().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:Z(g(),V(["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:k().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."),managedMcpServers:Z(g().refine(XD,{error:"server names may only contain letters, numbers, hyphens and underscores, and may not be __proto__, constructor or prototype"}),QD(),{error:eL}).optional().describe(`MCP servers the organization provides to every user, keyed by server name, each with the .mcp.json entry shape; only "http" and "sse" servers are accepted (nothing that names a program to run, no \${VAR} references). Honored from managed settings only; users cannot remove them, deniedMcpServers still applies, and they need no allowedMcpServers entry. Not read in Claude Desktop's Code tab on a third-party deployment or in Cowork sessions, where Claude Desktop supplies and locks the session's MCP servers itself.`),allowedMcpServers:I(HE()).optional().describe("Enterprise allowlist of the MCP servers users may use. Governs servers users add (user, project and local config, --mcp-config, agent frontmatter, plugins, claude.ai connectors); servers the organization itself delivers (managedMcpServers, and managed-mcp.json entries that use no ${VAR} expansion) are allowed without being listed; a managed-mcp.json entry that uses ${VAR} expansion is still checked against this list. If undefined, all servers are allowed. If empty array, users can use no servers of their own. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:I(BE()).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:yc().optional().describe("Custom commands to run before/after tool executions"),worktree:C({symlinkDirectories:I(g()).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(g()).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:V(["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:V(["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:g().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:k().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:k().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:k().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:k().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:k().optional().describe("Deprecated: use enableArtifact: false. Still honored — true disables the Artifact tool; false is ignored."),enableArtifact:k().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:k().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowSizeGuideline:V(["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:k().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:k().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:V(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),bashEditDiffEnabled:k().optional().describe("Whether the Bash tool shows a diff of the files a Bash command changed (PostToolUse Bash hooks get the changed-file list in tool_response). Set to false to turn that off. Default: on when the Bash tool handles file edits. Only user, flag or policy settings can turn it on outside auto and bypassPermissions modes."),bashOutputMaxChars:X().int().positive().optional().catch(void 0).describe("How many characters of a successful Bash or PowerShell command's output Claude receives inline (default 30000; values clamp to 4000-128000). Output past this is saved to a file and Claude receives a short preview plus the path. When set, this also replaces BASH_MAX_OUTPUT_LENGTH, which on its own only sizes the read-back window."),taskOutputMaxChars:X().int().positive().optional().catch(void 0).describe("How many characters of a background task's output the TaskOutput tool hands Claude inline (default 32000; values clamp to 4000-128000). Longer output is cut to its most recent characters with the path of the full output file, except that a shell command still running returns its first characters up to this size. When set, this also replaces TASK_MAX_OUTPUT_LENGTH, which on its own only sizes that window."),respondToBashCommands:k().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:k().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:I(g()).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(g()).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:k().optional().describe("When true (and set in managed settings), permission rules from user, project, local, and --settings files and allow rules from --allowedTools are ignored; only managed settings can add allow rules through settings. --disallowedTools and other deny and ask rules from the command line or the current session still apply."),allowManagedMcpServersOnly:k().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:k().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:Qe((o)=>Array.isArray(o)?o.filter((s)=>qee.includes(s)):o,ue([k(),I(V(qee))])).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:g(),padding:X().optional(),refreshInterval:X().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:k().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:g().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(Ret().catch(Zee)).transform((o)=>o.filter((s)=>s!==Zee)).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:g()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:Z(g(),ue([I(g()),k(),GP()])).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.'),prependPlugins:I(g()).optional().catch(void 0).describe("Managed plugins (plugin@marketplace ids that managed enabledPlugins sets true) whose hooks run first, outermost, in the listed order: the first id listed sees every event before any other plugin and every result after it. Managed plugins not listed here or in appendPlugins follow the listed ones; user, project and marketplace plugins come after those; then appendPlugins; then the built-in plugins. The bundled sec-default@builtin seats itself outermost (on a machine with managed settings and for Team and Enterprise organizations) unless this list is set, in which case list sec-default@builtin where it should sit or leave it out. Any other id that is not an enabled managed plugin is skipped; an id listed in both keys is prepended. Only honored from managed settings (or, on a machine with none, from user settings for your own plugins); ignored in project, local and --settings sources."),appendPlugins:I(g()).optional().catch(void 0).describe("Managed plugins (plugin@marketplace ids that managed enabledPlugins sets true) whose hooks run last among plugins, innermost, in the listed order: the last id listed sits just above the built-in plugins and sees each event as every other plugin left it. Only honored from managed settings (or, on a machine with none, from user settings for your own plugins); ignored in project, local and --settings sources."),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(ud()).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(ud()).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(ud()).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:k().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:k().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(g()).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:V(["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:g().min(1).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.'),gatewayInternalNetworks:I(g()).optional().catch([ite]).meta({default:void 0}).describe("IPv4 CIDR blocks (at most 4, each /8 to /32, not overlapping) your Cloud gateway sits in: the public block your organization numbers its internal network from, which lets /login reach a gateway there. A block must lie entirely outside private space, where /login accepts a gateway without this key. /login accepts a gateway inside a listed block over a direct connection only, and only when this machine's own address on that connection is inside the same block, so /login must happen from a machine whose own address is inside the block (not through a proxy, VPN pool, container or NAT segment outside it). A bar against copied settings files, not proof of location. Honored only from admin-controlled managed settings (MDM / managed-settings.json / policy helper); ignored in user, project, and remote-delivered settings."),parentSettingsBehavior:V(["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:V(["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 (a restrictive boolean or enum — "+"the allowManaged*Only locks, the disable* switches, the sandbox "+"lock family — takes the strictest value any source sets) and "+"arrays union, except fallbackModel, the restriction allowlists allowedMcpServers, availableModels, strictKnownMarketplaces and allowedChannelPlugins, and sandbox.credentials.awsPairs and sandbox.ripgrep (the highest source that sets one owns it whole), modelOverrides (the whole map of the highest source that sets it, dropped when that source sits below the one that sets availableModels), managedMcpServers (server names union; a name set by two sources takes the higher source's whole entry), and the keys taken from the highest source only: the auth pins forceLoginOrgUUID, forceLoginMethod, forceLoginGatewayUrl and gatewayInternalNetworks, the credential helpers apiKeyHelper, awsAuthRefresh, awsCredentialExport, gcpAuthRefresh, otelHeadersHelper and proxyAuthHelper, modelPicker, permissions.defaultMode, parentSettingsBehavior and the policyHelper configuration (env keeps its own per-key union). 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:ue([g(),I(g())]).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:k().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:g().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:g().optional().describe("Controls the output style for assistant responses"),viewMode:V(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:g().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:k().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:jD().optional(),feedbackSurveyRate:X().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:V(["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:k().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:C({mode:V(["append","replace"]),verbs:I(g())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:C({excludeDefault:k().optional().catch(void 0),tips:QQe().optional(),tipsFile:g().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:g().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:k().optional().describe("Whether to disable syntax highlighting in diffs"),spellcheck:C({enabled:k().optional().catch(void 0).describe("Turn on spell checking of the prompt input (default: false)"),checker:g().optional().catch(void 0).describe(`Which spell checker to run: ${LE.map((o)=>`"${o}"`).join(", ")}, or "auto" (default) for the first of those found on PATH`),language:g().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:g().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 ${LE.slice(0,-1).join(", ")} or ${LE.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:k().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),promptCacheTtl:V(hu).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:V(hu).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:k().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:V(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),maxEffortLevel:V(ph).optional().catch(void 0).describe("Maximum effort level. Anything above it (an /effort or /model pick, --effort, CLAUDE_CODE_EFFORT_LEVEL, a model default) is clamped to it, on every provider including Bedrock, Vertex and Foundry. Combines with an organization's per-model effort cap by taking the lower of the two; across settings files the lowest value wins, and modelSettings.<model>.maxEffortLevel replaces it per model. Enforced client-side: an effort supplied through CLAUDE_CODE_EXTRA_BODY is not clamped."),modelSettings:Qe((o)=>typeof o==="object"&&o!==null&&!Array.isArray(o)?bh(o,(s,i)=>Object.hasOwn(Object.prototype,i)):o,Z(g(),C({effortLevel:V(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for this model."),maxEffortLevel:V(ph).optional().catch(void 0).describe('Maximum effort level for this model. Within one settings file it replaces the top-level maxEffortLevel for the model ("max" exempts it); across settings files the lowest applicable value wins. Keyed like effortLevel: the canonical model name also matches its dated, [1m], Bedrock and Vertex spellings.')}).passthrough().optional().catch(void 0))).optional().catch(void 0).describe("Per-model settings keyed by canonical model name."),ultracode:k().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:ket().describe("Auto-compact window size"),...!1,advisorModel:g().optional().describe("Advisor model for the server-side advisor tool."),fastMode:k().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:k().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:k().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),emojiCompletionEnabled:k().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:k().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:k().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:V(["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:V(["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:g().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:V(jQ).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(g()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:Z(g(),C({mcpServers:Z(g(),Z(g(),ue([g(),X(),k(),I(g())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:Z(g(),ue([g(),X(),k(),I(g())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(GP())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:C({defaultEnvironmentId:g().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:V(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:g().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:g().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:g().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:g().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:V(["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:k().optional(),mode:V(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:k().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:k().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(tte()).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:k().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),timeFormat:ue([V(FQ),g()]).optional().describe('Clock format for times shown in the UI: "auto" (default, follows the locale), "12-hour", "24-hour", "24-hour-utc" ("18:05Z"), or a strftime pattern such as "%H:%M" (any value containing "%"; other values read as "auto"). A pattern replaces the time everywhere; message timestamps show only the pattern, so include %Y-%m-%d for the date. /config offers the presets; a pattern is set here.'),timeZone:g().optional().describe('IANA time zone for times shown in the UI, e.g. "UTC" or "Europe/Dublin". Default: the system time zone. An unknown name falls back to the system time zone.'),doneMeansMerged:k().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:V(["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:X().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:k().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:k().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:g().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:k().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:k().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:k().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:k().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:V(["disable"]).optional().describe("Disable auto mode"),remoteTools:C({allowUnattendedServing:k().optional().describe("@internal When false in managed or user settings, a cloud session in auto mode may not run commands on this computer without a person approving each one, whatever consent the computer has given; a project, local or --settings value is ignored. Default: true.")}).optional().describe("@internal How this computer serves tool calls to cloud sessions"),sshConfigs:I(C({id:g().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:g().describe("Display name for the SSH connection"),sshHost:g().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:X().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:g().optional().describe("Path to SSH identity file (private key)"),startDirectory:g().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:g().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:I(g()).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:g().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:ue([V(zQ),g().startsWith("custom:").transform((o)=>o)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:V(UQ).optional().catch(void 0).describe("Key binding mode for the prompt input"),keybindingFlavor:V(["classic","readline"]).optional().catch(void 0).describe("Deprecated: no longer has any effect. The prompt's word-editing keys always follow Bash (readline) conventions."),vimInsertModeRemaps:Z(g(),xe()).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:k().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:V(MQ).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:k().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:k().optional().describe("Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:k().optional().describe("When safeguards flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoContinueAtUsageLimit:k().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:k().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:k().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:k().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:k().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:k().optional().describe("Stamp each message with its arrival time"),terminalProgressBarEnabled:k().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:k().optional().describe("Enable the todo / task tracking panel"),teammateMode:V($Q).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:k().optional().describe("Start Remote Control bridge automatically each session"),remoteControl:C({shareHostProfile:V(jE).optional().catch(void 0).describe("@internal What a Remote Control environment reports about this machine when it registers: 'off' reports nothing, 'basic' the OS, architecture and detected developer tools, 'full' also the names of MCP servers configured on this machine (never a repository's .mcp.json). When unset, the level comes from the feature rollout, which may be any of the three. Managed, --settings and user settings choose the level (the most restrictive wins); project and local settings can only lower it, never raise it. Read when Remote Control starts; lowering it later applies from the next registration, raising it from the next start.")}).optional().describe("@internal Remote Control (`claude remote-control`) options"),isolatePeerMachines:k().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:V(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),crossSessionInbound:V(Ch).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:k().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:k().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:k().optional().describe("Allow Claude to push proactive mobile notifications"),...Pee(e)}).passthrough()}var dd=L(()=>KE(Ah())),Yee=Object.freeze({serverName:"invalid-entry-stripped"});function Jee(e,t,n){return I(t.catch((r)=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${r.issues[0]?.message??"failed validation"}`}),Yee))).transform((r)=>r.filter((o)=>o!==Yee)).optional()}var ite="(unreadable)";function bL(e,t,n,r,o){return I(xe()).transform((s)=>{let i=[];for(let[a,c]of s.entries()){let l=t.safeParse(c);if(l.success){i.push(l.data);let u=o?.(c,l.data);if(u!==void 0)n({path:`${e}[${a}]`,message:u,statusOnly:!0})}else{let u=l.error.issues[0],p=u===void 0?"failed validation":u.path.length?`${u.path.join(".")}: ${u.message}`:u.message;n({path:`${e}[${a}]`,message:`Invalid entry was ignored: ${p}`})}}if(s.length>0&&i.length===0)n({path:e,message:`Every entry of "${e}" was invalid; enforcing an empty allowlist (${r}) until it is fixed.`});return i}).optional().catch(()=>(n({path:e,message:`"${e}" was present but invalid; enforcing an empty allowlist (${r}) until it is fixed.`}),[]))}function kL(e,t){let n=dd(),r={};for(let[S,x]of Object.entries(n.shape))r[S]=x.catch((w)=>{e({path:S,message:`${w.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});for(let S of["prependPlugins","appendPlugins"])if(S in n.shape)r[S]=I(g()).optional().catch((x)=>{e({path:S,message:`${x.issues[0]?.message??"Failed schema validation"}. This field was ignored; read as unset.`});return});r.allowedMcpServers=Jee("allowedMcpServers",HE(),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=Jee("deniedMcpServers",BE(),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.managedMcpServers=xe().transform((S)=>CE(S,(x,w)=>e({path:x?`managedMcpServers.${x}`:"managedMcpServers",message:x?`Managed MCP server was ignored: ${w}`:w,statusOnly:!0}))).optional(),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.remoteTools=n.shape.remoteTools.catch(()=>(e({path:"remoteTools",message:'"remoteTools" was present but invalid; treating allowUnattendedServing as false (no unattended serving) until it is fixed.'}),{allowUnattendedServing:!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(xe()).transform((S,x)=>{let w=[];for(let N of S)if(typeof N==="string")w.push(N);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(N)}); the entry was ignored.`});return w}).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.allowedHttpHookUrls=bL("allowedHttpHookUrls",g(),e,"no HTTP hooks may run"),r.httpHookAllowedEnvVars=bL("httpHookAllowedEnvVars",g(),e,"no environment variables may be interpolated into HTTP hook headers"),r.allowedChannelPlugins=bL("allowedChannelPlugins",eet(),e,"no channel plugins admitted",(S,x)=>typeof S==="string"?`"allowedChannelPlugins" entry "${S}" was accepted; prefer the documented object form {"plugin": "${x.plugin}", "marketplace": "${x.marketplace}"}.`:void 0),r.gatewayInternalNetworks=I(g()).optional().catch(()=>(e({path:"gatewayInternalNetworks",message:'"gatewayInternalNetworks" was present but invalid; gateway sign-in governed by this source is refused until it is fixed.'}),[ite])),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=(S,x)=>{let w=S.safeParse(x);if(w.success)return;return w.error.issues.slice(0,3).map((N)=>N.path.length?`${N.path.join(".")}: ${N.message}`:N.message).join("; ")},i;r.policyHelper=Qe((S)=>{if(o=!1,i=S,S&&typeof S==="object"&&!Array.isArray(S)){let x=S;for(let w of["defaultSettings","default",...$E])if(x[w]!==void 0&&x[w]!==null)e({path:"policyHelper",message:`"${w}" 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 w of["policyHelper","policyHelpers"])if(x[w]!==void 0&&x[w]!==null)e({path:"policyHelper",message:`"${w}" 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 w of Wn)if(x[w]!==void 0&&x[w]!==null)e({path:"policyHelper",message:`"${w}" on the singular policyHelper is ignored — per-OS entries live on the policyHelpers MAP ("policyHelpers": {"${w}": ...}), 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.${Wn.join("/")}); this helper's output REPLACES the policy tier whatever the value says.`,statusOnly:!0});if(x.onFailure!==void 0&&x.onFailure!==null)e({path:"policyHelper",message:`"onFailure" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Wn.join("/")}); a failure of this helper REFUSES to start Claude Code whatever the value says.`,statusOnly:!0});if(x.retries!==void 0&&x.retries!==null)e({path:"policyHelper",message:`"retries" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Wn.join("/")}); this helper is run ONCE per start or refresh, never re-run, whatever the value says.`,statusOnly:!0});if(x.path===null||x.path===void 0)o=!0}return S===null?void 0:S},zE().optional()).catch((S)=>{e({path:"policyHelper",message:`${S.issues[0]?.message??s(zE(),i)??"Failed schema validation"}. This field was ignored.`,...o&&{statusOnly:!0}});return});let a=(S,x)=>{e({path:S,message:`"${S}" 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=[],l=(S)=>{let x=!1,w,N=xL(S,Ec().optional().catch((P)=>{x=!0,a(`policyHelpers.${S}.defaultSettings`,P.issues[0]?.message??s(Ec(),w&&typeof w==="object"&&!Array.isArray(w)?w.defaultSettings:void 0));return}));return Qe((P)=>{if(x=!1,w=P,S!=="default"&&P&&typeof P==="object"&&!Array.isArray(P)){let F=P;for(let q of[...$E,"claudeMd"])if(F[q]!==void 0&&F[q]!==null)e({path:`policyHelpers.${S}`,message:`"${q}" on the policyHelpers.${S} 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 q of["policyHelper","policyHelpers"])if(F[q]!==void 0&&F[q]!==null)e({path:`policyHelpers.${S}`,message:`"${q}" on the policyHelpers.${S} 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 q of Wn)if(F[q]!==void 0&&F[q]!==null)e({path:`policyHelpers.${S}`,message:`"${q}" on the policyHelpers.${S} entry is ignored — per-OS entries are SIBLINGS on the policyHelpers map, not nested inside each other. The intended ${q} config will NOT apply from here.`,statusOnly:!0});if(F.default!==void 0&&F.default!==null)e({path:`policyHelpers.${S}`,message:`"default" on the policyHelpers.${S} 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});let z=F.onFailure;if(z!==void 0&&z!==null&&!ote(z)){let q;if(typeof z==="string"){let ee=z.replace(/[^\x20-\x7e]/gu,"?");q=JSON.stringify(ee.length>Vee?`${ee.slice(0,Vee-1)}…`:ee)}else if(typeof z==="number"||typeof z==="boolean")q=String(z);else q=`a non-string value (${Array.isArray(z)?"array":typeof z})`;e({path:`policyHelpers.${S}.onFailure`,message:`"onFailure": ${q} on the policyHelpers.${S} entry is not a recognized value ("continue" or "refuse"); it is treated as "refuse" — a startup failure of this entry's helper with no static payload in its place will not start Claude Code.`,statusOnly:!0})}if(nte(P))return}return P===null?void 0:P},N.optional()).catch((P)=>{if(S==="default"){a("policyHelpers.default",P.issues[0]?.message??s(Ec(),w));return}if(x)return;let F=s(xL(S),w)??"failed validation",z=w,q=z&&typeof z==="object"&&!Array.isArray(z)?z:null,ee=q?.onFailure,te=ee!==void 0&&ee!==null&&ee!=="continue",ve=(Q)=>{let ut=`policyHelpers.${S}`;if(te)c.push({entryKey:S,message:Q});else e({path:ut,message:Q,statusOnly:!0})};if(q){let Q=q.defaultSettings;if(Q!==void 0&&Q!==null){let ut=Ec().safeParse(Q);if(ut.success){let De=q.outputBehavior,dt=De===void 0||De===null?null:rte().safeParse(De);if(dt&&!dt.success){ve(`Invalid entry was ignored: ${F}. 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 ${S} from this entry.`);return}return e({path:`policyHelpers.${S}`,message:`Invalid entry: its helper fields were ignored (${F}), but its "defaultSettings" static payload was kept. No policy helper runs on ${S} from this entry.`,statusOnly:!0}),{defaultSettings:ut.data,...dt&&{outputBehavior:dt.data}}}}}ve(`Invalid entry was ignored: ${F}. No policy helper runs on ${S} from this entry.`);return})};r.policyHelpers=Qe((S)=>{if(c=[],S&&typeof S==="object"&&!Array.isArray(S)){let x=S;for(let w of["defaultSettings",...$E,"claudeMd"])if(x[w]!==void 0&&x[w]!==null)e({path:"policyHelpers",message:`"${w}" 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 w of["policyHelper","policyHelpers"])if(x[w]!==void 0&&x[w]!==null)e({path:"policyHelpers",message:`"${w}" 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 w of EL.filter((N)=>N!=="defaultSettings"))if(x[w]!==void 0&&x[w]!==null){let N=w==="script"||w==="interpreter"?"; inline scripts are per-OS only (the singular policyHelper key takes a path)":w==="outputBehavior"||w==="onFailure"||w==="retries"?"":", or on the singular policyHelper key";e({path:"policyHelpers",message:`"${w}" directly on the policyHelpers map is ignored — helper configs go on a per-OS entry (policyHelpers.${Wn.join("/")})${N}. No helper runs from this field here.`,statusOnly:!0})}}return S===null?void 0:S},C(Object.fromEntries(RL.map((S)=>[S,l(S)]))).transform((S)=>{for(let x of Object.keys(S))if(S[x]===void 0)delete S[x];for(let{entryKey:x,message:w}of c){let N=`policyHelpers.${x}`,P=TL(x).find((z)=>S[z]?.defaultSettings!==void 0&&S[z]?.defaultSettings!==null),F=P!==void 0?`${P}.defaultSettings`:S.default!==void 0?"default":null;e(F!==null?{path:N,message:`${w} Its "onFailure" requires the helper; the "policyHelpers.${F}" static payload serves in its place.`,statusOnly:!0}:{path:N,message:`${w} Its "onFailure" requires the helper, so 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})}return c=[],S}).optional().catch((S)=>(e({path:"policyHelpers",message:`"policyHelpers" could not be parsed: expected an object mapping OS keys (${Wn.join(", ")}) to helper entries, plus an optional "default" settings payload (${S.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 u=Object.freeze({mode:"deny"}),p=Object.freeze({accessKeyIdVar:"_STRIPPED_",secretAccessKeyVar:"_STRIPPED_2_"}),f=0,m=[],h=t===void 0?"":`${[...t].reduce((S,x)=>Math.imul(S^x.charCodeAt(0),16777619)>>>0,2166136261).toString(16).toUpperCase().padStart(8,"0")}_`,_=(S,x)=>{if(typeof S!=="object"||S===null)return;let w=(W)=>x.some((qe)=>qe.path?.includes(W)),N=(W)=>{let qe=S[W];if(typeof qe==="string")return qe;return w(W)?"":void 0},P=N("accessKeyIdVar"),F=N("secretAccessKeyVar"),z=N("sessionTokenVar"),q=Zi;if(![P,F,z].some((W)=>W!==void 0&&q.includes(W)))return;let ee=(W)=>W!==void 0&&id().safeParse(W).success;f+=1;let te=(W)=>`${zD}${W}_${h}${f}_`,ve=ee(P)?P:te("ACCESS_KEY_ID"),Q=ee(F)&&F!==ve?F:te("SECRET_ACCESS_KEY"),ut=z===void 0?void 0:ee(z)&&z!==ve&&z!==Q?z:te("SESSION_TOKEN"),De=(W)=>W.startsWith(zD);if(!De(ve)&&!De(Q)){let W=q.includes(Q)?Q:void 0;if(Q=te("SECRET_ACCESS_KEY"),W!==void 0){let qe=_({accessKeyIdVar:W},[]);if(qe!==void 0)m.push(qe)}}let dt=wE().safeParse({accessKeyIdVar:ve,secretAccessKeyVar:Q,...ut!==void 0&&{sessionTokenVar:ut}});return dt.success?dt.data:void 0},y=(S,x,w)=>I(x.catch((N)=>{let P=w(N.value);if(P!==void 0)return e({path:`sandbox.credentials.${S}[]`,message:`Invalid entry was degraded to mode "deny": ${N.issues[0]?.message??"failed validation"}. The credential stays blocked (not masked) until the entry is fixed.${S==="files"?" Under sandbox.filesystem.disabled, file read-denies are not enforced.":""}`}),P;return e({path:`sandbox.credentials.${S}[]`,message:`Invalid entry was ignored: ${N.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),u})).transform((N)=>N.filter((P)=>P!==u)).optional().catch((N)=>{if(typeof N.value==="object"&&N.value!==null&&!Array.isArray(N.value)){let P=x.safeParse(N.value);if(P.success)return e({path:`sandbox.credentials.${S}`,message:`"${S}" must be an array; a lone entry object was accepted as a one-element list. Wrap it in [ ] to silence this warning.`}),[P.data];let F=w(N.value);if(F!==void 0)return e({path:`sandbox.credentials.${S}`,message:`"${S}" 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.`}),[F]}return e({path:`sandbox.credentials.${S}`,message:`${N.issues[0]?.message??"Invalid value"}. "${S}" was ignored; these credential entries are NOT protected until it is fixed.`}),[]}),b=C({files:y("files",EE(),(S)=>{if(typeof S!=="object"||S===null||!("mode"in S)||S.mode!=="mask"&&S.mode!=="deny"||!("path"in S)||typeof S.path!=="string")return;let x=EE().safeParse({path:S.path,mode:"deny"});return x.success?x.data:void 0}),envVars:y("envVars",xE(),(S)=>{if(typeof S!=="object"||S===null||!("mode"in S)||S.mode!=="mask"&&S.mode!=="deny"||!("name"in S)||typeof S.name!=="string")return;let x=xE().safeParse({name:S.name,mode:"deny"});return x.success?x.data:void 0}),allowPlaintextInject:k().optional().catch((S)=>(e({path:"sandbox.credentials.allowPlaintextInject",message:`${S.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(wE().catch((S)=>{let x=_(S.value,S.issues);if(x!==void 0)return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was degraded to a non-functional suppressor: ${S.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: ${S.issues[0]?.message??"failed validation"}. SigV4 re-signing stays unconfigured for this pair until it is fixed.`}),p})).transform((S)=>{let x=S.filter((w)=>w!==p);if(m.length>0)x.push(...m),m.length=0;return x}).optional().catch((S)=>{let x=typeof S.value==="object"&&S.value!==null?_(S.value,[]):void 0,w=typeof S.value==="object"&&S.value!==null&&(("accessKeyIdVar"in S.value)||("secretAccessKeyVar"in S.value)||("sessionTokenVar"in S.value));if(x===void 0&&w)return m.length=0,e({path:"sandbox.credentials.awsPairs",message:`${S.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 N=x!==void 0?[x]:Zi.flatMap((P)=>{let F=_({accessKeyIdVar:P},[]);return F!==void 0?[F]:[]});if(m.length>0)N.push(...m),m.length=0;return e({path:"sandbox.credentials.awsPairs",message:`${S.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.`}),N}),sigv4:C(Object.fromEntries(["streaming","presigned","sigv4a"].map((S)=>[S,V(["deny","passthrough"]).optional().catch((x)=>(e({path:`sandbox.credentials.sigv4.${S}`,message:`${x.issues[0]?.message??"Invalid value"}. "${S}" was degraded to an explicit deny; this SigV4 request shape stays denied until it is fixed.`}),"deny"))]))).optional().catch((S)=>(e({path:"sandbox.credentials.sigv4",message:`${S.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((S)=>{e({path:"sandbox.credentials",message:`${S.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=Zi.flatMap((w)=>{let N=_({accessKeyIdVar:w},[]);return N!==void 0?[N]:[]});return m.length=0,{allowPlaintextInject:!1,awsPairs:x,sigv4:{streaming:"deny",presigned:"deny",sigv4a:"deny"}}});return r.sandbox=jD().extend({credentials:b}).optional().catch((S)=>{e({path:"sandbox",message:`${S.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});let x=S.value;if(typeof x==="object"&&x!==null&&"credentials"in x){let w=b.safeParse(x.credentials);if(w.success&&w.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:w.data}}return}),C(r).passthrough().transform((S)=>{for(let x of Object.keys(S))if(S[x]===void 0)delete S[x];return S})}function Oet(){let e=V_();return e!==void 0&&q_(e)}function ate(){let e=In(),t=e==="wsl"&&!Oet()?"linux":e;switch(t){case"unknown":return{platform:t,chain:[]};default:return{platform:t,chain:TL(t)}}}var OL=[{alias:"additionalMarketplaces",canonical:"extraKnownMarketplaces"},{alias:"allowedMarketplaces",canonical:"strictKnownMarketplaces"}];function cte(e,t){if(!Ge(e))return[];let n=[];for(let{alias:r,canonical:o}of OL){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}function lte(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function GE(e){if(Array.isArray(e))return e.map(GE);if(e!==null&&typeof e==="object"){let t={};for(let n of Object.keys(e).sort())t[n]=GE(e[n]);return t}return e}var Iet=["enabled","enabledPlatforms"],Rh="network.allowedDomains";function dte(e){if(!e)return{shellSettings:{},envVars:{},sandboxSettings:{},hasHooks:!1,payloadSlots:{}};let t=pte(e),n=Det(e);Let([t,...n.map(([,i])=>i)]);let r={};for(let[i,a]of n){let c={shellSettings:a.hasHooks?{...a.shellSettings,hooks:xc(a.hooks)}:a.shellSettings,envVars:a.envVars,sandboxSettings:a.sandboxSettings};if(hte(c))r[i]=c}let{sandboxSwitches:o,...s}=t;return{...s,payloadSlots:r}}function pte(e){let t={},n;for(let l of IQ){let u=e[l];if(l==="policyHelpers"){if(u!==null&&typeof u==="object")for(let f of Wn){let m=zet(u[f]);if(m){if(t[`policyHelpers.${f}`]=m.command,m.scriptSize)n??={},n[`policyHelpers.${f}`]=m.scriptSize}}continue}let p;if(typeof u==="string")p=u;else if(u!==null&&typeof u==="object"&&"command"in u&&typeof u.command==="string")p=u.command;if(p!==void 0&&p.length>0)t[l]=p}let r=Wet(e);if(r&&typeof r==="object")for(let[l,u]of Object.entries(r)){let p=u?.source;if(!p||typeof p!=="object")continue;if(p.source==="url"&&typeof p.headersHelper==="string"&&p.headersHelper.length>0)t[`extraKnownMarketplaces[${me(l)}].source.headersHelper`]=ute(p.headersHelper,"url",p.url);if(p.source==="settings"&&Array.isArray(p.plugins)){let f=new Map;for(let m of p.plugins){let h=me(m?.name),_=f.get(h)??0;f.set(h,_+1);let y=m?.source;if(y!==null&&typeof y==="object"&&"source"in y&&y.source==="command"&&"command"in y&&typeof y.command==="string"&&y.command.length>0)t[`extraKnownMarketplaces[${me(l)}].plugins[${me(m.name)}][${_}].source.command`]=y.command;if(typeof m?.headersHelper==="string"&&m.headersHelper.length>0){let b=m.source,v=b!==null&&typeof b==="object";t[`extraKnownMarketplaces[${me(l)}].plugins[${me(m.name)}][${_}].headersHelper`]=ute(m.headersHelper,v&&"source"in b?b.source:void 0,v&&"url"in b?b.url:void 0)}}}}let o=e.sandbox,s={},i={enabled:Th(o,"enabled"),enabledPlatforms:Th(o,"enabledPlatforms"),[Rh]:Th(o,Rh)};if(o!==null&&typeof o==="object"){let l={enabled:i.enabled,enabledPlatforms:i.enabledPlatforms};for(let u of JD){let p=Bet(o[u]);if(p)t[`sandbox.${u}`]=xc({value:p,...l})}for(let u of DQ){let p=Th(o,u);if(Net(u,p))s[`sandbox.${u}`]=xc({value:p,...l,...gte.has(u)&&{allowedDomains:_te(i[Rh])}})}}let a={};if(e.env&&typeof e.env==="object")for(let[l,u]of Object.entries(e.env)){if(u===void 0)continue;let p=String(u);if(p.length>0&&!LQ(l,p))a[l]=p}let c=e.hooks!==void 0&&e.hooks!==null&&typeof e.hooks==="object"&&Object.keys(e.hooks).length>0;return{shellSettings:t,inlineHelperScriptSizes:n,envVars:a,sandboxSettings:s,hasHooks:c,hooks:c?e.hooks:void 0,sandboxSwitches:i}}function Det(e){return IL(e).map(([t,n])=>[t,pte(n)])}function IL(e){let t=[];for(let n of mte){let r=`policyHelpers.${n}`,o=Th(e,r);if(!lte(o))continue;let{policyHelper:s,policyHelpers:i,...a}=o;t.push([r,a])}return t}function fte(e){return Wn.find((t)=>e===`policyHelpers.${t}.defaultSettings`)}function Let(e){let t=e.map((r)=>Object.keys(r.sandboxSettings).length>0||JD.some((o)=>r.shellSettings[`sandbox.${o}`]!==void 0)),n=e.map((r)=>[...gte].some((o)=>r.sandboxSettings[`sandbox.${o}`]!==void 0));e.forEach((r,o)=>{if(t.some((s,i)=>s&&i!==o))for(let s of Iet){let i=r.sandboxSwitches[s];if(i!==void 0)r.sandboxSettings[`sandbox.${s}`]=xc({value:i})}if(n.some((s,i)=>s&&i!==o)){let s=r.sandboxSwitches[Rh];if(s!==void 0)r.sandboxSettings[`sandbox.${Rh}`]=xc({value:_te(s)??s})}})}var mte=[...Wn.map((e)=>`${e}.defaultSettings`),"default"];function PL(e){let t=[];for(let n of mte){let r=`policyHelpers.${n}`,o=e.payloadSlots[r];if(o!==void 0&&hte(o))t.push([r,o])}return t}function hte(e){return Object.keys(e.shellSettings).length>0||Object.keys(e.envVars).length>0||Object.keys(e.sandboxSettings).length>0}var gte=new Set(["credentials","network.tlsTerminate"]);function _te(e){return Array.isArray(e)?Tr(e.filter((t)=>typeof t==="string")).sort():void 0}function Th(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!=="object")return;n=n[r]}return n}function Net(e,t){if(t===void 0||t===null||t===!1)return!1;if(Array.isArray(t)&&t.length===0)return!1;return!(e==="credentials"&&Met(t))}function Met(e){if(typeof e!=="object"||e===null)return!1;return Object.entries(e).every(([t,n])=>{if(n===void 0)return!0;if(t==="files"||t==="envVars")return Array.isArray(n)&&n.every((r)=>typeof r==="object"&&r!==null&&r.mode==="deny");if(t==="sigv4")return typeof n==="object"&&n!==null&&Object.values(n).every((r)=>r===void 0||r==="deny");return t==="allowPlaintextInject"&&n===!1})}function Uet(e){return Object.keys(e.shellSettings).some(Fet)}function Fet(e){return Wn.some((t)=>e===`policyHelpers.${t}`)}function yte(e){return Uet(e)||Object.keys(e.shellSettings).some((t)=>t.startsWith("extraKnownMarketplaces["))||PL(e).length>0}function $et(e){return e==="sh"||e==="pwsh"}function zet(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&&$et(r))i={interpreter:r,script:Het(n)},a=jet(n);else return;return{command:me([i,o??null,s??null]),scriptSize:a}}function jet(e){return{bytes:Buffer.byteLength(e,"utf8"),lines:IM(e,`
|
|
220
220
|
`)+(e.endsWith(`
|
|
221
|
-
`)?0:1)}}function Het(e){return im(me(e))}function Bet(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 me([e.command,...t])}function Ket(e){return xc(Ste(e))}function Ste(e){return{shellSettings:e.shellSettings,envVars:e.envVars,sandboxSettings:Object.keys(e.sandboxSettings).length>0?e.sandboxSettings:void 0,hooks:e.hooks,payloadSlots:PL(e).length>0?Object.fromEntries(PL(e)):void 0}}function xc(e){return me(GE(e))}function bte(e){return im(Ket(e))}function Ete(e,t,n){if(bte(t)===e)return!0;return typeof n==="string"&&n.length>0&&im(xc({...Ste(t),claudeMd:n}))===e}function ute(e,t,n){return me([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}var Get=new Set(["dns","unix","ipv4","ipv6"]),AZt=new Set([...Get,"http","https","ws","wss","ftp","file","grpc","grpcs","otlp","xds","tcp","udp","tls","h2","h2c","http2"]);function xte(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function Wet(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of OL){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var Vet="remote-settings.json";var Ate="remote-settings-helper-consent";function qet(){return wte(Wt(),Ate)}function Zet(e){let t=dte(e);return yte(t)?t:void 0}function Yet(e){return bh(e,(t,n)=>n.startsWith("$")&&n!=="$schema")}class Cte{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;ineligibleReason=void 0;evalPolicySnapshotOnly=!1;lastLoadStatus=void 0;lastLoadStatusChanged=Tt();policySettingsNotified=!1;verifiedPayload=null;unverifiedView=null;projectedView=null;consentedPayload=null;deferredPayload=null;resetEpoch=0;backendView=void 0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified){if(this.verifiedPayload=e,t.consentDeferred)this.deferredPayload=e}}seedFromDisk(e){this.sessionCache=e;let t=Zet(e);if(t!==void 0){let n=ntt();if(n===void 0||!Ete(n,t,e.claudeMd))return}this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}dropConsentDeferral(){this.deferredPayload=null}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.evalPolicySnapshotOnly=!1,this.lastLoadStatus=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,this.unverifiedView=null,this.projectedView=null,this.consentedPayload=null,this.deferredPayload=null,this.resetEpoch++,this.emitLoadStatusChanged(void 0)}emitLoadStatusChanged(e){try{this.lastLoadStatusChanged.emit(e)}catch(t){ae(`Remote settings: load-status listener threw: ${Kr(t)}`,{level:"error"})}}}var Jet=new Je(()=>new Cte);function pd(){return Jet.of(Cn().host)}function WE(){return}function Tte(){return pd().evalPolicySnapshotOnly}function Rte(e){return e!==null&&pd().projectedView?.view===e}function Xet(e){return e&&Tte()?{...wQ(e),managedSourcesBehavior:"merge"}:e}function Qet(){return WE()??wte(Wt(),Vet)}var kte=8388608;function ett(){try{let e=rtt();if(e===null)return null;let t=ft(vu(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return Yet(t)}catch(e){if(t7(e))ae(`Remote settings: Disk cache exceeds ${kte} bytes; ignoring it as if absent`);return null}}var ttt=4096;function ntt(){let e=DL();if(e!==void 0)return e.attestation;try{return fc(qet(),ttt).trim()||void 0}catch{return}}function rtt(){let e=DL();if(e!==void 0)return e.content;return fc(Qet(),kte)}function DL(){let e=pd().backendView;if(!ye()||e===void 0||!e.ready||e.stoodDown||WE()!==void 0)return;if(!dU(e.configHome)){e.standDown("config home changed");return}return e}var JZt=tn.state("remote-settings"),XZt=tn.state(Ate);var ott=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",...BD,...KD,"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",...qD,...ZD,...YD,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...GD,"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 stt(e){if(!e||!e.env&&!("managedMcpServers"in e))return e;let{managedMcpServers:t,...n}=e;return e.env?{...n,env:bh(e.env,(r,o)=>ott.has(o.toUpperCase()))}:n}function Ote(){let e=Ite();if(e===null||Pte(pd(),e))return!1;if(vte(e))return!0;let t=IL(e);if(t.length===0)return!1;let{chain:n}=ate();return t.some(([r,o])=>{let s=fte(r);return(s===void 0||n.includes(s))&&vte(o)})}function vte(e){let t=e.managedMcpServers;return Ge(t)&&Object.keys(t).length>0}function Pte(e,t){return t===e.verifiedPayload||Boolean(WE())}function Ite(){let e=pd();if(!WE()&&e.eligible!==!0)return null;if(e.sessionCache)return e.sessionCache;let t=DL()!==void 0,n=ett();if(n){if(e.seedFromDisk(n),t)pc().invalidatePolicyLayer();else KX();return n}return null}function Dte(){let e=Ite(),t=pd(),n=Pte(t,e)?e:itt(t,e);if(n===null||!Tte())return n;if(t.projectedView?.raw!==n)t.projectedView={raw:n,view:Xet(n)};return t.projectedView.view}function itt(e,t){if(t===null)return null;if(e.unverifiedView?.raw!==t)e.unverifiedView={raw:t,view:stt(t)};return e.unverifiedView.view}var Lte={cli:!0,mcp:!0,"sdk-cli":!0,"sdk-ts":!0,"sdk-py":!0,bench:!0,"claude-vscode":!0,"claude-code-github-action":!0,"local-agent":!0,local_agent:!0,"claude-desktop":!0,remote:!0,remote_baku:!0,remote_cowork:!0,remote_trigger:!0,remote_cowork_trigger:!0,remote_desktop:!0,remote_mobile:!0,claude_in_slack:!0,"claude-in-slack":!0,"claude-in-teams":!0,"claude-desktop-3p":!0,"claude-security":!0,"ssh-remote":!0,"claude-coworker":!0,"claude-coworker-terminal":!0};var a9t=new Set(Object.keys(Lte));var att=new Set(["claude-desktop-3p","local-agent"]);function Nte(){let e=yn.CLAUDE_CODE_ENTRYPOINT;return e!==void 0&&att.has(e)}class Mte{entrypoint=void 0;interactive=!1;spawnedByAttendedSession=void 0;childSession=!1;claudecode=!1;coworkFrameArtifacts=!1;setEntrypoint(e){this.entrypoint=e}setInteractive(e){this.interactive=e}setSpawnedByAttendedSession(e){this.spawnedByAttendedSession=e}setChildSession(e){this.childSession=e}setClaudecode(e){this.claudecode=e}setCoworkFrameArtifacts(e){this.coworkFrameArtifacts=e}}var c9t=new Je(()=>new Mte);function ctt(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function Ute(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&ctt(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{userInfo as ltt}from"os";var Fte="com.anthropic.claudecode",VE="HKLM\\SOFTWARE\\Policies\\ClaudeCode",qE="HKCU\\SOFTWARE\\Policies\\ClaudeCode",kh="Settings",LL="/usr/bin/plutil",$te=["-convert","json","-o","-","--"],zte=["-lint","-s","--"],jte=5000,ZE=2097152,Hte="/mnt/c/Windows/System32/reg.exe",fd="/mnt/c/Program Files/ClaudeCode";function Oh(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=we("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function Bte(){let e="";try{e=ltt().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${Fte}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${Fte}.plist`,label:"device-level managed preferences"}),t}var Kte=512;function Gte(e){return e.map(utt)}function utt(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,errorClass:i,preserveOnWrite:a,mcpErrorMetadata:c,userWritable:l,wslIgnored:u,path:p,message:f,expected:m,suggestion:h,invalidValue:_,...y}=e,b=y;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,errorClass:i,preserveOnWrite:a,mcpErrorMetadata:c,userWritable:l,wslIgnored:u,path:Ph(p),message:Ph(f),expected:m===void 0?void 0:Ph(m),suggestion:h===void 0?void 0:Ph(h),invalidValue:typeof _==="string"?Ph(_):void 0}}function Ph(e){let t=xte(e.replace(/\s+/gu," "));return t.length>Kte?`${t.slice(0,Kte-1)}…`:t}var Hs="https://code.claude.com/docs/en",dtt=[{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:`${Hs}/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:`${Hs}/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:`${Hs}/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:`${Hs}/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:`${Hs}/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:`${Hs}/iam#working-directories`}}],ptt={permissions:`${Hs}/iam#configuring-permissions`,env:`${Hs}/settings#environment-variables`,hooks:`${Hs}/hooks`};function Wte(e){let t=dtt.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=ptt[Sv(e.path,".")];return n}var B9t=L(()=>KE(Ah(),{strictPolicyHelperKeys:!0}).strict());function Vte(e){return e.code==="invalid_type"}function qte(e){return e.code==="invalid_value"}function ftt(e){return e.code==="unrecognized_keys"}function Zte(e){return e.code==="too_small"}function Vn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function Yte(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Ih(e,t){return e.issues.map((n)=>{let r=n.path.map(String).join("."),o=n.message,s,i,a,c,l;if(qte(n))i=n.values.map((p)=>String(p)),a=i.join(" | "),c=void 0,l=void 0;else if(Vte(n)){a=n.expected;let p=Yte(n.message);c=p??Vn(n.input),l=p??Vn(n.input)}else if(Zte(n))a=String(n.minimum);else if(n.code==="custom"&&"params"in n)c=n.params.received,l=c;let u=Wte({path:r,code:n.code,expected:a,received:c,enumValues:i,message:n.message,value:c});if(qte(n))s=i?.map((p)=>`"${p}"`).join(", "),o=`Invalid value. Expected one of: ${s}`;else if(Vte(n)){let p=Yte(n.message)??Vn(n.input);if(n.expected==="object"&&p==="null"&&r==="")o="Invalid or malformed JSON";else o=`Expected ${n.expected}, but received ${p}`}else if(ftt(n)){let p=n.keys.join(", ");o=`Unrecognized ${yv(n.keys.length,"field")}: ${p}`}else if(Zte(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 mtt(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=yL(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 htt=new Set(fs);function gtt(e,t){if(!e||typeof e!=="object")return[];return[...oee(e,see)?[{file:t,path:"hooks",message:`PreToolUse/PermissionRequest hooks are declared outside "hooks" (at the top level or under another key) — ${Sc}.`,severity:"fatal",docLink:"https://code.claude.com/docs/en/hooks"}]:[],..._tt(e,t)]}function _tt(e,t){if(!("hooks"in e))return[];if(e.hooks===null||typeof e.hooks!=="object"||Array.isArray(e.hooks)){let o=Vn(e.hooks);if(Array.isArray(e.hooks)&&(e.hooks.some(Ge)||rL(e.hooks)))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o} — ${Sc}.`,invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}];return delete e.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o}. This field was ignored.`,severity:"warning",invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}]}let n=e.hooks;if(OE(n))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received a single matcher — ${Sc}.`,docLink:"https://code.claude.com/docs/en/hooks"}];let r=[];for(let o of Object.keys(n)){let s=bg(o);if(!htt.has(o)){if(_c(n[o],3,{matchersCount:!Array.isArray(n[o])})){r.push({file:t,path:`hooks.${s}`,message:`"${s}" is not a hook event, but it holds PreToolUse/PermissionRequest hooks — ${Sc}.`,docLink:"https://code.claude.com/docs/en/hooks"});continue}delete n[o],r.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${fs.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks",preserveOnWrite:!0});continue}if(!Array.isArray(n[o])){let i=n[o],a=Vn(i);if(vh.has(o)&&i!==null||_c(i,3,{matchersCount:!1})){r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a} — ${Sc}.`,invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks"});continue}delete n[o],r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a}. This entry was ignored.`,severity:"warning",invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks",...i!==null&&{preserveOnWrite:!0}})}}for(let[o,s]of Object.entries(n)){let{stripped:i,unloadableGuards:a}=aee(s,o);for(let c of a)r.push({file:t,path:c.aboutType?`hooks.${o}.${c.path}.type`:`hooks.${o}.${c.path}`,message:`${c.problem} — ${Sc}.${c.aboutType?` Valid types: ${[...kE()].join(", ")}`:""}`,severity:"fatal",invalidValue:c.received,docLink:"https://code.claude.com/docs/en/hooks"});for(let c of i)r.push({file:t,path:c.aboutType?`hooks.${o}.${c.path}.type`:`hooks.${o}.${c.path}`,message:c.aboutType?`${c.problem}; entry ignored. Valid types: ${[...kE()].join(", ")}`:`${c.problem}; ${c.hookIndex===void 0?"matcher":"entry"} ignored.`,severity:"warning",invalidValue:c.received,docLink:"https://code.claude.com/docs/en/hooks",preserveOnWrite:!0})}if(r.length>0&&Object.keys(n).length===0)delete e.hooks;return r}var ytt=[{key:"allowedMcpServers",schema:HE},{key:"deniedMcpServers",schema:BE}];function Stt(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of ytt){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 ${Vn(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 btt(e,t){if(!Ge(e)||e.managedMcpServers===void 0)return[];let r=[],o=CE(e.managedMcpServers,(s,i)=>r.push({file:t,path:s?`managedMcpServers.${s}`:"managedMcpServers",message:s?`Managed MCP server was ignored: ${i}`:i,severity:"warning"}));if(o===void 0)delete e.managedMcpServers;else e.managedMcpServers=o;return r}function Ett(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 xtt(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(pL)}function vtt(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=Vn(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=vL().safeParse(s[a]),l;if(!c.success){let u=Ett(s[a]);if(u!==void 0&&!Aee.has(u)||xtt(s[a]))continue;l=IE(c.error.issues)}else if(c.data.source.source==="settings"&&c.data.source.name!==a)l=`key "${is(a)}" must match the settings source name "${is(c.data.source.name)}"`;if(l!==void 0)i.push({file:t,path:`${r}.${is(a)}`,message:`Invalid marketplace entry was ignored: ${l}`,severity:"warning"}),delete s[a]}return i}function wtt(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!Ge(o)||!Array.isArray(o.options)){let c=Ge(o)?`options: ${Vn(o.options)}`:Vn(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object with an "options" array of { model, label?, description?, behavesAs? } rows; received ${c}. This field was ignored.`,severity:"warning",invalidValue:c}]}let s=[];if("replaceBuiltInOptions"in o&&typeof o.replaceBuiltInOptions!=="boolean"){let c=Vn(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=CL().safeParse(i[c]);if(l.success){a.push(i[c]);continue}s.push({file:t,path:`${r}.options.${c}`,message:`${Ctt(l.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:Vn(i[c])})}if(a.length!==i.length)o.options=a;return s}function Att(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 ${Vn(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!AL().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 ${Vn(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let c of Object.keys(a)){let l=wL().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.${is(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 Ctt(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function Ttt(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||Rtt(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[Ptt(o,t,n?.policySource===!0)]}function Rtt(e){return typeof e==="string"&&Ch.includes(e)}var ktt="crossSessionInbound";function Ott(e){let t=Ch.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${is(e).replace(/^<key>$/,"<value>")}"`:Vn(e);return`must be one of ${t}; received ${n}`}function Ptt(e,t,n=!1){let r=Ch.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:ktt,message:`"crossSessionInbound" ${Ott(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}var Jte="remoteControl.shareHostProfile";function Itt(e,t,n){if(!Ge(e)||e.remoteControl===void 0)return[];let r=n?.policySource===!0,o=jE.map((f)=>`"${f}"`).join(", "),s=r?'In managed settings this is treated as "off" (the most restrictive): Remote Control environments report nothing about this machine until an administrator fixes it.':"While it is present, Remote Control environments report nothing about this machine.",i=(f)=>({file:t,path:Jte,message:`${f}. ${s}`,severity:"warning",expected:o,...r?{statusOnly:!0}:{preserveOnWrite:!0}}),a=(f)=>typeof f==="string"?`"${is(f).replace(/^<key>$/,"<value>")}"`:Vn(f),c=e.remoteControl;if(!Ge(c)){if(r)e.remoteControl={shareHostProfile:"off"};else delete e.remoteControl;return[i(`"remoteControl" must be an object like { "shareHostProfile": ${o.replace(/, /g," | ")} }; received ${a(c)}`)]}let l=[],u=Object.keys(c).filter((f)=>f!=="shareHostProfile");if(u.length>0){if(r)c.shareHostProfile="off";l.push(i(`"remoteControl" has an unrecognized key ${u.map((f)=>`"${is(f)}"`).join(", ")} (its only key is "shareHostProfile")`))}let p=c.shareHostProfile;if(p!==void 0&&!(typeof p==="string"&&jE.includes(p))){if(r)c.shareHostProfile="off";else delete c.shareHostProfile;l.push(i(`"${Jte}" must be one of ${o}; received ${a(p)}`))}return l}function vc(e,t,n){return[...cte(e,t),...mtt(e,t),...gtt(e,t),...vtt(e,t),...wtt(e,t),...Att(e,t),...Ttt(e,t,{policySource:n?.policySource}),...Itt(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:Stt(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly}),...n?.mcpServerEntrySalvageOnly?btt(e,t):[]]}function jL(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),GX.filter((n)=>t.has(n))}function Ntt(){return No(hc(),"managed-settings.json")}function HL(e){if(In()==="wsl"&&e.wslInherits?.()){let t=NL(fd,e.store);if(t.settings)return t;let n=NL(hc(),e.store);return{settings:n.settings,errors:[...t.errors,...n.errors]}}return NL(hc(),e.store)}function Mtt(e){return e.endsWith(".json")&&!e.startsWith(".")}function NL(e,t){let n=[],r={},o=!1,{settings:s,errors:i}=md(No(e,"managed-settings.json"),t,void 0,!0);if(n.push(...i),s&&Object.keys(s).length>0)r=Gn(r,s,Lo),o=!0;let a=No(e,"managed-settings.d");try{let c=t.folderListingForPolicyWalk(a),l;if(c!==void 0)l=c;else l=tt().readdirSync(a).filter((u)=>(u.isFile()||u.isSymbolicLink())&&Mtt(u.name)).map((u)=>u.name).sort(),t.noteWalkListing(a,l);for(let u of l){let{settings:p,errors:f}=md(No(a,u),t,void 0,!0);if(n.push(...f),p&&Object.keys(p).length>0)r=Gn(r,p,Lo),o=!0}}catch(c){let l=Re(c);if(l!=="ENOENT"&&l!=="ENOTDIR")ae(`managed-settings.d read failed: ${c}`,{level:"error"}),n.push(Dh(a,c,"directory"))}return{settings:o&&Ac(r)?r:null,errors:n}}function Utt(e,t){if(rr(e))Htt(t);else ae(`settings file read failed at ${t}: ${e}`,{level:"error"})}function md(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{settings:s.settings?uo(s.settings):null,errors:s.errors};let i=ztt(e,n,r);return t.parsedFiles.set(o,i),{settings:i.settings?uo(i.settings):null,errors:i.errors}}function BL(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 JE(e,t){let n=Xte.get(e),r=n?.get(t);if(r)return{settings:r.settings&&uo(r.settings),errors:r.errors.map((s)=>({...s}))};let o=Ftt(e,t);if(n)n.set(t,o);else Xte.set(e,new Map([[t,o]]));return{settings:o.settings&&uo(o.settings),errors:o.errors.map((s)=>({...s}))}}var Xte=new WeakMap;function Ftt(e,t){let n=uo(e),r=vc(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=kL(sne(t,o),t).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...Ih(s.error,t)]};return{settings:Object.keys(s.data).length>0?s.data:null,errors:[...r,...o]}}function wc(e){return Nte()&&(e==="managedMcpServers"||e.startsWith("managedMcpServers."))}function one(e,t){if(!Ge(e)||!("managedMcpServers"in e))return[];return delete e.managedMcpServers,wc("managedMcpServers")?[]:[{file:t,path:"managedMcpServers",message:'"managedMcpServers" is only honored from managed settings and was ignored here.',severity:"warning"}]}function sne(e,t){return(n)=>{if(wc(n.path))return;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 ine(e){let t=e?.remote?e.remote():Dte(),n=!e?.remote&&!wc("managedMcpServers")&&Ote()?[{file:"remote managed settings",path:"managedMcpServers",message:"The organization's MCP servers in the cached remote settings are withheld until the server confirms them this session; they connect as soon as it does.",severity:"warning",statusOnly:!0}]:[];if(!t||Object.keys(t).length===0)return{settings:null,errors:n,servedSnapshot:!1};let{settings:r,errors:o}=JE(t,"remote managed settings");return{settings:r,errors:[...n,...Gte(o)],servedSnapshot:Rte(t)}}var Qte="parent managed settings";function $tt(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let n=JE(t,Qte);if(n.settings?.managedMcpServers!==void 0&&!wc("managedMcpServers"))n.errors.push({file:Qte,path:"managedMcpServers",message:`"managedMcpServers" is only honored from the organization's managed settings sources (server-managed, MDM, managed-settings.json), not from settings a host passes in, and was ignored here.`,severity:"warning",statusOnly:!0});return n}function ane(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=uo(t),r=[...one(n,"SDK inline settings"),...vc(n,"SDK inline settings")],o=dd().safeParse(n);if(!o.success)return{settings:null,errors:[...r,...Ih(o.error,"SDK inline settings")]};if(r.some((s)=>s.severity==="fatal"))return{settings:null,errors:r};return{settings:o.data,errors:r}}var XE=2097152;function ztt(e,t,n){try{let r;if(t!==void 0)r=t;else{let{resolvedPath:o}=ff(tt(),e);r=fc(o,XE)}return jtt(r,e,n)}catch(r){return Ktt(r,e)}}function jtt(e,t,n){if(e.trim()==="")return{settings:{},errors:[]};let r=uo(mc(e,!1));if(n){if(!Ge(r))return{settings:null,errors:[QE(t)]};let i=vc(r,t,{skipMcpServerEntryFilter:!0,policySource:!0}),a=[],c=kL(sne(t,a),t).safeParse(r);if(!c.success)return{settings:null,errors:[...i,...Ih(c.error,t)]};return{settings:c.data,errors:[...i,...a]}}let o=[...one(r,t),...vc(r,t)],s=dd().safeParse(r);if(!s.success){let i=Ih(s.error,t);return{settings:null,errors:[...o,...i]}}if(o.some((i)=>i.severity==="fatal"))return{settings:null,errors:o};return{settings:s.data,errors:o}}function QE(e,{userWritable:t=!1}={}){return t?{file:e,path:"",message:`Managed settings document (${e}) could not be parsed as a JSON object; none of its settings are in effect. Fix or remove it.`,severity:"warning",statusOnly:!0,userWritable:!0}:{file:e,path:"",message:"Managed settings document could not be parsed as a JSON object; none of its settings are in effect. Fix or remove it.",startupFatal:!0}}function Htt(e){ae(`Broken symlink or missing file encountered for settings.json at path: ${e}`)}function Btt(){return{settings:null,errors:[]}}function Ktt(e,t){if(Utt(e,t),rr(e))return Btt();return{settings:null,errors:[Dh(t,e)]}}function Dh(e,t,n="file"){return{file:e,path:"",message:`${n==="directory"?"Managed settings drop-in directory":"Settings file"} could not be read: ${t instanceof Error?t.message:String(t)}`,severity:"fatal",errorClass:"unreadable"}}function ene(e,t){switch(e){case"userSettings":return to(Wt());case"policySettings":case"projectSettings":return to(t.cwd);case"localSettings":return cne(t.cwd,t.canonicalGitRoot);case"flagSettings":return t.flagPath?Ltt(to(t.flagPath)):to(t.cwd)}}function cne(e,t){let n=Gtt(e,t);if(n.decided!==void 0)return n.decided;if(!qtt(n.root))return n.cwdResolved;return n.root}function Gtt(e,t){let n=t?.(e);if(!n)return{decided:to(e)};let r=to(n),o=to(e);if(r===o)return{decided:r};let s;try{s=Ztt()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function Wtt(e){return pc().localStoreProbes.canonicalRootOwnerUids(e,Vtt)}function Vtt(e){let t=tt(),n=null;try{n=t.lstatSync(No(e,".claude")).uid}catch(r){if(!rr(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:t.lstatSync(No(e,".git")).uid,claudeEntryUid:n}}function qtt(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}=Wtt(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 Ztt(){return pc().localStoreProbes.normalizedRealHomeDir(Ytt)}function Ytt(){let e=Qx(Dtt());if(e===null)throw Error("home directory realpath unavailable");return ot(e)}var tne={default:"settings.json",cowork:"cowork_settings.json"};function Jtt(e){if(e.coworkPlugins||yn.CLAUDE_CODE_USE_COWORK_PLUGINS)return tne.cowork;return tne.default}function Lh(e,t){switch(e){case"userSettings":return No(ene(e,t),Jtt(t));case"projectSettings":case"localSettings":return No(ene(e,t),lne(e));case"policySettings":return Ntt();case"flagSettings":return t.flagPath}}function lne(e){switch(e){case"projectSettings":return No(".claude","settings.json");case"localSettings":return No(".claude","settings.local.json")}}function une(e){if(cne(e.cwd,e.canonicalGitRoot)===to(e.cwd))return;return No(to(e.cwd),lne("localSettings"))}function dne(e,t){let n=t.store.perSource.get(e);if(n!==void 0)return n;let r=vnt(e,t);return t.store.perSource.set(e,r),r}function Xtt(e,t=!1){return!e||e.parentSettingsBehavior==="merge"||t}var Qtt=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function ent(e){let t={};for(let{path:n,restrictive:r}of fh){let o=js(e,n);if(n[0]==="sandbox"&&mh(r).includes(o))qi(t,n,o)}return t.sandbox??{}}var tnt=/^(?:Read|Edit)\((?:\.\/)?!/;function nnt(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.remoteTools?.allowUnattendedServing===!1)n.remoteTools={...n.remoteTools,allowUnattendedServing:!1};if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(e.disableAutoMode==="disable")n.disableAutoMode="disable";let r=e.remoteControl?.shareHostProfile;if(r==="off"||r==="basic")n.remoteControl={...n.remoteControl,shareHostProfile:r};if(Ute(e.attribution,e.includeCoAuthoredBy)==="disabled")n.attribution={...n.attribution,commitTrailers:!1};if(e.attribution?.sessionUrl===!1)n.attribution={...n.attribution,sessionUrl:!1};let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)n.strictPluginOnlyCustomization=o;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 s=Sh(e.permissions,["deny","ask"]);for(let i of["deny","ask"]){let a=s[i];if(a!==void 0)s[i]=a.filter((c)=>{if(!tnt.test(c))return!0;return ae(`Ignoring ${i} rule "${c}" from the parent process's managed settings: a rule starting with "!" removes paths from the rules listed before it instead of restricting anything, so it is not merged into the policy rules. Spell the deny without the exception instead.`,{level:"warn"}),!1})}if(e.permissions.disableBypassPermissionsMode==="disable")s.disableBypassPermissionsMode="disable";if(e.permissions.disableAutoMode==="disable")s.disableAutoMode="disable";if(e.permissions.blockReadsOutsideWorkingDirectories===!0)s.blockReadsOutsideWorkingDirectories=!0;if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:a}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)s.allow=i;if(a)s.additionalDirectories=a}if(Object.keys(s).length>0)n.permissions=s}if(e.sandbox){let{network:s,filesystem:i,credentials:a}=e.sandbox,c={},l=s?Sh(s,["deniedDomains"]):{},u=i?Sh(i,["denyRead","denyWrite"]):{};if(s){if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&s.allowedDomains)l.allowedDomains=s.allowedDomains}if(Object.keys(l).length>0)c.network=l;if(i){if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)u.allowRead=i.allowRead}if(Object.keys(u).length>0)c.filesystem=u;if(a){let p=(a.files??[]).map((h)=>h.mode==="deny"?{path:h.path,mode:"deny"}:{path:h.path,mode:"mask",injectHosts:[]}),f=(a.envVars??[]).filter((h)=>h.mode==="deny").map((h)=>({name:h.name,mode:"deny"})),m={...p.length>0&&{files:p},...f.length>0&&{envVars:f}};if(a.sigv4){let h={};for(let _ of["streaming","presigned","sigv4a"])if(a.sigv4[_]==="deny")h[_]="deny";m.sigv4=h}{let h=pne(a.awsPairs??[],[]);if(h.length>0)m.awsPairs=h}if(Object.keys(m).length>0)c.credentials=m}if(Gn(c,ent(e)),Object.keys(c).length>0)n.sandbox=c}return n}function pne(e,t){let n=Zi,r=new Set(t.flatMap(nne));return Tr(e.flatMap(nne)).filter((o)=>n.includes(o)&&!r.has(o)).map((o,s)=>({accessKeyIdVar:o,secretAccessKeyVar:`${vE}${s+1}_`}))}function nne(e){if(!Ge(e))return[];return[e.accessKeyIdVar,e.secretAccessKeyVar,e.sessionTokenVar].filter((t)=>typeof t==="string")}var rnt=new Set([...[...WD].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...VD,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE"]);function ont(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 YE(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(!rnt.has(n.toUpperCase()))t[n]=r;e.env=t}}function FL(){return In()==="macos"?"plist":"hklm"}function fne(e){let t=GL(e);if(t.composes==="tier")return"helper";let n=$L(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return FL();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 $L(e){let t=[],{settings:n,errors:r,servedSnapshot:o}=ine(e);t.push(...r);let s=GL(e),i=s.composes==="remoteSlot"?s.helper:UL(n),{settings:a,errors:c}=BL(e);t.push(...c);let l=UL(a),{settings:u,errors:p}=e.file?.()??HL(e);t.push(...p);let f=UL(u),{settings:m,errors:h}=$tt(e);t.push(...h);let _=m!==null&&(l===null&&f===null||(l??f)?.parentSettingsBehavior==="merge"),y=[unt(i,o&&s.composes!=="remoteSlot",[l,f,..._?[Sh(m,lnt)]:[]]),l,f].filter((Q)=>Q!==null),v=(s.composes==="remoteSlot"?s.helper:[n,a,u].find((Q)=>Q!==null&&(Q===n&&o?i!==null:Q.managedSourcesBehavior!==void 0||Ac(Q))))?.managedSourcesBehavior,S=i!==null&&o&&s.composes!=="remoteSlot",{admin:x,merged:w}=snt(y,v,S),N={remote:i!==null,mdm:l!==null,file:f!==null},P=[];if(w){let Q=N.remote?"remote":N.mdm?FL():"file",ut=[[l,FL()],[f,"file"]];for(let[De,dt]of ut){if(De===null||De===y[0]||S&&De===y[1])continue;let W=KL.filter((An)=>Object.values(De[An]??{}).some((xt)=>xt!==void 0&&xt!==null)),[qe]=W;if(qe===void 0)continue;P.push(dt),t.push({file:ML[dt],path:qe,message:`${W.map((An)=>`"${An}"`).join(" and ")} in ${ML[dt]} ignored: policy helper configuration is read from the highest managed settings source only (${ML[Q]} here), even with managedSourcesBehavior "merge". Configure the helper in that source instead.`,severity:"warning",statusOnly:!0})}}let F=(Q)=>Q!==null&&(Q===y[0]||Object.keys(yh(Q,bne())).length>0),z={remote:F(i),mdm:F(l),file:F(f)},q={allowManagedPermissionRulesOnly:y.some((Q)=>Q.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:x?.forceLoginOrgUUID,allowedMcpServers:x?.allowedMcpServers,availableModels:x?.availableModels,sandbox:{network:{allowManagedDomainsOnly:y.some((Q)=>Q.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:y.some((Q)=>Q.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},ee=m&&Xtt(x,S&&!N.mdm&&!N.file)?nnt(m,q):null,te=ee&&Object.keys(ee).length>0?ee:null,ve=ont(m,e.hostManagedProvider);return{tiers:y,admin:x,parentSlice:te,hostModelOverlay:ve,errors:t,present:N,merged:w,composed:z,snapshotFirst:S,shadowedHelperSources:P}}function snt(e,t,n){let r=e[0];if(!r)return{admin:null,merged:!1};let{managedSourcesBehavior:o,...s}=r;if(t!=="merge"||e.length<2)return{admin:o===void 0?r:s,merged:!1};let i=e.slice(1).map((c,l)=>{let u=n&&l===0?{...c}:yh(c,bne());if(!(n&&l===0)){for(let f of Qtt)if(js(u,f)!==void 0)qi(u,f,void 0)}let p=js(u.sandbox,["enabledPlatforms"]);if(Array.isArray(p)&&p.includes(In()))qi(u,["sandbox","enabledPlatforms"],void 0);else if(p!==void 0)delete u.sandbox;return u}),a={};for(let c of[...i].reverse())Gn(a,c,zL);return Gn(a,s,n?dnt:zL),pnt(a,[r,...i]),int(a,[r,...i],n),{admin:a,merged:!0}}var mne=["managedSourcesBehavior","wslInheritsWindowsSettings"],KL=["policyHelper","policyHelpers"],ML={remote:"server-managed settings",plist:"the managed preferences plist",hklm:"the HKLM policy key",file:"managed-settings.json"};function Ac(e){return Object.keys(e).some((t)=>!mne.includes(t))}function UL(e){return e&&Ac(e)?e:null}function int(e,t,n){let r=t.findIndex((s)=>s.availableModels!==void 0),o=t.findIndex((s)=>s.modelOverrides!==void 0);if(o!==-1&&(r===-1||o<=r||n&&r===0))e.modelOverrides={...t[o].modelOverrides};else delete e.modelOverrides}var hne=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins"],ant=["awsPairs","ripgrep"];function gne(e,t,n){if(t===void 0)return e;if(Array.isArray(t))return n==="awsPairs"&&Array.isArray(e)?[...t,...pne(e,t)]:[...t];if(!Ge(t))return t;return vd(t,(r)=>Array.isArray(r)?[...r]:r)}var cnt=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedMarketplaces","allowedHttpHookUrls","httpHookAllowedEnvVars"],lnt=["allowedMcpServers","availableModels"];function unt(e,t,n){if(e===null||!t)return e;let r=cnt.filter((o)=>n.some((s)=>s?.[o]!==void 0));return r.length===0?e:yh(e,r)}function zL(e,t,n){if(n!==void 0&&(hne.includes(n)||ant.includes(n)))return gne(e,t,n);return _ne(e,t,n)}function dnt(e,t,n){if(n!==void 0&&hne.includes(n))return gne(e,t,n);return _ne(e,t,n)}function _ne(e,t,n){if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Tr([...t,...e]);return Lo(e,t,n)}function pnt(e,t){let n=t[0],r=e;for(let{path:o,restrictive:s}of fh){let i=mh(s),a=Math.min(...t.map((c)=>i.indexOf(js(c,o))).filter((c)=>c!==-1));if(Number.isFinite(a))qi(r,o,i[a]);else if(js(n,o)===void 0&&js(e,o)!==void 0)qi(r,o,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Tr(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 GL(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=ine(e).settings,o="remote";else if(r=BL(e).settings)o=In()==="macos"?"plist":"hklm";else r=(e.file?.()??HL(e)).settings,o="file";e.store.policy.mergedHelper={helper:gnt(r,t),mergedOver:Object.keys(yne(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function yne(e){return yh(e??{},KL)}function fnt(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)}var mnt=["forceLoginOrgUUID","gatewayInternalNetworks","allowedHttpHookUrls","httpHookAllowedEnvVars","allowRead"];function hnt(e,t,n){let r=n!==void 0&&t!==void 0&&mnt.includes(n)?t:zL(e,t,n);return r===t&&Array.isArray(r)?[...r]:r}function gnt(e,t){let n=yne(e),r=Gn({},n,t,hnt);if(n.env&&t.env)r.env=fnt(n.env,t.env);return r}var Sne=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var _nt=[...Sne,"otelHeadersHelper","proxyAuthHelper","forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","env","modelPicker",...KL,...mne];function bne(){return _nt}function ynt(e){return OQ.some((t)=>e.startsWith(t))||kQ.includes(e)}function Snt(e,t,n,r=0){let o=new Map,s=new Map,i=!1;for(let[a,c]of e.entries()){let l=new Set,u=t?.[a]===!0;for(let[p,f]of Object.entries(c??{})){let m=p.toUpperCase(),h=ynt(m);if(h&&f.trim()==="")continue;if(h&&i)continue;if(h&&a>r&&t?.[a]===!0)continue;let _=o.get(m);if(_!==void 0){if(l.has(m))s.set(p,f);else if(!s.has(p))s.set(p,_);continue}if(a>r&&n?.[a]?.has(m))continue;if(s.set(p,f),l.add(m),o.set(m,f),h)u=!0}if(u)i=!0}return Object.fromEntries(s)}var bnt="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function rne(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==bnt)t[n]=r;return t}function Ent(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function xnt(e){let t=BL(e);return t.settings?t.errors:[...t.errors,...(e.file?.()??HL(e)).errors]}function Ene(e){let t=GL(e),n=(e.helperWarnings?.()??[]).filter((_)=>!wc(_.path));if(t.composes==="tier"){let{helper:_}=t;e.store.lastPolicyEnvComposition=null;let y=e.hostManagedProvider?{..._}:_;if(e.hostManagedProvider)YE(y);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&_.availableModels!==void 0?_.modelOverrides:void 0};let b=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?xnt(e).filter((v)=>!v.statusOnly):[],...$L(e).errors.filter((v)=>v.statusOnly)];return{settings:y,errors:[...b,...n]}}let{tiers:r,admin:o,parentSlice:s,hostModelOverlay:i,errors:a,present:c,snapshotFirst:l}=$L(e);if(a.push(...n),!o&&!s){e.store.lastPolicyEnvComposition=null,e.store.policy.pairedModelOverrides={value:void 0};let _=e.hkcu?.();if(_&&Object.keys(_.settings).length>0){let y=e.hostManagedProvider?{..._.settings}:_.settings;if(e.hostManagedProvider){if(YE(y),i)Object.assign(y,i)}return{settings:y,errors:[...a,..._.errors]}}if(i)return{settings:{...i},errors:[...a,..._?.errors??[]]};return{settings:null,errors:[...a,..._?.errors??[]]}}let u=Gn({},s??{},o??{},Lo);if(r.some((_)=>_.forceRemoteSettingsRefresh===!0))u.forceRemoteSettingsRefresh=!0;let p=yn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,f=u.env;if(!p){let _=Snt(r.map((y)=>y.env),r.map((y)=>(y.otelHeadersHelper??"").trim()!==""),r.map((y)=>{let b=new Set;for(let v of Sne){let S=y[v];if(typeof S==="string"&&S.trim()!=="")for(let x of PQ[v])b.add(x)}return b.size>0?b:void 0}),l?1:0);if(Object.keys(_).length>0)u.env=_;else delete u.env}if(u.env){let _=rne(u.env);if(_&&Object.keys(_).length>0)u.env=_;else delete u.env}if(e.hostManagedProvider){if(YE(u),i)Object.assign(u,i)}let m={env:rne(f)};if(e.hostManagedProvider)YE(m);let h=!p&&!Ent(u.env,m.env);return e.store.lastPolicyEnvComposition={unionOptedOut:p,unionChangedEnv:h,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:pf(r,(_)=>Object.keys(_.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:u,errors:a}}function vnt(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return Ene(t).settings;let r=Lh(e,t),{settings:o}=r?md(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=ane(t);if(s)return Gn(o||{},s,Lo)}if(e==="localSettings"&&n){let s=une(t);if(s){let{settings:i}=md(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),Gn(i,o||{},Lo)}}return o}function wnt(e,t){return{...e,...t}}function Lo(e,t,n){if(n==="modelPicker"&&t!==void 0)return xne(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Tr([...e,...t])}if((n==="extraKnownMarketplaces"||n==="managedMcpServers")&&Ge(e)&&Ge(t))return wnt(e,t);return}function xne(e){if(!Ge(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>Ge(n)?{...n}:n)}}}function Ant(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();uh("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=Gn(r,n,Lo);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 jL(e)){if(l==="policySettings"){let{settings:p,errors:f}=Ene(e);if(c=p,p)r=Gn(r,p,Lo);a(f);continue}if(l==="localSettings"){let p=une(e);if(p&&!i.has(to(p))){i.add(to(p));let{settings:f,errors:m}=md(p,e.store);if(a(m),f)e.onLegacyLocalSettingsRead?.("cascade"),r=Gn(r,f,Lo)}}let u=Lh(l,e);if(u){let p=to(u),f=l==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(p)||f){i.add(p);let{settings:m,errors:h}=md(u,e.store,l==="flagSettings"?e.flagExpectedContent:void 0);if(a(h),m)r=Gn(r,m,Lo)}}if(l==="flagSettings"){let{settings:p,errors:f}=ane(e);if(a(f),p)r=Gn(r,p,Lo)}}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=xne(c.modelPicker)}return uh("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 Cnt(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=Ant(e);return e.store.mergedSettings=n,n}function Tnt(e){let{settings:t}=Cnt(e);return t||{}}function vne(e){e.store.invalidateAll();let t=[];for(let n of jL(e)){let r=dne(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:Tnt(e),sources:t}}function wne(e,t){let n=jL(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(dne(o,t)?.[e]!==void 0)return o}return null}import{execFile as Rnt}from"child_process";import{accessSync as knt,closeSync as Ont,constants as Pnt,openSync as Int,readSync as Dnt}from"fs";class Rne{promise=null;start(){if(this.promise)return;this.promise=VL()}reset(){this.promise=null}}var Lnt=new Rne;function Nnt(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 WL(e,t,n){let r=Date.now();return new Promise((o)=>{try{Rnt(e,t,{encoding:"utf-8",timeout:jte,windowsHide:!0,...n!==void 0&&{maxBuffer:n}},(s,i)=>{o({stdout:i??"",...Nnt(s),durationMs:Date.now()-r})})}catch(s){let i=s.code;o({stdout:"",status:"spawn_error",exitCode:null,errno:typeof i==="string"?i:null,signal:null,durationMs:Date.now()-r})}})}function Ane(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function Cne(e){return e.status==="ok"||e.status==="exited"&&e.exitCode!==null}function Mnt(e){return e.status==="spawn_error"&&e.errno==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}function Unt(e){let t;try{return t=Int(e,"r"),Dnt(t,Buffer.alloc(1),0,1,0),null}catch(n){return{code:n&&typeof n==="object"&&"code"in n?n.code:void 0,message:n instanceof Error?n.message:String(n)}}finally{if(t!==void 0)try{Ont(t)}catch{}}}function VL(){return(async()=>{if(process.platform==="darwin"){let e=Bte(),n=(await Promise.all(e.map(async({path:o,...s})=>{try{knt(o,Pnt.R_OK)}catch(l){let u=l&&typeof l==="object"&&"code"in l?l.code:void 0;if(u==="ENOENT"||u==="ENOTDIR")return null;return{stdout:null,unreadReason:l instanceof Error?l.message:String(l),...s}}let i=await WL(LL,[...$te,o],ZE);if(!Cne(i))return{stdout:null,unreadReason:"plutil did not finish converting it",...s};if(i.status==="ok")return{stdout:i.stdout,...s};let a=await WL(LL,[...zte,o]);if(!Cne(a))return{stdout:null,unreadReason:"plutil did not finish checking it",...s};if(a.status==="ok")return{stdout:null,unreadReason:"it holds a value plutil cannot convert to JSON (a date or data value)",...s};let c=Unt(o);if(c!==null){if(c.code==="ENOENT"||c.code==="ENOTDIR")return null;return{stdout:null,unreadReason:c.message,...s}}return{stdout:"",...s}}))).filter((o)=>o!==null),r=n.findIndex((o)=>o.stdout!==null);return{plistStdouts:r===-1?n:n.slice(0,r+1),hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`;return Tne(t)}if(Oh())return Tne(Hte);return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}async function Tne(e){let t=(o)=>WL(e,["query",o,"/v",kh],ZE),[n,r]=await Promise.all([t(VE),t(qE)]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,...Mnt(n)&&{hklmUnreadReason:`the value exceeds ${ZE/1048576} MiB`},hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:Ane(n),hkcu:Ane(r)}}}function kne(){return Lnt.promise}var Bs=Object.freeze({settings:{},errors:[]});class Une{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await(kne()??VL()),{mdm:o,hkcu:s,wslInherits:i}=await qnt(r,e);this.replace(o,s,i);let a=Date.now()-t;ae(`MDM settings load completed in ${a}ms`);try{Ri("tengu_managed_settings_os_read",Vnt(r,a))}catch{}if(Object.keys(o.settings).length>0){ae(`MDM settings found: ${Object.keys(o.settings).join(", ")}`);try{uh("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 One="@builtin",Fnt=["prependPlugins","appendPlugins"];function $nt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var znt=new Je(()=>new Une);function Nh(){return znt.of(Cn().host)}function jnt(e){Nh().startLoad(e)}async function Fne(){let e=Nh();if(!e.loadPromise)jnt();await e.loadPromise}function $ne(){return Nh().mdm??Bs}function zne(){return Nh().hkcu??Bs}function jne(){return Nh().wslInherits}function qL(e,t,{userWritable:n=!1}={}){let r=mc(e,!1);if(!Ge(r))return{settings:{},errors:[QE(t,{userWritable:n})]};let o=[],s=r;if(n&&"managedMcpServers"in r){if(s={...r},delete s.managedMcpServers,!wc("managedMcpServers"))o.push({file:t,path:"managedMcpServers",message:`"managedMcpServers" is only honored from administrator-controlled managed settings and was ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}if(n){for(let u of Fnt){if(!(u in s))continue;s=s===r?{...r}:s,delete s[u],o.push({file:t,path:u,message:`"${u}" is only honored from administrator-controlled managed settings and was ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}let l=s.enabledPlugins;if($nt(l)){if(Object.entries(l).filter(([p,f])=>p.endsWith(One)||f!==!1).length>0){s=s===r?{...r}:s;let p=aE(l,(f,m)=>!m.endsWith(One)&&f===!1);if(Object.keys(p).length>0)s.enabledPlugins=p;else delete s.enabledPlugins;o.push({file:t,path:"enabledPlugins",message:`"enabledPlugins" entries that enable a plugin, or name a built-in, are only honored from administrator-controlled managed settings and were ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}}}let{settings:i,errors:a}=JE(s,t),c=[...o,...a];return{settings:i??{},errors:n?c.map((l)=>({...l.severity==="warning"&&!l.startupFatal?l:{...Hnt(l),severity:"warning",statusOnly:!0},userWritable:!0})):c}}function Hnt({startupFatal:e,...t}){return t}function Pne(e,t,n){return{file:e,path:"",message:`Managed settings document (${e}) could not be read: ${t}; none of its settings are in effect.`,severity:n?"warning":"fatal",statusOnly:!0,errorClass:"unreadable",...n&&{userWritable:!0}}}function Ine(e,t="Settings"){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^[ \\t]+${n}[ \\t]+REG_(?:EXPAND_)?SZ[ \\t]+([\\s\\S]*)`,"im"),o=e.match(r)?.[1]?.trimEnd();return o?o:null}var Bnt=new Map([["ENOENT",_n("ENOENT")],["EACCES",_n("EACCES")],["EPERM",_n("EPERM")],["ENOEXEC",_n("ENOEXEC")],["EAGAIN",_n("EAGAIN")],["EMFILE",_n("EMFILE")],["ENOMEM",_n("ENOMEM")],["ETIMEDOUT",_n("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",_n("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),Knt=new Map([["SIGTERM",_n("SIGTERM")],["SIGKILL",_n("SIGKILL")],["SIGINT",_n("SIGINT")]]);function Gnt(e){if(!e)return;return Bnt.get(e)??_n("other")}function Wnt(e){if(!e)return;return Knt.get(e)??_n("other")}function Dne(e,t){if(!t)return{};return{[`${e}_status`]:hi(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:Gnt(t.errno),[`${e}_signal`]:Wnt(t.signal),[`${e}_duration_ms`]:t.durationMs}}function Vnt(e,t){return{is_wsl:Oh(),await_ms:t,...Dne("hklm",e.outcomes.hklm),...Dne("hkcu",e.outcomes.hkcu)}}async function qnt(e,t){let n=[];for(let c of e.plistStdouts??[]){let{label:l,userWritable:u}=c;if(c.stdout===null){n.push(Pne(l,c.unreadReason,u));continue}let p=qL(c.stdout,l,{userWritable:u});if(Ac(p.settings))return{mdm:{settings:p.settings,errors:[...n,...p.errors],...u&&{userWritable:u}},hkcu:Bs,wslInherits:!1};n.push(...p.errors)}let r=`Registry: ${VE}\\${kh}`,o=null;if(e.hklmStdout!==null)o=qL(Ine(e.hklmStdout)??"",r);else if(e.hklmUnreadReason!==void 0)n.push(Pne(r,e.hklmUnreadReason,!1));if(o)n.push(...o.errors);let s=Oh(),i=!1;if(s){if(i=o?.settings.wslInheritsWindowsSettings===!0,!i){let c=await Ynt(t);if(i=c.flag,!i)n.push(...c.records)}}let a=n.length>0?{settings:{},errors:n}:Bs;if(s&&!i){let c=new Set(o?.errors.filter((l)=>l.severity==="warning"));return{mdm:n.length>0?{settings:{},errors:n.map((l)=>c.has(l)?{...l,wslIgnored:!0}:l)}:Bs,hkcu:Bs,wslInherits:!1}}if(o){if(Ac(o.settings))return{mdm:o,hkcu:Bs,wslInherits:i}}if(await Znt(i,t))return{mdm:a,hkcu:Bs,wslInherits:i};if(e.hkcuStdout!==null){let c=qL(Ine(e.hkcuStdout)??"",`Registry: ${qE}\\${kh}`,{userWritable:!0});if(!s||c.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:l,managedSourcesBehavior:u,...p}=c.settings;return{mdm:a,hkcu:{settings:p,errors:c.errors},wslInherits:i}}if(c.errors.length>0)return{mdm:a,hkcu:{settings:{},errors:c.errors},wslInherits:i}}return{mdm:a,hkcu:Bs,wslInherits:i}}async function Hne(e,t){if(ye()&&t!==void 0)return(await o7(e,XE)).content;return fc(e,XE)}async function Bne(e,t){if(ye()&&t!==void 0)return await tt().readdir(e);return tt().readdirSync(e)}async function Znt(e,t){if(e&&await Mne(fd,t))return!0;return Mne(hc(),t)}async function Lne(e,t){let n=uo(mc(await Hne(e,t),!1));if(!n||typeof n!=="object")return!1;return vc(n,e,{skipMcpServerEntryFilter:!0,policySource:!0}),Ac(n)}function Nne(e){let t=Re(e);return t==="ENOENT"||t==="ENOTDIR"}async function Ynt(e){let t=[];async function n(s){let i;try{i=await Hne(s,e)}catch(c){if(!Nne(c))t.push(Dh(s,c));return!1}if(i.trim()==="")return!1;let a=mc(i,!1);if(!Ge(a))return t.push(QE(s)),!1;return a.wslInheritsWindowsSettings===!0}if(await n(hd(fd,"managed-settings.json")))return{flag:!0,records:t};let r=hd(fd,"managed-settings.d"),o;try{o=await Bne(r,e)}catch(s){if(!Nne(s))t.push(Dh(r,s,"directory"));return{flag:!1,records:t}}for(let s of o)if((s.isFile()||s.isSymbolicLink())&&s.name.endsWith(".json")&&!s.name.startsWith(".")&&await n(hd(r,s.name)))return{flag:!0,records:t};return{flag:!1,records:t}}async function Mne(e,t){try{if(await Lne(hd(e,"managed-settings.json"),t))return!0}catch{}try{let n=hd(e,"managed-settings.d"),r=await Bne(n,t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(await Lne(hd(n,o.name),t))return!0}catch{}}}catch{}return!1}var Xnt={user:"userSettings",project:"projectSettings",local:"localSettings"},Kne={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},Qnt=["user","project","local"],ert=new Set(["bypassPermissions","auto","acceptEdits"]),trt=new Set(["project"]),nrt=new Set(["project","local"]);function rrt(e){let t=e.effective.permissions?.defaultMode;if(!t||!ert.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((WX.includes(t)?nrt:trt).has(r.source)){let{defaultMode:s,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}async function Gne(e={}){await Fne();let t={store:new ng,cwd:Jnt(e.cwd??tt().cwd()),allowedSources:(e.settingSources??Qnt).map((a)=>Xnt[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:$ne,hkcu:zne,wslInherits:jne,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=vne(t),o=fne(t)??void 0,s=r.map(({source:a,settings:c})=>({source:Kne[a],settings:c,path:a==="policySettings"?void 0:Lh(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let c=wne(a,t);if(c)i[a]={source:Kne[c],path:c==="policySettings"?void 0:Lh(c,t),...c==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function BJt(e){return Gne(e)}var hrt=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function Wne(e){let t;try{t=ft(vu(e.toString("utf8")))}catch{return e}if(!Vne(t))return e;let n=!1;for(let o of hrt)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(Vne(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?me(t):e}function Vne(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function grt(e,t){if(!e)return;let n=e;try{let r=ft(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=me(r)}catch{}await Jne(t,n,{mode:384})}function _rt(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=GZ(KZ);return new Promise((t)=>{ort("security",["find-generic-password","-a",WZ(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function ere(e,t,n,r,o=60000,s){if(!Xe(t))return;let i=no(n,r),a=await Ur(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=wn(urt(),`claude-resume-${QL()}`);try{let l=wn(c,"projects",i);await ZL(l,{recursive:!0,mode:448});let u=wn(l,`${t}.jsonl`);await rm(u,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??wn(YL(),".claude"),m;try{m=await Yne(wn(f,".credentials.json"),"utf-8")}catch(b){if(!rr(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await _rt()??m;await grt(m,wn(c,".credentials.json"));let h=BZ(yn.CLAUDE_CONFIG_DIR),_=wn(p??YL(),".claude.json");await qS(_,wn(c,".claude.json"),void 0,eI(s,_,h.globalConfig,tn.globalConfig()));let y=wn(f,"settings.json");if(await qS(y,wn(c,"settings.json"),Wne,eI(s,y,h.userSettings,tn.userSettings())),await qS(wn(f,"cowork_settings.json"),wn(c,"cowork_settings.json"),Wne),e.listSubkeys)await yrt(e,{projectKey:i,sessionId:t},wn(l,t),o);return c}catch(l){throw await ex(c),l}}async function yrt(e,t,n,r){let o=await Ur(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=Mh(n,s+".jsonl");if(!s||Xne(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+e0)){ae(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Ur(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(XL(u))c.push(u);else l.push(u);if(l.length>0)await ZL(JL(i),{recursive:!0}),await rm(i,l);if(c.length>0){let u=c.at(-1),p=Mh(n,s+".meta.json");await ZL(JL(p),{recursive:!0});let{type:f,...m}=u;await Jne(p,me(m),{mode:384})}}}function t0(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,h;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="custom")p=s.prompt,h=s.snapshot;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections,h=s.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.269";let{abortController:_=Td(),additionalDirectories:y=[],agent:b,agents:v,allowedTools:S=[],betas:x,canUseTool:w,continue:N,cwd:P,debug:F,debugFile:z,disallowedTools:q=[],tools:ee,env:te,executable:ve=el()?"bun":"node",executableArgs:Q=[],extraArgs:ut={},fallbackModel:De,enableFileCheckpointing:dt,toolConfig:W,forkSession:qe,hooks:An,includeHookEvents:xt,includePartialMessages:ce,forwardSubagentText:re,onElicitation:$e,onUserDialog:nt,supportedDialogKinds:ie,perTaskStopAffordance:_t,workspaceTrust:rt,persistSession:ct,sessionStore:on,sessionStoreFlush:as,thinking:pt,effort:Uh,maxThinkingTokens:nx,maxTurns:are,maxBudgetUsd:cre,taskBudget:lre,mcpServers:r0,model:ure,outputFormat:o0,permissionMode:dre,allowDangerouslySkipPermissions:pre=!1,permissionPromptToolName:fre,permissionPrompts:mre,plugins:Fh,pluginDelivery:rx="argv",getOAuthToken:s0,getHostAuthToken:i0,workload:a0,resume:c0,resumeSessionAt:hre,resumeDropsTurn:gre,sessionId:_re,skills:l0,stderr:yre,strictMcpConfig:Sre}=u,u0=dre??(e?.resolvePermissionModeInCli?void 0:"default");if(on&&ct===!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(ie!==void 0&&ie.length>0&&!nt)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let d0=rt?.accepted===!0&&(typeof rt.directory!=="string"||!(drt.isAbsolute(rt.directory)||prt.isAbsolute(rt.directory)))?void 0:rt;if(rt!==void 0&&d0===void 0)ae("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});if(on&&N&&!c0&&!on.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(on&&dt)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(on&&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"});if(qZ(!!w,u0??"default",S),rx!=="argv"&&rx!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let p0=rx==="initialize"&&Fh!==void 0&&Fh.length>0,ox=u.pathToClaudeCodeExecutable;if(!ox){let Nn=mrt(import.meta.url),qn=lrt(Nn),Mo=sG((Cc)=>qn.resolve(Cc));if(!Mo)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.`);ox=Mo}let f0=o0?.type==="json_schema"?o0.schema:void 0,sn=te?{...te}:{...process.env};if(!sn.CLAUDE_CODE_ENTRYPOINT)sn.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!sn.CLAUDE_AGENT_SDK_VERSION)sn.CLAUDE_AGENT_SDK_VERSION="0.3.269";if(dt)sn.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(s0)sn.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(i0)sn.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(W?.askUserQuestion?.previewFormat)sn.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=W.askUserQuestion.previewFormat;for(let[Nn,qn]of[[W?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[W?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"]])if(Nn)sn[qn]="1";else if(!te){for(let Mo of Object.keys(sn))if(Mo.toUpperCase()===qn)delete sn[Mo]}let sx={};if(tx.propagation.inject(tx.context.active(),sx),"traceparent"in sx){for(let Nn of["TRACEPARENT","TRACESTATE"])if(!(Nn in(te??{})))delete sn[Nn]}for(let[Nn,qn]of Object.entries(sx)){let Mo=Nn.toUpperCase();if(!(Mo in(te??{})))sn[Mo]=qn}let m0={},h0=new Map;if(r0)for(let[Nn,qn]of Object.entries(r0))if(qn.type==="sdk"&&qn.instance)h0.set(Nn,qn);else m0[Nn]=qn;let gd;if(pt)switch(pt.type){case"adaptive":gd={type:"adaptive",display:pt.display};break;case"enabled":gd={type:"enabled",budgetTokens:pt.budgetTokens,display:pt.display};break;case"disabled":gd={type:"disabled"};break}else if(nx!==void 0)gd=nx===0?{type:"disabled"}:{type:"enabled",budgetTokens:nx};if(r){if(sn.CLAUDE_CONFIG_DIR=r,process.platform==="win32")sn.CLAUDE_SECURESTORAGE_CONFIG_DIR=te?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??te?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let g0=new pR({abortController:_,additionalDirectories:y,agent:b,betas:x,cwd:P,debug:F,debugFile:z,executable:ve,executableArgs:Q,extraArgs:a0?{...ut,workload:a0}:ut,pathToClaudeCodeExecutable:ox,env:sn,forkSession:qe,stderr:yre,thinkingConfig:gd,effort:Uh,maxTurns:are,maxBudgetUsd:cre,taskBudget:lre,model:ure,fallbackModel:De,jsonSchema:f0,permissionMode:u0,allowDangerouslySkipPermissions:pre,permissionPromptToolName:fre,permissionPrompts:mre,continueConversation:on?void 0:N,resume:c0,resumeSessionAt:hre,resumeDropsTurn:gre,sessionId:_re,settings:typeof i==="object"?me(i):i,managedSettings:a?me(a):void 0,settingSources:c,skills:l0,allowedTools:S,disallowedTools:q,tools:ee,mcpServers:m0,strictMcpConfig:Sre,canUseTool:!!w,hooks:!!An,includeHookEvents:xt,includePartialMessages:ce,persistSession:ct,sessionMirror:!!on,plugins:Fh,pluginsViaInitialize:p0,sandbox:l,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),bre={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:u.planModeInstructions,systemPromptSnapshot:h,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:v,title:u.title,skills:l0,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:re,supportedDialogKinds:ie,perTaskStopAffordance:_t,workspaceTrust:d0,plugins:p0?Fh:void 0},ix=new Wy(g0,n,w,An,_,h0,f0,bre,$e,s0,i0,nt);if(on){let Nn=()=>wn(sn.CLAUDE_CONFIG_DIR??wn(YL(),".claude"),"projects"),qn=as==="eager",Mo=new gR(async(Cc,ax)=>{let _d=Zne(Cc,Nn());if(_d)await on.append(_d,ax);else ae(`[SessionStore] dropping mirror frame: filePath ${Cc} is not under ${Nn()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Cc,ax)=>{let _d=Zne(Cc,Nn());if(_d)ix.reportMirrorError(_d,ax.message)},maxPendingEntries:qn?0:Vy,maxPendingBytes:qn?0:_u});ix.setTranscriptMirrorBatcher(Mo)}return{queryInstance:ix,transport:g0,abortController:_,processEnv:sn}}function n0(e,t,n,r){if(typeof n==="string")t.write(me({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
|
|
221
|
+
`)?0:1)}}function Het(e){return im(me(e))}function Bet(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 me([e.command,...t])}function Ket(e){return xc(Ste(e))}function Ste(e){return{shellSettings:e.shellSettings,envVars:e.envVars,sandboxSettings:Object.keys(e.sandboxSettings).length>0?e.sandboxSettings:void 0,hooks:e.hooks,payloadSlots:PL(e).length>0?Object.fromEntries(PL(e)):void 0}}function xc(e){return me(GE(e))}function bte(e){return im(Ket(e))}function Ete(e,t,n){if(bte(t)===e)return!0;return typeof n==="string"&&n.length>0&&im(xc({...Ste(t),claudeMd:n}))===e}function ute(e,t,n){return me([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}var Get=new Set(["dns","unix","ipv4","ipv6"]),AZt=new Set([...Get,"http","https","ws","wss","ftp","file","grpc","grpcs","otlp","xds","tcp","udp","tls","h2","h2c","http2"]);function xte(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function Wet(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of OL){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var Vet="remote-settings.json";var Ate="remote-settings-helper-consent";function qet(){return wte(Wt(),Ate)}function Zet(e){let t=dte(e);return yte(t)?t:void 0}function Yet(e){return bh(e,(t,n)=>n.startsWith("$")&&n!=="$schema")}class Cte{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;ineligibleReason=void 0;evalPolicySnapshotOnly=!1;lastLoadStatus=void 0;lastLoadStatusChanged=Tt();policySettingsNotified=!1;verifiedPayload=null;unverifiedView=null;projectedView=null;consentedPayload=null;deferredPayload=null;resetEpoch=0;backendView=void 0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified){if(this.verifiedPayload=e,t.consentDeferred)this.deferredPayload=e}}seedFromDisk(e){this.sessionCache=e;let t=Zet(e);if(t!==void 0){let n=ntt();if(n===void 0||!Ete(n,t,e.claudeMd))return}this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}dropConsentDeferral(){this.deferredPayload=null}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.evalPolicySnapshotOnly=!1,this.lastLoadStatus=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,this.unverifiedView=null,this.projectedView=null,this.consentedPayload=null,this.deferredPayload=null,this.resetEpoch++,this.emitLoadStatusChanged(void 0)}emitLoadStatusChanged(e){try{this.lastLoadStatusChanged.emit(e)}catch(t){ae(`Remote settings: load-status listener threw: ${Kr(t)}`,{level:"error"})}}}var Jet=new Je(()=>new Cte);function pd(){return Jet.of(Cn().host)}function WE(){return}function Tte(){return pd().evalPolicySnapshotOnly}function Rte(e){return e!==null&&pd().projectedView?.view===e}function Xet(e){return e&&Tte()?{...wQ(e),managedSourcesBehavior:"merge"}:e}function Qet(){return WE()??wte(Wt(),Vet)}var kte=8388608;function ett(){try{let e=rtt();if(e===null)return null;let t=ft(vu(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return Yet(t)}catch(e){if(t7(e))ae(`Remote settings: Disk cache exceeds ${kte} bytes; ignoring it as if absent`);return null}}var ttt=4096;function ntt(){let e=DL();if(e!==void 0)return e.attestation;try{return fc(qet(),ttt).trim()||void 0}catch{return}}function rtt(){let e=DL();if(e!==void 0)return e.content;return fc(Qet(),kte)}function DL(){let e=pd().backendView;if(!ye()||e===void 0||!e.ready||e.stoodDown||WE()!==void 0)return;if(!dU(e.configHome)){e.standDown("config home changed");return}return e}var JZt=tn.state("remote-settings"),XZt=tn.state(Ate);var ott=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",...BD,...KD,"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",...qD,...ZD,...YD,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...GD,"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 stt(e){if(!e||!e.env&&!("managedMcpServers"in e))return e;let{managedMcpServers:t,...n}=e;return e.env?{...n,env:bh(e.env,(r,o)=>ott.has(o.toUpperCase()))}:n}function Ote(){let e=Ite();if(e===null||Pte(pd(),e))return!1;if(vte(e))return!0;let t=IL(e);if(t.length===0)return!1;let{chain:n}=ate();return t.some(([r,o])=>{let s=fte(r);return(s===void 0||n.includes(s))&&vte(o)})}function vte(e){let t=e.managedMcpServers;return Ge(t)&&Object.keys(t).length>0}function Pte(e,t){return t===e.verifiedPayload||Boolean(WE())}function Ite(){let e=pd();if(!WE()&&e.eligible!==!0)return null;if(e.sessionCache)return e.sessionCache;let t=DL()!==void 0,n=ett();if(n){if(e.seedFromDisk(n),t)pc().invalidatePolicyLayer();else KX();return n}return null}function Dte(){let e=Ite(),t=pd(),n=Pte(t,e)?e:itt(t,e);if(n===null||!Tte())return n;if(t.projectedView?.raw!==n)t.projectedView={raw:n,view:Xet(n)};return t.projectedView.view}function itt(e,t){if(t===null)return null;if(e.unverifiedView?.raw!==t)e.unverifiedView={raw:t,view:stt(t)};return e.unverifiedView.view}var Lte={cli:!0,mcp:!0,"sdk-cli":!0,"sdk-ts":!0,"sdk-py":!0,bench:!0,"claude-vscode":!0,"claude-code-github-action":!0,"local-agent":!0,local_agent:!0,"claude-desktop":!0,remote:!0,remote_baku:!0,remote_cowork:!0,remote_trigger:!0,remote_cowork_trigger:!0,remote_desktop:!0,remote_mobile:!0,claude_in_slack:!0,"claude-in-slack":!0,"claude-in-teams":!0,"claude-desktop-3p":!0,"claude-security":!0,"ssh-remote":!0,"claude-coworker":!0,"claude-coworker-terminal":!0};var a9t=new Set(Object.keys(Lte));var att=new Set(["claude-desktop-3p","local-agent"]);function Nte(){let e=yn.CLAUDE_CODE_ENTRYPOINT;return e!==void 0&&att.has(e)}class Mte{entrypoint=void 0;interactive=!1;spawnedByAttendedSession=void 0;childSession=!1;claudecode=!1;coworkFrameArtifacts=!1;setEntrypoint(e){this.entrypoint=e}setInteractive(e){this.interactive=e}setSpawnedByAttendedSession(e){this.spawnedByAttendedSession=e}setChildSession(e){this.childSession=e}setClaudecode(e){this.claudecode=e}setCoworkFrameArtifacts(e){this.coworkFrameArtifacts=e}}var c9t=new Je(()=>new Mte);function ctt(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function Ute(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&ctt(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{userInfo as ltt}from"os";var Fte="com.anthropic.claudecode",VE="HKLM\\SOFTWARE\\Policies\\ClaudeCode",qE="HKCU\\SOFTWARE\\Policies\\ClaudeCode",kh="Settings",LL="/usr/bin/plutil",$te=["-convert","json","-o","-","--"],zte=["-lint","-s","--"],jte=5000,ZE=2097152,Hte="/mnt/c/Windows/System32/reg.exe",fd="/mnt/c/Program Files/ClaudeCode";function Oh(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=we("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function Bte(){let e="";try{e=ltt().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${Fte}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${Fte}.plist`,label:"device-level managed preferences"}),t}var Kte=512;function Gte(e){return e.map(utt)}function utt(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,errorClass:i,preserveOnWrite:a,mcpErrorMetadata:c,userWritable:l,wslIgnored:u,path:p,message:f,expected:m,suggestion:h,invalidValue:_,...y}=e,b=y;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,errorClass:i,preserveOnWrite:a,mcpErrorMetadata:c,userWritable:l,wslIgnored:u,path:Ph(p),message:Ph(f),expected:m===void 0?void 0:Ph(m),suggestion:h===void 0?void 0:Ph(h),invalidValue:typeof _==="string"?Ph(_):void 0}}function Ph(e){let t=xte(e.replace(/\s+/gu," "));return t.length>Kte?`${t.slice(0,Kte-1)}…`:t}var Hs="https://code.claude.com/docs/en",dtt=[{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:`${Hs}/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:`${Hs}/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:`${Hs}/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:`${Hs}/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:`${Hs}/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:`${Hs}/iam#working-directories`}}],ptt={permissions:`${Hs}/iam#configuring-permissions`,env:`${Hs}/settings#environment-variables`,hooks:`${Hs}/hooks`};function Wte(e){let t=dtt.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=ptt[Sv(e.path,".")];return n}var B9t=L(()=>KE(Ah(),{strictPolicyHelperKeys:!0}).strict());function Vte(e){return e.code==="invalid_type"}function qte(e){return e.code==="invalid_value"}function ftt(e){return e.code==="unrecognized_keys"}function Zte(e){return e.code==="too_small"}function Vn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function Yte(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Ih(e,t){return e.issues.map((n)=>{let r=n.path.map(String).join("."),o=n.message,s,i,a,c,l;if(qte(n))i=n.values.map((p)=>String(p)),a=i.join(" | "),c=void 0,l=void 0;else if(Vte(n)){a=n.expected;let p=Yte(n.message);c=p??Vn(n.input),l=p??Vn(n.input)}else if(Zte(n))a=String(n.minimum);else if(n.code==="custom"&&"params"in n)c=n.params.received,l=c;let u=Wte({path:r,code:n.code,expected:a,received:c,enumValues:i,message:n.message,value:c});if(qte(n))s=i?.map((p)=>`"${p}"`).join(", "),o=`Invalid value. Expected one of: ${s}`;else if(Vte(n)){let p=Yte(n.message)??Vn(n.input);if(n.expected==="object"&&p==="null"&&r==="")o="Invalid or malformed JSON";else o=`Expected ${n.expected}, but received ${p}`}else if(ftt(n)){let p=n.keys.join(", ");o=`Unrecognized ${yv(n.keys.length,"field")}: ${p}`}else if(Zte(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 mtt(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=yL(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 htt=new Set(fs);function gtt(e,t){if(!e||typeof e!=="object")return[];return[...oee(e,see)?[{file:t,path:"hooks",message:`PreToolUse/PermissionRequest hooks are declared outside "hooks" (at the top level or under another key) — ${Sc}.`,severity:"fatal",docLink:"https://code.claude.com/docs/en/hooks"}]:[],..._tt(e,t)]}function _tt(e,t){if(!("hooks"in e))return[];if(e.hooks===null||typeof e.hooks!=="object"||Array.isArray(e.hooks)){let o=Vn(e.hooks);if(Array.isArray(e.hooks)&&(e.hooks.some(Ge)||rL(e.hooks)))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o} — ${Sc}.`,invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}];return delete e.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o}. This field was ignored.`,severity:"warning",invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}]}let n=e.hooks;if(OE(n))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received a single matcher — ${Sc}.`,docLink:"https://code.claude.com/docs/en/hooks"}];let r=[];for(let o of Object.keys(n)){let s=bg(o);if(!htt.has(o)){if(_c(n[o],3,{matchersCount:!Array.isArray(n[o])})){r.push({file:t,path:`hooks.${s}`,message:`"${s}" is not a hook event, but it holds PreToolUse/PermissionRequest hooks — ${Sc}.`,docLink:"https://code.claude.com/docs/en/hooks"});continue}delete n[o],r.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${fs.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks",preserveOnWrite:!0});continue}if(!Array.isArray(n[o])){let i=n[o],a=Vn(i);if(vh.has(o)&&i!==null||_c(i,3,{matchersCount:!1})){r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a} — ${Sc}.`,invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks"});continue}delete n[o],r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a}. This entry was ignored.`,severity:"warning",invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks",...i!==null&&{preserveOnWrite:!0}})}}for(let[o,s]of Object.entries(n)){let{stripped:i,unloadableGuards:a}=aee(s,o);for(let c of a)r.push({file:t,path:c.aboutType?`hooks.${o}.${c.path}.type`:`hooks.${o}.${c.path}`,message:`${c.problem} — ${Sc}.${c.aboutType?` Valid types: ${[...kE()].join(", ")}`:""}`,severity:"fatal",invalidValue:c.received,docLink:"https://code.claude.com/docs/en/hooks"});for(let c of i)r.push({file:t,path:c.aboutType?`hooks.${o}.${c.path}.type`:`hooks.${o}.${c.path}`,message:c.aboutType?`${c.problem}; entry ignored. Valid types: ${[...kE()].join(", ")}`:`${c.problem}; ${c.hookIndex===void 0?"matcher":"entry"} ignored.`,severity:"warning",invalidValue:c.received,docLink:"https://code.claude.com/docs/en/hooks",preserveOnWrite:!0})}if(r.length>0&&Object.keys(n).length===0)delete e.hooks;return r}var ytt=[{key:"allowedMcpServers",schema:HE},{key:"deniedMcpServers",schema:BE}];function Stt(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of ytt){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 ${Vn(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 btt(e,t){if(!Ge(e)||e.managedMcpServers===void 0)return[];let r=[],o=CE(e.managedMcpServers,(s,i)=>r.push({file:t,path:s?`managedMcpServers.${s}`:"managedMcpServers",message:s?`Managed MCP server was ignored: ${i}`:i,severity:"warning"}));if(o===void 0)delete e.managedMcpServers;else e.managedMcpServers=o;return r}function Ett(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 xtt(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(pL)}function vtt(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=Vn(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=vL().safeParse(s[a]),l;if(!c.success){let u=Ett(s[a]);if(u!==void 0&&!Aee.has(u)||xtt(s[a]))continue;l=IE(c.error.issues)}else if(c.data.source.source==="settings"&&c.data.source.name!==a)l=`key "${is(a)}" must match the settings source name "${is(c.data.source.name)}"`;if(l!==void 0)i.push({file:t,path:`${r}.${is(a)}`,message:`Invalid marketplace entry was ignored: ${l}`,severity:"warning"}),delete s[a]}return i}function wtt(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!Ge(o)||!Array.isArray(o.options)){let c=Ge(o)?`options: ${Vn(o.options)}`:Vn(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object with an "options" array of { model, label?, description?, behavesAs? } rows; received ${c}. This field was ignored.`,severity:"warning",invalidValue:c}]}let s=[];if("replaceBuiltInOptions"in o&&typeof o.replaceBuiltInOptions!=="boolean"){let c=Vn(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=CL().safeParse(i[c]);if(l.success){a.push(i[c]);continue}s.push({file:t,path:`${r}.options.${c}`,message:`${Ctt(l.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:Vn(i[c])})}if(a.length!==i.length)o.options=a;return s}function Att(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 ${Vn(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!AL().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 ${Vn(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let c of Object.keys(a)){let l=wL().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.${is(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 Ctt(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function Ttt(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||Rtt(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[Ptt(o,t,n?.policySource===!0)]}function Rtt(e){return typeof e==="string"&&Ch.includes(e)}var ktt="crossSessionInbound";function Ott(e){let t=Ch.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${is(e).replace(/^<key>$/,"<value>")}"`:Vn(e);return`must be one of ${t}; received ${n}`}function Ptt(e,t,n=!1){let r=Ch.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:ktt,message:`"crossSessionInbound" ${Ott(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}var Jte="remoteControl.shareHostProfile";function Itt(e,t,n){if(!Ge(e)||e.remoteControl===void 0)return[];let r=n?.policySource===!0,o=jE.map((f)=>`"${f}"`).join(", "),s=r?'In managed settings this is treated as "off" (the most restrictive): Remote Control environments report nothing about this machine until an administrator fixes it.':"While it is present, Remote Control environments report nothing about this machine.",i=(f)=>({file:t,path:Jte,message:`${f}. ${s}`,severity:"warning",expected:o,...r?{statusOnly:!0}:{preserveOnWrite:!0}}),a=(f)=>typeof f==="string"?`"${is(f).replace(/^<key>$/,"<value>")}"`:Vn(f),c=e.remoteControl;if(!Ge(c)){if(r)e.remoteControl={shareHostProfile:"off"};else delete e.remoteControl;return[i(`"remoteControl" must be an object like { "shareHostProfile": ${o.replace(/, /g," | ")} }; received ${a(c)}`)]}let l=[],u=Object.keys(c).filter((f)=>f!=="shareHostProfile");if(u.length>0){if(r)c.shareHostProfile="off";l.push(i(`"remoteControl" has an unrecognized key ${u.map((f)=>`"${is(f)}"`).join(", ")} (its only key is "shareHostProfile")`))}let p=c.shareHostProfile;if(p!==void 0&&!(typeof p==="string"&&jE.includes(p))){if(r)c.shareHostProfile="off";else delete c.shareHostProfile;l.push(i(`"${Jte}" must be one of ${o}; received ${a(p)}`))}return l}function vc(e,t,n){return[...cte(e,t),...mtt(e,t),...gtt(e,t),...vtt(e,t),...wtt(e,t),...Att(e,t),...Ttt(e,t,{policySource:n?.policySource}),...Itt(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:Stt(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly}),...n?.mcpServerEntrySalvageOnly?btt(e,t):[]]}function jL(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),GX.filter((n)=>t.has(n))}function Ntt(){return No(hc(),"managed-settings.json")}function HL(e){if(In()==="wsl"&&e.wslInherits?.()){let t=NL(fd,e.store);if(t.settings)return t;let n=NL(hc(),e.store);return{settings:n.settings,errors:[...t.errors,...n.errors]}}return NL(hc(),e.store)}function Mtt(e){return e.endsWith(".json")&&!e.startsWith(".")}function NL(e,t){let n=[],r={},o=!1,{settings:s,errors:i}=md(No(e,"managed-settings.json"),t,void 0,!0);if(n.push(...i),s&&Object.keys(s).length>0)r=Gn(r,s,Lo),o=!0;let a=No(e,"managed-settings.d");try{let c=t.folderListingForPolicyWalk(a),l;if(c!==void 0)l=c;else l=tt().readdirSync(a).filter((u)=>(u.isFile()||u.isSymbolicLink())&&Mtt(u.name)).map((u)=>u.name).sort(),t.noteWalkListing(a,l);for(let u of l){let{settings:p,errors:f}=md(No(a,u),t,void 0,!0);if(n.push(...f),p&&Object.keys(p).length>0)r=Gn(r,p,Lo),o=!0}}catch(c){let l=Re(c);if(l!=="ENOENT"&&l!=="ENOTDIR")ae(`managed-settings.d read failed: ${c}`,{level:"error"}),n.push(Dh(a,c,"directory"))}return{settings:o&&Ac(r)?r:null,errors:n}}function Utt(e,t){if(rr(e))Htt(t);else ae(`settings file read failed at ${t}: ${e}`,{level:"error"})}function md(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{settings:s.settings?uo(s.settings):null,errors:s.errors};let i=ztt(e,n,r);return t.parsedFiles.set(o,i),{settings:i.settings?uo(i.settings):null,errors:i.errors}}function BL(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 JE(e,t){let n=Xte.get(e),r=n?.get(t);if(r)return{settings:r.settings&&uo(r.settings),errors:r.errors.map((s)=>({...s}))};let o=Ftt(e,t);if(n)n.set(t,o);else Xte.set(e,new Map([[t,o]]));return{settings:o.settings&&uo(o.settings),errors:o.errors.map((s)=>({...s}))}}var Xte=new WeakMap;function Ftt(e,t){let n=uo(e),r=vc(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=kL(sne(t,o),t).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...Ih(s.error,t)]};return{settings:Object.keys(s.data).length>0?s.data:null,errors:[...r,...o]}}function wc(e){return Nte()&&(e==="managedMcpServers"||e.startsWith("managedMcpServers."))}function one(e,t){if(!Ge(e)||!("managedMcpServers"in e))return[];return delete e.managedMcpServers,wc("managedMcpServers")?[]:[{file:t,path:"managedMcpServers",message:'"managedMcpServers" is only honored from managed settings and was ignored here.',severity:"warning"}]}function sne(e,t){return(n)=>{if(wc(n.path))return;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 ine(e){let t=e?.remote?e.remote():Dte(),n=!e?.remote&&!wc("managedMcpServers")&&Ote()?[{file:"remote managed settings",path:"managedMcpServers",message:"The organization's MCP servers in the cached remote settings are withheld until the server confirms them this session; they connect as soon as it does.",severity:"warning",statusOnly:!0}]:[];if(!t||Object.keys(t).length===0)return{settings:null,errors:n,servedSnapshot:!1};let{settings:r,errors:o}=JE(t,"remote managed settings");return{settings:r,errors:[...n,...Gte(o)],servedSnapshot:Rte(t)}}var Qte="parent managed settings";function $tt(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let n=JE(t,Qte);if(n.settings?.managedMcpServers!==void 0&&!wc("managedMcpServers"))n.errors.push({file:Qte,path:"managedMcpServers",message:`"managedMcpServers" is only honored from the organization's managed settings sources (server-managed, MDM, managed-settings.json), not from settings a host passes in, and was ignored here.`,severity:"warning",statusOnly:!0});return n}function ane(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=uo(t),r=[...one(n,"SDK inline settings"),...vc(n,"SDK inline settings")],o=dd().safeParse(n);if(!o.success)return{settings:null,errors:[...r,...Ih(o.error,"SDK inline settings")]};if(r.some((s)=>s.severity==="fatal"))return{settings:null,errors:r};return{settings:o.data,errors:r}}var XE=2097152;function ztt(e,t,n){try{let r;if(t!==void 0)r=t;else{let{resolvedPath:o}=ff(tt(),e);r=fc(o,XE)}return jtt(r,e,n)}catch(r){return Ktt(r,e)}}function jtt(e,t,n){if(e.trim()==="")return{settings:{},errors:[]};let r=uo(mc(e,!1));if(n){if(!Ge(r))return{settings:null,errors:[QE(t)]};let i=vc(r,t,{skipMcpServerEntryFilter:!0,policySource:!0}),a=[],c=kL(sne(t,a),t).safeParse(r);if(!c.success)return{settings:null,errors:[...i,...Ih(c.error,t)]};return{settings:c.data,errors:[...i,...a]}}let o=[...one(r,t),...vc(r,t)],s=dd().safeParse(r);if(!s.success){let i=Ih(s.error,t);return{settings:null,errors:[...o,...i]}}if(o.some((i)=>i.severity==="fatal"))return{settings:null,errors:o};return{settings:s.data,errors:o}}function QE(e,{userWritable:t=!1}={}){return t?{file:e,path:"",message:`Managed settings document (${e}) could not be parsed as a JSON object; none of its settings are in effect. Fix or remove it.`,severity:"warning",statusOnly:!0,userWritable:!0}:{file:e,path:"",message:"Managed settings document could not be parsed as a JSON object; none of its settings are in effect. Fix or remove it.",startupFatal:!0}}function Htt(e){ae(`Broken symlink or missing file encountered for settings.json at path: ${e}`)}function Btt(){return{settings:null,errors:[]}}function Ktt(e,t){if(Utt(e,t),rr(e))return Btt();return{settings:null,errors:[Dh(t,e)]}}function Dh(e,t,n="file"){return{file:e,path:"",message:`${n==="directory"?"Managed settings drop-in directory":"Settings file"} could not be read: ${t instanceof Error?t.message:String(t)}`,severity:"fatal",errorClass:"unreadable"}}function ene(e,t){switch(e){case"userSettings":return to(Wt());case"policySettings":case"projectSettings":return to(t.cwd);case"localSettings":return cne(t.cwd,t.canonicalGitRoot);case"flagSettings":return t.flagPath?Ltt(to(t.flagPath)):to(t.cwd)}}function cne(e,t){let n=Gtt(e,t);if(n.decided!==void 0)return n.decided;if(!qtt(n.root))return n.cwdResolved;return n.root}function Gtt(e,t){let n=t?.(e);if(!n)return{decided:to(e)};let r=to(n),o=to(e);if(r===o)return{decided:r};let s;try{s=Ztt()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function Wtt(e){return pc().localStoreProbes.canonicalRootOwnerUids(e,Vtt)}function Vtt(e){let t=tt(),n=null;try{n=t.lstatSync(No(e,".claude")).uid}catch(r){if(!rr(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:t.lstatSync(No(e,".git")).uid,claudeEntryUid:n}}function qtt(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}=Wtt(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 Ztt(){return pc().localStoreProbes.normalizedRealHomeDir(Ytt)}function Ytt(){let e=Qx(Dtt());if(e===null)throw Error("home directory realpath unavailable");return ot(e)}var tne={default:"settings.json",cowork:"cowork_settings.json"};function Jtt(e){if(e.coworkPlugins||yn.CLAUDE_CODE_USE_COWORK_PLUGINS)return tne.cowork;return tne.default}function Lh(e,t){switch(e){case"userSettings":return No(ene(e,t),Jtt(t));case"projectSettings":case"localSettings":return No(ene(e,t),lne(e));case"policySettings":return Ntt();case"flagSettings":return t.flagPath}}function lne(e){switch(e){case"projectSettings":return No(".claude","settings.json");case"localSettings":return No(".claude","settings.local.json")}}function une(e){if(cne(e.cwd,e.canonicalGitRoot)===to(e.cwd))return;return No(to(e.cwd),lne("localSettings"))}function dne(e,t){let n=t.store.perSource.get(e);if(n!==void 0)return n;let r=vnt(e,t);return t.store.perSource.set(e,r),r}function Xtt(e,t=!1){return!e||e.parentSettingsBehavior==="merge"||t}var Qtt=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function ent(e){let t={};for(let{path:n,restrictive:r}of fh){let o=js(e,n);if(n[0]==="sandbox"&&mh(r).includes(o))qi(t,n,o)}return t.sandbox??{}}var tnt=/^(?:Read|Edit)\((?:\.\/)?!/;function nnt(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.remoteTools?.allowUnattendedServing===!1)n.remoteTools={...n.remoteTools,allowUnattendedServing:!1};if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(e.disableAutoMode==="disable")n.disableAutoMode="disable";let r=e.remoteControl?.shareHostProfile;if(r==="off"||r==="basic")n.remoteControl={...n.remoteControl,shareHostProfile:r};if(Ute(e.attribution,e.includeCoAuthoredBy)==="disabled")n.attribution={...n.attribution,commitTrailers:!1};if(e.attribution?.sessionUrl===!1)n.attribution={...n.attribution,sessionUrl:!1};let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)n.strictPluginOnlyCustomization=o;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 s=Sh(e.permissions,["deny","ask"]);for(let i of["deny","ask"]){let a=s[i];if(a!==void 0)s[i]=a.filter((c)=>{if(!tnt.test(c))return!0;return ae(`Ignoring ${i} rule "${c}" from the parent process's managed settings: a rule starting with "!" removes paths from the rules listed before it instead of restricting anything, so it is not merged into the policy rules. Spell the deny without the exception instead.`,{level:"warn"}),!1})}if(e.permissions.disableBypassPermissionsMode==="disable")s.disableBypassPermissionsMode="disable";if(e.permissions.disableAutoMode==="disable")s.disableAutoMode="disable";if(e.permissions.blockReadsOutsideWorkingDirectories===!0)s.blockReadsOutsideWorkingDirectories=!0;if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:a}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)s.allow=i;if(a)s.additionalDirectories=a}if(Object.keys(s).length>0)n.permissions=s}if(e.sandbox){let{network:s,filesystem:i,credentials:a}=e.sandbox,c={},l=s?Sh(s,["deniedDomains"]):{},u=i?Sh(i,["denyRead","denyWrite"]):{};if(s){if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&s.allowedDomains)l.allowedDomains=s.allowedDomains}if(Object.keys(l).length>0)c.network=l;if(i){if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)u.allowRead=i.allowRead}if(Object.keys(u).length>0)c.filesystem=u;if(a){let p=(a.files??[]).map((h)=>h.mode==="deny"?{path:h.path,mode:"deny"}:{path:h.path,mode:"mask",injectHosts:[]}),f=(a.envVars??[]).filter((h)=>h.mode==="deny").map((h)=>({name:h.name,mode:"deny"})),m={...p.length>0&&{files:p},...f.length>0&&{envVars:f}};if(a.sigv4){let h={};for(let _ of["streaming","presigned","sigv4a"])if(a.sigv4[_]==="deny")h[_]="deny";m.sigv4=h}{let h=pne(a.awsPairs??[],[]);if(h.length>0)m.awsPairs=h}if(Object.keys(m).length>0)c.credentials=m}if(Gn(c,ent(e)),Object.keys(c).length>0)n.sandbox=c}return n}function pne(e,t){let n=Zi,r=new Set(t.flatMap(nne));return Tr(e.flatMap(nne)).filter((o)=>n.includes(o)&&!r.has(o)).map((o,s)=>({accessKeyIdVar:o,secretAccessKeyVar:`${vE}${s+1}_`}))}function nne(e){if(!Ge(e))return[];return[e.accessKeyIdVar,e.secretAccessKeyVar,e.sessionTokenVar].filter((t)=>typeof t==="string")}var rnt=new Set([...[...WD].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...VD,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CONTEXT_COLLAPSE_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE"]);function ont(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 YE(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(!rnt.has(n.toUpperCase()))t[n]=r;e.env=t}}function FL(){return In()==="macos"?"plist":"hklm"}function fne(e){let t=GL(e);if(t.composes==="tier")return"helper";let n=$L(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return FL();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 $L(e){let t=[],{settings:n,errors:r,servedSnapshot:o}=ine(e);t.push(...r);let s=GL(e),i=s.composes==="remoteSlot"?s.helper:UL(n),{settings:a,errors:c}=BL(e);t.push(...c);let l=UL(a),{settings:u,errors:p}=e.file?.()??HL(e);t.push(...p);let f=UL(u),{settings:m,errors:h}=$tt(e);t.push(...h);let _=m!==null&&(l===null&&f===null||(l??f)?.parentSettingsBehavior==="merge"),y=[unt(i,o&&s.composes!=="remoteSlot",[l,f,..._?[Sh(m,lnt)]:[]]),l,f].filter((Q)=>Q!==null),v=(s.composes==="remoteSlot"?s.helper:[n,a,u].find((Q)=>Q!==null&&(Q===n&&o?i!==null:Q.managedSourcesBehavior!==void 0||Ac(Q))))?.managedSourcesBehavior,S=i!==null&&o&&s.composes!=="remoteSlot",{admin:x,merged:w}=snt(y,v,S),N={remote:i!==null,mdm:l!==null,file:f!==null},P=[];if(w){let Q=N.remote?"remote":N.mdm?FL():"file",ut=[[l,FL()],[f,"file"]];for(let[De,dt]of ut){if(De===null||De===y[0]||S&&De===y[1])continue;let W=KL.filter((An)=>Object.values(De[An]??{}).some((xt)=>xt!==void 0&&xt!==null)),[qe]=W;if(qe===void 0)continue;P.push(dt),t.push({file:ML[dt],path:qe,message:`${W.map((An)=>`"${An}"`).join(" and ")} in ${ML[dt]} ignored: policy helper configuration is read from the highest managed settings source only (${ML[Q]} here), even with managedSourcesBehavior "merge". Configure the helper in that source instead.`,severity:"warning",statusOnly:!0})}}let F=(Q)=>Q!==null&&(Q===y[0]||Object.keys(yh(Q,bne())).length>0),z={remote:F(i),mdm:F(l),file:F(f)},q={allowManagedPermissionRulesOnly:y.some((Q)=>Q.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:x?.forceLoginOrgUUID,allowedMcpServers:x?.allowedMcpServers,availableModels:x?.availableModels,sandbox:{network:{allowManagedDomainsOnly:y.some((Q)=>Q.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:y.some((Q)=>Q.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},ee=m&&Xtt(x,S&&!N.mdm&&!N.file)?nnt(m,q):null,te=ee&&Object.keys(ee).length>0?ee:null,ve=ont(m,e.hostManagedProvider);return{tiers:y,admin:x,parentSlice:te,hostModelOverlay:ve,errors:t,present:N,merged:w,composed:z,snapshotFirst:S,shadowedHelperSources:P}}function snt(e,t,n){let r=e[0];if(!r)return{admin:null,merged:!1};let{managedSourcesBehavior:o,...s}=r;if(t!=="merge"||e.length<2)return{admin:o===void 0?r:s,merged:!1};let i=e.slice(1).map((c,l)=>{let u=n&&l===0?{...c}:yh(c,bne());if(!(n&&l===0)){for(let f of Qtt)if(js(u,f)!==void 0)qi(u,f,void 0)}let p=js(u.sandbox,["enabledPlatforms"]);if(Array.isArray(p)&&p.includes(In()))qi(u,["sandbox","enabledPlatforms"],void 0);else if(p!==void 0)delete u.sandbox;return u}),a={};for(let c of[...i].reverse())Gn(a,c,zL);return Gn(a,s,n?dnt:zL),pnt(a,[r,...i]),int(a,[r,...i],n),{admin:a,merged:!0}}var mne=["managedSourcesBehavior","wslInheritsWindowsSettings"],KL=["policyHelper","policyHelpers"],ML={remote:"server-managed settings",plist:"the managed preferences plist",hklm:"the HKLM policy key",file:"managed-settings.json"};function Ac(e){return Object.keys(e).some((t)=>!mne.includes(t))}function UL(e){return e&&Ac(e)?e:null}function int(e,t,n){let r=t.findIndex((s)=>s.availableModels!==void 0),o=t.findIndex((s)=>s.modelOverrides!==void 0);if(o!==-1&&(r===-1||o<=r||n&&r===0))e.modelOverrides={...t[o].modelOverrides};else delete e.modelOverrides}var hne=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins"],ant=["awsPairs","ripgrep"];function gne(e,t,n){if(t===void 0)return e;if(Array.isArray(t))return n==="awsPairs"&&Array.isArray(e)?[...t,...pne(e,t)]:[...t];if(!Ge(t))return t;return vd(t,(r)=>Array.isArray(r)?[...r]:r)}var cnt=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedMarketplaces","allowedHttpHookUrls","httpHookAllowedEnvVars"],lnt=["allowedMcpServers","availableModels"];function unt(e,t,n){if(e===null||!t)return e;let r=cnt.filter((o)=>n.some((s)=>s?.[o]!==void 0));return r.length===0?e:yh(e,r)}function zL(e,t,n){if(n!==void 0&&(hne.includes(n)||ant.includes(n)))return gne(e,t,n);return _ne(e,t,n)}function dnt(e,t,n){if(n!==void 0&&hne.includes(n))return gne(e,t,n);return _ne(e,t,n)}function _ne(e,t,n){if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Tr([...t,...e]);return Lo(e,t,n)}function pnt(e,t){let n=t[0],r=e;for(let{path:o,restrictive:s}of fh){let i=mh(s),a=Math.min(...t.map((c)=>i.indexOf(js(c,o))).filter((c)=>c!==-1));if(Number.isFinite(a))qi(r,o,i[a]);else if(js(n,o)===void 0&&js(e,o)!==void 0)qi(r,o,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Tr(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 GL(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=ine(e).settings,o="remote";else if(r=BL(e).settings)o=In()==="macos"?"plist":"hklm";else r=(e.file?.()??HL(e)).settings,o="file";e.store.policy.mergedHelper={helper:gnt(r,t),mergedOver:Object.keys(yne(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function yne(e){return yh(e??{},KL)}function fnt(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)}var mnt=["forceLoginOrgUUID","gatewayInternalNetworks","allowedHttpHookUrls","httpHookAllowedEnvVars","allowRead"];function hnt(e,t,n){let r=n!==void 0&&t!==void 0&&mnt.includes(n)?t:zL(e,t,n);return r===t&&Array.isArray(r)?[...r]:r}function gnt(e,t){let n=yne(e),r=Gn({},n,t,hnt);if(n.env&&t.env)r.env=fnt(n.env,t.env);return r}var Sne=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var _nt=[...Sne,"otelHeadersHelper","proxyAuthHelper","forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","env","modelPicker",...KL,...mne];function bne(){return _nt}function ynt(e){return OQ.some((t)=>e.startsWith(t))||kQ.includes(e)}function Snt(e,t,n,r=0){let o=new Map,s=new Map,i=!1;for(let[a,c]of e.entries()){let l=new Set,u=t?.[a]===!0;for(let[p,f]of Object.entries(c??{})){let m=p.toUpperCase(),h=ynt(m);if(h&&f.trim()==="")continue;if(h&&i)continue;if(h&&a>r&&t?.[a]===!0)continue;let _=o.get(m);if(_!==void 0){if(l.has(m))s.set(p,f);else if(!s.has(p))s.set(p,_);continue}if(a>r&&n?.[a]?.has(m))continue;if(s.set(p,f),l.add(m),o.set(m,f),h)u=!0}if(u)i=!0}return Object.fromEntries(s)}var bnt="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function rne(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==bnt)t[n]=r;return t}function Ent(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function xnt(e){let t=BL(e);return t.settings?t.errors:[...t.errors,...(e.file?.()??HL(e)).errors]}function Ene(e){let t=GL(e),n=(e.helperWarnings?.()??[]).filter((_)=>!wc(_.path));if(t.composes==="tier"){let{helper:_}=t;e.store.lastPolicyEnvComposition=null;let y=e.hostManagedProvider?{..._}:_;if(e.hostManagedProvider)YE(y);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&_.availableModels!==void 0?_.modelOverrides:void 0};let b=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?xnt(e).filter((v)=>!v.statusOnly):[],...$L(e).errors.filter((v)=>v.statusOnly)];return{settings:y,errors:[...b,...n]}}let{tiers:r,admin:o,parentSlice:s,hostModelOverlay:i,errors:a,present:c,snapshotFirst:l}=$L(e);if(a.push(...n),!o&&!s){e.store.lastPolicyEnvComposition=null,e.store.policy.pairedModelOverrides={value:void 0};let _=e.hkcu?.();if(_&&Object.keys(_.settings).length>0){let y=e.hostManagedProvider?{..._.settings}:_.settings;if(e.hostManagedProvider){if(YE(y),i)Object.assign(y,i)}return{settings:y,errors:[...a,..._.errors]}}if(i)return{settings:{...i},errors:[...a,..._?.errors??[]]};return{settings:null,errors:[...a,..._?.errors??[]]}}let u=Gn({},s??{},o??{},Lo);if(r.some((_)=>_.forceRemoteSettingsRefresh===!0))u.forceRemoteSettingsRefresh=!0;let p=yn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,f=u.env;if(!p){let _=Snt(r.map((y)=>y.env),r.map((y)=>(y.otelHeadersHelper??"").trim()!==""),r.map((y)=>{let b=new Set;for(let v of Sne){let S=y[v];if(typeof S==="string"&&S.trim()!=="")for(let x of PQ[v])b.add(x)}return b.size>0?b:void 0}),l?1:0);if(Object.keys(_).length>0)u.env=_;else delete u.env}if(u.env){let _=rne(u.env);if(_&&Object.keys(_).length>0)u.env=_;else delete u.env}if(e.hostManagedProvider){if(YE(u),i)Object.assign(u,i)}let m={env:rne(f)};if(e.hostManagedProvider)YE(m);let h=!p&&!Ent(u.env,m.env);return e.store.lastPolicyEnvComposition={unionOptedOut:p,unionChangedEnv:h,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:pf(r,(_)=>Object.keys(_.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:u,errors:a}}function vnt(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return Ene(t).settings;let r=Lh(e,t),{settings:o}=r?md(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=ane(t);if(s)return Gn(o||{},s,Lo)}if(e==="localSettings"&&n){let s=une(t);if(s){let{settings:i}=md(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),Gn(i,o||{},Lo)}}return o}function wnt(e,t){return{...e,...t}}function Lo(e,t,n){if(n==="modelPicker"&&t!==void 0)return xne(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Tr([...e,...t])}if((n==="extraKnownMarketplaces"||n==="managedMcpServers")&&Ge(e)&&Ge(t))return wnt(e,t);return}function xne(e){if(!Ge(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>Ge(n)?{...n}:n)}}}function Ant(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();uh("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=Gn(r,n,Lo);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 jL(e)){if(l==="policySettings"){let{settings:p,errors:f}=Ene(e);if(c=p,p)r=Gn(r,p,Lo);a(f);continue}if(l==="localSettings"){let p=une(e);if(p&&!i.has(to(p))){i.add(to(p));let{settings:f,errors:m}=md(p,e.store);if(a(m),f)e.onLegacyLocalSettingsRead?.("cascade"),r=Gn(r,f,Lo)}}let u=Lh(l,e);if(u){let p=to(u),f=l==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(p)||f){i.add(p);let{settings:m,errors:h}=md(u,e.store,l==="flagSettings"?e.flagExpectedContent:void 0);if(a(h),m)r=Gn(r,m,Lo)}}if(l==="flagSettings"){let{settings:p,errors:f}=ane(e);if(a(f),p)r=Gn(r,p,Lo)}}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=xne(c.modelPicker)}return uh("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 Cnt(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=Ant(e);return e.store.mergedSettings=n,n}function Tnt(e){let{settings:t}=Cnt(e);return t||{}}function vne(e){e.store.invalidateAll();let t=[];for(let n of jL(e)){let r=dne(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:Tnt(e),sources:t}}function wne(e,t){let n=jL(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(dne(o,t)?.[e]!==void 0)return o}return null}import{execFile as Rnt}from"child_process";import{accessSync as knt,closeSync as Ont,constants as Pnt,openSync as Int,readSync as Dnt}from"fs";class Rne{promise=null;start(){if(this.promise)return;this.promise=VL()}reset(){this.promise=null}}var Lnt=new Rne;function Nnt(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 WL(e,t,n){let r=Date.now();return new Promise((o)=>{try{Rnt(e,t,{encoding:"utf-8",timeout:jte,windowsHide:!0,...n!==void 0&&{maxBuffer:n}},(s,i)=>{o({stdout:i??"",...Nnt(s),durationMs:Date.now()-r})})}catch(s){let i=s.code;o({stdout:"",status:"spawn_error",exitCode:null,errno:typeof i==="string"?i:null,signal:null,durationMs:Date.now()-r})}})}function Ane(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function Cne(e){return e.status==="ok"||e.status==="exited"&&e.exitCode!==null}function Mnt(e){return e.status==="spawn_error"&&e.errno==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}function Unt(e){let t;try{return t=Int(e,"r"),Dnt(t,Buffer.alloc(1),0,1,0),null}catch(n){return{code:n&&typeof n==="object"&&"code"in n?n.code:void 0,message:n instanceof Error?n.message:String(n)}}finally{if(t!==void 0)try{Ont(t)}catch{}}}function VL(){return(async()=>{if(process.platform==="darwin"){let e=Bte(),n=(await Promise.all(e.map(async({path:o,...s})=>{try{knt(o,Pnt.R_OK)}catch(l){let u=l&&typeof l==="object"&&"code"in l?l.code:void 0;if(u==="ENOENT"||u==="ENOTDIR")return null;return{stdout:null,unreadReason:l instanceof Error?l.message:String(l),...s}}let i=await WL(LL,[...$te,o],ZE);if(!Cne(i))return{stdout:null,unreadReason:"plutil did not finish converting it",...s};if(i.status==="ok")return{stdout:i.stdout,...s};let a=await WL(LL,[...zte,o]);if(!Cne(a))return{stdout:null,unreadReason:"plutil did not finish checking it",...s};if(a.status==="ok")return{stdout:null,unreadReason:"it holds a value plutil cannot convert to JSON (a date or data value)",...s};let c=Unt(o);if(c!==null){if(c.code==="ENOENT"||c.code==="ENOTDIR")return null;return{stdout:null,unreadReason:c.message,...s}}return{stdout:"",...s}}))).filter((o)=>o!==null),r=n.findIndex((o)=>o.stdout!==null);return{plistStdouts:r===-1?n:n.slice(0,r+1),hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`;return Tne(t)}if(Oh())return Tne(Hte);return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}async function Tne(e){let t=(o)=>WL(e,["query",o,"/v",kh],ZE),[n,r]=await Promise.all([t(VE),t(qE)]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,...Mnt(n)&&{hklmUnreadReason:`the value exceeds ${ZE/1048576} MiB`},hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:Ane(n),hkcu:Ane(r)}}}function kne(){return Lnt.promise}var Bs=Object.freeze({settings:{},errors:[]});class Une{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await(kne()??VL()),{mdm:o,hkcu:s,wslInherits:i}=await qnt(r,e);this.replace(o,s,i);let a=Date.now()-t;ae(`MDM settings load completed in ${a}ms`);try{Ri("tengu_managed_settings_os_read",Vnt(r,a))}catch{}if(Object.keys(o.settings).length>0){ae(`MDM settings found: ${Object.keys(o.settings).join(", ")}`);try{uh("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 One="@builtin",Fnt=["prependPlugins","appendPlugins"];function $nt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var znt=new Je(()=>new Une);function Nh(){return znt.of(Cn().host)}function jnt(e){Nh().startLoad(e)}async function Fne(){let e=Nh();if(!e.loadPromise)jnt();await e.loadPromise}function $ne(){return Nh().mdm??Bs}function zne(){return Nh().hkcu??Bs}function jne(){return Nh().wslInherits}function qL(e,t,{userWritable:n=!1}={}){let r=mc(e,!1);if(!Ge(r))return{settings:{},errors:[QE(t,{userWritable:n})]};let o=[],s=r;if(n&&"managedMcpServers"in r){if(s={...r},delete s.managedMcpServers,!wc("managedMcpServers"))o.push({file:t,path:"managedMcpServers",message:`"managedMcpServers" is only honored from administrator-controlled managed settings and was ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}if(n){for(let u of Fnt){if(!(u in s))continue;s=s===r?{...r}:s,delete s[u],o.push({file:t,path:u,message:`"${u}" is only honored from administrator-controlled managed settings and was ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}let l=s.enabledPlugins;if($nt(l)){if(Object.entries(l).filter(([p,f])=>p.endsWith(One)||f!==!1).length>0){s=s===r?{...r}:s;let p=aE(l,(f,m)=>!m.endsWith(One)&&f===!1);if(Object.keys(p).length>0)s.enabledPlugins=p;else delete s.enabledPlugins;o.push({file:t,path:"enabledPlugins",message:`"enabledPlugins" entries that enable a plugin, or name a built-in, are only honored from administrator-controlled managed settings and were ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}}}let{settings:i,errors:a}=JE(s,t),c=[...o,...a];return{settings:i??{},errors:n?c.map((l)=>({...l.severity==="warning"&&!l.startupFatal?l:{...Hnt(l),severity:"warning",statusOnly:!0},userWritable:!0})):c}}function Hnt({startupFatal:e,...t}){return t}function Pne(e,t,n){return{file:e,path:"",message:`Managed settings document (${e}) could not be read: ${t}; none of its settings are in effect.`,severity:n?"warning":"fatal",statusOnly:!0,errorClass:"unreadable",...n&&{userWritable:!0}}}function Ine(e,t="Settings"){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^[ \\t]+${n}[ \\t]+REG_(?:EXPAND_)?SZ[ \\t]+([\\s\\S]*)`,"im"),o=e.match(r)?.[1]?.trimEnd();return o?o:null}var Bnt=new Map([["ENOENT",_n("ENOENT")],["EACCES",_n("EACCES")],["EPERM",_n("EPERM")],["ENOEXEC",_n("ENOEXEC")],["EAGAIN",_n("EAGAIN")],["EMFILE",_n("EMFILE")],["ENOMEM",_n("ENOMEM")],["ETIMEDOUT",_n("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",_n("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),Knt=new Map([["SIGTERM",_n("SIGTERM")],["SIGKILL",_n("SIGKILL")],["SIGINT",_n("SIGINT")]]);function Gnt(e){if(!e)return;return Bnt.get(e)??_n("other")}function Wnt(e){if(!e)return;return Knt.get(e)??_n("other")}function Dne(e,t){if(!t)return{};return{[`${e}_status`]:hi(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:Gnt(t.errno),[`${e}_signal`]:Wnt(t.signal),[`${e}_duration_ms`]:t.durationMs}}function Vnt(e,t){return{is_wsl:Oh(),await_ms:t,...Dne("hklm",e.outcomes.hklm),...Dne("hkcu",e.outcomes.hkcu)}}async function qnt(e,t){let n=[];for(let c of e.plistStdouts??[]){let{label:l,userWritable:u}=c;if(c.stdout===null){n.push(Pne(l,c.unreadReason,u));continue}let p=qL(c.stdout,l,{userWritable:u});if(Ac(p.settings))return{mdm:{settings:p.settings,errors:[...n,...p.errors],...u&&{userWritable:u}},hkcu:Bs,wslInherits:!1};n.push(...p.errors)}let r=`Registry: ${VE}\\${kh}`,o=null;if(e.hklmStdout!==null)o=qL(Ine(e.hklmStdout)??"",r);else if(e.hklmUnreadReason!==void 0)n.push(Pne(r,e.hklmUnreadReason,!1));if(o)n.push(...o.errors);let s=Oh(),i=!1;if(s){if(i=o?.settings.wslInheritsWindowsSettings===!0,!i){let c=await Ynt(t);if(i=c.flag,!i)n.push(...c.records)}}let a=n.length>0?{settings:{},errors:n}:Bs;if(s&&!i){let c=new Set(o?.errors.filter((l)=>l.severity==="warning"));return{mdm:n.length>0?{settings:{},errors:n.map((l)=>c.has(l)?{...l,wslIgnored:!0}:l)}:Bs,hkcu:Bs,wslInherits:!1}}if(o){if(Ac(o.settings))return{mdm:o,hkcu:Bs,wslInherits:i}}if(await Znt(i,t))return{mdm:a,hkcu:Bs,wslInherits:i};if(e.hkcuStdout!==null){let c=qL(Ine(e.hkcuStdout)??"",`Registry: ${qE}\\${kh}`,{userWritable:!0});if(!s||c.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:l,managedSourcesBehavior:u,...p}=c.settings;return{mdm:a,hkcu:{settings:p,errors:c.errors},wslInherits:i}}if(c.errors.length>0)return{mdm:a,hkcu:{settings:{},errors:c.errors},wslInherits:i}}return{mdm:a,hkcu:Bs,wslInherits:i}}async function Hne(e,t){if(ye()&&t!==void 0)return(await o7(e,XE)).content;return fc(e,XE)}async function Bne(e,t){if(ye()&&t!==void 0)return await tt().readdir(e);return tt().readdirSync(e)}async function Znt(e,t){if(e&&await Mne(fd,t))return!0;return Mne(hc(),t)}async function Lne(e,t){let n=uo(mc(await Hne(e,t),!1));if(!n||typeof n!=="object")return!1;return vc(n,e,{skipMcpServerEntryFilter:!0,policySource:!0}),Ac(n)}function Nne(e){let t=Re(e);return t==="ENOENT"||t==="ENOTDIR"}async function Ynt(e){let t=[];async function n(s){let i;try{i=await Hne(s,e)}catch(c){if(!Nne(c))t.push(Dh(s,c));return!1}if(i.trim()==="")return!1;let a=mc(i,!1);if(!Ge(a))return t.push(QE(s)),!1;return a.wslInheritsWindowsSettings===!0}if(await n(hd(fd,"managed-settings.json")))return{flag:!0,records:t};let r=hd(fd,"managed-settings.d"),o;try{o=await Bne(r,e)}catch(s){if(!Nne(s))t.push(Dh(r,s,"directory"));return{flag:!1,records:t}}for(let s of o)if((s.isFile()||s.isSymbolicLink())&&s.name.endsWith(".json")&&!s.name.startsWith(".")&&await n(hd(r,s.name)))return{flag:!0,records:t};return{flag:!1,records:t}}async function Mne(e,t){try{if(await Lne(hd(e,"managed-settings.json"),t))return!0}catch{}try{let n=hd(e,"managed-settings.d"),r=await Bne(n,t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(await Lne(hd(n,o.name),t))return!0}catch{}}}catch{}return!1}var Xnt={user:"userSettings",project:"projectSettings",local:"localSettings"},Kne={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},Qnt=["user","project","local"],ert=new Set(["bypassPermissions","auto","acceptEdits"]),trt=new Set(["project"]),nrt=new Set(["project","local"]);function rrt(e){let t=e.effective.permissions?.defaultMode;if(!t||!ert.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((WX.includes(t)?nrt:trt).has(r.source)){let{defaultMode:s,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}async function Gne(e={}){await Fne();let t={store:new ng,cwd:Jnt(e.cwd??tt().cwd()),allowedSources:(e.settingSources??Qnt).map((a)=>Xnt[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:$ne,hkcu:zne,wslInherits:jne,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=vne(t),o=fne(t)??void 0,s=r.map(({source:a,settings:c})=>({source:Kne[a],settings:c,path:a==="policySettings"?void 0:Lh(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let c=wne(a,t);if(c)i[a]={source:Kne[c],path:c==="policySettings"?void 0:Lh(c,t),...c==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function BJt(e){return Gne(e)}var hrt=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function Wne(e){let t;try{t=ft(vu(e.toString("utf8")))}catch{return e}if(!Vne(t))return e;let n=!1;for(let o of hrt)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(Vne(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?me(t):e}function Vne(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function grt(e,t){if(!e)return;let n=e;try{let r=ft(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=me(r)}catch{}await Jne(t,n,{mode:384})}function _rt(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=GZ(KZ);return new Promise((t)=>{ort("security",["find-generic-password","-a",WZ(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function ere(e,t,n,r,o=60000,s){if(!Xe(t))return;let i=no(n,r),a=await Ur(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=wn(urt(),`claude-resume-${QL()}`);try{let l=wn(c,"projects",i);await ZL(l,{recursive:!0,mode:448});let u=wn(l,`${t}.jsonl`);await rm(u,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??wn(YL(),".claude"),m;try{m=await Yne(wn(f,".credentials.json"),"utf-8")}catch(b){if(!rr(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await _rt()??m;await grt(m,wn(c,".credentials.json"));let h=BZ(yn.CLAUDE_CONFIG_DIR),_=wn(p??YL(),".claude.json");await qS(_,wn(c,".claude.json"),void 0,eI(s,_,h.globalConfig,tn.globalConfig()));let y=wn(f,"settings.json");if(await qS(y,wn(c,"settings.json"),Wne,eI(s,y,h.userSettings,tn.userSettings())),await qS(wn(f,"cowork_settings.json"),wn(c,"cowork_settings.json"),Wne),e.listSubkeys)await yrt(e,{projectKey:i,sessionId:t},wn(l,t),o);return c}catch(l){throw await ex(c),l}}async function yrt(e,t,n,r){let o=await Ur(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=Mh(n,s+".jsonl");if(!s||Xne(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+e0)){ae(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Ur(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(XL(u))c.push(u);else l.push(u);if(l.length>0)await ZL(JL(i),{recursive:!0}),await rm(i,l);if(c.length>0){let u=c.at(-1),p=Mh(n,s+".meta.json");await ZL(JL(p),{recursive:!0});let{type:f,...m}=u;await Jne(p,me(m),{mode:384})}}}function t0(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,h;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="custom")p=s.prompt,h=s.snapshot;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections,h=s.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.270";let{abortController:_=Td(),additionalDirectories:y=[],agent:b,agents:v,allowedTools:S=[],betas:x,canUseTool:w,continue:N,cwd:P,debug:F,debugFile:z,disallowedTools:q=[],tools:ee,env:te,executable:ve=el()?"bun":"node",executableArgs:Q=[],extraArgs:ut={},fallbackModel:De,enableFileCheckpointing:dt,toolConfig:W,forkSession:qe,hooks:An,includeHookEvents:xt,includePartialMessages:ce,forwardSubagentText:re,onElicitation:$e,onUserDialog:nt,supportedDialogKinds:ie,perTaskStopAffordance:_t,workspaceTrust:rt,persistSession:ct,sessionStore:on,sessionStoreFlush:as,thinking:pt,effort:Uh,maxThinkingTokens:nx,maxTurns:are,maxBudgetUsd:cre,taskBudget:lre,mcpServers:r0,model:ure,outputFormat:o0,permissionMode:dre,allowDangerouslySkipPermissions:pre=!1,permissionPromptToolName:fre,permissionPrompts:mre,plugins:Fh,pluginDelivery:rx="argv",getOAuthToken:s0,getHostAuthToken:i0,workload:a0,resume:c0,resumeSessionAt:hre,resumeDropsTurn:gre,sessionId:_re,skills:l0,stderr:yre,strictMcpConfig:Sre}=u,u0=dre??(e?.resolvePermissionModeInCli?void 0:"default");if(on&&ct===!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(ie!==void 0&&ie.length>0&&!nt)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let d0=rt?.accepted===!0&&(typeof rt.directory!=="string"||!(drt.isAbsolute(rt.directory)||prt.isAbsolute(rt.directory)))?void 0:rt;if(rt!==void 0&&d0===void 0)ae("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});if(on&&N&&!c0&&!on.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(on&&dt)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(on&&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"});if(qZ(!!w,u0??"default",S),rx!=="argv"&&rx!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let p0=rx==="initialize"&&Fh!==void 0&&Fh.length>0,ox=u.pathToClaudeCodeExecutable;if(!ox){let Nn=mrt(import.meta.url),qn=lrt(Nn),Mo=sG((Cc)=>qn.resolve(Cc));if(!Mo)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.`);ox=Mo}let f0=o0?.type==="json_schema"?o0.schema:void 0,sn=te?{...te}:{...process.env};if(!sn.CLAUDE_CODE_ENTRYPOINT)sn.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!sn.CLAUDE_AGENT_SDK_VERSION)sn.CLAUDE_AGENT_SDK_VERSION="0.3.270";if(dt)sn.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(s0)sn.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(i0)sn.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(W?.askUserQuestion?.previewFormat)sn.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=W.askUserQuestion.previewFormat;for(let[Nn,qn]of[[W?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[W?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"]])if(Nn)sn[qn]="1";else if(!te){for(let Mo of Object.keys(sn))if(Mo.toUpperCase()===qn)delete sn[Mo]}let sx={};if(tx.propagation.inject(tx.context.active(),sx),"traceparent"in sx){for(let Nn of["TRACEPARENT","TRACESTATE"])if(!(Nn in(te??{})))delete sn[Nn]}for(let[Nn,qn]of Object.entries(sx)){let Mo=Nn.toUpperCase();if(!(Mo in(te??{})))sn[Mo]=qn}let m0={},h0=new Map;if(r0)for(let[Nn,qn]of Object.entries(r0))if(qn.type==="sdk"&&qn.instance)h0.set(Nn,qn);else m0[Nn]=qn;let gd;if(pt)switch(pt.type){case"adaptive":gd={type:"adaptive",display:pt.display};break;case"enabled":gd={type:"enabled",budgetTokens:pt.budgetTokens,display:pt.display};break;case"disabled":gd={type:"disabled"};break}else if(nx!==void 0)gd=nx===0?{type:"disabled"}:{type:"enabled",budgetTokens:nx};if(r){if(sn.CLAUDE_CONFIG_DIR=r,process.platform==="win32")sn.CLAUDE_SECURESTORAGE_CONFIG_DIR=te?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??te?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let g0=new pR({abortController:_,additionalDirectories:y,agent:b,betas:x,cwd:P,debug:F,debugFile:z,executable:ve,executableArgs:Q,extraArgs:a0?{...ut,workload:a0}:ut,pathToClaudeCodeExecutable:ox,env:sn,forkSession:qe,stderr:yre,thinkingConfig:gd,effort:Uh,maxTurns:are,maxBudgetUsd:cre,taskBudget:lre,model:ure,fallbackModel:De,jsonSchema:f0,permissionMode:u0,allowDangerouslySkipPermissions:pre,permissionPromptToolName:fre,permissionPrompts:mre,continueConversation:on?void 0:N,resume:c0,resumeSessionAt:hre,resumeDropsTurn:gre,sessionId:_re,settings:typeof i==="object"?me(i):i,managedSettings:a?me(a):void 0,settingSources:c,skills:l0,allowedTools:S,disallowedTools:q,tools:ee,mcpServers:m0,strictMcpConfig:Sre,canUseTool:!!w,hooks:!!An,includeHookEvents:xt,includePartialMessages:ce,persistSession:ct,sessionMirror:!!on,plugins:Fh,pluginsViaInitialize:p0,sandbox:l,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),bre={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:u.planModeInstructions,systemPromptSnapshot:h,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:v,title:u.title,skills:l0,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:re,supportedDialogKinds:ie,perTaskStopAffordance:_t,workspaceTrust:d0,plugins:p0?Fh:void 0},ix=new Wy(g0,n,w,An,_,h0,f0,bre,$e,s0,i0,nt);if(on){let Nn=()=>wn(sn.CLAUDE_CONFIG_DIR??wn(YL(),".claude"),"projects"),qn=as==="eager",Mo=new gR(async(Cc,ax)=>{let _d=Zne(Cc,Nn());if(_d)await on.append(_d,ax);else ae(`[SessionStore] dropping mirror frame: filePath ${Cc} is not under ${Nn()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Cc,ax)=>{let _d=Zne(Cc,Nn());if(_d)ix.reportMirrorError(_d,ax.message)},maxPendingEntries:qn?0:Vy,maxPendingBytes:qn?0:_u});ix.setTranscriptMirrorBatcher(Mo)}return{queryInstance:ix,transport:g0,abortController:_,processEnv:sn}}function n0(e,t,n,r){if(typeof n==="string")t.write(me({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
|
|
222
222
|
`);else e.streamInput(n).catch((o)=>r.abort(o))}var Srt=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function ex(e){for(let t=0;;t++)try{return await crt(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!Srt.has(Re(n)??""))return;await Mr((t+1)*100)}}function brt(e,t){e.waitForExit().catch(()=>{}).finally(()=>ex(t))}function KJt({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return Ert(e,t);let{queryInstance:n,transport:r,abortController:o}=t0(t,{isSingleUserTurn:typeof e==="string"});return n0(n,r,e,o),n}function Ert(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s}=t0({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),i=Mh(t.cwd??"."),a=t.sessionStore,c=t.loadTimeoutMs??60000,l=t.resume;return(async()=>{if(!l)l=(await Ur(a.listSessions(no(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 ere(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(()=>brt(r,p))}if(!n.isClosed())r.spawn()}).catch((p)=>{let f=Ar(p);r.spawnAbort(f),n.setError(f)}),n0(n,r,e,o),n}async function GJt({options:e,initializeTimeoutMs:t=60000}={}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=Mh(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 Ur(e.sessionStore.listSessions(no(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 ere(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let m=function(){if(f)return;f=!0,u.close()},a=t0(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(()=>ex(h))})}let p=`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`;await Ur(u.initializationResult(),t,p).catch((h)=>{throw VF(h,p)?kn(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{n0(u,c,h,l)}catch(_){throw u.close(),_}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(()=>ex(n))}throw await i,a}}async function WJt(e,t){if(t?.sessionStore)return Crt(t.sessionStore,e,t);return g4(e,t)}async function VJt(e){if(e?.sessionStore)return vrt(e.sessionStore,e);return pZ(e)}async function qJt(e,t){if(t?.sessionStore)return Trt(t.sessionStore,e,t);return fZ(e,t)}async function ZJt(e,t,n){if(n?.sessionStore)return Rrt(n.sessionStore,e,t,n.dir);return yZ(e,t,n)}async function YJt(e,t,n){if(n?.sessionStore)return krt(n.sessionStore,e,t,n.dir);return SZ(e,t,n)}async function JJt(e,t){if(!Xe(e))throw new Ze(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=no(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return bZ(e,t)}async function XJt(e,t){if(t?.sessionStore)return Ort(t.sessionStore,e,t);return wZ(e,t)}async function QJt(e,t,n,r){if(!Xe(e))throw new Ze(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=ye(),s=o?r:void 0,i=await ki(e,n?.dir,cr(s),o);if(!i)throw Error(`Session ${e} not found`);let a=no(n?.dir),c=n?.batchSize&&n.batchSize>0?n.batchSize:Vy,l=s===void 0?void 0:Za(JL(i.filePath),pn),u=s!==void 0&&l!==void 0?{backend:s,projectKey:l}:void 0;if(u!==void 0)await XP(u.backend,tn.transcript(u.projectKey,e),{projectKey:a,sessionId:e},t,c);else await qne(i.filePath,{projectKey:a,sessionId:e},t,c);if(n?.includeSubagents===!1)return;if(u!==void 0){let m=await FZ(u.backend,u.projectKey,e),h=await $Z(u.backend,u.projectKey,e,m);for(let _ of m){let y={projectKey:a,sessionId:e,subpath:VS(_)};await XP(u.backend,_.kind==="agent"?tn.transcript(u.projectKey,e,_.agentId,_.agentRelPath):tn.journal(u.projectKey,e,_.agentRelPath),y,t,c);let b=h.get(y.subpath),v;if(b!==void 0)try{v=ft(b)}catch(S){ae(`importSessionToStore: skipping unreadable sidecar for ${y.subpath}: ${S}`)}if(v!==void 0)await t.append(y,[{type:"agent_metadata",...v}])}return}let p=i.filePath.replace(/\.jsonl$/,""),f=wn(p,"subagents");for(let m of await xrt(f)){let h=Qne(p,m).split(e0);h[h.length-1]=h.at(-1).replace(/\.jsonl$/,"");let _={projectKey:a,sessionId:e,subpath:h.join("/")};await qne(m,_,t,c);let y=m.replace(/\.jsonl$/,".meta.json"),b;try{b=ft(await Yne(y,"utf8"))}catch(v){if(!rr(v))ae(`importSessionToStore: skipping unreadable sidecar ${y}: ${v}`)}if(b!==void 0)await t.append(_,[{type:"agent_metadata",...b}])}}async function qne(e,t,n,r){let o=frt({input:srt(e,{encoding:"utf8"}),crlfDelay:1/0}),s=[],i=0;for await(let a of o){if(!a)continue;try{s.push(ft(a))}catch(c){ae(`importSessionToStore: skipping unparseable line in ${e}: ${c}`);continue}if(i+=a.length,s.length>=r||i>=_u)await n.append(t,s),s=[],i=0}if(s.length>0)await n.append(t,s)}async function xrt(e){let t=[];async function n(r){let o;try{o=await art(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=wn(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 e5t(e,t){if(t?.sessionStore)return Prt(t.sessionStore,e,t.dir);return LZ(e,t)}async function t5t(e,t,n){if(n?.sessionStore)return Irt(n.sessionStore,e,t,n);return NZ(e,t,n)}function tre(e){let t=Mh(e??"."),n;try{n=irt(t)}catch{n=t}return ot(n)}function no(e,t){let n=tre(e);if(t===void 0)return Ps(n);return(t.CLAUDE_CONFIG_DIR?Nv(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??om(n)}function nre(e){return e.map((t)=>me(t)).join(`
|
|
223
223
|
`)+`
|
|
224
224
|
`}function rre(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 XL(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}async function vrt(e,t){let n=tre(t.dir),r=Ps(n),o=t.offset??0,s=t.limit;if(e.listSessionSummaries)return wrt(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=rre(a,s,o);return ore(e,c,t.dir,n)}async function wrt(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:DM(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=rre(c,o,s),u=l.filter((p)=>p.info===void 0);if(u.length>0){let p=await ore(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 ore(e,t,n,r){return(await Promise.allSettled(t.map(async(s)=>{let i=await ire(e,s.sessionId,n);if(!i)return null;let a=Lu(s.sessionId,sre(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 sre(e,t){let n=Buffer.from(e,"utf-8"),r=n.length,o=n.subarray(0,zn).toString("utf-8"),s=r>zn?n.subarray(r-zn).toString("utf-8"):o;return{mtime:t,size:r,head:o,tail:s}}function Art(e){let t=e.trimEnd(),n=t.slice(t.lastIndexOf(`
|