@anthropic-ai/claude-agent-sdk 0.3.176 → 0.3.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
3
3
 
4
- // Version: 0.3.176
4
+ // Version: 0.3.177
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -112,7 +112,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
112
112
  `+" ".repeat(t))},"\t":{"\n":Array(200).fill(0).map((e,t)=>`
113
113
  `+"\t".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+"\t".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
114
114
  `+"\t".repeat(t))}};var MN;(function(e){e.DEFAULT={allowTrailingComma:!1}})(MN||(MN={}));var DN;(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"})(DN||(DN={}));var NN;(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"})(NN||(NN={}));var jN;(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"})(jN||(jN={}));function rg(e){return e.startsWith("\uFEFF")?e.slice(1):e}import Ne from"node:path";import UN from"node:os";import $x from"node:process";var Vn=UN.homedir(),Ox=UN.tmpdir(),{env:Is}=$x,eee=(e)=>{let t=Ne.join(Vn,"Library");return{data:Ne.join(t,"Application Support",e),config:Ne.join(t,"Preferences",e),cache:Ne.join(t,"Caches",e),log:Ne.join(t,"Logs",e),temp:Ne.join(Ox,e)}},tee=(e)=>{let t=Is.APPDATA||Ne.join(Vn,"AppData","Roaming"),r=Is.LOCALAPPDATA||Ne.join(Vn,"AppData","Local");return{data:Ne.join(r,e,"Data"),config:Ne.join(t,e,"Config"),cache:Ne.join(r,e,"Cache"),log:Ne.join(r,e,"Log"),temp:Ne.join(Ox,e)}},ree=(e)=>{let t=Ne.basename(Vn);return{data:Ne.join(Is.XDG_DATA_HOME||Ne.join(Vn,".local","share"),e),config:Ne.join(Is.XDG_CONFIG_HOME||Ne.join(Vn,".config"),e),cache:Ne.join(Is.XDG_CACHE_HOME||Ne.join(Vn,".cache"),e),log:Ne.join(Is.XDG_STATE_HOME||Ne.join(Vn,".local","state"),e),temp:Ne.join(Ox,t,e)}};function Ax(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if($x.platform==="darwin")return eee(e);if($x.platform==="win32")return tee(e);return ree(e)}var dIe=Ax("claude-cli");function nee(){if(process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return"essential-traffic";if(process.env.DISABLE_TELEMETRY)return"no-telemetry";if(Ee(process.env.DO_NOT_TRACK))return"no-telemetry";return"default"}function zN(){return nee()==="essential-traffic"}var oee=100,Cx=[];function iee(e){if(Cx.length>=oee)Cx.shift();Cx.push(e)}var see=[],LN=null;var NIe=Ce(()=>process.argv.includes("--hard-fail"));function ng(e){let t=kr(e);try{if(Ee(process.env.CLAUDE_CODE_USE_BEDROCK)||Ee(process.env.CLAUDE_CODE_USE_VERTEX)||Ee(process.env.CLAUDE_CODE_USE_FOUNDRY)||Ee(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||Ee(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||zN())return;let o={error:t.stack||t.message,timestamp:new Date().toISOString()};if(iee(o),LN===null){see.push({type:"error",error:t});return}LN.logError(t)}catch{}}var Rs=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,BN=new Set,Mx=typeof process==="object"&&!!process?process:{},HN=(e,t,r,o)=>{typeof Mx.emitWarning==="function"?Mx.emitWarning(e,t,r,o):console.error(`[${r}] ${t}: ${e}`)},og=globalThis.AbortController,FN=globalThis.AbortSignal;if(typeof og>"u"){FN=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(o,n){this._onabort.push(n)}},og=class{constructor(){t()}signal=new FN;abort(o){if(this.signal.aborted)return;this.signal.reason=o,this.signal.aborted=!0;for(let n of this.signal._onabort)n(o);this.signal.onabort?.(o)}};let e=Mx.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{if(!e)return;e=!1,HN("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 aee=(e)=>!BN.has(e),UIe=Symbol("type"),Wn=(e)=>e&&e===Math.floor(e)&&e>0&&isFinite(e),qN=(e)=>!Wn(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?eu:null;class eu extends Array{constructor(e){super(e);this.fill(0)}}class $s{heap;length;static#n=!1;static create(e){let t=qN(e);if(!t)return[];$s.#n=!0;let r=new $s(e,t);return $s.#n=!1,r}constructor(e,t){if(!$s.#n)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 ig{#n;#d;#g;#h;#$;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#o;#r;#e;#l;#p;#c;#s;#b;#a;#_;#v;#f;#S;#T;#u;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#f,sizes:e.#_,keyMap:e.#o,keyList:e.#r,valList:e.#e,next:e.#l,prev:e.#p,get head(){return e.#c},get tail(){return e.#s},free:e.#b,isBackgroundFetch:(t)=>e.#t(t),backgroundFetch:(t,r,o,n)=>e.#M(t,r,o,n),moveToTail:(t)=>e.#R(t),indexes:(t)=>e.#x(t),rindexes:(t)=>e.#w(t),isStale:(t)=>e.#m(t)}}get max(){return this.#n}get maxSize(){return this.#d}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#$}get memoMethod(){return this.#O}get dispose(){return this.#g}get disposeAfter(){return this.#h}constructor(e){let{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:n,updateAgeOnGet:i,updateAgeOnHas:s,allowStale:a,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:p,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:g,fetchMethod:h,memoMethod:y,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:x,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:A,ignoreFetchAbort:U}=e;if(t!==0&&!Wn(t))throw TypeError("max option must be a nonnegative integer");let se=t?qN(t):Array;if(!se)throw Error("invalid max value: "+t);if(this.#n=t,this.#d=f,this.maxEntrySize=m||this.#d,this.sizeCalculation=g,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#O=y,h!==void 0&&typeof h!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#$=h,this.#T=!!h,this.#o=new Map,this.#r=Array(t).fill(void 0),this.#e=Array(t).fill(void 0),this.#l=new se(t),this.#p=new se(t),this.#c=0,this.#s=0,this.#b=$s.create(t),this.#i=0,this.#y=0,typeof c==="function")this.#g=c;if(typeof u==="function")this.#h=u,this.#a=[];else this.#h=void 0,this.#a=void 0;if(this.#S=!!this.#g,this.#u=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!w,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!U,this.maxEntrySize!==0){if(this.#d!==0){if(!Wn(this.#d))throw TypeError("maxSize must be a positive integer if specified")}if(!Wn(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!x,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!s,this.ttlResolution=Wn(o)||o===0?o:1,this.ttlAutopurge=!!n,this.ttl=r||0,this.ttl){if(!Wn(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#n===0&&this.ttl===0&&this.#d===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#n&&!this.#d){if(aee("LRU_CACHE_UNBOUNDED"))BN.add("LRU_CACHE_UNBOUNDED"),HN("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",ig)}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#D(){let e=new eu(this.#n),t=new eu(this.#n);this.#f=e,this.#v=t,this.#N=(n,i,s=Rs.now())=>{if(t[n]=i!==0?s:0,e[n]=i,i!==0&&this.ttlAutopurge){let a=setTimeout(()=>{if(this.#m(n))this.#k(this.#r[n],"expire")},i+1);if(a.unref)a.unref()}},this.#P=(n)=>{t[n]=e[n]!==0?Rs.now():0},this.#E=(n,i)=>{if(e[i]){let s=e[i],a=t[i];if(!s||!a)return;n.ttl=s,n.start=a,n.now=r||o();let c=n.now-a;n.remainingTTL=s-c}};let r=0,o=()=>{let n=Rs.now();if(this.ttlResolution>0){r=n;let i=setTimeout(()=>r=0,this.ttlResolution);if(i.unref)i.unref()}return n};this.getRemainingTTL=(n)=>{let i=this.#o.get(n);if(i===void 0)return 0;let s=e[i],a=t[i];if(!s||!a)return 1/0;let c=(r||o())-a;return s-c},this.#m=(n)=>{let i=t[n],s=e[n];return!!s&&!!i&&(r||o())-i>s}}#P=()=>{};#E=()=>{};#N=()=>{};#m=()=>!1;#F(){let e=new eu(this.#n);this.#y=0,this.#_=e,this.#I=(t)=>{this.#y-=e[t],e[t]=0},this.#j=(t,r,o,n)=>{if(this.#t(r))return 0;if(!Wn(o))if(n){if(typeof n!=="function")throw TypeError("sizeCalculation must be a function");if(o=n(r,t),!Wn(o))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 o},this.#A=(t,r,o)=>{if(e[t]=r,this.#d){let n=this.#d-e[t];while(this.#y>n)this.#C(!0)}if(this.#y+=e[t],o)o.entrySize=r,o.totalCalculatedSize=this.#y}}#I=(e)=>{};#A=(e,t,r)=>{};#j=(e,t,r,o)=>{if(r||o)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#x({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#s;;){if(!this.#U(t))break;if(e||!this.#m(t))yield t;if(t===this.#c)break;else t=this.#p[t]}}*#w({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#c;;){if(!this.#U(t))break;if(e||!this.#m(t))yield t;if(t===this.#s)break;else t=this.#l[t]}}#U(e){return e!==void 0&&this.#o.get(this.#r[e])===e}*entries(){for(let e of this.#x())if(this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e]))yield[this.#r[e],this.#e[e]]}*rentries(){for(let e of this.#w())if(this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e]))yield[this.#r[e],this.#e[e]]}*keys(){for(let e of this.#x()){let t=this.#r[e];if(t!==void 0&&!this.#t(this.#e[e]))yield t}}*rkeys(){for(let e of this.#w()){let t=this.#r[e];if(t!==void 0&&!this.#t(this.#e[e]))yield t}}*values(){for(let e of this.#x())if(this.#e[e]!==void 0&&!this.#t(this.#e[e]))yield this.#e[e]}*rvalues(){for(let e of this.#w())if(this.#e[e]!==void 0&&!this.#t(this.#e[e]))yield this.#e[e]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#x()){let o=this.#e[r],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0)continue;if(e(n,this.#r[r],this))return this.get(this.#r[r],t)}}forEach(e,t=this){for(let r of this.#x()){let o=this.#e[r],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0)continue;e.call(t,n,this.#r[r],this)}}rforEach(e,t=this){for(let r of this.#w()){let o=this.#e[r],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0)continue;e.call(t,n,this.#r[r],this)}}purgeStale(){let e=!1;for(let t of this.#w({allowStale:!0}))if(this.#m(t))this.#k(this.#r[t],"expire"),e=!0;return e}info(e){let t=this.#o.get(e);if(t===void 0)return;let r=this.#e[t],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let n={value:o};if(this.#f&&this.#v){let i=this.#f[t],s=this.#v[t];if(i&&s){let a=i-(Rs.now()-s);n.ttl=a,n.start=Date.now()}}if(this.#_)n.size=this.#_[t];return n}dump(){let e=[];for(let t of this.#x({allowStale:!0})){let r=this.#r[t],o=this.#e[t],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0||r===void 0)continue;let i={value:n};if(this.#f&&this.#v){i.ttl=this.#f[t];let s=Rs.now()-this.#v[t];i.start=Math.floor(Date.now()-s)}if(this.#_)i.size=this.#_[t];e.unshift([r,i])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Rs.now()-o}this.set(t,r.value,r)}}set(e,t,r={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:n,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,u=this.#j(e,t,r.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize){if(a)a.set="miss",a.maxEntrySizeExceeded=!0;return this.#k(e,"set"),this}let d=this.#i===0?void 0:this.#o.get(e);if(d===void 0){if(d=this.#i===0?this.#s:this.#b.length!==0?this.#b.pop():this.#i===this.#n?this.#C(!1):this.#i,this.#r[d]=e,this.#e[d]=t,this.#o.set(e,d),this.#l[this.#s]=d,this.#p[d]=this.#s,this.#s=d,this.#i++,this.#A(d,u,a),a)a.set="add";c=!1}else{this.#R(d);let p=this.#e[d];if(t!==p){if(this.#T&&this.#t(p)){p.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=p;if(f!==void 0&&!i){if(this.#S)this.#g?.(f,e,"set");if(this.#u)this.#a?.push([f,e,"set"])}}else if(!i){if(this.#S)this.#g?.(p,e,"set");if(this.#u)this.#a?.push([p,e,"set"])}if(this.#I(d),this.#A(d,u,a),this.#e[d]=t,a){a.set="replace";let f=p&&this.#t(p)?p.__staleWhileFetching:p;if(f!==void 0)a.oldValue=f}}else if(a)a.set="update"}if(o!==0&&!this.#f)this.#D();if(this.#f){if(!c)this.#N(d,o,n);if(a)this.#E(a,d)}if(!i&&this.#u&&this.#a){let p=this.#a,f;while(f=p?.shift())this.#h?.(...f)}return this}pop(){try{while(this.#i){let e=this.#e[this.#c];if(this.#C(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#a){let e=this.#a,t;while(t=e?.shift())this.#h?.(...t)}}}#C(e){let t=this.#c,r=this.#r[t],o=this.#e[t];if(this.#T&&this.#t(o))o.__abortController.abort(Error("evicted"));else if(this.#S||this.#u){if(this.#S)this.#g?.(o,r,"evict");if(this.#u)this.#a?.push([o,r,"evict"])}if(this.#I(t),e)this.#r[t]=void 0,this.#e[t]=void 0,this.#b.push(t);if(this.#i===1)this.#c=this.#s=0,this.#b.length=0;else this.#c=this.#l[t];return this.#o.delete(r),this.#i--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,n=this.#o.get(e);if(n!==void 0){let i=this.#e[n];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(!this.#m(n)){if(r)this.#P(n);if(o)o.has="hit",this.#E(o,n);return!0}else if(o)o.has="stale",this.#E(o,n)}else if(o)o.has="miss";return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,o=this.#o.get(e);if(o===void 0||!r&&this.#m(o))return;let n=this.#e[o];return this.#t(n)?n.__staleWhileFetching:n}#M(e,t,r,o){let n=t===void 0?void 0:this.#e[t];if(this.#t(n))return n;let i=new og,{signal:s}=r;s?.addEventListener("abort",()=>i.abort(s.reason),{signal:i.signal});let a={signal:i.signal,options:r,context:o},c=(g,h=!1)=>{let{aborted:y}=i.signal,v=r.ignoreFetchAbort&&g!==void 0;if(r.status)if(y&&!h){if(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,v)r.status.fetchAbortIgnored=!0}else r.status.fetchResolved=!0;if(y&&!v&&!h)return d(i.signal.reason);let x=f;if(this.#e[t]===f)if(g===void 0)if(x.__staleWhileFetching)this.#e[t]=x.__staleWhileFetching;else this.#k(e,"fetch");else{if(r.status)r.status.fetchUpdated=!0;this.set(e,g,a.options)}return g},u=(g)=>{if(r.status)r.status.fetchRejected=!0,r.status.fetchError=g;return d(g)},d=(g)=>{let{aborted:h}=i.signal,y=h&&r.allowStaleOnFetchAbort,v=y||r.allowStaleOnFetchRejection,x=v||r.noDeleteOnFetchRejection,w=f;if(this.#e[t]===f){if(!x||w.__staleWhileFetching===void 0)this.#k(e,"fetch");else if(!y)this.#e[t]=w.__staleWhileFetching}if(v){if(r.status&&w.__staleWhileFetching!==void 0)r.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw g},p=(g,h)=>{let y=this.#$?.(e,n,a);if(y&&y instanceof Promise)y.then((v)=>g(v===void 0?void 0:v),h);i.signal.addEventListener("abort",()=>{if(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort){if(g(void 0),r.allowStaleOnFetchAbort)g=(v)=>c(v,!0)}})};if(r.status)r.status.fetchDispatched=!0;let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:i,__staleWhileFetching:n,__returned:void 0});if(t===void 0)this.set(e,m,{...a.options,status:void 0}),t=this.#o.get(e);else this.#e[t]=m;return m}#t(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof og}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:h=!1,status:y,signal:v}=t;if(!this.#T){if(y)y.fetch="get";return this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:n,status:y})}let x={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:n,ttl:i,noDisposeOnSet:s,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:y,signal:v},w=this.#o.get(e);if(w===void 0){if(y)y.fetch="miss";let A=this.#M(e,w,x,g);return A.__returned=A}else{let A=this.#e[w];if(this.#t(A)){let Lt=r&&A.__staleWhileFetching!==void 0;if(y){if(y.fetch="inflight",Lt)y.returnedStale=!0}return Lt?A.__staleWhileFetching:A.__returned=A}let U=this.#m(w);if(!h&&!U){if(y)y.fetch="hit";if(this.#R(w),o)this.#P(w);if(y)this.#E(y,w);return A}let se=this.#M(e,w,x,g),Ye=se.__staleWhileFetching!==void 0&&r;if(y){if(y.fetch=U?"stale":"refresh",Ye&&U)y.returnedStale=!0}return Ye?se.__staleWhileFetching:se.__returned=se}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(r===void 0)throw Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#O;if(!r)throw Error("no memoMethod provided to constructor");let{context:o,forceRefresh:n,...i}=t,s=this.get(e,i);if(!n&&s!==void 0)return s;let a=r(e,s,{options:i,context:o});return this.set(e,a,i),a}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:i}=t,s=this.#o.get(e);if(s!==void 0){let a=this.#e[s],c=this.#t(a);if(i)this.#E(i,s);if(this.#m(s)){if(i)i.get="stale";if(!c){if(!n)this.#k(e,"expire");if(i&&r)i.returnedStale=!0;return r?a:void 0}else{if(i&&r&&a.__staleWhileFetching!==void 0)i.returnedStale=!0;return r?a.__staleWhileFetching:void 0}}else{if(i)i.get="hit";if(c)return a.__staleWhileFetching;if(this.#R(s),o)this.#P(s);return a}}else if(i)i.get="miss"}#z(e,t){this.#p[t]=e,this.#l[e]=t}#R(e){if(e!==this.#s){if(e===this.#c)this.#c=this.#l[e];else this.#z(this.#p[e],this.#l[e]);this.#z(this.#s,e),this.#s=e}}delete(e){return this.#k(e,"delete")}#k(e,t){let r=!1;if(this.#i!==0){let o=this.#o.get(e);if(o!==void 0)if(r=!0,this.#i===1)this.#L(t);else{this.#I(o);let n=this.#e[o];if(this.#t(n))n.__abortController.abort(Error("deleted"));else if(this.#S||this.#u){if(this.#S)this.#g?.(n,e,t);if(this.#u)this.#a?.push([n,e,t])}if(this.#o.delete(e),this.#r[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#p[o];else if(o===this.#c)this.#c=this.#l[o];else{let i=this.#p[o];this.#l[i]=this.#l[o];let s=this.#l[o];this.#p[s]=this.#p[o]}this.#i--,this.#b.push(o)}}if(this.#u&&this.#a?.length){let o=this.#a,n;while(n=o?.shift())this.#h?.(...n)}return r}clear(){return this.#L("delete")}#L(e){for(let t of this.#w({allowStale:!0})){let r=this.#e[t];if(this.#t(r))r.__abortController.abort(Error("deleted"));else{let o=this.#r[t];if(this.#S)this.#g?.(r,o,e);if(this.#u)this.#a?.push([r,o,e])}}if(this.#o.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#v)this.#f.fill(0),this.#v.fill(0);if(this.#_)this.#_.fill(0);if(this.#c=0,this.#s=0,this.#b.length=0,this.#y=0,this.#i=0,this.#u&&this.#a){let t=this.#a,r;while(r=t?.shift())this.#h?.(...r)}}}function ZN(e,t,r=100){let o=new ig({max:r}),n=(...i)=>{let s=t(...i),a=o.get(s);if(a!==void 0)return a;let c=e(...i);return o.set(s,c),c};return n.cache={clear:()=>o.clear(),size:()=>o.size,delete:(i)=>o.delete(i),get:(i)=>o.peek(i),has:(i)=>o.has(i)},n}var cee=8192;function WN(e,t){try{return{ok:!0,value:JSON.parse(rg(e))}}catch(r){if(t)ng(r);return{ok:!1}}}var VN=ZN(WN,(e)=>e,50);var Os=Object.assign(function(t,r=!0){if(!t)return null;let o=t.length>cee?WN(t,r):VN(t,r);return o.ok?o.value:null},{cache:VN.cache});import{join as uee}from"path";import{readdir as rRe,readFile as lee}from"fs/promises";import{release as KN}from"os";var Ho=Ce(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){if(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)return"wsl";try{let e=Be().readFileSync("/proc/version",{encoding:"utf8"});if(e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl"))return"wsl"}catch(e){ee(`Failed to read /proc/version for WSL detection: ${e}`,{level:"error"})}return"linux"}return"unknown"}catch(e){return ng(e),"unknown"}});var cRe=Ce(()=>{if(process.platform!=="linux")return;try{let e=Be().readFileSync("/proc/version",{encoding:"utf8"}),t=e.match(/WSL(\d+)/i);if(t&&t[1])return t[1];if(e.toLowerCase().includes("microsoft"))return"1";return}catch(e){ee(`Failed to read /proc/version for WSL detection: ${e}`,{level:"error"});return}}),lRe=Ce(async()=>{if(process.platform!=="linux")return;let e={linuxKernel:KN()};try{let t=await lee("/etc/os-release","utf8");for(let r of t.split(`
115
- `)){let o=r.match(/^(ID|VERSION_ID)=(.*)$/);if(o&&o[1]&&o[2]){let n=o[2].replace(/^"|"$/g,"");if(o[1]==="ID")e.linuxDistroId=n;else e.linuxDistroVersion=n}}}catch{}return e});var uRe=Ce(()=>{if(process.platform!=="darwin")return;let t=KN().match(/^(\d+)\./);if(!t||!t[1])return;return parseInt(t[1],10)-9});var qo=Ce(function(){switch(Ho()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),gRe=Ce(function(){return uee(qo(),"managed-settings.d")});function dee(e,t,r){if(r!==void 0&&!dn(e[t],r)||r===void 0&&!(t in e))wi(e,t,r)}var tu=dee;function pee(e){return function(t,r,o){var n=-1,i=Object(t),s=o(t),a=s.length;while(a--){var c=s[e?a:++n];if(r(i[c],c,i)===!1)break}return t}}var GN=pee;var fee=GN(),JN=fee;function mee(e){return Kt(e)&&Ei(e)}var XN=mee;var gee="[object Object]",hee=Function.prototype,yee=Object.prototype,YN=hee.toString,bee=yee.hasOwnProperty,_ee=YN.call(Object);function vee(e){if(!Kt(e)||wr(e)!=gee)return!1;var t=fd(e);if(t===null)return!0;var r=bee.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&YN.call(r)==_ee}var QN=vee;function See(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var ru=See;function xee(e){return bE(e,ud(e))}var ej=xee;function wee(e,t,r,o,n,i,s){var a=ru(e,r),c=ru(t,r),u=s.get(c);if(u){tu(e,r,u);return}var d=i?i(a,c,r+"",e,t,s):void 0,p=d===void 0;if(p){var f=dt(c),m=!f&&Fa(c),g=!f&&!m&&cd(c);if(d=c,f||m||g)if(dt(a))d=a;else if(XN(a))d=jE(a);else if(m)p=!1,d=vh(c,!0);else if(g)p=!1,d=LE(c,!0);else d=[];else if(QN(c)||Lr(c)){if(d=a,Lr(a))d=ej(a);else if(!Qe(a)||Yo(a))d=HE(c)}else p=!1}if(p)s.set(c,d),n(d,c,o,i,s),s.delete(c);tu(e,r,d)}var tj=wee;function rj(e,t,r,o,n){if(e===t)return;JN(t,function(i,s){if(n||(n=new yE),Qe(i))tj(e,t,s,r,rj,o,n);else{var a=o?o(ru(e,s),i,s+"",e,t,n):void 0;if(a===void 0)a=i;tu(e,s,a)}},ud)}var nj=rj;function kee(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var oj=kee;var ij=Math.max;function Eee(e,t,r){return t=ij(t===void 0?e.length-1:t,0),function(){var o=arguments,n=-1,i=ij(o.length-t,0),s=Array(i);while(++n<i)s[n]=o[t+n];n=-1;var a=Array(t+1);while(++n<t)a[n]=o[n];return a[t]=r(s),oj(e,this,a)}}var sg=Eee;function Tee(e){return function(){return e}}var sj=Tee;var Pee=!xi?md:function(e,t){return xi(e,"toString",{configurable:!0,enumerable:!1,value:sj(t),writable:!0})},aj=Pee;var Iee=800,Ree=16,$ee=Date.now;function Oee(e){var t=0,r=0;return function(){var o=$ee(),n=Ree-(o-r);if(r=o,n>0){if(++t>=Iee)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var cj=Oee;var Aee=cj(aj),ag=Aee;function Cee(e,t){return ag(sg(e,t,md),e+"")}var lj=Cee;function Mee(e,t,r){if(!Qe(r))return!1;var o=typeof t;if(o=="number"?Ei(r)&&vn(t,r.length):o=="string"&&(t in r))return dn(r[t],e);return!1}var uj=Mee;function Dee(e){return lj(function(t,r){var o=-1,n=r.length,i=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;if(i=e.length>3&&typeof i=="function"?(n--,i):void 0,s&&uj(r[0],r[1],s))i=n<3?void 0:i,n=1;t=Object(t);while(++o<n){var a=r[o];if(a)e(t,a,o,i)}return t})}var dj=Dee;var Nee=dj(function(e,t,r,o){nj(e,t,r,o)}),on=Nee;function jee(e,t,r,o){if(!Qe(e))return e;t=Sn(t,e);var n=-1,i=t.length,s=i-1,a=e;while(a!=null&&++n<i){var c=Pi(t[n]),u=r;if(c==="__proto__"||c==="constructor"||c==="prototype")return e;if(n!=s){var d=a[c];if(u=o?o(d,c,a):void 0,u===void 0)u=Qe(d)?d:vn(t[n+1])?[]:{}}rd(a,c,u),a=a[c]}return e}var pj=jee;function Uee(e,t,r){var o=-1,n=t.length,i={};while(++o<n){var s=t[o],a=QE(e,s);if(r(a,s))pj(i,Sn(s,e),a)}return i}var fj=Uee;function zee(e,t){return fj(e,t,function(r,o){return rT(e,o)})}var mj=zee;var gj=Ht?Ht.isConcatSpreadable:void 0;function Lee(e){return dt(e)||Lr(e)||!!(gj&&e&&e[gj])}var hj=Lee;function yj(e,t,r,o,n){var i=-1,s=e.length;r||(r=hj),n||(n=[]);while(++i<s){var a=e[i];if(t>0&&r(a))if(t>1)yj(a,t-1,r,o,n);else UE(n,a);else if(!o)n[n.length]=a}return n}var bj=yj;function Fee(e){var t=e==null?0:e.length;return t?bj(e,1):[]}var _j=Fee;function Bee(e){return ag(sg(e,void 0,_j),e+"")}var vj=Bee;var Hee=vj(function(e,t){return e==null?{}:mj(e,t)}),cg=Hee;import{dirname as lre,join as Xn,resolve as uu}from"path";import{join as qee}from"path";var Zee="remote-settings.json",Dx=null,Vee;function Sj(){return}function Wee(){return Sj()??qee(qt(),Zee)}function Kee(){try{let e=Bo(Wee()),t=Ze(rg(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return t}catch{return null}}function xj(){if(!Sj()&&Vee!==!0)return null;if(Dx)return Dx;let e=Kee();if(e)return Dx=e,mo(),e;return null}var wj=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];import{userInfo as Gee}from"os";var kj="com.anthropic.claudecode",nu="HKLM\\SOFTWARE\\Policies\\ClaudeCode",ou="HKCU\\SOFTWARE\\Policies\\ClaudeCode",Kn="Settings",Ej="/usr/bin/plutil",Tj=["-convert","json","-o","-","--"],Pj=5000,Nx="/mnt/c/Windows/System32/reg.exe",As="/mnt/c/Program Files/ClaudeCode";function lg(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Ot("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function Ij(){let e="";try{e=Gee().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${kj}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${kj}.plist`,label:"device-level managed preferences"}),t}import{isAbsolute as Rj}from"path";var Jee=P(()=>l.object({allowedDomains:l.array(l.string()).optional(),deniedDomains:l.array(l.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:l.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:l.array(l.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:l.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:l.boolean().optional(),allowMachLookup:l.array(l.string().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:l.number().optional(),socksProxyPort:l.number().optional(),tlsTerminate:l.object({caCertPath:l.string().min(1).optional(),caKeyPath:l.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session.")}).optional()),Xee=P(()=>l.object({allowWrite:l.array(l.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:l.array(l.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:l.array(l.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:l.array(l.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:l.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),$j=P(()=>l.object({enabled:l.boolean().optional(),failIfUnavailable:l.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:l.boolean().optional(),allowUnsandboxedCommands:l.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:Jee(),filesystem:Xee(),ignoreViolations:l.record(l.string(),l.array(l.string())).optional(),enableWeakerNestedSandbox:l.boolean().optional(),enableWeakerNetworkIsolation:l.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. "+"**Reduces security** — opens a potential data exfiltration vector through the trustd service. Default: false"),excludedCommands:l.array(l.string()).optional(),ripgrep:l.object({command:l.string(),args:l.array(l.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:l.preprocess((e)=>typeof e==="string"&&Rj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:l.preprocess((e)=>typeof e==="string"&&Rj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough());var Oj=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],Aj=["normal","vim"],Cj=["auto","tmux","in-process"],Yee=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],Mj=["auto",...Yee];var E$e=Ho()==="macos"?"⏺":"●";var iu=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],Qee=[...iu,"bubble"],Dj=Qee;var C$e=P(()=>Vv.enum(Dj)),M$e=P(()=>Vv.enum(iu));var Nj=["bash","powershell"];var su=P(()=>l.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));function ete(){let e=l.object({type:l.literal("command").describe("Shell command hook type"),command:l.string().describe("Shell command to execute"),args:l.array(l.string()).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:su(),shell:l.enum(Nj).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:l.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:l.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:l.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:l.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),t=l.object({type:l.literal("prompt").describe("LLM prompt hook type"),prompt:l.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:l.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-4-6"). If not specified, uses the default small fast model.'),continueOnBlock:l.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=l.object({type:l.literal("mcp_tool").describe("MCP tool hook type"),server:l.string().describe("Name of an already-configured MCP server to invoke"),tool:l.string().describe("Name of the tool on that server to call"),input:l.record(l.string(),l.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),o=l.object({type:l.literal("http").describe("HTTP hook type"),url:l.string().url().describe("URL to POST the hook input JSON to"),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:l.record(l.string(),l.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:l.array(l.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=l.object({type:l.literal("agent").describe("Agentic verifier hook type"),prompt:l.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:l.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:o,AgentHookSchema:n,McpToolHookSchema:r}}var jj=P(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:r,HttpHookSchema:o,McpToolHookSchema:n}=ete();return l.discriminatedUnion("type",[e,t,r,o,n])}),Uj=P(()=>l.object({matcher:l.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:l.array(jj()).describe("List of hooks to execute when the matcher matches")})),Zo=P(()=>l.partialRecord(l.enum(Xo),l.array(Uj())));var q$e=P(()=>l.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),Z$e=P(()=>l.enum(["stdio","sse","sse-ide","http","ws","sdk"])),Cs=P(()=>l.literal("comms").optional().catch(void 0)),Gn=P(()=>l.number().int().positive()),tte=P(()=>l.object({type:l.literal("stdio").optional(),command:l.string().min(1,"Command cannot be empty"),args:l.array(l.string()).default([]),env:l.record(l.string(),l.string()).optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),rte=P(()=>l.boolean()),zj=P(()=>l.object({clientId:l.string().optional(),callbackPort:l.number().int().positive().optional(),authServerMetadataUrl:l.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:l.string().min(1).optional(),xaa:rte().optional()})),nte=P(()=>l.object({type:l.literal("sse"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:zj().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs(),toolPermissions:l.record(l.string(),jx()).optional()})),ote=P(()=>l.object({type:l.literal("sse-ide"),url:l.string(),ideName:l.string(),ideRunningInWindows:l.boolean().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),ite=P(()=>l.object({type:l.literal("ws-ide"),url:l.string(),ideName:l.string(),authToken:l.string().optional(),ideRunningInWindows:l.boolean().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),ste=P(()=>l.object({type:l.enum(["http","streamable-http"]).transform(()=>"http"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:zj().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs(),toolPermissions:l.record(l.string(),jx()).optional()})),ate=P(()=>l.object({type:l.literal("ws"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),cte=P(()=>l.object({type:l.literal("sdk"),name:l.string(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional()})),jx=P(()=>l.enum(["allow","ask","blocked"])),lte=P(()=>l.object({type:l.literal("claudeai-proxy"),url:l.string(),id:l.string(),displayName:l.string().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),toolPermissions:l.record(l.string(),jx()).optional(),stateless:l.boolean().optional(),cachedInitResponse:l.record(l.string(),l.unknown()).nullish()})),ug=P(()=>l.union([tte(),nte(),ote(),ite(),ste(),ate(),cte(),lte()])),V$e=P(()=>l.object({mcpServers:l.record(l.string(),ug())}));var ute=new Set(["claude-community","claude-plugins-community"]),dte=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"]),Hj=new Set([...dte,...ute]);var pte=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,fte=/[^\u0020-\u007E]/;function mte(e){if(Hj.has(e.toLowerCase()))return!1;if(fte.test(e))return!0;return pte.test(e)}var vr=P(()=>l.string().startsWith("./")),Vo=P(()=>vr().endsWith(".json")),Lj=P(()=>l.union([vr().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"),l.string().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),zx=P(()=>vr().endsWith(".md")),Lx=P(()=>l.union([zx(),vr()])),qj=P(()=>l.string().min(1,"Marketplace must have a name").refine((e)=>!e.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine((e)=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((e)=>!mte(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine((e)=>e.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine((e)=>e.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine((e)=>e.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),Fx=P(()=>l.object({name:l.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:l.string().optional().describe("Contact email for support or feedback"),url:l.string().optional().describe("Website, GitHub profile, or organization URL")})),gte=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:l.string().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:l.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:l.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:Fx().optional().describe("Information about the plugin creator or maintainer"),homepage:l.string().url().optional().describe("Plugin homepage or documentation URL"),repository:l.string().optional().describe("Source code repository URL"),license:l.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:l.array(l.string()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:l.boolean().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:l.array(zte()).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.`)})),eOe=P(()=>l.object({description:l.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:l.lazy(()=>Zo()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),hte=P(()=>l.object({hooks:l.union([Vo().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>Zo()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),l.array(l.union([Vo().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>Zo()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),yte=P(()=>l.object({source:Lx().optional().describe("Path to command markdown file, relative to plugin root"),content:l.string().optional().describe("Inline markdown content for the command"),description:l.string().optional().describe("Command description override"),argumentHint:l.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:l.string().optional().describe("Default model for this command"),allowedTools:l.array(l.string()).optional().describe("Tools allowed when command runs")}).refine((e)=>e.source&&!e.content||!e.source&&e.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),bte=P(()=>l.object({commands:l.union([Lx().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."),l.array(Lx().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."),l.record(l.string(),yte()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),_te=P(()=>l.object({agents:l.union([zx().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."),l.array(zx().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.")])})),vte=P(()=>l.object({skills:l.union([vr().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory."),l.array(vr().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory.")).describe("List of skill directory paths, loaded in addition to the skills/ directory.")])})),Zj=P(()=>l.object({outputStyles:l.union([vr().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."),l.array(vr().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.")])})),Vj=P(()=>l.object({themes:l.union([vr().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."),l.array(vr().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.")])})),Ste=P(()=>l.object({})),Fj=P(()=>l.string().min(1)),xte=P(()=>l.string().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),wte=P(()=>l.object({mcpServers:l.union([Vo().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),Lj().describe("Path or URL to MCPB file containing MCP server configuration"),l.record(l.string(),ug()).describe("MCP server configurations keyed by server name"),l.array(l.union([Vo().describe("Path to MCP servers configuration file"),Lj().describe("Path or URL to MCPB file"),l.record(l.string(),ug()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),Wj=P(()=>l.object({type:l.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:l.string().describe("Human-readable label shown in the config dialog"),description:l.string().describe("Help text shown beneath the field in the config dialog"),required:l.boolean().optional().describe("If true, validation fails when this field is empty"),default:l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]).optional().describe("Default value used when the user provides nothing"),multiple:l.boolean().optional().describe("For string type: allow an array of strings"),sensitive:l.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:l.number().optional().describe("Minimum value (number type only)"),max:l.number().optional().describe("Maximum value (number type only)")}).strict()),kte=P(()=>l.object({userConfig:l.record(l.string().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"),Wj()).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.")})),Ete=P(()=>l.object({channels:l.array(l.object({server:l.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:l.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:l.record(l.string(),Wj()).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.")})),Bj=P(()=>l.strictObject({command:l.string().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:l.array(Fj()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:l.record(xte(),Fj()).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:l.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:l.record(l.string(),l.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:l.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:l.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:l.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:l.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:l.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:l.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:l.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:l.boolean().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.")})),Tte=P(()=>l.strictObject({name:l.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:l.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:l.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:l.union([l.literal("always"),l.string().startsWith("on-skill-invoke:").refine((e)=>e.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),Pte=P(()=>l.array(Tte()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),Kj=P(()=>l.object({monitors:l.union([Vo().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Pte()]).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.")})),Ite=P(()=>l.object({lspServers:l.union([Vo().describe("Path to .lsp.json configuration file relative to plugin root"),l.record(l.string(),Bj()).describe("LSP server configurations keyed by server name"),l.array(l.union([Vo().describe("Path to LSP configuration file"),l.record(l.string(),Bj()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),Gj=P(()=>l.string().refine((e)=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine((e)=>{let t=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,r=/^[a-z0-9][a-z0-9-._]*$/;return t.test(e)||r.test(e)},"Invalid npm package name format")),Rte=P(()=>l.object({settings:l.record(l.string(),l.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),$te=P(()=>l.object({experimental:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,l.object({...Vj().partial().shape,...Kj().partial().shape,...Zj().partial().shape,evals:l.union([l.string(),l.array(l.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),Ote=P(()=>l.object({...gte().shape,...hte().partial().shape,...bte().partial().shape,..._te().partial().shape,...vte().partial().shape,...Zj().partial().shape,...Vj().partial().shape,...Ste().shape,...Ete().partial().shape,...wte().partial().shape,...Ite().partial().shape,...Kj().partial().shape,...Rte().partial().shape,...kte().partial().shape,...$te().partial().shape})),au=P(()=>l.discriminatedUnion("source",[l.object({source:l.literal("url"),url:l.string().url().describe("Direct URL to marketplace.json file"),headers:l.record(l.string(),l.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().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.")}),l.object({source:l.literal("git"),url:l.string().describe("Full git repository URL"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().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.")}),l.object({source:l.literal("npm"),package:Gj().describe("NPM package containing marketplace.json")}),l.object({source:l.literal("file"),path:l.string().describe("Local file path to marketplace.json")}),l.object({source:l.literal("directory"),path:l.string().describe("Local directory containing .claude-plugin/marketplace.json")}),l.object({source:l.literal("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."),l.object({source:l.literal("hostPattern"),hostPattern:l.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against "github.com". For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),l.object({source:l.literal("pathPattern"),pathPattern:l.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),l.object({source:l.literal("settings"),name:qj().refine((e)=>!Hj.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:l.array(Ate()).describe("Plugin entries declared inline in settings.json"),owner:Fx().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).")])),Ux=P(()=>l.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),Jj=P(()=>l.union([l.preprocess((e)=>e==="."?"./":e,vr()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),l.object({source:l.literal("npm"),package:Gj().or(l.string().refine((e)=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(e)||!e.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:l.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:l.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),l.object({source:l.literal("url"),url:l.string().describe("Full git repository URL (https:// or git@)"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Ux().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Ux().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("git-subdir"),url:l.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:l.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Ux().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."),l.object({source:l.literal("unsupported")}).describe("Placeholder for source types this Claude Code version does not "+"recognize. 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 a clear "update Claude Code" message.')])),Ate=P(()=>l.object({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:Jj().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:l.string().optional(),version:l.string().optional(),strict:l.boolean().optional()}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine((e)=>typeof e.source==="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."}));var Cte=P(()=>l.object({cli:l.array(l.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:l.array(l.string().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:l.array(l.string().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:l.array(l.object({file:l.string().max(256),pattern:l.string().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:l.array(l.string().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.`)})),Mte=P(()=>l.object({topic:l.string().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:Cte().optional().describe("Matchers that determine when the plugin is relevant.")})),Dte=P(()=>Ote().partial().extend({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:Jj().describe("Where to fetch the plugin from"),category:l.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:l.array(l.string()).optional().describe("Tags for searchability and discovery"),strict:l.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,Mte().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.`)})),Nte=P(()=>l.object({name:l.string().min(1).refine((e)=>!e.includes(" "))}));function jte(e){let t=Dte();return e.flatMap((r,o)=>{let n=t.safeParse(r);if(n.success)return[n.data];let i=Nte().safeParse(r).data?.name,s=n.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(i)return ee(`Stubbing unparseable marketplace plugin entry (${i}): ${s}`,{level:"warn"}),[{name:i,source:{source:"unsupported"},strict:!0}];return ee(`Dropping unparseable marketplace plugin entry (index ${o}): ${s}`,{level:"warn"}),[]})}var tOe=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:qj(),version:l.string().optional().describe("Marketplace manifest version"),description:l.string().optional().describe("Human-readable description of this marketplace"),owner:Fx().describe("Marketplace maintainer or curator information"),plugins:l.array(l.unknown()).transform(jte).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:l.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:l.object({pluginRoot:l.string().optional().describe("Base path for relative plugin sources"),version:l.string().optional().describe("Marketplace version"),description:l.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:l.array(l.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust.")})),Xj=P(()=>l.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),Ute=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,zte=P(()=>l.union([l.string().regex(Ute,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),l.object({name:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),Lte=P(()=>l.object({version:l.string().describe("Currently installed version"),installedAt:l.string().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),installPath:l.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:l.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),Fte=P(()=>l.object({version:l.literal(1).describe("Schema version 1"),plugins:l.record(Xj(),Lte()).describe("Map of plugin IDs to their installation metadata")})),Bte=P(()=>l.enum(["managed","user","project","local"])),Hte=P(()=>l.object({scope:Bte().describe("Installation scope"),projectPath:l.string().optional().describe("Project path (required for project/local scopes)"),installPath:l.string().describe("Absolute path to the versioned plugin directory"),version:l.string().optional().describe("Currently installed version"),installedAt:l.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to"),auto:l.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),qte=P(()=>l.object({version:l.literal(2).describe("Schema version 2"),plugins:l.record(Xj(),l.array(Hte())).describe("Map of plugin IDs to arrays of installation entries")})),rOe=P(()=>l.union([Fte(),qte()])),Zte=P(()=>l.object({source:au().describe("Where to fetch the marketplace from"),installLocation:l.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:l.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),nOe=P(()=>l.record(l.string(),Zte()));var Vte=["autoMode","deepLink","voice","assistant","briefView","screenReader"],cu={},dg={autoMode:{buildGate:()=>!1,shape:()=>cu,permissionsShape:()=>cu,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:l.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>cu},assistant:{buildGate:()=>!1,shape:()=>cu},briefView:{buildGate:()=>!0,shape:()=>({defaultView:l.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>cu}};function Bx(){return Vte.filter((e)=>dg[e].buildGate())}function Yj(e){let t={};for(let r of e)t={...t,...dg[r].shape()};return t}function Qj(e){let t={};for(let r of e)t={...t,...dg[r].permissionsShape?.()};return t}function eU(e){let t=[];for(let r of e)t.push(...dg[r].permissionModes?.()??[]);return t}function Hx(e){let t=e.split("__"),[r,o,...n]=t;if(r!=="mcp"||!o)return null;let i=n.length>0?n.join("__"):void 0;return{serverName:o,toolName:i}}var tU={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool"};function Ms(e){return Object.hasOwn(tU,e)?tU[e]:e}var rU="workspace",mOe=`mcp__${rU}__bash`,gOe=`mcp__${rU}__web_fetch`;function qx(e){return e.includes("*")}function Wte(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function nU(e){let t=Kte(e,"(");if(t===-1)return{toolName:Ms(e)};let r=Gte(e,")");if(r===-1||r<=t)return{toolName:Ms(e)};if(r!==e.length-1)return{toolName:Ms(e)};let o=e.substring(0,t),n=e.substring(t+1,r);if(!o)return{toolName:Ms(e)};if(n===""||n==="*")return{toolName:Ms(o)};let i=Wte(n);return{toolName:Ms(o),ruleContent:i}}function Kte(e,t){for(let r=0;r<e.length;r++)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}function Gte(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}var pg={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 oU(e){return pg.filePatternTools.includes(e)}function iU(e){return pg.bashPrefixTools.includes(e)}function sU(e){return Object.hasOwn(pg.customValidation,e)?pg.customValidation[e]:void 0}function cU(e,t){let r=0,o=t-1;while(o>=0&&e[o]==="\\")r++,o--;return r%2!==0}function Zx(e,t){let r=0;for(let o=0;o<e.length;o++)if(e[o]===t&&!cU(e,o))r++;return r}function Jte(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!cU(e,t))return!0}return!1}function aU(e){if(!qx(e))return null;let t=Hx(e);if(t&&!qx(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 Vx(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let r=Zx(e,"("),o=Zx(e,")");if(r!==o)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(Jte(e)){let a=e.substring(0,e.indexOf("("));if(!a)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}}let n=nU(e),i=Hx(n.toolName);if(i){if(n.ruleContent!==void 0||Zx(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${n.toolName}" without parentheses, or use "mcp__${i.serverName}__*" for all tools`,examples:[`mcp__${i.serverName}`,`mcp__${i.serverName}__*`,i.toolName&&i.toolName!=="*"?`mcp__${i.serverName}__${i.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let a=aU(n.toolName);if(a)return a}return{valid:!0}}if(!n.toolName||n.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let a=aU(n.toolName);if(a)return a}if(!n.toolName.includes("_")&&n.toolName[0]!==n.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${Eh(String(n.toolName))}"`};let s=sU(n.toolName);if(s&&n.ruleContent!==void 0){let a=s(n.ruleContent);if(!a.valid)return a}if(iU(n.toolName)&&n.ruleContent!==void 0){let a=n.ruleContent;if(a.includes(":*")&&!a.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(a===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(oU(n.toolName)&&n.ruleContent!==void 0){if(n.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${n.toolName}(*.ts) - matches .ts files`,`${n.toolName}(src/**) - matches all files in src`,`${n.toolName}(**/*.test.ts) - matches test files`]}}return{valid:!0}}var Wx=P(()=>uU()),lU=P(()=>uU("allow"));function uU(e){return l.string().superRefine((t,r)=>{let o=Vx(t,e);if(!o.valid){let n=o.error;if(o.suggestion)n+=`. ${o.suggestion}`;if(o.examples&&o.examples.length>0)n+=`. Examples: ${o.examples.join(", ")}`;r.addIssue({code:l.ZodIssueCode.custom,message:n,params:{received:t}})}})}var Xte=P(()=>l.record(l.string(),l.coerce.string()));function gU(e){return l.object({allow:l.array(lU()).optional().describe("List of permission rules for allowed operations"),deny:l.array(Wx()).optional().describe("List of permission rules for denied operations"),ask:l.array(Wx()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:l.enum([...iu,...eU(e)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:l.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...Qj(e),additionalDirectories:l.array(l.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var NOe=P(()=>gU(Bx())),Yte=P(()=>l.object({source:au().describe("Where to fetch the marketplace from"),installLocation:l.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),fg=P(()=>l.object({serverName:l.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>Zy([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"'})),mg=P(()=>l.object({serverName:l.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>Zy([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"'})),Qte=P(()=>l.object({path:l.string().describe("Absolute path to the helper executable"),timeoutMs:l.number().int().min(1000).optional(),refreshIntervalMs:l.union([l.literal(0),l.number().int().min(60000)]).optional()})),dU=["skills","agents","hooks","mcp"],pU=Object.freeze({type:"invalid-entry-stripped"}),ere=P(()=>l.union([l.object({type:l.literal("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:l.string().describe("Regex matched against turn output (tool results and assistant text)"),url:l.string().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:l.string().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),l.object({type:l.string().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function hU(e){return l.object({$schema:l.string().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:l.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:l.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:l.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:l.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:l.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:Qte().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...Ee(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:l.object({issuer:l.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:l.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:l.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:l.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:l.object({enabled:l.boolean().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:l.number().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 120). Re-fires every interval until you take a break."),breakThresholdMinutes:l.number().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 15)"),message:l.string().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:l.object({enabled:l.boolean().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:l.string().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:l.string().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:l.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:l.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:l.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:l.boolean().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:Xte().optional().describe("Environment variables to set for Claude Code sessions"),attribution:l.object({commit:l.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:l.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:l.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,includeGitInstructions:l.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:gU(e).optional().describe("Tool usage permissions configuration"),model:l.string().optional().describe("Override the default model used by Claude Code"),fallbackModel:l.array(l.string()).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:l.array(l.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),enforceAvailableModels:l.boolean().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:l.record(l.string(),l.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:l.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:l.array(l.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:l.array(l.string()).optional().describe("List of rejected MCP servers from .mcp.json"),skillOverrides:l.record(l.string(),l.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),disableBundledSkills:l.boolean().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:l.array(fg()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:l.array(mg()).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:Zo().optional().describe("Custom commands to run before/after tool executions"),worktree:l.object({symlinkDirectories:l.array(l.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:l.array(l.string()).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:l.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:l.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:l.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:l.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:l.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableWorkflows:l.boolean().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:l.boolean().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableWorkflows:l.boolean().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowKeywordTriggerEnabled:l.boolean().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:l.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:l.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:l.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:l.array(l.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:l.array(l.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:l.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:l.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),allowAllClaudeAiMcps:l.boolean().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:l.preprocess((t)=>Array.isArray(t)?t.filter((r)=>dU.includes(r)):t,l.union([l.boolean(),l.array(l.enum(dU))])).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:l.object({type:l.literal("command"),command:l.string(),padding:l.number().optional(),refreshInterval:l.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:l.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:l.string().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:l.array(ere().catch(pU)).transform((t)=>t.filter((r)=>r!==pU)).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:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:l.record(l.string(),l.union([l.array(l.string()),l.boolean(),l.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json — setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:l.record(l.string(),Yte()).check((t)=>{for(let[r,o]of Object.entries(t.value))if(o.source.source==="settings"&&o.source.name!==r)t.issues.push({code:"custom",input:o.source.name,path:[r,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${r}" but source.name "${o.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:l.array(au()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. "+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:l.array(au()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),pluginSuggestionMarketplaces:l.array(l.string()).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:l.enum(["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:l.string().url().optional().catch(void 0).describe('@internal Cloud gateway URL to pre-fill and auto-connect to during login. Typically set in local managed settings alongside forceLoginMethod: "gateway" so users never type the URL. Hidden from public SDK types until Cloud gateway is documented.'),parentSettingsBehavior:l.enum(["first-wins","merge"]).optional().describe('Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" '+"(default): parent is dropped — admin tiers are the only policy "+`source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:l.union([l.string(),l.array(l.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:l.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:l.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:l.string().optional().describe("Controls the output style for assistant responses"),viewMode:l.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:l.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:l.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:$j().optional(),feedbackSurveyRate:l.number().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:l.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:l.object({mode:l.enum(["append","replace"]),verbs:l.array(l.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:l.object({excludeDefault:l.boolean().optional(),tips:l.array(l.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:l.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:l.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:l.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:l.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:l.boolean().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:l.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:l.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:l.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:l.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:l.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:l.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:l.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:l.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:l.array(l.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:l.record(l.string(),l.object({mcpServers:l.record(l.string(),l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:l.object({defaultEnvironmentId:l.string().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:l.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:l.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:l.string().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:l.string().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:l.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:l.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),...!1,voice:l.object({enabled:l.boolean().optional(),mode:l.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:l.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:l.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:l.array(l.object({marketplace:l.string(),plugin:l.string()})).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:l.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:l.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),totalTokensReminder:l.enum(["off","infinite","fixed","countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt and after each tool result. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),autoMemoryEnabled:l.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:l.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:l.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:l.boolean().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:l.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:l.boolean().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:l.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:l.array(l.object({id:l.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:l.string().describe("Display name for the SSH connection"),sshHost:l.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:l.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:l.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:l.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:l.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:l.array(l.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:l.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:l.union([l.enum(Mj),l.string().startsWith("custom:").transform((t)=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:l.enum(Aj).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:l.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:l.enum(Oj).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:l.boolean().optional().describe("Automatically compact conversation when context fills"),switchModelsOnFlag:l.boolean().optional().describe("When safety measures flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:l.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:l.boolean().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:l.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:l.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:l.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:l.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:l.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:l.enum(Cj).optional().catch(void 0).describe("How spawned teammates execute (tmux, in-process, auto)"),remoteControlAtStartup:l.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:l.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:l.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:l.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:l.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:l.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...Yj(e)}).passthrough()}var Wo=P(()=>hU(Bx())),fU=Object.freeze({serverName:"invalid-entry-stripped"});function mU(e,t,r){return l.array(t.catch((o)=>(r({path:`${e}[]`,message:`Invalid entry was ignored: ${o.issues[0]?.message??"failed validation"}`}),fU))).transform((o)=>o.filter((n)=>n!==fU)).optional()}function Kx(e){let t=Wo(),r={};for(let[n,i]of Object.entries(t.shape))r[n]=i.catch((s)=>{e({path:n,message:`${s.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});return r.allowedMcpServers=mU("allowedMcpServers",fg(),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=mU("deniedMcpServers",mg(),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.allowManagedMcpServersOnly=t.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),r.enforceAvailableModels=t.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),r.availableModels=l.array(l.unknown()).transform((n,i)=>{let s=[];for(let a of n)if(typeof a==="string")s.push(a);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(a)}); the entry was ignored.`});return s}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),r.forceLoginOrgUUID=t.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[])),l.object(r).passthrough().transform((n)=>{for(let i of Object.keys(n))if(n[i]===void 0)delete n[i];return n})}var an="https://code.claude.com/docs/en",tre=[{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:`${an}/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:`${an}/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:`${an}/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:`${an}/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:`${an}/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:`${an}/iam#working-directories`}}],rre={permissions:`${an}/iam#configuring-permissions`,env:`${an}/settings#environment-variables`,hooks:`${an}/hooks`};function yU(e){let t=tre.find((o)=>o.matches(e));if(!t)return null;let r={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!r.suggestion)r.suggestion=`Valid values: ${e.enumValues.map((o)=>`"${o}"`).join(", ")}`;if(!r.docLink&&e.path)r.docLink=rre[Th(e.path,".")];return r}var QOe=P(()=>Wo().strict());function bU(e){return e.code==="invalid_type"}function _U(e){return e.code==="invalid_value"}function nre(e){return e.code==="unrecognized_keys"}function vU(e){return e.code==="too_small"}function Ds(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function SU(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function lu(e,t){return e.issues.map((r)=>{let o=r.path.map(String).join("."),n=r.message,i,s,a,c,u;if(_U(r))s=r.values.map((p)=>String(p)),a=s.join(" | "),c=void 0,u=void 0;else if(bU(r)){a=r.expected;let p=SU(r.message);c=p??Ds(r.input),u=p??Ds(r.input)}else if(vU(r))a=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,u=c;let d=yU({path:o,code:r.code,expected:a,received:c,enumValues:s,message:r.message,value:c});if(_U(r))i=s?.map((p)=>`"${p}"`).join(", "),n=`Invalid value. Expected one of: ${i}`;else if(bU(r)){let p=SU(r.message)??Ds(r.input);if(r.expected==="object"&&p==="null"&&o==="")n="Invalid or malformed JSON";else n=`Expected ${r.expected}, but received ${p}`}else if(nre(r)){let p=r.keys.join(", ");n=`Unrecognized ${ST(r.keys.length,"field")}: ${p}`}else if(vU(r))n=`Number must be greater than or equal to ${r.minimum}`,i=String(r.minimum);return{file:t,path:o,message:n,expected:i,invalidValue:u,suggestion:d?.suggestion,docLink:d?.docLink}})}function ore(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!r.permissions||typeof r.permissions!=="object")return[];let o=r.permissions,n=[];for(let i of["allow","deny","ask"]){let s=o[i];if(!Array.isArray(s))continue;o[i]=s.filter((a)=>{if(typeof a!=="string")return n.push({file:t,path:`permissions.${i}`,message:`Non-string value in ${i} array was removed`,severity:"warning",invalidValue:a}),!1;let c=Vx(a,i);if(!c.valid){let u=`Invalid permission rule "${a}" was skipped: ${c.error}`;if(c.suggestion)u+=`. ${c.suggestion}`;return n.push({file:t,path:`permissions.${i}`,message:u,severity:"warning",invalidValue:a}),!1}return!0})}return n}var ire=new Set(Xo);function sre(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!("hooks"in r))return[];if(r.hooks===null||typeof r.hooks!=="object"||Array.isArray(r.hooks)){let i=Ds(r.hooks);return delete r.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${i}. This field was ignored.`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"}]}let o=r.hooks,n=[];for(let i of Object.keys(o)){if(!ire.has(i)){delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Unknown hook event "${i}" was ignored. Valid events: ${Xo.join(", ")}`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(o[i])){let s=Ds(o[i]);delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Hook event "${i}" must be an array of matchers; received ${s}. This entry was ignored.`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"})}}if(n.length>0&&Object.keys(o).length===0)delete r.hooks;return n}var are=[{key:"allowedMcpServers",schema:fg},{key:"deniedMcpServers",schema:mg}];function cre(e,t){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:n,schema:i}of are){if(!(n in r))continue;if(!Array.isArray(r[n])){let c=r[n];delete r[n],o.push({file:t,path:n,message:`"${n}" must be an array; received ${Ds(c)}. This field was ignored.`,severity:"warning",invalidValue:c});continue}let s=r[n],a=[];for(let c=0;c<s.length;c++){let u=i().safeParse(s[c]);if(u.success)a.push(s[c]);else o.push({file:t,path:`${n}[${c}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:s[c]})}if(a.length<s.length)r[n]=a}return o}function Ko(e,t,r){return[...ore(e,t),...sre(e,t),...r?.skipMcpServerEntryFilter?[]:cre(e,t)]}function Xx(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),wj.filter((r)=>t.has(r))}function ure(){return Xn(qo(),"managed-settings.json")}function wU(e){if(Ho()==="wsl"&&e.wslInherits?.()){let t=Gx(As);if(t.settings)return t;let r=Gx(qo());return{settings:r.settings,errors:[...t.errors,...r.errors]}}return Gx(qo())}function Gx(e){let t=[],r={},o=!1,{settings:n,errors:i}=gg(Xn(e,"managed-settings.json"),void 0,!0);if(t.push(...i),n&&Object.keys(n).length>0)r=on(r,n,Jn),o=!0;let s=Xn(e,"managed-settings.d");try{let u=Be().readdirSync(s).filter((d)=>(d.isFile()||d.isSymbolicLink())&&d.name.endsWith(".json")&&!d.name.startsWith(".")).map((d)=>d.name).sort();for(let d of u){let{settings:p,errors:f}=gg(Xn(s,d),void 0,!0);if(t.push(...f),p&&Object.keys(p).length>0)r=on(r,p,Jn),o=!0}}catch(u){let d=Ge(u);if(d!=="ENOENT"&&d!=="ENOTDIR")ee(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:a,...c}=r;return{settings:o&&Object.keys(c).length>0?r:null,errors:t}}function dre(e,t){if(zr(e))ee(`Broken symlink or missing file encountered for settings.json at path: ${t}`);else ee(`settings file read failed at ${t}: ${e}`,{level:"error"})}function gg(e,t,r){let o=aT(e);if(o)return{settings:o.settings?xn(o.settings):null,errors:o.errors};let n=fre(e,t,r);return cT(e,n),{settings:n.settings?xn(n.settings):null,errors:n.errors}}function kU(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 hg(e,t){let r=xn(e),o=Ko(r,t,{skipMcpServerEntryFilter:!0}),n=[],i=Kx((s)=>n.push({file:t,path:s.path,message:s.message,severity:"warning"})).safeParse(r);if(!i.success)return{settings:null,errors:[...o,...lu(i.error,t)]};return{settings:Object.keys(i.data).length>0?i.data:null,errors:[...o,...n]}}function EU(e){let t=e?.remote?e.remote():xj();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return hg(t,"remote managed settings")}function pre(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return hg(t,"parent managed settings")}function TU(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let r=xn(t),o=Ko(r,"SDK inline settings"),n=Wo().safeParse(r);if(!n.success)return{settings:null,errors:[...o,...lu(n.error,"SDK inline settings")]};return{settings:n.data,errors:o}}function fre(e,t,r){try{let o;if(t!==void 0)o=t;else{let{resolvedPath:a}=hd(Be(),e);o=Bo(a)}if(o.trim()==="")return{settings:{},errors:[]};let n=xn(Os(o,!1));if(r){let a=Ko(n,e,{skipMcpServerEntryFilter:!0}),c=[],u=Kx((d)=>c.push({file:e,path:d.path,message:d.message,severity:"warning"})).safeParse(n);if(!u.success)return{settings:null,errors:[...a,...lu(u.error,e)]};return{settings:u.data,errors:[...a,...c]}}let i=Ko(n,e),s=Wo().safeParse(n);if(!s.success){let a=lu(s.error,e);return{settings:null,errors:[...i,...a]}}return{settings:s.data,errors:i}}catch(o){if(dre(o,e),zr(o))return{settings:null,errors:[]};return{settings:null,errors:[{file:e,path:"",message:`Settings file could not be read: ${o instanceof Error?o.message:String(o)}`,severity:"fatal"}]}}}function xU(e,t){switch(e){case"userSettings":return uu(qt());case"policySettings":case"projectSettings":case"localSettings":return uu(t.cwd);case"flagSettings":return t.flagPath?lre(uu(t.flagPath)):uu(t.cwd)}}function mre(e){if(e.coworkPlugins||Ee(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function du(e,t){switch(e){case"userSettings":return Xn(xU(e,t),mre(t));case"projectSettings":case"localSettings":return Xn(xU(e,t),gre(e));case"policySettings":return ure();case"flagSettings":return t.flagPath}}function gre(e){switch(e){case"projectSettings":return Xn(".claude","settings.json");case"localSettings":return Xn(".claude","settings.local.json")}}function PU(e,t){let r=iT(e);if(r!==void 0)return r;let o=bre(e,t);return sT(e,o),o}function hre(e){return!e||e.parentSettingsBehavior==="merge"}function yre(e,t){let r={};if(e.allowManagedHooksOnly===!0)r.allowManagedHooksOnly=!0;if(e.allowManagedMcpServersOnly===!0)r.allowManagedMcpServersOnly=!0;if(e.allowManagedPermissionRulesOnly===!0)r.allowManagedPermissionRulesOnly=!0;let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)r.strictPluginOnlyCustomization=o;if(e.deniedMcpServers)r.deniedMcpServers=e.deniedMcpServers;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)r.forceLoginOrgUUID=e.forceLoginOrgUUID;if(t.allowedMcpServers===void 0&&e.allowedMcpServers)r.allowedMcpServers=e.allowedMcpServers;if(t.availableModels===void 0&&e.availableModels)r.availableModels=e.availableModels;if(e.enforceAvailableModels===!0)r.enforceAvailableModels=!0;if(e.permissions){let n=cg(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable")n.disableBypassPermissionsMode="disable";if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:s}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)n.allow=i;if(s)n.additionalDirectories=s}if(Object.keys(n).length>0)r.permissions=n}if(e.sandbox){let{network:n,filesystem:i}=e.sandbox,s={};if(e.sandbox.enabled===!0)s.enabled=!0;if(e.sandbox.failIfUnavailable===!0)s.failIfUnavailable=!0;if(e.sandbox.allowUnsandboxedCommands===!1)s.allowUnsandboxedCommands=!1;if(e.sandbox.autoAllowBashIfSandboxed===!1)s.autoAllowBashIfSandboxed=!1;if(n){let a=cg(n,["deniedDomains"]);if(n.allowManagedDomainsOnly===!0)a.allowManagedDomainsOnly=!0;if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&n.allowedDomains)a.allowedDomains=n.allowedDomains;if(Object.keys(a).length>0)s.network=a}if(i){let a=cg(i,["denyRead","denyWrite"]);if(i.allowManagedReadPathsOnly===!0)a.allowManagedReadPathsOnly=!0;if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)a.allowRead=i.allowRead;if(Object.keys(a).length>0)s.filesystem=a}if(Object.keys(s).length>0)r.sandbox=s}return r}function IU(e){if(e.helper?.())return"helper";if(EU(e).settings)return"remote";if(kU(e).settings)return Ho()==="macos"?"plist":"hklm";if((e.file?.()??wU(e)).settings)return"file";if(RU(e).parentSlice)return"parent";let t=e.hkcu?.();return t&&Object.keys(t.settings).length>0?"hkcu":null}function RU(e){let t=[],{settings:r,errors:o}=EU(e);t.push(...o);let{settings:n,errors:i}=kU(e);t.push(...i);let{settings:s,errors:a}=e.file?.()??wU(e);t.push(...a);let{settings:c,errors:u}=pre(e);t.push(...u);let d=[r,n,s].filter((h)=>h!==null),p=d[0]??null,f={allowManagedPermissionRulesOnly:d.some((h)=>h.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:d.find((h)=>h.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:d.find((h)=>h.allowedMcpServers!==void 0)?.allowedMcpServers,availableModels:d[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:d.some((h)=>h.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:d.some((h)=>h.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},m=c&&hre(p)?yre(c,f):null,g=m&&Object.keys(m).length>0?m:null;return{tiers:d,admin:p,parentSlice:g,errors:t}}function $U(e){let t=e.helper?.();if(t)return{settings:t,errors:e.helperWarnings?.()??[]};let{admin:r,parentSlice:o,errors:n}=RU(e);if(!r&&!o){let i=e.hkcu?.();if(i&&Object.keys(i.settings).length>0)return{settings:i.settings,errors:[...n,...i.errors]};return{settings:null,errors:[...n,...i?.errors??[]]}}return{settings:on({},o??{},r??{},Jn),errors:n}}function bre(e,t){if(e==="policySettings")return $U(t).settings;let r=du(e,t),{settings:o}=r?gg(r,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:n}=TU(t);if(n)return on(o||{},n,Jn)}return o}function _re(e,t){return Dd([...e,...t])}function Jn(e,t,r){if(Array.isArray(e)&&Array.isArray(t)){if(r==="fallbackModel")return t;return _re(e,t)}return}var Jx=!1;function vre(e){if(Jx)return{settings:{},errors:[]};let t=Date.now();Ql("info","settings_load_started"),Jx=!0;try{let r=lT(),o={};if(r)o=on(o,r,Jn);let n=[],i=new Set,s=new Set,a=null;for(let c of Xx(e)){if(c==="policySettings"){let{settings:d,errors:p}=$U(e);if(a=d,d)o=on(o,d,Jn);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}continue}let u=du(c,e);if(u){let d=uu(u);if(!s.has(d)){s.add(d);let{settings:p,errors:f}=gg(u,c==="flagSettings"?e.flagExpectedContent:void 0);for(let m of f){let g=`${m.file}:${m.path}:${m.message}`;if(!i.has(g))i.add(g),n.push(m)}if(p)o=on(o,p,Jn)}}if(c==="flagSettings"){let{settings:d,errors:p}=TU(e);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}if(d)o=on(o,d,Jn)}}if(a){if(a.availableModels!==void 0)o.availableModels=[...a.availableModels];if(a.enforceAvailableModels!==void 0)o.enforceAvailableModels=a.enforceAvailableModels}return Ql("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:s.size,error_count:n.length}),{settings:o,errors:n}}finally{Jx=!1}}function Sre(e){let t=nT();if(t!==null)return t;let r=vre(e);return oT(r),r}function xre(e){let{settings:t}=Sre(e);return t||{}}function OU(e){mo();let t=[];for(let r of Xx(e)){let o=PU(r,e);if(o&&Object.keys(o).length>0)t.push({source:r,settings:o})}return{effective:xre(e),sources:t}}function AU(e,t){let r=Xx(t);for(let o=r.length-1;o>=0;o--){let n=r[o];if(PU(n,t)?.[e]!==void 0)return n}return null}import{execFile as wre}from"child_process";import{existsSync as kre}from"fs";var Ere=null;function pu(e,t){return new Promise((r)=>{try{wre(e,t,{encoding:"utf-8",timeout:Pj,windowsHide:!0},(o,n)=>{r({stdout:n??"",code:o?1:0})})}catch{r({stdout:"",code:1})}})}function CU(){return(async()=>{if(process.platform==="darwin"){let e=Ij(),r=(await Promise.all(e.map(async({path:o,label:n})=>{if(!kre(o))return{stdout:"",label:n,ok:!1};let{stdout:i,code:s}=await pu(Ej,[...Tj,o]);return{stdout:i,label:n,ok:s===0&&!!i}}))).find((o)=>o.ok);return{plistStdouts:r?[{stdout:r.stdout,label:r.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[r,o]=await Promise.all([pu(t,["query",nu,"/v",Kn]),pu(t,["query",ou,"/v",Kn])]);return{plistStdouts:null,hklmStdout:r.code===0?r.stdout:null,hkcuStdout:o.code===0?o.stdout:null}}if(lg()){let[e,t]=await Promise.all([pu(Nx,["query",nu,"/v",Kn]),pu(Nx,["query",ou,"/v",Kn])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function MU(){return Ere}var Yn=Object.freeze({settings:{},errors:[]}),UU=null,zU=null,LU=!1,yg=null;function Tre(){if(yg)return;yg=(async()=>{let e=Date.now(),t=MU()??CU(),{mdm:r,hkcu:o,wslInherits:n}=Pre(await t);UU=r,zU=o,LU=n;let i=Date.now()-e;if(ee(`MDM settings load completed in ${i}ms`),Object.keys(r.settings).length>0){ee(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{Ql("info","mdm_settings_loaded",{duration_ms:i,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})()}async function FU(){if(!yg)Tre();await yg}function BU(){return UU??Yn}function HU(){return zU??Yn}function qU(){return LU}function Yx(e,t){let r=Os(e,!1);if(!r||typeof r!=="object")return{settings:{},errors:[]};let{settings:o,errors:n}=hg(r,t);return{settings:o??{},errors:n}}function DU(e,t="Settings"){let r=e.split(/\r?\n/),o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s+${o}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let i of r){let s=i.match(n);if(s&&s[1])return s[1].trimEnd()}return null}function Pre(e){let t=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:s,label:a}=e.plistStdouts[0],c=Yx(s,a),{wslInheritsWindowsSettings:u,...d}=c.settings;if(Object.keys(d).length>0)return{mdm:c,hkcu:Yn,wslInherits:!1};t.push(...c.errors)}let r=null;if(e.hklmStdout){let s=DU(e.hklmStdout);if(s)r=Yx(s,`Registry: ${nu}\\${Kn}`)}if(r)t.push(...r.errors);let o=t.length>0?{settings:{},errors:t}:Yn,n=lg(),i=!1;if(n){if(i=r?.settings.wslInheritsWindowsSettings===!0||Rre(),!i)return{mdm:o,hkcu:Yn,wslInherits:!1}}if(r){let{wslInheritsWindowsSettings:s,...a}=r.settings;if(Object.keys(a).length>0)return{mdm:r,hkcu:Yn,wslInherits:i}}if(Ire(i))return{mdm:o,hkcu:Yn,wslInherits:i};if(e.hkcuStdout){let s=DU(e.hkcuStdout);if(s){let a=Yx(s,`Registry: ${ou}\\${Kn}`);if(!n||a.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:c,...u}=a.settings;return{mdm:o,hkcu:{settings:u,errors:a.errors},wslInherits:i}}if(a.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:a.errors},wslInherits:i}}}return{mdm:o,hkcu:Yn,wslInherits:i}}function Ire(e){if(e&&jU(As))return!0;return jU(qo())}function NU(e){let t=xn(Os(Bo(e),!1));if(!t||typeof t!=="object")return!1;Ko(t,e);let{wslInheritsWindowsSettings:r,...o}=t;return Object.keys(o).length>0}function Rre(){function e(t){try{let r=Os(Bo(t),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(e(Ns(As,"managed-settings.json")))return!0;try{let t=Ns(As,"managed-settings.d");for(let r of Be().readdirSync(t))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&e(Ns(t,r.name)))return!0}catch{}return!1}function jU(e){try{if(NU(Ns(e,"managed-settings.json")))return!0}catch{}try{let t=Ns(e,"managed-settings.d"),r=Be().readdirSync(t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(NU(Ns(t,o.name)))return!0}catch{}}}catch{}return!1}var Ore={user:"userSettings",project:"projectSettings",local:"localSettings"},ZU={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},Are=["user","project","local"],Cre=new Set(["bypassPermissions","auto","acceptEdits"]),Mre=new Set(["project"]);function Dre(e){let t=e.effective.permissions?.defaultMode;if(!t||!Cre.has(t))return e.effective;for(let r=e.sources.length-1;r>=0;r--){let o=e.sources[r];if(o.settings.permissions?.defaultMode!==void 0){if(Mre.has(o.source)){let{defaultMode:n,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}async function VU(e={}){await FU();let t={cwd:$re(e.cwd??Be().cwd()),allowedSources:(e.settingSources??Are).map((r)=>Ore[r]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:BU,hkcu:HU,wslInherits:qU,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}};try{let{effective:r,sources:o}=OU(t),n=IU(t)??void 0,i=o.map(({source:a,settings:c})=>({source:ZU[a],settings:c,path:a==="policySettings"?void 0:du(a,t),...a==="policySettings"&&{policyOrigin:n}})),s={};for(let a of Object.keys(r)){let c=AU(a,t);if(c)s[a]={source:ZU[c],path:c==="policySettings"?void 0:du(c,t),...c==="policySettings"&&{policyOrigin:n}}}return{effective:r,provenance:s,sources:i}}finally{mo()}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function kCe(e){return VU(e)}async function Vre(e,t){try{await zre(e,t)}catch(r){if(!zr(r))throw r}}async function Wre(e,t){if(!e)return;let r=e;try{let o=Ze(e);if(o?.claudeAiOauth?.refreshToken)delete o.claudeAiOauth.refreshToken,r=pe(o)}catch{}await QU(t,r,{mode:384})}function Kre(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=v0(_0);return new Promise((t)=>{Nre("security",["find-generic-password","-a",S0(),"-w","-s",e],{encoding:"utf-8",timeout:5000},(r,o)=>t(r?void 0:o.trim()||void 0))})}async function rz(e,t,r,o,n=60000){if(!Se(t))return;let i=rr(r),s=await Ar(e.load({projectKey:i,sessionId:t}),n,`SessionStore.load() timed out after ${n}ms for session ${t}`);if(!s||s.length===0)return;let a=zt(Hre(),`claude-resume-${ow()}`);try{let c=zt(a,"projects",i);await Qx(c,{recursive:!0});let u=zt(c,`${t}.jsonl`);await ec(u,s);let d=o?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,p=d??zt(ew(),".claude"),f;try{f=await YU(zt(p,".credentials.json"),"utf-8")}catch(m){if(!zr(m))throw m}if(!d&&!(o??process.env).ANTHROPIC_API_KEY&&!(o??process.env).CLAUDE_CODE_OAUTH_TOKEN)f=await Kre()??f;if(await Wre(f,zt(a,".credentials.json")),await Vre(zt(d??ew(),".claude.json"),zt(a,".claude.json")),e.listSubkeys){let m=zt(c,t),g=await Ar(e.listSubkeys({projectKey:i,sessionId:t}),n,`SessionStore.listSubkeys() timed out after ${n}ms for session ${t}`);for(let h of g){let y=fu(m,h+".jsonl");if(!h||ez(h)||h.split(/[\\/]/).includes("..")||!y.startsWith(m+iw)){ee(`[SessionStore] skipping unsafe subpath from listSubkeys: ${h}`,{level:"warn"});continue}let v=await Ar(e.load({projectKey:i,sessionId:t,subpath:h}),n,`SessionStore.load() timed out after ${n}ms for session ${t} subpath ${h}`);if(!v||v.length===0)continue;let x=[],w=[];for(let A of v)if(nw(A))x.push(A);else w.push(A);if(w.length>0)await Qx(WU(y),{recursive:!0}),await ec(y,w);if(x.length>0){let A=x.at(-1),U=fu(m,h+".meta.json");await Qx(WU(U),{recursive:!0});let{type:se,...Le}=A;await QU(U,pe(Le),{mode:384})}}}return a}catch(c){throw await bg(a),c}}function tw(e,t,r,o){let{systemPrompt:n,settings:i,managedSettings:s,settingSources:a,sandbox:c,...u}=e??{},d,p,f;if(n===void 0)d="";else if(typeof n==="string")d=n;else if(Array.isArray(n))d=n;else if(n.type==="preset")p=n.append,f=n.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.176";let{abortController:m=qs(),additionalDirectories:g=[],agent:h,agents:y,allowedTools:v=[],betas:x,canUseTool:w,continue:A,cwd:U,debug:se,debugFile:Le,disallowedTools:Ye=[],tools:Lt,env:yt,executable:Qn=_u()?"bun":"node",executableArgs:Go=[],extraArgs:Rr={},fallbackModel:js,enableFileCheckpointing:cn,toolConfig:V,forkSession:mu,hooks:gu,includeHookEvents:Us,includePartialMessages:zs,forwardSubagentText:Ls,onElicitation:hu,onUserDialog:je,supportedDialogKinds:Ft,persistSession:Sr,sessionStore:$r,sessionStoreFlush:az,thinking:Fs,effort:cz,maxThinkingTokens:vg,maxTurns:lz,maxBudgetUsd:uz,taskBudget:dz,mcpServers:sw,model:pz,outputFormat:aw,permissionMode:fz="default",allowDangerouslySkipPermissions:mz=!1,permissionPromptToolName:gz,plugins:hz,getOAuthToken:cw,getHostAuthToken:lw,workload:uw,resume:dw,resumeSessionAt:yz,sessionId:bz,skills:pw,stderr:_z,strictMcpConfig:vz}=u;if($r&&Sr===!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(Ft!==void 0&&Ft.length>0&&!je)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if($r&&A&&!dw&&!$r.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if($r&&cn)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if($r&&u.spawnClaudeCodeProcess)ee("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});let Sg=u.pathToClaudeCodeExecutable;if(!Sg){let $t=Zre(import.meta.url),nr=Bre($t),eo=LT((Jo)=>nr.resolve(Jo));if(!eo)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.`);Sg=eo}let fw=aw?.type==="json_schema"?aw.schema:void 0,ut=yt?{...yt}:{...process.env};if(!ut.CLAUDE_CODE_ENTRYPOINT)ut.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!ut.CLAUDE_AGENT_SDK_VERSION)ut.CLAUDE_AGENT_SDK_VERSION="0.3.176";if(cn)ut.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(cw)ut.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(lw)ut.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(V?.askUserQuestion?.previewFormat)ut.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=V.askUserQuestion.previewFormat;let xg={};if(_g.propagation.inject(_g.context.active(),xg),"traceparent"in xg){for(let $t of["TRACEPARENT","TRACESTATE"])if(!($t in(yt??{})))delete ut[$t]}for(let[$t,nr]of Object.entries(xg)){let eo=$t.toUpperCase();if(!(eo in(yt??{})))ut[eo]=nr}let mw={},gw=new Map;if(sw)for(let[$t,nr]of Object.entries(sw))if(nr.type==="sdk"&&nr.instance)gw.set($t,nr.instance);else mw[$t]=nr;let Bs;if(Fs)switch(Fs.type){case"adaptive":Bs={type:"adaptive",display:Fs.display};break;case"enabled":Bs={type:"enabled",budgetTokens:Fs.budgetTokens,display:Fs.display};break;case"disabled":Bs={type:"disabled"};break}else if(vg!==void 0)Bs=vg===0?{type:"disabled"}:{type:"enabled",budgetTokens:vg};if(r){if(ut.CLAUDE_CONFIG_DIR=r,process.platform==="win32")ut.CLAUDE_SECURESTORAGE_CONFIG_DIR=yt?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??yt?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let hw=new Dh({abortController:m,additionalDirectories:g,agent:h,betas:x,cwd:U,debug:se,debugFile:Le,executable:Qn,executableArgs:Go,extraArgs:uw?{...Rr,workload:uw}:Rr,pathToClaudeCodeExecutable:Sg,env:ut,forkSession:mu,stderr:_z,thinkingConfig:Bs,effort:cz,maxTurns:lz,maxBudgetUsd:uz,taskBudget:dz,model:pz,fallbackModel:js,jsonSchema:fw,permissionMode:fz,allowDangerouslySkipPermissions:mz,permissionPromptToolName:gz,continueConversation:$r?void 0:A,resume:dw,resumeSessionAt:yz,sessionId:bz,settings:typeof i==="object"?pe(i):i,managedSettings:s?pe(s):void 0,settingSources:a,skills:pw,allowedTools:v,disallowedTools:Ye,tools:Lt,mcpServers:mw,strictMcpConfig:vz,canUseTool:!!w,hooks:!!gu,includeHookEvents:Us,includePartialMessages:zs,persistSession:Sr,sessionMirror:!!$r,plugins:hz,sandbox:c,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),Sz={systemPrompt:d,appendSystemPrompt:p,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:f,agents:y,title:u.title,skills:pw,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:Ls,supportedDialogKinds:Ft},wg=new zh(hw,t,w,gu,m,gw,fw,Sz,hu,cw,lw,je);if($r){let $t=()=>zt(ut.CLAUDE_CONFIG_DIR??zt(ew(),".claude"),"projects"),nr=az==="eager",eo=new Lh(async(Jo,kg)=>{let Hs=XU(Jo,$t());if(Hs)await $r.append(Hs,kg);else ee(`[SessionStore] dropping mirror frame: filePath ${Jo} is not under ${$t()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(Jo,kg)=>{let Hs=XU(Jo,$t());if(Hs)wg.reportMirrorError(Hs,kg.message)},nr?0:vd,nr?0:Sd);wg.setTranscriptMirrorBatcher(eo)}return{queryInstance:wg,transport:hw,abortController:m,processEnv:ut}}function rw(e,t,r,o){if(typeof r==="string")t.write(pe({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:r}]},parent_tool_use_id:null})+`
115
+ `)){let o=r.match(/^(ID|VERSION_ID)=(.*)$/);if(o&&o[1]&&o[2]){let n=o[2].replace(/^"|"$/g,"");if(o[1]==="ID")e.linuxDistroId=n;else e.linuxDistroVersion=n}}}catch{}return e});var uRe=Ce(()=>{if(process.platform!=="darwin")return;let t=KN().match(/^(\d+)\./);if(!t||!t[1])return;return parseInt(t[1],10)-9});var qo=Ce(function(){switch(Ho()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),gRe=Ce(function(){return uee(qo(),"managed-settings.d")});function dee(e,t,r){if(r!==void 0&&!dn(e[t],r)||r===void 0&&!(t in e))wi(e,t,r)}var tu=dee;function pee(e){return function(t,r,o){var n=-1,i=Object(t),s=o(t),a=s.length;while(a--){var c=s[e?a:++n];if(r(i[c],c,i)===!1)break}return t}}var GN=pee;var fee=GN(),JN=fee;function mee(e){return Kt(e)&&Ei(e)}var XN=mee;var gee="[object Object]",hee=Function.prototype,yee=Object.prototype,YN=hee.toString,bee=yee.hasOwnProperty,_ee=YN.call(Object);function vee(e){if(!Kt(e)||wr(e)!=gee)return!1;var t=fd(e);if(t===null)return!0;var r=bee.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&YN.call(r)==_ee}var QN=vee;function See(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var ru=See;function xee(e){return bE(e,ud(e))}var ej=xee;function wee(e,t,r,o,n,i,s){var a=ru(e,r),c=ru(t,r),u=s.get(c);if(u){tu(e,r,u);return}var d=i?i(a,c,r+"",e,t,s):void 0,p=d===void 0;if(p){var f=dt(c),m=!f&&Fa(c),g=!f&&!m&&cd(c);if(d=c,f||m||g)if(dt(a))d=a;else if(XN(a))d=jE(a);else if(m)p=!1,d=vh(c,!0);else if(g)p=!1,d=LE(c,!0);else d=[];else if(QN(c)||Lr(c)){if(d=a,Lr(a))d=ej(a);else if(!Qe(a)||Yo(a))d=HE(c)}else p=!1}if(p)s.set(c,d),n(d,c,o,i,s),s.delete(c);tu(e,r,d)}var tj=wee;function rj(e,t,r,o,n){if(e===t)return;JN(t,function(i,s){if(n||(n=new yE),Qe(i))tj(e,t,s,r,rj,o,n);else{var a=o?o(ru(e,s),i,s+"",e,t,n):void 0;if(a===void 0)a=i;tu(e,s,a)}},ud)}var nj=rj;function kee(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var oj=kee;var ij=Math.max;function Eee(e,t,r){return t=ij(t===void 0?e.length-1:t,0),function(){var o=arguments,n=-1,i=ij(o.length-t,0),s=Array(i);while(++n<i)s[n]=o[t+n];n=-1;var a=Array(t+1);while(++n<t)a[n]=o[n];return a[t]=r(s),oj(e,this,a)}}var sg=Eee;function Tee(e){return function(){return e}}var sj=Tee;var Pee=!xi?md:function(e,t){return xi(e,"toString",{configurable:!0,enumerable:!1,value:sj(t),writable:!0})},aj=Pee;var Iee=800,Ree=16,$ee=Date.now;function Oee(e){var t=0,r=0;return function(){var o=$ee(),n=Ree-(o-r);if(r=o,n>0){if(++t>=Iee)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var cj=Oee;var Aee=cj(aj),ag=Aee;function Cee(e,t){return ag(sg(e,t,md),e+"")}var lj=Cee;function Mee(e,t,r){if(!Qe(r))return!1;var o=typeof t;if(o=="number"?Ei(r)&&vn(t,r.length):o=="string"&&(t in r))return dn(r[t],e);return!1}var uj=Mee;function Dee(e){return lj(function(t,r){var o=-1,n=r.length,i=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;if(i=e.length>3&&typeof i=="function"?(n--,i):void 0,s&&uj(r[0],r[1],s))i=n<3?void 0:i,n=1;t=Object(t);while(++o<n){var a=r[o];if(a)e(t,a,o,i)}return t})}var dj=Dee;var Nee=dj(function(e,t,r,o){nj(e,t,r,o)}),on=Nee;function jee(e,t,r,o){if(!Qe(e))return e;t=Sn(t,e);var n=-1,i=t.length,s=i-1,a=e;while(a!=null&&++n<i){var c=Pi(t[n]),u=r;if(c==="__proto__"||c==="constructor"||c==="prototype")return e;if(n!=s){var d=a[c];if(u=o?o(d,c,a):void 0,u===void 0)u=Qe(d)?d:vn(t[n+1])?[]:{}}rd(a,c,u),a=a[c]}return e}var pj=jee;function Uee(e,t,r){var o=-1,n=t.length,i={};while(++o<n){var s=t[o],a=QE(e,s);if(r(a,s))pj(i,Sn(s,e),a)}return i}var fj=Uee;function zee(e,t){return fj(e,t,function(r,o){return rT(e,o)})}var mj=zee;var gj=Ht?Ht.isConcatSpreadable:void 0;function Lee(e){return dt(e)||Lr(e)||!!(gj&&e&&e[gj])}var hj=Lee;function yj(e,t,r,o,n){var i=-1,s=e.length;r||(r=hj),n||(n=[]);while(++i<s){var a=e[i];if(t>0&&r(a))if(t>1)yj(a,t-1,r,o,n);else UE(n,a);else if(!o)n[n.length]=a}return n}var bj=yj;function Fee(e){var t=e==null?0:e.length;return t?bj(e,1):[]}var _j=Fee;function Bee(e){return ag(sg(e,void 0,_j),e+"")}var vj=Bee;var Hee=vj(function(e,t){return e==null?{}:mj(e,t)}),cg=Hee;import{dirname as lre,join as Xn,resolve as uu}from"path";import{join as qee}from"path";var Zee="remote-settings.json",Dx=null,Vee;function Sj(){return}function Wee(){return Sj()??qee(qt(),Zee)}function Kee(){try{let e=Bo(Wee()),t=Ze(rg(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return t}catch{return null}}function xj(){if(!Sj()&&Vee!==!0)return null;if(Dx)return Dx;let e=Kee();if(e)return Dx=e,mo(),e;return null}var wj=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];import{userInfo as Gee}from"os";var kj="com.anthropic.claudecode",nu="HKLM\\SOFTWARE\\Policies\\ClaudeCode",ou="HKCU\\SOFTWARE\\Policies\\ClaudeCode",Kn="Settings",Ej="/usr/bin/plutil",Tj=["-convert","json","-o","-","--"],Pj=5000,Nx="/mnt/c/Windows/System32/reg.exe",As="/mnt/c/Program Files/ClaudeCode";function lg(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Ot("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function Ij(){let e="";try{e=Gee().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${kj}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${kj}.plist`,label:"device-level managed preferences"}),t}import{isAbsolute as Rj}from"path";var Jee=P(()=>l.object({allowedDomains:l.array(l.string()).optional(),deniedDomains:l.array(l.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:l.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:l.array(l.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:l.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:l.boolean().optional(),allowMachLookup:l.array(l.string().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:l.number().optional(),socksProxyPort:l.number().optional(),tlsTerminate:l.object({caCertPath:l.string().min(1).optional(),caKeyPath:l.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session.")}).optional()),Xee=P(()=>l.object({allowWrite:l.array(l.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:l.array(l.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:l.array(l.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:l.array(l.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:l.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),$j=P(()=>l.object({enabled:l.boolean().optional(),failIfUnavailable:l.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:l.boolean().optional(),allowUnsandboxedCommands:l.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:Jee(),filesystem:Xee(),ignoreViolations:l.record(l.string(),l.array(l.string())).optional(),enableWeakerNestedSandbox:l.boolean().optional(),enableWeakerNetworkIsolation:l.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. "+"**Reduces security** — opens a potential data exfiltration vector through the trustd service. Default: false"),excludedCommands:l.array(l.string()).optional(),ripgrep:l.object({command:l.string(),args:l.array(l.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:l.preprocess((e)=>typeof e==="string"&&Rj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:l.preprocess((e)=>typeof e==="string"&&Rj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough());var Oj=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],Aj=["normal","vim"],Cj=["auto","tmux","in-process"],Yee=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],Mj=["auto",...Yee];var E$e=Ho()==="macos"?"⏺":"●";var iu=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],Qee=[...iu,"bubble"],Dj=Qee;var C$e=P(()=>Vv.enum(Dj)),M$e=P(()=>Vv.enum(iu));var Nj=["bash","powershell"];var su=P(()=>l.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));function ete(){let e=l.object({type:l.literal("command").describe("Shell command hook type"),command:l.string().describe("Shell command to execute"),args:l.array(l.string()).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:su(),shell:l.enum(Nj).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:l.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:l.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:l.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:l.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),t=l.object({type:l.literal("prompt").describe("LLM prompt hook type"),prompt:l.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:l.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-4-6"). If not specified, uses the default small fast model.'),continueOnBlock:l.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=l.object({type:l.literal("mcp_tool").describe("MCP tool hook type"),server:l.string().describe("Name of an already-configured MCP server to invoke"),tool:l.string().describe("Name of the tool on that server to call"),input:l.record(l.string(),l.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),o=l.object({type:l.literal("http").describe("HTTP hook type"),url:l.string().url().describe("URL to POST the hook input JSON to"),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:l.record(l.string(),l.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:l.array(l.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=l.object({type:l.literal("agent").describe("Agentic verifier hook type"),prompt:l.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:su(),timeout:l.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:l.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:o,AgentHookSchema:n,McpToolHookSchema:r}}var jj=P(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:r,HttpHookSchema:o,McpToolHookSchema:n}=ete();return l.discriminatedUnion("type",[e,t,r,o,n])}),Uj=P(()=>l.object({matcher:l.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:l.array(jj()).describe("List of hooks to execute when the matcher matches")})),Zo=P(()=>l.partialRecord(l.enum(Xo),l.array(Uj())));var q$e=P(()=>l.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),Z$e=P(()=>l.enum(["stdio","sse","sse-ide","http","ws","sdk"])),Cs=P(()=>l.literal("comms").optional().catch(void 0)),Gn=P(()=>l.number().int().positive()),tte=P(()=>l.object({type:l.literal("stdio").optional(),command:l.string().min(1,"Command cannot be empty"),args:l.array(l.string()).default([]),env:l.record(l.string(),l.string()).optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),rte=P(()=>l.boolean()),zj=P(()=>l.object({clientId:l.string().optional(),callbackPort:l.number().int().positive().optional(),authServerMetadataUrl:l.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:l.string().min(1).optional(),xaa:rte().optional()})),nte=P(()=>l.object({type:l.literal("sse"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:zj().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs(),toolPermissions:l.record(l.string(),jx()).optional()})),ote=P(()=>l.object({type:l.literal("sse-ide"),url:l.string(),ideName:l.string(),ideRunningInWindows:l.boolean().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),ite=P(()=>l.object({type:l.literal("ws-ide"),url:l.string(),ideName:l.string(),authToken:l.string().optional(),ideRunningInWindows:l.boolean().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),ste=P(()=>l.object({type:l.enum(["http","streamable-http"]).transform(()=>"http"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:zj().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs(),toolPermissions:l.record(l.string(),jx()).optional()})),ate=P(()=>l.object({type:l.literal("ws"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),role:Cs()})),cte=P(()=>l.object({type:l.literal("sdk"),name:l.string(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional()})),jx=P(()=>l.enum(["allow","ask","blocked"])),lte=P(()=>l.object({type:l.literal("claudeai-proxy"),url:l.string(),id:l.string(),displayName:l.string().optional(),timeout:Gn().optional(),alwaysLoad:l.boolean().optional(),toolPermissions:l.record(l.string(),jx()).optional(),stateless:l.boolean().optional(),cachedInitResponse:l.record(l.string(),l.unknown()).nullish()})),ug=P(()=>l.union([tte(),nte(),ote(),ite(),ste(),ate(),cte(),lte()])),V$e=P(()=>l.object({mcpServers:l.record(l.string(),ug())}));var ute=new Set(["claude-community","claude-plugins-community"]),dte=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"]),Hj=new Set([...dte,...ute]);var pte=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,fte=/[^\u0020-\u007E]/;function mte(e){if(Hj.has(e.toLowerCase()))return!1;if(fte.test(e))return!0;return pte.test(e)}var vr=P(()=>l.string().startsWith("./")),Vo=P(()=>vr().endsWith(".json")),Lj=P(()=>l.union([vr().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"),l.string().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),zx=P(()=>vr().endsWith(".md")),Lx=P(()=>l.union([zx(),vr()])),qj=P(()=>l.string().min(1,"Marketplace must have a name").refine((e)=>!e.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine((e)=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((e)=>!mte(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine((e)=>e.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine((e)=>e.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine((e)=>e.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),Fx=P(()=>l.object({name:l.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:l.string().optional().describe("Contact email for support or feedback"),url:l.string().optional().describe("Website, GitHub profile, or organization URL")})),gte=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:l.string().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:l.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:l.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:Fx().optional().describe("Information about the plugin creator or maintainer"),homepage:l.string().url().optional().describe("Plugin homepage or documentation URL"),repository:l.string().optional().describe("Source code repository URL"),license:l.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:l.array(l.string()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:l.boolean().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:l.array(zte()).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.`)})),eOe=P(()=>l.object({description:l.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:l.lazy(()=>Zo()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),hte=P(()=>l.object({hooks:l.union([Vo().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>Zo()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),l.array(l.union([Vo().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>Zo()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),yte=P(()=>l.object({source:Lx().optional().describe("Path to command markdown file, relative to plugin root"),content:l.string().optional().describe("Inline markdown content for the command"),description:l.string().optional().describe("Command description override"),argumentHint:l.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:l.string().optional().describe("Default model for this command"),allowedTools:l.array(l.string()).optional().describe("Tools allowed when command runs")}).refine((e)=>e.source&&!e.content||!e.source&&e.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),bte=P(()=>l.object({commands:l.union([Lx().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."),l.array(Lx().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."),l.record(l.string(),yte()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),_te=P(()=>l.object({agents:l.union([zx().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."),l.array(zx().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.")])})),vte=P(()=>l.object({skills:l.union([vr().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory."),l.array(vr().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory.")).describe("List of skill directory paths, loaded in addition to the skills/ directory.")])})),Zj=P(()=>l.object({outputStyles:l.union([vr().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."),l.array(vr().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.")])})),Vj=P(()=>l.object({themes:l.union([vr().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."),l.array(vr().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.")])})),Ste=P(()=>l.object({})),Fj=P(()=>l.string().min(1)),xte=P(()=>l.string().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),wte=P(()=>l.object({mcpServers:l.union([Vo().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),Lj().describe("Path or URL to MCPB file containing MCP server configuration"),l.record(l.string(),ug()).describe("MCP server configurations keyed by server name"),l.array(l.union([Vo().describe("Path to MCP servers configuration file"),Lj().describe("Path or URL to MCPB file"),l.record(l.string(),ug()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),Wj=P(()=>l.object({type:l.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:l.string().describe("Human-readable label shown in the config dialog"),description:l.string().describe("Help text shown beneath the field in the config dialog"),required:l.boolean().optional().describe("If true, validation fails when this field is empty"),default:l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]).optional().describe("Default value used when the user provides nothing"),multiple:l.boolean().optional().describe("For string type: allow an array of strings"),sensitive:l.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:l.number().optional().describe("Minimum value (number type only)"),max:l.number().optional().describe("Maximum value (number type only)")}).strict()),kte=P(()=>l.object({userConfig:l.record(l.string().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"),Wj()).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.")})),Ete=P(()=>l.object({channels:l.array(l.object({server:l.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:l.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:l.record(l.string(),Wj()).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.")})),Bj=P(()=>l.strictObject({command:l.string().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:l.array(Fj()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:l.record(xte(),Fj()).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:l.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:l.record(l.string(),l.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:l.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:l.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:l.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:l.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:l.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:l.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:l.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:l.boolean().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.")})),Tte=P(()=>l.strictObject({name:l.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:l.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:l.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:l.union([l.literal("always"),l.string().startsWith("on-skill-invoke:").refine((e)=>e.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),Pte=P(()=>l.array(Tte()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),Kj=P(()=>l.object({monitors:l.union([Vo().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Pte()]).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.")})),Ite=P(()=>l.object({lspServers:l.union([Vo().describe("Path to .lsp.json configuration file relative to plugin root"),l.record(l.string(),Bj()).describe("LSP server configurations keyed by server name"),l.array(l.union([Vo().describe("Path to LSP configuration file"),l.record(l.string(),Bj()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),Gj=P(()=>l.string().refine((e)=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine((e)=>{let t=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,r=/^[a-z0-9][a-z0-9-._]*$/;return t.test(e)||r.test(e)},"Invalid npm package name format")),Rte=P(()=>l.object({settings:l.record(l.string(),l.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),$te=P(()=>l.object({experimental:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,l.object({...Vj().partial().shape,...Kj().partial().shape,...Zj().partial().shape,evals:l.union([l.string(),l.array(l.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),Ote=P(()=>l.object({...gte().shape,...hte().partial().shape,...bte().partial().shape,..._te().partial().shape,...vte().partial().shape,...Zj().partial().shape,...Vj().partial().shape,...Ste().shape,...Ete().partial().shape,...wte().partial().shape,...Ite().partial().shape,...Kj().partial().shape,...Rte().partial().shape,...kte().partial().shape,...$te().partial().shape})),au=P(()=>l.discriminatedUnion("source",[l.object({source:l.literal("url"),url:l.string().url().describe("Direct URL to marketplace.json file"),headers:l.record(l.string(),l.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().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.")}),l.object({source:l.literal("git"),url:l.string().describe("Full git repository URL"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().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.")}),l.object({source:l.literal("npm"),package:Gj().describe("NPM package containing marketplace.json")}),l.object({source:l.literal("file"),path:l.string().describe("Local file path to marketplace.json")}),l.object({source:l.literal("directory"),path:l.string().describe("Local directory containing .claude-plugin/marketplace.json")}),l.object({source:l.literal("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."),l.object({source:l.literal("hostPattern"),hostPattern:l.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against "github.com". For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),l.object({source:l.literal("pathPattern"),pathPattern:l.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),l.object({source:l.literal("settings"),name:qj().refine((e)=>!Hj.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:l.array(Ate()).describe("Plugin entries declared inline in settings.json"),owner:Fx().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).")])),Ux=P(()=>l.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),Jj=P(()=>l.union([l.preprocess((e)=>e==="."?"./":e,vr()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),l.object({source:l.literal("npm"),package:Gj().or(l.string().refine((e)=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(e)||!e.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:l.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:l.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),l.object({source:l.literal("url"),url:l.string().describe("Full git repository URL (https:// or git@)"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Ux().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Ux().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("git-subdir"),url:l.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:l.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Ux().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."),l.object({source:l.literal("unsupported")}).describe("Placeholder for source types this Claude Code version does not "+"recognize. 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 a clear "update Claude Code" message.')])),Ate=P(()=>l.object({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:Jj().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:l.string().optional(),version:l.string().optional(),strict:l.boolean().optional()}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine((e)=>typeof e.source==="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."}));var Cte=P(()=>l.object({cli:l.array(l.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:l.array(l.string().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:l.array(l.string().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:l.array(l.object({file:l.string().max(256),pattern:l.string().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:l.array(l.string().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.`)})),Mte=P(()=>l.object({topic:l.string().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:Cte().optional().describe("Matchers that determine when the plugin is relevant.")})),Dte=P(()=>Ote().partial().extend({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:Jj().describe("Where to fetch the plugin from"),category:l.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:l.array(l.string()).optional().describe("Tags for searchability and discovery"),strict:l.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,Mte().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.`)})),Nte=P(()=>l.object({name:l.string().min(1).refine((e)=>!e.includes(" "))}));function jte(e){let t=Dte();return e.flatMap((r,o)=>{let n=t.safeParse(r);if(n.success)return[n.data];let i=Nte().safeParse(r).data?.name,s=n.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(i)return ee(`Stubbing unparseable marketplace plugin entry (${i}): ${s}`,{level:"warn"}),[{name:i,source:{source:"unsupported"},strict:!0}];return ee(`Dropping unparseable marketplace plugin entry (index ${o}): ${s}`,{level:"warn"}),[]})}var tOe=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:qj(),version:l.string().optional().describe("Marketplace manifest version"),description:l.string().optional().describe("Human-readable description of this marketplace"),owner:Fx().describe("Marketplace maintainer or curator information"),plugins:l.array(l.unknown()).transform(jte).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:l.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:l.object({pluginRoot:l.string().optional().describe("Base path for relative plugin sources"),version:l.string().optional().describe("Marketplace version"),description:l.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:l.array(l.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust.")})),Xj=P(()=>l.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),Ute=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,zte=P(()=>l.union([l.string().regex(Ute,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),l.object({name:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),Lte=P(()=>l.object({version:l.string().describe("Currently installed version"),installedAt:l.string().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),installPath:l.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:l.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),Fte=P(()=>l.object({version:l.literal(1).describe("Schema version 1"),plugins:l.record(Xj(),Lte()).describe("Map of plugin IDs to their installation metadata")})),Bte=P(()=>l.enum(["managed","user","project","local"])),Hte=P(()=>l.object({scope:Bte().describe("Installation scope"),projectPath:l.string().optional().describe("Project path (required for project/local scopes)"),installPath:l.string().describe("Absolute path to the versioned plugin directory"),version:l.string().optional().describe("Currently installed version"),installedAt:l.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to"),auto:l.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),qte=P(()=>l.object({version:l.literal(2).describe("Schema version 2"),plugins:l.record(Xj(),l.array(Hte())).describe("Map of plugin IDs to arrays of installation entries")})),rOe=P(()=>l.union([Fte(),qte()])),Zte=P(()=>l.object({source:au().describe("Where to fetch the marketplace from"),installLocation:l.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:l.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),nOe=P(()=>l.record(l.string(),Zte()));var Vte=["autoMode","deepLink","voice","assistant","briefView","screenReader"],cu={},dg={autoMode:{buildGate:()=>!1,shape:()=>cu,permissionsShape:()=>cu,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:l.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>cu},assistant:{buildGate:()=>!1,shape:()=>cu},briefView:{buildGate:()=>!0,shape:()=>({defaultView:l.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>cu}};function Bx(){return Vte.filter((e)=>dg[e].buildGate())}function Yj(e){let t={};for(let r of e)t={...t,...dg[r].shape()};return t}function Qj(e){let t={};for(let r of e)t={...t,...dg[r].permissionsShape?.()};return t}function eU(e){let t=[];for(let r of e)t.push(...dg[r].permissionModes?.()??[]);return t}function Hx(e){let t=e.split("__"),[r,o,...n]=t;if(r!=="mcp"||!o)return null;let i=n.length>0?n.join("__"):void 0;return{serverName:o,toolName:i}}var tU={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool"};function Ms(e){return Object.hasOwn(tU,e)?tU[e]:e}var rU="workspace",mOe=`mcp__${rU}__bash`,gOe=`mcp__${rU}__web_fetch`;function qx(e){return e.includes("*")}function Wte(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function nU(e){let t=Kte(e,"(");if(t===-1)return{toolName:Ms(e)};let r=Gte(e,")");if(r===-1||r<=t)return{toolName:Ms(e)};if(r!==e.length-1)return{toolName:Ms(e)};let o=e.substring(0,t),n=e.substring(t+1,r);if(!o)return{toolName:Ms(e)};if(n===""||n==="*")return{toolName:Ms(o)};let i=Wte(n);return{toolName:Ms(o),ruleContent:i}}function Kte(e,t){for(let r=0;r<e.length;r++)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}function Gte(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}var pg={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 oU(e){return pg.filePatternTools.includes(e)}function iU(e){return pg.bashPrefixTools.includes(e)}function sU(e){return Object.hasOwn(pg.customValidation,e)?pg.customValidation[e]:void 0}function cU(e,t){let r=0,o=t-1;while(o>=0&&e[o]==="\\")r++,o--;return r%2!==0}function Zx(e,t){let r=0;for(let o=0;o<e.length;o++)if(e[o]===t&&!cU(e,o))r++;return r}function Jte(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!cU(e,t))return!0}return!1}function aU(e){if(!qx(e))return null;let t=Hx(e);if(t&&!qx(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 Vx(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let r=Zx(e,"("),o=Zx(e,")");if(r!==o)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(Jte(e)){let a=e.substring(0,e.indexOf("("));if(!a)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}}let n=nU(e),i=Hx(n.toolName);if(i){if(n.ruleContent!==void 0||Zx(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${n.toolName}" without parentheses, or use "mcp__${i.serverName}__*" for all tools`,examples:[`mcp__${i.serverName}`,`mcp__${i.serverName}__*`,i.toolName&&i.toolName!=="*"?`mcp__${i.serverName}__${i.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let a=aU(n.toolName);if(a)return a}return{valid:!0}}if(!n.toolName||n.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let a=aU(n.toolName);if(a)return a}if(!n.toolName.includes("_")&&n.toolName[0]!==n.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${Eh(String(n.toolName))}"`};let s=sU(n.toolName);if(s&&n.ruleContent!==void 0){let a=s(n.ruleContent);if(!a.valid)return a}if(iU(n.toolName)&&n.ruleContent!==void 0){let a=n.ruleContent;if(a.includes(":*")&&!a.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(a===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(oU(n.toolName)&&n.ruleContent!==void 0){if(n.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${n.toolName}(*.ts) - matches .ts files`,`${n.toolName}(src/**) - matches all files in src`,`${n.toolName}(**/*.test.ts) - matches test files`]}}return{valid:!0}}var Wx=P(()=>uU()),lU=P(()=>uU("allow"));function uU(e){return l.string().superRefine((t,r)=>{let o=Vx(t,e);if(!o.valid){let n=o.error;if(o.suggestion)n+=`. ${o.suggestion}`;if(o.examples&&o.examples.length>0)n+=`. Examples: ${o.examples.join(", ")}`;r.addIssue({code:l.ZodIssueCode.custom,message:n,params:{received:t}})}})}var Xte=P(()=>l.record(l.string(),l.coerce.string()));function gU(e){return l.object({allow:l.array(lU()).optional().describe("List of permission rules for allowed operations"),deny:l.array(Wx()).optional().describe("List of permission rules for denied operations"),ask:l.array(Wx()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:l.enum([...iu,...eU(e)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:l.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...Qj(e),additionalDirectories:l.array(l.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var NOe=P(()=>gU(Bx())),Yte=P(()=>l.object({source:au().describe("Where to fetch the marketplace from"),installLocation:l.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),fg=P(()=>l.object({serverName:l.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>Zy([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"'})),mg=P(()=>l.object({serverName:l.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>Zy([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"'})),Qte=P(()=>l.object({path:l.string().describe("Absolute path to the helper executable"),timeoutMs:l.number().int().min(1000).optional(),refreshIntervalMs:l.union([l.literal(0),l.number().int().min(60000)]).optional()})),dU=["skills","agents","hooks","mcp"],pU=Object.freeze({type:"invalid-entry-stripped"}),ere=P(()=>l.union([l.object({type:l.literal("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:l.string().describe("Regex matched against turn output (tool results and assistant text)"),url:l.string().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:l.string().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),l.object({type:l.string().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function hU(e){return l.object({$schema:l.string().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:l.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:l.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:l.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:l.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:l.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:Qte().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...Ee(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:l.object({issuer:l.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:l.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:l.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:l.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:l.object({enabled:l.boolean().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:l.number().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 120). Re-fires every interval until you take a break."),breakThresholdMinutes:l.number().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 15)"),message:l.string().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:l.object({enabled:l.boolean().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:l.string().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:l.string().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:l.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:l.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:l.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:l.boolean().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:Xte().optional().describe("Environment variables to set for Claude Code sessions"),attribution:l.object({commit:l.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:l.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:l.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,includeGitInstructions:l.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:gU(e).optional().describe("Tool usage permissions configuration"),model:l.string().optional().describe("Override the default model used by Claude Code"),fallbackModel:l.array(l.string()).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:l.array(l.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),enforceAvailableModels:l.boolean().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:l.record(l.string(),l.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:l.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:l.array(l.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:l.array(l.string()).optional().describe("List of rejected MCP servers from .mcp.json"),skillOverrides:l.record(l.string(),l.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),disableBundledSkills:l.boolean().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:l.array(fg()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:l.array(mg()).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:Zo().optional().describe("Custom commands to run before/after tool executions"),worktree:l.object({symlinkDirectories:l.array(l.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:l.array(l.string()).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:l.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:l.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:l.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:l.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:l.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableWorkflows:l.boolean().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:l.boolean().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableWorkflows:l.boolean().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowKeywordTriggerEnabled:l.boolean().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:l.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:l.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:l.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:l.array(l.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:l.array(l.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:l.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:l.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),allowAllClaudeAiMcps:l.boolean().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:l.preprocess((t)=>Array.isArray(t)?t.filter((r)=>dU.includes(r)):t,l.union([l.boolean(),l.array(l.enum(dU))])).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:l.object({type:l.literal("command"),command:l.string(),padding:l.number().optional(),refreshInterval:l.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:l.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:l.string().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:l.array(ere().catch(pU)).transform((t)=>t.filter((r)=>r!==pU)).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:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:l.record(l.string(),l.union([l.array(l.string()),l.boolean(),l.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json — setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:l.record(l.string(),Yte()).check((t)=>{for(let[r,o]of Object.entries(t.value))if(o.source.source==="settings"&&o.source.name!==r)t.issues.push({code:"custom",input:o.source.name,path:[r,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${r}" but source.name "${o.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:l.array(au()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. "+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:l.array(au()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),pluginSuggestionMarketplaces:l.array(l.string()).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:l.enum(["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:l.string().url().optional().catch(void 0).describe('@internal Cloud gateway URL to pre-fill and auto-connect to during login. Typically set in local managed settings alongside forceLoginMethod: "gateway" so users never type the URL. Hidden from public SDK types until Cloud gateway is documented.'),parentSettingsBehavior:l.enum(["first-wins","merge"]).optional().describe('Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" '+"(default): parent is dropped — admin tiers are the only policy "+`source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:l.union([l.string(),l.array(l.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:l.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:l.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:l.string().optional().describe("Controls the output style for assistant responses"),viewMode:l.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:l.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:l.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:$j().optional(),feedbackSurveyRate:l.number().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:l.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:l.object({mode:l.enum(["append","replace"]),verbs:l.array(l.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:l.object({excludeDefault:l.boolean().optional(),tips:l.array(l.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:l.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:l.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:l.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:l.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:l.boolean().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:l.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:l.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:l.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:l.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:l.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:l.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:l.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:l.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:l.array(l.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:l.record(l.string(),l.object({mcpServers:l.record(l.string(),l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:l.object({defaultEnvironmentId:l.string().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:l.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:l.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:l.string().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:l.string().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:l.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:l.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),...!1,voice:l.object({enabled:l.boolean().optional(),mode:l.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:l.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:l.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:l.array(l.object({marketplace:l.string(),plugin:l.string()})).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:l.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:l.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),totalTokensReminder:l.enum(["off","infinite","fixed","countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt and after each tool result. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),autoMemoryEnabled:l.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:l.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:l.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:l.boolean().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:l.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:l.boolean().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:l.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:l.array(l.object({id:l.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:l.string().describe("Display name for the SSH connection"),sshHost:l.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:l.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:l.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:l.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:l.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:l.array(l.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:l.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:l.union([l.enum(Mj),l.string().startsWith("custom:").transform((t)=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:l.enum(Aj).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:l.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:l.enum(Oj).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:l.boolean().optional().describe("Automatically compact conversation when context fills"),switchModelsOnFlag:l.boolean().optional().describe("When safety measures flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:l.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:l.boolean().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:l.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:l.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:l.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:l.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:l.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:l.enum(Cj).optional().catch(void 0).describe("How spawned teammates execute (tmux, in-process, auto)"),remoteControlAtStartup:l.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:l.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:l.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:l.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:l.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:l.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...Yj(e)}).passthrough()}var Wo=P(()=>hU(Bx())),fU=Object.freeze({serverName:"invalid-entry-stripped"});function mU(e,t,r){return l.array(t.catch((o)=>(r({path:`${e}[]`,message:`Invalid entry was ignored: ${o.issues[0]?.message??"failed validation"}`}),fU))).transform((o)=>o.filter((n)=>n!==fU)).optional()}function Kx(e){let t=Wo(),r={};for(let[n,i]of Object.entries(t.shape))r[n]=i.catch((s)=>{e({path:n,message:`${s.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});return r.allowedMcpServers=mU("allowedMcpServers",fg(),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=mU("deniedMcpServers",mg(),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.allowManagedMcpServersOnly=t.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),r.enforceAvailableModels=t.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),r.availableModels=l.array(l.unknown()).transform((n,i)=>{let s=[];for(let a of n)if(typeof a==="string")s.push(a);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(a)}); the entry was ignored.`});return s}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),r.forceLoginOrgUUID=t.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[])),l.object(r).passthrough().transform((n)=>{for(let i of Object.keys(n))if(n[i]===void 0)delete n[i];return n})}var an="https://code.claude.com/docs/en",tre=[{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:`${an}/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:`${an}/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:`${an}/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:`${an}/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:`${an}/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:`${an}/iam#working-directories`}}],rre={permissions:`${an}/iam#configuring-permissions`,env:`${an}/settings#environment-variables`,hooks:`${an}/hooks`};function yU(e){let t=tre.find((o)=>o.matches(e));if(!t)return null;let r={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!r.suggestion)r.suggestion=`Valid values: ${e.enumValues.map((o)=>`"${o}"`).join(", ")}`;if(!r.docLink&&e.path)r.docLink=rre[Th(e.path,".")];return r}var QOe=P(()=>Wo().strict());function bU(e){return e.code==="invalid_type"}function _U(e){return e.code==="invalid_value"}function nre(e){return e.code==="unrecognized_keys"}function vU(e){return e.code==="too_small"}function Ds(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function SU(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function lu(e,t){return e.issues.map((r)=>{let o=r.path.map(String).join("."),n=r.message,i,s,a,c,u;if(_U(r))s=r.values.map((p)=>String(p)),a=s.join(" | "),c=void 0,u=void 0;else if(bU(r)){a=r.expected;let p=SU(r.message);c=p??Ds(r.input),u=p??Ds(r.input)}else if(vU(r))a=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,u=c;let d=yU({path:o,code:r.code,expected:a,received:c,enumValues:s,message:r.message,value:c});if(_U(r))i=s?.map((p)=>`"${p}"`).join(", "),n=`Invalid value. Expected one of: ${i}`;else if(bU(r)){let p=SU(r.message)??Ds(r.input);if(r.expected==="object"&&p==="null"&&o==="")n="Invalid or malformed JSON";else n=`Expected ${r.expected}, but received ${p}`}else if(nre(r)){let p=r.keys.join(", ");n=`Unrecognized ${ST(r.keys.length,"field")}: ${p}`}else if(vU(r))n=`Number must be greater than or equal to ${r.minimum}`,i=String(r.minimum);return{file:t,path:o,message:n,expected:i,invalidValue:u,suggestion:d?.suggestion,docLink:d?.docLink}})}function ore(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!r.permissions||typeof r.permissions!=="object")return[];let o=r.permissions,n=[];for(let i of["allow","deny","ask"]){let s=o[i];if(!Array.isArray(s))continue;o[i]=s.filter((a)=>{if(typeof a!=="string")return n.push({file:t,path:`permissions.${i}`,message:`Non-string value in ${i} array was removed`,severity:"warning",invalidValue:a}),!1;let c=Vx(a,i);if(!c.valid){let u=`Invalid permission rule "${a}" was skipped: ${c.error}`;if(c.suggestion)u+=`. ${c.suggestion}`;return n.push({file:t,path:`permissions.${i}`,message:u,severity:"warning",invalidValue:a}),!1}return!0})}return n}var ire=new Set(Xo);function sre(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!("hooks"in r))return[];if(r.hooks===null||typeof r.hooks!=="object"||Array.isArray(r.hooks)){let i=Ds(r.hooks);return delete r.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${i}. This field was ignored.`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"}]}let o=r.hooks,n=[];for(let i of Object.keys(o)){if(!ire.has(i)){delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Unknown hook event "${i}" was ignored. Valid events: ${Xo.join(", ")}`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(o[i])){let s=Ds(o[i]);delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Hook event "${i}" must be an array of matchers; received ${s}. This entry was ignored.`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"})}}if(n.length>0&&Object.keys(o).length===0)delete r.hooks;return n}var are=[{key:"allowedMcpServers",schema:fg},{key:"deniedMcpServers",schema:mg}];function cre(e,t){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:n,schema:i}of are){if(!(n in r))continue;if(!Array.isArray(r[n])){let c=r[n];delete r[n],o.push({file:t,path:n,message:`"${n}" must be an array; received ${Ds(c)}. This field was ignored.`,severity:"warning",invalidValue:c});continue}let s=r[n],a=[];for(let c=0;c<s.length;c++){let u=i().safeParse(s[c]);if(u.success)a.push(s[c]);else o.push({file:t,path:`${n}[${c}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:s[c]})}if(a.length<s.length)r[n]=a}return o}function Ko(e,t,r){return[...ore(e,t),...sre(e,t),...r?.skipMcpServerEntryFilter?[]:cre(e,t)]}function Xx(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),wj.filter((r)=>t.has(r))}function ure(){return Xn(qo(),"managed-settings.json")}function wU(e){if(Ho()==="wsl"&&e.wslInherits?.()){let t=Gx(As);if(t.settings)return t;let r=Gx(qo());return{settings:r.settings,errors:[...t.errors,...r.errors]}}return Gx(qo())}function Gx(e){let t=[],r={},o=!1,{settings:n,errors:i}=gg(Xn(e,"managed-settings.json"),void 0,!0);if(t.push(...i),n&&Object.keys(n).length>0)r=on(r,n,Jn),o=!0;let s=Xn(e,"managed-settings.d");try{let u=Be().readdirSync(s).filter((d)=>(d.isFile()||d.isSymbolicLink())&&d.name.endsWith(".json")&&!d.name.startsWith(".")).map((d)=>d.name).sort();for(let d of u){let{settings:p,errors:f}=gg(Xn(s,d),void 0,!0);if(t.push(...f),p&&Object.keys(p).length>0)r=on(r,p,Jn),o=!0}}catch(u){let d=Ge(u);if(d!=="ENOENT"&&d!=="ENOTDIR")ee(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:a,...c}=r;return{settings:o&&Object.keys(c).length>0?r:null,errors:t}}function dre(e,t){if(zr(e))ee(`Broken symlink or missing file encountered for settings.json at path: ${t}`);else ee(`settings file read failed at ${t}: ${e}`,{level:"error"})}function gg(e,t,r){let o=aT(e);if(o)return{settings:o.settings?xn(o.settings):null,errors:o.errors};let n=fre(e,t,r);return cT(e,n),{settings:n.settings?xn(n.settings):null,errors:n.errors}}function kU(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 hg(e,t){let r=xn(e),o=Ko(r,t,{skipMcpServerEntryFilter:!0}),n=[],i=Kx((s)=>n.push({file:t,path:s.path,message:s.message,severity:"warning"})).safeParse(r);if(!i.success)return{settings:null,errors:[...o,...lu(i.error,t)]};return{settings:Object.keys(i.data).length>0?i.data:null,errors:[...o,...n]}}function EU(e){let t=e?.remote?e.remote():xj();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return hg(t,"remote managed settings")}function pre(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return hg(t,"parent managed settings")}function TU(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let r=xn(t),o=Ko(r,"SDK inline settings"),n=Wo().safeParse(r);if(!n.success)return{settings:null,errors:[...o,...lu(n.error,"SDK inline settings")]};return{settings:n.data,errors:o}}function fre(e,t,r){try{let o;if(t!==void 0)o=t;else{let{resolvedPath:a}=hd(Be(),e);o=Bo(a)}if(o.trim()==="")return{settings:{},errors:[]};let n=xn(Os(o,!1));if(r){let a=Ko(n,e,{skipMcpServerEntryFilter:!0}),c=[],u=Kx((d)=>c.push({file:e,path:d.path,message:d.message,severity:"warning"})).safeParse(n);if(!u.success)return{settings:null,errors:[...a,...lu(u.error,e)]};return{settings:u.data,errors:[...a,...c]}}let i=Ko(n,e),s=Wo().safeParse(n);if(!s.success){let a=lu(s.error,e);return{settings:null,errors:[...i,...a]}}return{settings:s.data,errors:i}}catch(o){if(dre(o,e),zr(o))return{settings:null,errors:[]};return{settings:null,errors:[{file:e,path:"",message:`Settings file could not be read: ${o instanceof Error?o.message:String(o)}`,severity:"fatal"}]}}}function xU(e,t){switch(e){case"userSettings":return uu(qt());case"policySettings":case"projectSettings":case"localSettings":return uu(t.cwd);case"flagSettings":return t.flagPath?lre(uu(t.flagPath)):uu(t.cwd)}}function mre(e){if(e.coworkPlugins||Ee(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function du(e,t){switch(e){case"userSettings":return Xn(xU(e,t),mre(t));case"projectSettings":case"localSettings":return Xn(xU(e,t),gre(e));case"policySettings":return ure();case"flagSettings":return t.flagPath}}function gre(e){switch(e){case"projectSettings":return Xn(".claude","settings.json");case"localSettings":return Xn(".claude","settings.local.json")}}function PU(e,t){let r=iT(e);if(r!==void 0)return r;let o=bre(e,t);return sT(e,o),o}function hre(e){return!e||e.parentSettingsBehavior==="merge"}function yre(e,t){let r={};if(e.allowManagedHooksOnly===!0)r.allowManagedHooksOnly=!0;if(e.allowManagedMcpServersOnly===!0)r.allowManagedMcpServersOnly=!0;if(e.allowManagedPermissionRulesOnly===!0)r.allowManagedPermissionRulesOnly=!0;let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)r.strictPluginOnlyCustomization=o;if(e.deniedMcpServers)r.deniedMcpServers=e.deniedMcpServers;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)r.forceLoginOrgUUID=e.forceLoginOrgUUID;if(t.allowedMcpServers===void 0&&e.allowedMcpServers)r.allowedMcpServers=e.allowedMcpServers;if(t.availableModels===void 0&&e.availableModels)r.availableModels=e.availableModels;if(e.enforceAvailableModels===!0)r.enforceAvailableModels=!0;if(e.permissions){let n=cg(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable")n.disableBypassPermissionsMode="disable";if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:s}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)n.allow=i;if(s)n.additionalDirectories=s}if(Object.keys(n).length>0)r.permissions=n}if(e.sandbox){let{network:n,filesystem:i}=e.sandbox,s={};if(e.sandbox.enabled===!0)s.enabled=!0;if(e.sandbox.failIfUnavailable===!0)s.failIfUnavailable=!0;if(e.sandbox.allowUnsandboxedCommands===!1)s.allowUnsandboxedCommands=!1;if(e.sandbox.autoAllowBashIfSandboxed===!1)s.autoAllowBashIfSandboxed=!1;if(n){let a=cg(n,["deniedDomains"]);if(n.allowManagedDomainsOnly===!0)a.allowManagedDomainsOnly=!0;if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&n.allowedDomains)a.allowedDomains=n.allowedDomains;if(Object.keys(a).length>0)s.network=a}if(i){let a=cg(i,["denyRead","denyWrite"]);if(i.allowManagedReadPathsOnly===!0)a.allowManagedReadPathsOnly=!0;if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)a.allowRead=i.allowRead;if(Object.keys(a).length>0)s.filesystem=a}if(Object.keys(s).length>0)r.sandbox=s}return r}function IU(e){if(e.helper?.())return"helper";if(EU(e).settings)return"remote";if(kU(e).settings)return Ho()==="macos"?"plist":"hklm";if((e.file?.()??wU(e)).settings)return"file";if(RU(e).parentSlice)return"parent";let t=e.hkcu?.();return t&&Object.keys(t.settings).length>0?"hkcu":null}function RU(e){let t=[],{settings:r,errors:o}=EU(e);t.push(...o);let{settings:n,errors:i}=kU(e);t.push(...i);let{settings:s,errors:a}=e.file?.()??wU(e);t.push(...a);let{settings:c,errors:u}=pre(e);t.push(...u);let d=[r,n,s].filter((h)=>h!==null),p=d[0]??null,f={allowManagedPermissionRulesOnly:d.some((h)=>h.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:d.find((h)=>h.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:d.find((h)=>h.allowedMcpServers!==void 0)?.allowedMcpServers,availableModels:d[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:d.some((h)=>h.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:d.some((h)=>h.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},m=c&&hre(p)?yre(c,f):null,g=m&&Object.keys(m).length>0?m:null;return{tiers:d,admin:p,parentSlice:g,errors:t}}function $U(e){let t=e.helper?.();if(t)return{settings:t,errors:e.helperWarnings?.()??[]};let{admin:r,parentSlice:o,errors:n}=RU(e);if(!r&&!o){let i=e.hkcu?.();if(i&&Object.keys(i.settings).length>0)return{settings:i.settings,errors:[...n,...i.errors]};return{settings:null,errors:[...n,...i?.errors??[]]}}return{settings:on({},o??{},r??{},Jn),errors:n}}function bre(e,t){if(e==="policySettings")return $U(t).settings;let r=du(e,t),{settings:o}=r?gg(r,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:n}=TU(t);if(n)return on(o||{},n,Jn)}return o}function _re(e,t){return Dd([...e,...t])}function Jn(e,t,r){if(Array.isArray(e)&&Array.isArray(t)){if(r==="fallbackModel")return t;return _re(e,t)}return}var Jx=!1;function vre(e){if(Jx)return{settings:{},errors:[]};let t=Date.now();Ql("info","settings_load_started"),Jx=!0;try{let r=lT(),o={};if(r)o=on(o,r,Jn);let n=[],i=new Set,s=new Set,a=null;for(let c of Xx(e)){if(c==="policySettings"){let{settings:d,errors:p}=$U(e);if(a=d,d)o=on(o,d,Jn);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}continue}let u=du(c,e);if(u){let d=uu(u);if(!s.has(d)){s.add(d);let{settings:p,errors:f}=gg(u,c==="flagSettings"?e.flagExpectedContent:void 0);for(let m of f){let g=`${m.file}:${m.path}:${m.message}`;if(!i.has(g))i.add(g),n.push(m)}if(p)o=on(o,p,Jn)}}if(c==="flagSettings"){let{settings:d,errors:p}=TU(e);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}if(d)o=on(o,d,Jn)}}if(a){if(a.availableModels!==void 0)o.availableModels=[...a.availableModels];if(a.enforceAvailableModels!==void 0)o.enforceAvailableModels=a.enforceAvailableModels}return Ql("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:s.size,error_count:n.length}),{settings:o,errors:n}}finally{Jx=!1}}function Sre(e){let t=nT();if(t!==null)return t;let r=vre(e);return oT(r),r}function xre(e){let{settings:t}=Sre(e);return t||{}}function OU(e){mo();let t=[];for(let r of Xx(e)){let o=PU(r,e);if(o&&Object.keys(o).length>0)t.push({source:r,settings:o})}return{effective:xre(e),sources:t}}function AU(e,t){let r=Xx(t);for(let o=r.length-1;o>=0;o--){let n=r[o];if(PU(n,t)?.[e]!==void 0)return n}return null}import{execFile as wre}from"child_process";import{existsSync as kre}from"fs";var Ere=null;function pu(e,t){return new Promise((r)=>{try{wre(e,t,{encoding:"utf-8",timeout:Pj,windowsHide:!0},(o,n)=>{r({stdout:n??"",code:o?1:0})})}catch{r({stdout:"",code:1})}})}function CU(){return(async()=>{if(process.platform==="darwin"){let e=Ij(),r=(await Promise.all(e.map(async({path:o,label:n})=>{if(!kre(o))return{stdout:"",label:n,ok:!1};let{stdout:i,code:s}=await pu(Ej,[...Tj,o]);return{stdout:i,label:n,ok:s===0&&!!i}}))).find((o)=>o.ok);return{plistStdouts:r?[{stdout:r.stdout,label:r.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[r,o]=await Promise.all([pu(t,["query",nu,"/v",Kn]),pu(t,["query",ou,"/v",Kn])]);return{plistStdouts:null,hklmStdout:r.code===0?r.stdout:null,hkcuStdout:o.code===0?o.stdout:null}}if(lg()){let[e,t]=await Promise.all([pu(Nx,["query",nu,"/v",Kn]),pu(Nx,["query",ou,"/v",Kn])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function MU(){return Ere}var Yn=Object.freeze({settings:{},errors:[]}),UU=null,zU=null,LU=!1,yg=null;function Tre(){if(yg)return;yg=(async()=>{let e=Date.now(),t=MU()??CU(),{mdm:r,hkcu:o,wslInherits:n}=Pre(await t);UU=r,zU=o,LU=n;let i=Date.now()-e;if(ee(`MDM settings load completed in ${i}ms`),Object.keys(r.settings).length>0){ee(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{Ql("info","mdm_settings_loaded",{duration_ms:i,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})()}async function FU(){if(!yg)Tre();await yg}function BU(){return UU??Yn}function HU(){return zU??Yn}function qU(){return LU}function Yx(e,t){let r=Os(e,!1);if(!r||typeof r!=="object")return{settings:{},errors:[]};let{settings:o,errors:n}=hg(r,t);return{settings:o??{},errors:n}}function DU(e,t="Settings"){let r=e.split(/\r?\n/),o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s+${o}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let i of r){let s=i.match(n);if(s&&s[1])return s[1].trimEnd()}return null}function Pre(e){let t=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:s,label:a}=e.plistStdouts[0],c=Yx(s,a),{wslInheritsWindowsSettings:u,...d}=c.settings;if(Object.keys(d).length>0)return{mdm:c,hkcu:Yn,wslInherits:!1};t.push(...c.errors)}let r=null;if(e.hklmStdout){let s=DU(e.hklmStdout);if(s)r=Yx(s,`Registry: ${nu}\\${Kn}`)}if(r)t.push(...r.errors);let o=t.length>0?{settings:{},errors:t}:Yn,n=lg(),i=!1;if(n){if(i=r?.settings.wslInheritsWindowsSettings===!0||Rre(),!i)return{mdm:o,hkcu:Yn,wslInherits:!1}}if(r){let{wslInheritsWindowsSettings:s,...a}=r.settings;if(Object.keys(a).length>0)return{mdm:r,hkcu:Yn,wslInherits:i}}if(Ire(i))return{mdm:o,hkcu:Yn,wslInherits:i};if(e.hkcuStdout){let s=DU(e.hkcuStdout);if(s){let a=Yx(s,`Registry: ${ou}\\${Kn}`);if(!n||a.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:c,...u}=a.settings;return{mdm:o,hkcu:{settings:u,errors:a.errors},wslInherits:i}}if(a.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:a.errors},wslInherits:i}}}return{mdm:o,hkcu:Yn,wslInherits:i}}function Ire(e){if(e&&jU(As))return!0;return jU(qo())}function NU(e){let t=xn(Os(Bo(e),!1));if(!t||typeof t!=="object")return!1;Ko(t,e);let{wslInheritsWindowsSettings:r,...o}=t;return Object.keys(o).length>0}function Rre(){function e(t){try{let r=Os(Bo(t),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(e(Ns(As,"managed-settings.json")))return!0;try{let t=Ns(As,"managed-settings.d");for(let r of Be().readdirSync(t))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&e(Ns(t,r.name)))return!0}catch{}return!1}function jU(e){try{if(NU(Ns(e,"managed-settings.json")))return!0}catch{}try{let t=Ns(e,"managed-settings.d"),r=Be().readdirSync(t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(NU(Ns(t,o.name)))return!0}catch{}}}catch{}return!1}var Ore={user:"userSettings",project:"projectSettings",local:"localSettings"},ZU={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},Are=["user","project","local"],Cre=new Set(["bypassPermissions","auto","acceptEdits"]),Mre=new Set(["project"]);function Dre(e){let t=e.effective.permissions?.defaultMode;if(!t||!Cre.has(t))return e.effective;for(let r=e.sources.length-1;r>=0;r--){let o=e.sources[r];if(o.settings.permissions?.defaultMode!==void 0){if(Mre.has(o.source)){let{defaultMode:n,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}async function VU(e={}){await FU();let t={cwd:$re(e.cwd??Be().cwd()),allowedSources:(e.settingSources??Are).map((r)=>Ore[r]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:BU,hkcu:HU,wslInherits:qU,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}};try{let{effective:r,sources:o}=OU(t),n=IU(t)??void 0,i=o.map(({source:a,settings:c})=>({source:ZU[a],settings:c,path:a==="policySettings"?void 0:du(a,t),...a==="policySettings"&&{policyOrigin:n}})),s={};for(let a of Object.keys(r)){let c=AU(a,t);if(c)s[a]={source:ZU[c],path:c==="policySettings"?void 0:du(c,t),...c==="policySettings"&&{policyOrigin:n}}}return{effective:r,provenance:s,sources:i}}finally{mo()}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function kCe(e){return VU(e)}async function Vre(e,t){try{await zre(e,t)}catch(r){if(!zr(r))throw r}}async function Wre(e,t){if(!e)return;let r=e;try{let o=Ze(e);if(o?.claudeAiOauth?.refreshToken)delete o.claudeAiOauth.refreshToken,r=pe(o)}catch{}await QU(t,r,{mode:384})}function Kre(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=v0(_0);return new Promise((t)=>{Nre("security",["find-generic-password","-a",S0(),"-w","-s",e],{encoding:"utf-8",timeout:5000},(r,o)=>t(r?void 0:o.trim()||void 0))})}async function rz(e,t,r,o,n=60000){if(!Se(t))return;let i=rr(r),s=await Ar(e.load({projectKey:i,sessionId:t}),n,`SessionStore.load() timed out after ${n}ms for session ${t}`);if(!s||s.length===0)return;let a=zt(Hre(),`claude-resume-${ow()}`);try{let c=zt(a,"projects",i);await Qx(c,{recursive:!0});let u=zt(c,`${t}.jsonl`);await ec(u,s);let d=o?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,p=d??zt(ew(),".claude"),f;try{f=await YU(zt(p,".credentials.json"),"utf-8")}catch(m){if(!zr(m))throw m}if(!d&&!(o??process.env).ANTHROPIC_API_KEY&&!(o??process.env).CLAUDE_CODE_OAUTH_TOKEN)f=await Kre()??f;if(await Wre(f,zt(a,".credentials.json")),await Vre(zt(d??ew(),".claude.json"),zt(a,".claude.json")),e.listSubkeys){let m=zt(c,t),g=await Ar(e.listSubkeys({projectKey:i,sessionId:t}),n,`SessionStore.listSubkeys() timed out after ${n}ms for session ${t}`);for(let h of g){let y=fu(m,h+".jsonl");if(!h||ez(h)||h.split(/[\\/]/).includes("..")||!y.startsWith(m+iw)){ee(`[SessionStore] skipping unsafe subpath from listSubkeys: ${h}`,{level:"warn"});continue}let v=await Ar(e.load({projectKey:i,sessionId:t,subpath:h}),n,`SessionStore.load() timed out after ${n}ms for session ${t} subpath ${h}`);if(!v||v.length===0)continue;let x=[],w=[];for(let A of v)if(nw(A))x.push(A);else w.push(A);if(w.length>0)await Qx(WU(y),{recursive:!0}),await ec(y,w);if(x.length>0){let A=x.at(-1),U=fu(m,h+".meta.json");await Qx(WU(U),{recursive:!0});let{type:se,...Le}=A;await QU(U,pe(Le),{mode:384})}}}return a}catch(c){throw await bg(a),c}}function tw(e,t,r,o){let{systemPrompt:n,settings:i,managedSettings:s,settingSources:a,sandbox:c,...u}=e??{},d,p,f;if(n===void 0)d="";else if(typeof n==="string")d=n;else if(Array.isArray(n))d=n;else if(n.type==="preset")p=n.append,f=n.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.177";let{abortController:m=qs(),additionalDirectories:g=[],agent:h,agents:y,allowedTools:v=[],betas:x,canUseTool:w,continue:A,cwd:U,debug:se,debugFile:Le,disallowedTools:Ye=[],tools:Lt,env:yt,executable:Qn=_u()?"bun":"node",executableArgs:Go=[],extraArgs:Rr={},fallbackModel:js,enableFileCheckpointing:cn,toolConfig:V,forkSession:mu,hooks:gu,includeHookEvents:Us,includePartialMessages:zs,forwardSubagentText:Ls,onElicitation:hu,onUserDialog:je,supportedDialogKinds:Ft,persistSession:Sr,sessionStore:$r,sessionStoreFlush:az,thinking:Fs,effort:cz,maxThinkingTokens:vg,maxTurns:lz,maxBudgetUsd:uz,taskBudget:dz,mcpServers:sw,model:pz,outputFormat:aw,permissionMode:fz="default",allowDangerouslySkipPermissions:mz=!1,permissionPromptToolName:gz,plugins:hz,getOAuthToken:cw,getHostAuthToken:lw,workload:uw,resume:dw,resumeSessionAt:yz,sessionId:bz,skills:pw,stderr:_z,strictMcpConfig:vz}=u;if($r&&Sr===!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(Ft!==void 0&&Ft.length>0&&!je)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if($r&&A&&!dw&&!$r.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if($r&&cn)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if($r&&u.spawnClaudeCodeProcess)ee("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});let Sg=u.pathToClaudeCodeExecutable;if(!Sg){let $t=Zre(import.meta.url),nr=Bre($t),eo=LT((Jo)=>nr.resolve(Jo));if(!eo)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.`);Sg=eo}let fw=aw?.type==="json_schema"?aw.schema:void 0,ut=yt?{...yt}:{...process.env};if(!ut.CLAUDE_CODE_ENTRYPOINT)ut.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!ut.CLAUDE_AGENT_SDK_VERSION)ut.CLAUDE_AGENT_SDK_VERSION="0.3.177";if(cn)ut.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(cw)ut.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(lw)ut.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(V?.askUserQuestion?.previewFormat)ut.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=V.askUserQuestion.previewFormat;let xg={};if(_g.propagation.inject(_g.context.active(),xg),"traceparent"in xg){for(let $t of["TRACEPARENT","TRACESTATE"])if(!($t in(yt??{})))delete ut[$t]}for(let[$t,nr]of Object.entries(xg)){let eo=$t.toUpperCase();if(!(eo in(yt??{})))ut[eo]=nr}let mw={},gw=new Map;if(sw)for(let[$t,nr]of Object.entries(sw))if(nr.type==="sdk"&&nr.instance)gw.set($t,nr.instance);else mw[$t]=nr;let Bs;if(Fs)switch(Fs.type){case"adaptive":Bs={type:"adaptive",display:Fs.display};break;case"enabled":Bs={type:"enabled",budgetTokens:Fs.budgetTokens,display:Fs.display};break;case"disabled":Bs={type:"disabled"};break}else if(vg!==void 0)Bs=vg===0?{type:"disabled"}:{type:"enabled",budgetTokens:vg};if(r){if(ut.CLAUDE_CONFIG_DIR=r,process.platform==="win32")ut.CLAUDE_SECURESTORAGE_CONFIG_DIR=yt?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??yt?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let hw=new Dh({abortController:m,additionalDirectories:g,agent:h,betas:x,cwd:U,debug:se,debugFile:Le,executable:Qn,executableArgs:Go,extraArgs:uw?{...Rr,workload:uw}:Rr,pathToClaudeCodeExecutable:Sg,env:ut,forkSession:mu,stderr:_z,thinkingConfig:Bs,effort:cz,maxTurns:lz,maxBudgetUsd:uz,taskBudget:dz,model:pz,fallbackModel:js,jsonSchema:fw,permissionMode:fz,allowDangerouslySkipPermissions:mz,permissionPromptToolName:gz,continueConversation:$r?void 0:A,resume:dw,resumeSessionAt:yz,sessionId:bz,settings:typeof i==="object"?pe(i):i,managedSettings:s?pe(s):void 0,settingSources:a,skills:pw,allowedTools:v,disallowedTools:Ye,tools:Lt,mcpServers:mw,strictMcpConfig:vz,canUseTool:!!w,hooks:!!gu,includeHookEvents:Us,includePartialMessages:zs,persistSession:Sr,sessionMirror:!!$r,plugins:hz,sandbox:c,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:o}),Sz={systemPrompt:d,appendSystemPrompt:p,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:f,agents:y,title:u.title,skills:pw,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:Ls,supportedDialogKinds:Ft},wg=new zh(hw,t,w,gu,m,gw,fw,Sz,hu,cw,lw,je);if($r){let $t=()=>zt(ut.CLAUDE_CONFIG_DIR??zt(ew(),".claude"),"projects"),nr=az==="eager",eo=new Lh(async(Jo,kg)=>{let Hs=XU(Jo,$t());if(Hs)await $r.append(Hs,kg);else ee(`[SessionStore] dropping mirror frame: filePath ${Jo} is not under ${$t()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(Jo,kg)=>{let Hs=XU(Jo,$t());if(Hs)wg.reportMirrorError(Hs,kg.message)},nr?0:vd,nr?0:Sd);wg.setTranscriptMirrorBatcher(eo)}return{queryInstance:wg,transport:hw,abortController:m,processEnv:ut}}function rw(e,t,r,o){if(typeof r==="string")t.write(pe({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:r}]},parent_tool_use_id:null})+`
116
116
  `);else e.streamInput(r).catch((n)=>o.abort(n))}var Gre=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function bg(e){for(let t=0;;t++)try{return await Fre(e,{recursive:!0,force:!0})}catch(r){if(t>=4||!Gre.has(Ge(r)??""))return;await yu((t+1)*100)}}function Jre(e,t){e.waitForExit().catch(()=>{}).finally(()=>bg(t))}function ECe({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore){let{queryInstance:i,transport:s,abortController:a,processEnv:c}=tw({...t},typeof e==="string",void 0,!0),u=fu(t.cwd??"."),d=t.sessionStore,p=t.loadTimeoutMs??60000,f=t.resume;return(async()=>{if(!f)f=(await Ar(d.listSessions(rr(u)),p,`SessionStore.listSessions() timed out after ${p}ms`)).slice().sort((h,y)=>y.mtime-h.mtime)[0]?.sessionId;if(!f)return;return rz(d,f,u,t.env,t.loadTimeoutMs)})().then((g)=>{if(g){s.updateResume(f);let h={CLAUDE_CONFIG_DIR:g};if(process.platform==="win32"){let y=t.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??t.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";h.CLAUDE_SECURESTORAGE_CONFIG_DIR=y,c.CLAUDE_SECURESTORAGE_CONFIG_DIR=y}s.updateEnv(h),c.CLAUDE_CONFIG_DIR=g,i.addCleanupCallback(()=>Jre(s,g))}if(!i.isClosed())s.spawn()}).catch((g)=>{let h=kr(g);s.spawnAbort(h),i.setError(h)}),rw(i,s,e,a),i}let{queryInstance:r,transport:o,abortController:n}=tw(t,typeof e==="string");return rw(r,o,e,n),r}async function TCe({options:e,initializeTimeoutMs:t=60000}={}){let r,o=e?.resume;if((o||e?.continue)&&e?.sessionStore){let a=fu(e.cwd??".");if(!o){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let c=e.loadTimeoutMs??60000;o=(await Ar(e.sessionStore.listSessions(rr(a)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((d,p)=>p.mtime-d.mtime)[0]?.sessionId}if(o)r=await rz(e.sessionStore,o,a,e.env,e.loadTimeoutMs)}let n,i,s;try{let f=function(){if(p)return;p=!0,d.close()},a=tw(r&&o&&o!==e?.resume?{...e,resume:o}:e,!1,r);n=a.queryInstance;let{transport:c,abortController:u}=a;i=c;let d=a.queryInstance;if(r){let m=r;d.addCleanupCallback(()=>{s=c.waitForExit().catch(()=>{}).then(()=>bg(m))})}await Ar(d.initializationResult(),t,`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`);let p=!1;return{query(m){if(p)throw Error("WarmQuery.query() can only be called once");p=!0;try{rw(d,c,m,u)}catch(g){throw d.close(),g}if(typeof m==="string")d.setIsSingleUserTurn(!0);return d},close:f,async[Symbol.asyncDispose](){p=!0,d.close(),await s}}}catch(a){if(n?.close(),r&&!s){let c=i;s=(c?c.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>bg(r))}throw await s,a}}async function PCe(e,t){if(t?.sessionStore)return ene(t.sessionStore,e,t);return JR(e,t)}async function ICe(e){if(e?.sessionStore)return Yre(e.sessionStore,e);return YR(e)}async function RCe(e,t){if(t?.sessionStore)return tne(t.sessionStore,e,t);return QR(e,t)}async function $Ce(e,t,r){if(r?.sessionStore)return rne(r.sessionStore,e,t,r.dir);return n0(e,t,r)}async function OCe(e,t,r){if(r?.sessionStore)return nne(r.sessionStore,e,t,r.dir);return o0(e,t,r)}async function ACe(e,t){if(!Se(e))throw Error(`Invalid sessionId: ${e}`);if(t?.sessionStore){if(!t.sessionStore.delete)return;let r=rr(t.dir);await t.sessionStore.delete({projectKey:r,sessionId:e});return}return i0(e,t)}async function CCe(e,t){if(t?.sessionStore)return one(t.sessionStore,e,t);return c0(e,t)}async function MCe(e,t,r){if(!Se(e))throw Error(`Invalid sessionId: ${e}`);let o=await kn(e,r?.dir);if(!o)throw Error(`Session ${e} not found`);let n=rr(r?.dir),i=r?.batchSize&&r.batchSize>0?r.batchSize:vd;if(await KU(o.filePath,{projectKey:n,sessionId:e},t,i),r?.includeSubagents===!1)return;let s=o.filePath.replace(/\.jsonl$/,""),a=zt(s,"subagents");for(let c of await Xre(a)){let u=tz(s,c).split(iw);u[u.length-1]=u.at(-1).replace(/\.jsonl$/,"");let d={projectKey:n,sessionId:e,subpath:u.join("/")};await KU(c,d,t,i);let p=c.replace(/\.jsonl$/,".meta.json");try{let f=Ze(await YU(p,"utf8"));await t.append(d,[{type:"agent_metadata",...f}])}catch(f){if(!zr(f))throw f}}}async function KU(e,t,r,o){let n=qre({input:jre(e,{encoding:"utf8"}),crlfDelay:1/0}),i=[],s=0;for await(let a of n){if(!a)continue;if(i.push(Ze(a)),s+=a.length,i.length>=o||s>=Sd)await r.append(t,i),i=[],s=0}if(i.length>0)await r.append(t,i)}async function Xre(e){let t=[];async function r(o){let n;try{n=await Lre(o,{withFileTypes:!0})}catch{return}for(let i of n){let s=zt(o,i.name);if(i.isDirectory())await r(s);else if(i.isFile()&&i.name.endsWith(".jsonl"))t.push(s)}}return await r(e),t}async function DCe(e,t){if(t?.sessionStore)return ine(t.sessionStore,e,t.dir);return m0(e,t)}async function NCe(e,t,r){if(r?.sessionStore)return sne(r.sessionStore,e,t,r);return g0(e,t,r)}function nz(e){let t=fu(e??"."),r;try{r=Ure(t)}catch{r=t}return Or(r)}function rr(e){return So(nz(e))}function oz(e){return e.map((t)=>pe(t)).join(`
117
117
  `)+`
118
118
  `}function GU(e,t,r){if(t!==void 0&&t>0)return e.slice(r,r+t);if(r>0)return e.slice(r);return e}function nw(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}async function Yre(e,t){let r=nz(t.dir),o=So(r),n=t.offset??0,i=t.limit;if(e.listSessionSummaries){let u=await e.listSessionSummaries(o),d=e.listSessions?new Map((await e.listSessions(o)).map((g)=>[g.sessionId,g])):void 0,p=[];for(let g of u){let h=d?.get(g.sessionId);if(d&&!h)continue;let y=h!==void 0&&g.mtime<h.mtime;p.push({sessionId:g.sessionId,mtime:y?h.mtime:g.mtime,info:y?void 0:kw(g,r)})}if(d){let g=new Set(u.map((h)=>h.sessionId));for(let[h,y]of d)if(!g.has(h))p.push({sessionId:h,mtime:y.mtime})}else ee("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");p.sort((g,h)=>h.mtime-g.mtime);let f=GU(p,i,n),m=f.filter((g)=>g.info===void 0);if(m.length>0){let g=await JU(e,m,t.dir,r),h=new Map(g.map((y)=>[y.sessionId,y]));for(let y of f)if(y.info===void 0)y.info=h.get(y.sessionId)??null}return f.flatMap((g)=>g.info?[g.info]:[])}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(o)).slice().sort((u,d)=>d.mtime-u.mtime),c=GU(a,i,n);return JU(e,c,t.dir,r)}async function JU(e,t,r,o){return(await Promise.allSettled(t.map(async(i)=>{let s=await sz(e,i.sessionId,r);if(!s)return null;let a=Ni(i.sessionId,iz(s,i.mtime),o);return a?{...a,lastModified:i.mtime}:null}))).flatMap((i,s)=>{let a=t[s];if(i.status==="fulfilled")return i.value?[i.value]:[];return[{sessionId:a.sessionId,summary:"",lastModified:a.mtime}]})}function iz(e,t){let r=Buffer.from(e,"utf-8"),o=r.length,n=r.subarray(0,ar).toString("utf-8"),i=o>ar?r.subarray(o-ar).toString("utf-8"):n;return{mtime:t,size:o,head:n,tail:i}}function Qre(e){let t=e.trimEnd(),r=t.slice(t.lastIndexOf(`