@anthropic-ai/claude-agent-sdk 0.2.139 → 0.2.140

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.2.139
4
+ // Version: 0.2.140
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(Q)})},"\t":{"\n":Array(200).fill(0).map(($,Q)=>{return`
113
113
  `+"\t".repeat(Q)}),"\r":Array(200).fill(0).map(($,Q)=>{return"\r"+"\t".repeat(Q)}),"\r\n":Array(200).fill(0).map(($,Q)=>{return`\r
114
114
  `+"\t".repeat(Q)})}};var $E;(function($){$.DEFAULT={allowTrailingComma:!1}})($E||($E={}));var QE;(function($){$[$.None=0]="None",$[$.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",$[$.UnexpectedEndOfString=2]="UnexpectedEndOfString",$[$.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",$[$.InvalidUnicode=4]="InvalidUnicode",$[$.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",$[$.InvalidCharacter=6]="InvalidCharacter"})(QE||(QE={}));var XE;(function($){$[$.OpenBraceToken=1]="OpenBraceToken",$[$.CloseBraceToken=2]="CloseBraceToken",$[$.OpenBracketToken=3]="OpenBracketToken",$[$.CloseBracketToken=4]="CloseBracketToken",$[$.CommaToken=5]="CommaToken",$[$.ColonToken=6]="ColonToken",$[$.NullKeyword=7]="NullKeyword",$[$.TrueKeyword=8]="TrueKeyword",$[$.FalseKeyword=9]="FalseKeyword",$[$.StringLiteral=10]="StringLiteral",$[$.NumericLiteral=11]="NumericLiteral",$[$.LineCommentTrivia=12]="LineCommentTrivia",$[$.BlockCommentTrivia=13]="BlockCommentTrivia",$[$.LineBreakTrivia=14]="LineBreakTrivia",$[$.Trivia=15]="Trivia",$[$.Unknown=16]="Unknown",$[$.EOF=17]="EOF"})(XE||(XE={}));var JE;(function($){$[$.InvalidSymbol=1]="InvalidSymbol",$[$.InvalidNumberFormat=2]="InvalidNumberFormat",$[$.PropertyNameExpected=3]="PropertyNameExpected",$[$.ValueExpected=4]="ValueExpected",$[$.ColonExpected=5]="ColonExpected",$[$.CommaExpected=6]="CommaExpected",$[$.CloseBraceExpected=7]="CloseBraceExpected",$[$.CloseBracketExpected=8]="CloseBracketExpected",$[$.EndOfFileExpected=9]="EndOfFileExpected",$[$.InvalidCommentToken=10]="InvalidCommentToken",$[$.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",$[$.UnexpectedEndOfString=12]="UnexpectedEndOfString",$[$.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",$[$.InvalidUnicode=14]="InvalidUnicode",$[$.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",$[$.InvalidCharacter=16]="InvalidCharacter"})(JE||(JE={}));function XG($){return $.startsWith("\uFEFF")?$.slice(1):$}import y$ from"node:path";import YE from"node:os";import Az from"node:process";var p1=YE.homedir(),Iz=YE.tmpdir(),{env:I9}=Az,Ps=($)=>{let Q=y$.join(p1,"Library");return{data:y$.join(Q,"Application Support",$),config:y$.join(Q,"Preferences",$),cache:y$.join(Q,"Caches",$),log:y$.join(Q,"Logs",$),temp:y$.join(Iz,$)}},Es=($)=>{let Q=I9.APPDATA||y$.join(p1,"AppData","Roaming"),X=I9.LOCALAPPDATA||y$.join(p1,"AppData","Local");return{data:y$.join(X,$,"Data"),config:y$.join(Q,$,"Config"),cache:y$.join(X,$,"Cache"),log:y$.join(X,$,"Log"),temp:y$.join(Iz,$)}},bs=($)=>{let Q=y$.basename(p1);return{data:y$.join(I9.XDG_DATA_HOME||y$.join(p1,".local","share"),$),config:y$.join(I9.XDG_CONFIG_HOME||y$.join(p1,".config"),$),cache:y$.join(I9.XDG_CACHE_HOME||y$.join(p1,".cache"),$),log:y$.join(I9.XDG_STATE_HOME||y$.join(p1,".local","state"),$),temp:y$.join(Iz,Q,$)}};function Rz($,{suffix:Q="nodejs"}={}){if(typeof $!=="string")throw TypeError(`Expected a string, got ${typeof $}`);if(Q)$+=`-${Q}`;if(Az.platform==="darwin")return Ps($);if(Az.platform==="win32")return Es($);return bs($)}var H2$=Rz("claude-cli");function Ss(){if(process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return"essential-traffic";if(process.env.DISABLE_TELEMETRY)return"no-telemetry";if(R$(process.env.DO_NOT_TRACK))return"no-telemetry";return"default"}function WE(){return Ss()==="essential-traffic"}var _s=100,Pz=[];function ks($){if(Pz.length>=_s)Pz.shift();Pz.push($)}var vs=[],GE=null;var C2$=v$(()=>{return process.argv.includes("--hard-fail")});function R9($){let Q=I4($);try{if(R$(process.env.CLAUDE_CODE_USE_BEDROCK)||R$(process.env.CLAUDE_CODE_USE_VERTEX)||R$(process.env.CLAUDE_CODE_USE_FOUNDRY)||R$(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||R$(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||WE())return;let Y={error:Q.stack||Q.message,timestamp:new Date().toISOString()};if(ks(Y),GE===null){vs.push({type:"error",error:Q});return}GE.logError(Q)}catch{}}var P9=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,HE=new Set,Ez=typeof process==="object"&&!!process?process:{},KE=($,Q,X,Y)=>{typeof Ez.emitWarning==="function"?Ez.emitWarning($,Q,X,Y):console.error(`[${X}] ${Q}: ${$}`)},JG=globalThis.AbortController,UE=globalThis.AbortSignal;if(typeof JG>"u"){UE=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(Y,J){this._onabort.push(J)}},JG=class{constructor(){Q()}signal=new UE;abort(Y){if(this.signal.aborted)return;this.signal.reason=Y,this.signal.aborted=!0;for(let J of this.signal._onabort)J(Y);this.signal.onabort?.(Y)}};let $=Ez.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!$)return;$=!1,KE("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",Q)}}var Cs=($)=>!HE.has($),x2$=Symbol("type"),d1=($)=>$&&$===Math.floor($)&&$>0&&isFinite($),qE=($)=>!d1($)?null:$<=Math.pow(2,8)?Uint8Array:$<=Math.pow(2,16)?Uint16Array:$<=Math.pow(2,32)?Uint32Array:$<=Number.MAX_SAFE_INTEGER?sX:null;class sX extends Array{constructor($){super($);this.fill(0)}}class E9{heap;length;static#H=!1;static create($){let Q=qE($);if(!Q)return[];E9.#H=!0;let X=new E9($,Q);return E9.#H=!1,X}constructor($,Q){if(!E9.#H)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q($),this.length=0}push($){this.heap[this.length++]=$}pop(){return this.heap[--this.length]}}class YG{#H;#V;#w;#O;#_;#k;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Y;#D;#J;#X;#$;#K;#B;#U;#W;#F;#G;#Z;#M;#z;#L;#P;#q;static unsafeExposeInternals($){return{starts:$.#M,ttls:$.#z,sizes:$.#Z,keyMap:$.#J,keyList:$.#X,valList:$.#$,next:$.#K,prev:$.#B,get head(){return $.#U},get tail(){return $.#W},free:$.#F,isBackgroundFetch:(Q)=>$.#Q(Q),backgroundFetch:(Q,X,Y,J)=>$.#T(Q,X,Y,J),moveToTail:(Q)=>$.#S(Q),indexes:(Q)=>$.#j(Q),rindexes:(Q)=>$.#A(Q),isStale:(Q)=>$.#N(Q)}}get max(){return this.#H}get maxSize(){return this.#V}get calculatedSize(){return this.#D}get size(){return this.#Y}get fetchMethod(){return this.#_}get memoMethod(){return this.#k}get dispose(){return this.#w}get disposeAfter(){return this.#O}constructor($){let{max:Q=0,ttl:X,ttlResolution:Y=1,ttlAutopurge:J,updateAgeOnGet:W,updateAgeOnHas:G,allowStale:U,dispose:H,disposeAfter:q,noDisposeOnSet:V,noUpdateTTL:B,maxSize:z=0,maxEntrySize:N=0,sizeCalculation:w,fetchMethod:O,memoMethod:D,noDeleteOnFetchRejection:M,noDeleteOnStaleGet:R,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:k,ignoreFetchAbort:u}=$;if(Q!==0&&!d1(Q))throw TypeError("max option must be a nonnegative integer");let W$=Q?qE(Q):Array;if(!W$)throw Error("invalid max value: "+Q);if(this.#H=Q,this.#V=z,this.maxEntrySize=N||this.#V,this.sizeCalculation=w,this.sizeCalculation){if(!this.#V&&!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(D!==void 0&&typeof D!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#k=D,O!==void 0&&typeof O!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#_=O,this.#P=!!O,this.#J=new Map,this.#X=Array(Q).fill(void 0),this.#$=Array(Q).fill(void 0),this.#K=new W$(Q),this.#B=new W$(Q),this.#U=0,this.#W=0,this.#F=E9.create(Q),this.#Y=0,this.#D=0,typeof H==="function")this.#w=H;if(typeof q==="function")this.#O=q,this.#G=[];else this.#O=void 0,this.#G=void 0;if(this.#L=!!this.#w,this.#q=!!this.#O,this.noDisposeOnSet=!!V,this.noUpdateTTL=!!B,this.noDeleteOnFetchRejection=!!M,this.allowStaleOnFetchRejection=!!P,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!u,this.maxEntrySize!==0){if(this.#V!==0){if(!d1(this.#V))throw TypeError("maxSize must be a positive integer if specified")}if(!d1(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!U,this.noDeleteOnStaleGet=!!R,this.updateAgeOnGet=!!W,this.updateAgeOnHas=!!G,this.ttlResolution=d1(Y)||Y===0?Y:1,this.ttlAutopurge=!!J,this.ttl=X||0,this.ttl){if(!d1(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#x()}if(this.#H===0&&this.ttl===0&&this.#V===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#H&&!this.#V){if(Cs("LRU_CACHE_UNBOUNDED"))HE.add("LRU_CACHE_UNBOUNDED"),KE("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",YG)}}getRemainingTTL($){return this.#J.has($)?1/0:0}#x(){let $=new sX(this.#H),Q=new sX(this.#H);this.#z=$,this.#M=Q,this.#y=(J,W,G=P9.now())=>{if(Q[J]=W!==0?G:0,$[J]=W,W!==0&&this.ttlAutopurge){let U=setTimeout(()=>{if(this.#N(J))this.#I(this.#X[J],"expire")},W+1);if(U.unref)U.unref()}},this.#E=(J)=>{Q[J]=$[J]!==0?P9.now():0},this.#R=(J,W)=>{if($[W]){let G=$[W],U=Q[W];if(!G||!U)return;J.ttl=G,J.start=U,J.now=X||Y();let H=J.now-U;J.remainingTTL=G-H}};let X=0,Y=()=>{let J=P9.now();if(this.ttlResolution>0){X=J;let W=setTimeout(()=>X=0,this.ttlResolution);if(W.unref)W.unref()}return J};this.getRemainingTTL=(J)=>{let W=this.#J.get(J);if(W===void 0)return 0;let G=$[W],U=Q[W];if(!G||!U)return 1/0;let H=(X||Y())-U;return G-H},this.#N=(J)=>{let W=Q[J],G=$[J];return!!G&&!!W&&(X||Y())-W>G}}#E=()=>{};#R=()=>{};#y=()=>{};#N=()=>!1;#m(){let $=new sX(this.#H);this.#D=0,this.#Z=$,this.#b=(Q)=>{this.#D-=$[Q],$[Q]=0},this.#f=(Q,X,Y,J)=>{if(this.#Q(X))return 0;if(!d1(Y))if(J){if(typeof J!=="function")throw TypeError("sizeCalculation must be a function");if(Y=J(X,Q),!d1(Y))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 Y},this.#v=(Q,X,Y)=>{if($[Q]=X,this.#V){let J=this.#V-$[Q];while(this.#D>J)this.#C(!0)}if(this.#D+=$[Q],Y)Y.entrySize=X,Y.totalCalculatedSize=this.#D}}#b=($)=>{};#v=($,Q,X)=>{};#f=($,Q,X,Y)=>{if(X||Y)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:$=this.allowStale}={}){if(this.#Y)for(let Q=this.#W;;){if(!this.#g(Q))break;if($||!this.#N(Q))yield Q;if(Q===this.#U)break;else Q=this.#B[Q]}}*#A({allowStale:$=this.allowStale}={}){if(this.#Y)for(let Q=this.#U;;){if(!this.#g(Q))break;if($||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#K[Q]}}#g($){return $!==void 0&&this.#J.get(this.#X[$])===$}*entries(){for(let $ of this.#j())if(this.#$[$]!==void 0&&this.#X[$]!==void 0&&!this.#Q(this.#$[$]))yield[this.#X[$],this.#$[$]]}*rentries(){for(let $ of this.#A())if(this.#$[$]!==void 0&&this.#X[$]!==void 0&&!this.#Q(this.#$[$]))yield[this.#X[$],this.#$[$]]}*keys(){for(let $ of this.#j()){let Q=this.#X[$];if(Q!==void 0&&!this.#Q(this.#$[$]))yield Q}}*rkeys(){for(let $ of this.#A()){let Q=this.#X[$];if(Q!==void 0&&!this.#Q(this.#$[$]))yield Q}}*values(){for(let $ of this.#j())if(this.#$[$]!==void 0&&!this.#Q(this.#$[$]))yield this.#$[$]}*rvalues(){for(let $ of this.#A())if(this.#$[$]!==void 0&&!this.#Q(this.#$[$]))yield this.#$[$]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find($,Q={}){for(let X of this.#j()){let Y=this.#$[X],J=this.#Q(Y)?Y.__staleWhileFetching:Y;if(J===void 0)continue;if($(J,this.#X[X],this))return this.get(this.#X[X],Q)}}forEach($,Q=this){for(let X of this.#j()){let Y=this.#$[X],J=this.#Q(Y)?Y.__staleWhileFetching:Y;if(J===void 0)continue;$.call(Q,J,this.#X[X],this)}}rforEach($,Q=this){for(let X of this.#A()){let Y=this.#$[X],J=this.#Q(Y)?Y.__staleWhileFetching:Y;if(J===void 0)continue;$.call(Q,J,this.#X[X],this)}}purgeStale(){let $=!1;for(let Q of this.#A({allowStale:!0}))if(this.#N(Q))this.#I(this.#X[Q],"expire"),$=!0;return $}info($){let Q=this.#J.get($);if(Q===void 0)return;let X=this.#$[Q],Y=this.#Q(X)?X.__staleWhileFetching:X;if(Y===void 0)return;let J={value:Y};if(this.#z&&this.#M){let W=this.#z[Q],G=this.#M[Q];if(W&&G){let U=W-(P9.now()-G);J.ttl=U,J.start=Date.now()}}if(this.#Z)J.size=this.#Z[Q];return J}dump(){let $=[];for(let Q of this.#j({allowStale:!0})){let X=this.#X[Q],Y=this.#$[Q],J=this.#Q(Y)?Y.__staleWhileFetching:Y;if(J===void 0||X===void 0)continue;let W={value:J};if(this.#z&&this.#M){W.ttl=this.#z[Q];let G=P9.now()-this.#M[Q];W.start=Math.floor(Date.now()-G)}if(this.#Z)W.size=this.#Z[Q];$.unshift([X,W])}return $}load($){this.clear();for(let[Q,X]of $){if(X.start){let Y=Date.now()-X.start;X.start=P9.now()-Y}this.set(Q,X.value,X)}}set($,Q,X={}){if(Q===void 0)return this.delete($),this;let{ttl:Y=this.ttl,start:J,noDisposeOnSet:W=this.noDisposeOnSet,sizeCalculation:G=this.sizeCalculation,status:U}=X,{noUpdateTTL:H=this.noUpdateTTL}=X,q=this.#f($,Q,X.size||0,G);if(this.maxEntrySize&&q>this.maxEntrySize){if(U)U.set="miss",U.maxEntrySizeExceeded=!0;return this.#I($,"set"),this}let V=this.#Y===0?void 0:this.#J.get($);if(V===void 0){if(V=this.#Y===0?this.#W:this.#F.length!==0?this.#F.pop():this.#Y===this.#H?this.#C(!1):this.#Y,this.#X[V]=$,this.#$[V]=Q,this.#J.set($,V),this.#K[this.#W]=V,this.#B[V]=this.#W,this.#W=V,this.#Y++,this.#v(V,q,U),U)U.set="add";H=!1}else{this.#S(V);let B=this.#$[V];if(Q!==B){if(this.#P&&this.#Q(B)){B.__abortController.abort(Error("replaced"));let{__staleWhileFetching:z}=B;if(z!==void 0&&!W){if(this.#L)this.#w?.(z,$,"set");if(this.#q)this.#G?.push([z,$,"set"])}}else if(!W){if(this.#L)this.#w?.(B,$,"set");if(this.#q)this.#G?.push([B,$,"set"])}if(this.#b(V),this.#v(V,q,U),this.#$[V]=Q,U){U.set="replace";let z=B&&this.#Q(B)?B.__staleWhileFetching:B;if(z!==void 0)U.oldValue=z}}else if(U)U.set="update"}if(Y!==0&&!this.#z)this.#x();if(this.#z){if(!H)this.#y(V,Y,J);if(U)this.#R(U,V)}if(!W&&this.#q&&this.#G){let B=this.#G,z;while(z=B?.shift())this.#O?.(...z)}return this}pop(){try{while(this.#Y){let $=this.#$[this.#U];if(this.#C(!0),this.#Q($)){if($.__staleWhileFetching)return $.__staleWhileFetching}else if($!==void 0)return $}}finally{if(this.#q&&this.#G){let $=this.#G,Q;while(Q=$?.shift())this.#O?.(...Q)}}}#C($){let Q=this.#U,X=this.#X[Q],Y=this.#$[Q];if(this.#P&&this.#Q(Y))Y.__abortController.abort(Error("evicted"));else if(this.#L||this.#q){if(this.#L)this.#w?.(Y,X,"evict");if(this.#q)this.#G?.push([Y,X,"evict"])}if(this.#b(Q),$)this.#X[Q]=void 0,this.#$[Q]=void 0,this.#F.push(Q);if(this.#Y===1)this.#U=this.#W=0,this.#F.length=0;else this.#U=this.#K[Q];return this.#J.delete(X),this.#Y--,Q}has($,Q={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:Y}=Q,J=this.#J.get($);if(J!==void 0){let W=this.#$[J];if(this.#Q(W)&&W.__staleWhileFetching===void 0)return!1;if(!this.#N(J)){if(X)this.#E(J);if(Y)Y.has="hit",this.#R(Y,J);return!0}else if(Y)Y.has="stale",this.#R(Y,J)}else if(Y)Y.has="miss";return!1}peek($,Q={}){let{allowStale:X=this.allowStale}=Q,Y=this.#J.get($);if(Y===void 0||!X&&this.#N(Y))return;let J=this.#$[Y];return this.#Q(J)?J.__staleWhileFetching:J}#T($,Q,X,Y){let J=Q===void 0?void 0:this.#$[Q];if(this.#Q(J))return J;let W=new JG,{signal:G}=X;G?.addEventListener("abort",()=>W.abort(G.reason),{signal:W.signal});let U={signal:W.signal,options:X,context:Y},H=(w,O=!1)=>{let{aborted:D}=W.signal,M=X.ignoreFetchAbort&&w!==void 0;if(X.status)if(D&&!O){if(X.status.fetchAborted=!0,X.status.fetchError=W.signal.reason,M)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(D&&!M&&!O)return V(W.signal.reason);let R=z;if(this.#$[Q]===z)if(w===void 0)if(R.__staleWhileFetching)this.#$[Q]=R.__staleWhileFetching;else this.#I($,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set($,w,U.options)}return w},q=(w)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=w;return V(w)},V=(w)=>{let{aborted:O}=W.signal,D=O&&X.allowStaleOnFetchAbort,M=D||X.allowStaleOnFetchRejection,R=M||X.noDeleteOnFetchRejection,P=z;if(this.#$[Q]===z){if(!R||P.__staleWhileFetching===void 0)this.#I($,"fetch");else if(!D)this.#$[Q]=P.__staleWhileFetching}if(M){if(X.status&&P.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return P.__staleWhileFetching}else if(P.__returned===P)throw w},B=(w,O)=>{let D=this.#_?.($,J,U);if(D&&D instanceof Promise)D.then((M)=>w(M===void 0?void 0:M),O);W.signal.addEventListener("abort",()=>{if(!X.ignoreFetchAbort||X.allowStaleOnFetchAbort){if(w(void 0),X.allowStaleOnFetchAbort)w=(M)=>H(M,!0)}})};if(X.status)X.status.fetchDispatched=!0;let z=new Promise(B).then(H,q),N=Object.assign(z,{__abortController:W,__staleWhileFetching:J,__returned:void 0});if(Q===void 0)this.set($,N,{...U.options,status:void 0}),Q=this.#J.get($);else this.#$[Q]=N;return N}#Q($){if(!this.#P)return!1;let Q=$;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof JG}async fetch($,Q={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:J=this.noDeleteOnStaleGet,ttl:W=this.ttl,noDisposeOnSet:G=this.noDisposeOnSet,size:U=0,sizeCalculation:H=this.sizeCalculation,noUpdateTTL:q=this.noUpdateTTL,noDeleteOnFetchRejection:V=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:B=this.allowStaleOnFetchRejection,ignoreFetchAbort:z=this.ignoreFetchAbort,allowStaleOnFetchAbort:N=this.allowStaleOnFetchAbort,context:w,forceRefresh:O=!1,status:D,signal:M}=Q;if(!this.#P){if(D)D.fetch="get";return this.get($,{allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:J,status:D})}let R={allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:J,ttl:W,noDisposeOnSet:G,size:U,sizeCalculation:H,noUpdateTTL:q,noDeleteOnFetchRejection:V,allowStaleOnFetchRejection:B,allowStaleOnFetchAbort:N,ignoreFetchAbort:z,status:D,signal:M},P=this.#J.get($);if(P===void 0){if(D)D.fetch="miss";let k=this.#T($,P,R,w);return k.__returned=k}else{let k=this.#$[P];if(this.#Q(k)){let u6=X&&k.__staleWhileFetching!==void 0;if(D){if(D.fetch="inflight",u6)D.returnedStale=!0}return u6?k.__staleWhileFetching:k.__returned=k}let u=this.#N(P);if(!O&&!u){if(D)D.fetch="hit";if(this.#S(P),Y)this.#E(P);if(D)this.#R(D,P);return k}let W$=this.#T($,P,R,w),a$=W$.__staleWhileFetching!==void 0&&X;if(D){if(D.fetch=u?"stale":"refresh",a$&&u)D.returnedStale=!0}return a$?W$.__staleWhileFetching:W$.__returned=W$}}async forceFetch($,Q={}){let X=await this.fetch($,Q);if(X===void 0)throw Error("fetch() returned undefined");return X}memo($,Q={}){let X=this.#k;if(!X)throw Error("no memoMethod provided to constructor");let{context:Y,forceRefresh:J,...W}=Q,G=this.get($,W);if(!J&&G!==void 0)return G;let U=X($,G,{options:W,context:Y});return this.set($,U,W),U}get($,Q={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:J=this.noDeleteOnStaleGet,status:W}=Q,G=this.#J.get($);if(G!==void 0){let U=this.#$[G],H=this.#Q(U);if(W)this.#R(W,G);if(this.#N(G)){if(W)W.get="stale";if(!H){if(!J)this.#I($,"expire");if(W&&X)W.returnedStale=!0;return X?U:void 0}else{if(W&&X&&U.__staleWhileFetching!==void 0)W.returnedStale=!0;return X?U.__staleWhileFetching:void 0}}else{if(W)W.get="hit";if(H)return U.__staleWhileFetching;if(this.#S(G),Y)this.#E(G);return U}}else if(W)W.get="miss"}#h($,Q){this.#B[Q]=$,this.#K[$]=Q}#S($){if($!==this.#W){if($===this.#U)this.#U=this.#K[$];else this.#h(this.#B[$],this.#K[$]);this.#h(this.#W,$),this.#W=$}}delete($){return this.#I($,"delete")}#I($,Q){let X=!1;if(this.#Y!==0){let Y=this.#J.get($);if(Y!==void 0)if(X=!0,this.#Y===1)this.#u(Q);else{this.#b(Y);let J=this.#$[Y];if(this.#Q(J))J.__abortController.abort(Error("deleted"));else if(this.#L||this.#q){if(this.#L)this.#w?.(J,$,Q);if(this.#q)this.#G?.push([J,$,Q])}if(this.#J.delete($),this.#X[Y]=void 0,this.#$[Y]=void 0,Y===this.#W)this.#W=this.#B[Y];else if(Y===this.#U)this.#U=this.#K[Y];else{let W=this.#B[Y];this.#K[W]=this.#K[Y];let G=this.#K[Y];this.#B[G]=this.#B[Y]}this.#Y--,this.#F.push(Y)}}if(this.#q&&this.#G?.length){let Y=this.#G,J;while(J=Y?.shift())this.#O?.(...J)}return X}clear(){return this.#u("delete")}#u($){for(let Q of this.#A({allowStale:!0})){let X=this.#$[Q];if(this.#Q(X))X.__abortController.abort(Error("deleted"));else{let Y=this.#X[Q];if(this.#L)this.#w?.(X,Y,$);if(this.#q)this.#G?.push([X,Y,$])}}if(this.#J.clear(),this.#$.fill(void 0),this.#X.fill(void 0),this.#z&&this.#M)this.#z.fill(0),this.#M.fill(0);if(this.#Z)this.#Z.fill(0);if(this.#U=0,this.#W=0,this.#F.length=0,this.#D=0,this.#Y=0,this.#q&&this.#G){let Q=this.#G,X;while(X=Q?.shift())this.#O?.(...X)}}}function VE($,Q,X=100){let Y=new YG({max:X}),J=(...W)=>{let G=Q(...W),U=Y.get(G);if(U!==void 0)return U;let H=$(...W);return Y.set(G,H),H};return J.cache={clear:()=>Y.clear(),size:()=>Y.size,delete:(W)=>Y.delete(W),get:(W)=>Y.peek(W),has:(W)=>Y.has(W)},J}var Ts=8192;function zE($,Q){try{return{ok:!0,value:JSON.parse(XG($))}}catch(X){if(Q)R9(X);return{ok:!1}}}var BE=VE(zE,($)=>$,50),b9=Object.assign(function(Q,X=!0){if(!Q)return null;let Y=Q.length>Ts?zE(Q,X):BE(Q,X);return Y.ok?Y.value:null},{cache:BE.cache});import{join as ys}from"path";import{readdir as s2$,readFile as xs}from"fs/promises";import{release as NE}from"os";var m0=v$(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){try{let $=m$().readFileSync("/proc/version",{encoding:"utf8"});if($.toLowerCase().includes("microsoft")||$.toLowerCase().includes("wsl"))return"wsl"}catch($){R9($)}return"linux"}return"unknown"}catch($){return R9($),"unknown"}}),JD$=v$(()=>{if(process.platform!=="linux")return;try{let $=m$().readFileSync("/proc/version",{encoding:"utf8"}),Q=$.match(/WSL(\d+)/i);if(Q&&Q[1])return Q[1];if($.toLowerCase().includes("microsoft"))return"1";return}catch($){R9($);return}}),YD$=v$(async()=>{if(process.platform!=="linux")return;let $={linuxKernel:NE()};try{let Q=await xs("/etc/os-release","utf8");for(let X of Q.split(`
115
- `)){let Y=X.match(/^(ID|VERSION_ID)=(.*)$/);if(Y&&Y[1]&&Y[2]){let J=Y[2].replace(/^"|"$/g,"");if(Y[1]==="ID")$.linuxDistroId=J;else $.linuxDistroVersion=J}}}catch{}return $});var WD$=v$(()=>{if(process.platform!=="darwin")return;let Q=NE().match(/^(\d+)\./);if(!Q||!Q[1])return;return parseInt(Q[1],10)-9});var l0=v$(function(){switch(m0()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),qD$=v$(function(){return ys(l0(),"managed-settings.d")});import{isAbsolute as wE}from"path";var fs=S(()=>K.object({allowedDomains:K.array(K.string()).optional(),deniedDomains:K.array(K.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:K.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:K.array(K.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:K.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:K.boolean().optional(),allowMachLookup:K.array(K.string().refine(($)=>{return!($.endsWith("*")?$.slice(0,-1):$).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:K.number().optional(),socksProxyPort:K.number().optional()}).optional()),gs=S(()=>K.object({allowWrite:K.array(K.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:K.array(K.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:K.array(K.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:K.array(K.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:K.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),OE=S(()=>K.object({enabled:K.boolean().optional(),failIfUnavailable:K.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:K.boolean().optional(),allowUnsandboxedCommands:K.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:fs(),filesystem:gs(),ignoreViolations:K.record(K.string(),K.array(K.string())).optional(),enableWeakerNestedSandbox:K.boolean().optional(),enableWeakerNetworkIsolation:K.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:K.array(K.string()).optional(),ripgrep:K.object({command:K.string(),args:K.array(K.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:K.preprocess(($)=>typeof $==="string"&&wE($)?$:void 0,K.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:K.preprocess(($)=>typeof $==="string"&&wE($)?$:void 0,K.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 DE=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],FE=["normal","vim"],ZE=["auto","tmux","in-process"],hs=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],ME=["auto",...hs];var FD$=m0()==="macos"?"⏺":"●";var eX=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],us=[...eX,"bubble"],LE=us;var PD$=S(()=>mV.enum(LE)),ED$=S(()=>mV.enum(eX));var jE=["bash","powershell"];var $J=S(()=>K.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 ms(){let $=K.object({type:K.literal("command").describe("Shell command hook type"),command:K.string().describe("Shell command to execute"),args:K.array(K.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:$J(),shell:K.enum(jE).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:K.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:K.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:K.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:K.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".')}),Q=K.object({type:K.literal("prompt").describe("LLM prompt hook type"),prompt:K.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:K.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:K.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:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")}),X=K.object({type:K.literal("mcp_tool").describe("MCP tool hook type"),server:K.string().describe("Name of an already-configured MCP server to invoke"),tool:K.string().describe("Name of the tool on that server to call"),input:K.record(K.string(),K.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:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")}),Y=K.object({type:K.literal("http").describe("HTTP hook type"),url:K.string().url().describe("URL to POST the hook input JSON to"),if:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:K.record(K.string(),K.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:K.array(K.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:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")}),J=K.object({type:K.literal("agent").describe("Agentic verifier hook type"),prompt:K.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:K.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:$,PromptHookSchema:Q,HttpHookSchema:Y,AgentHookSchema:J,McpToolHookSchema:X}}var AE=S(()=>{let{BashCommandHookSchema:$,PromptHookSchema:Q,AgentHookSchema:X,HttpHookSchema:Y,McpToolHookSchema:J}=ms();return K.discriminatedUnion("type",[$,Q,X,Y,J])}),IE=S(()=>K.object({matcher:K.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:K.array(AE()).describe("List of hooks to execute when the matcher matches")})),c0=S(()=>K.partialRecord(K.enum(s0),K.array(IE())));var fD$=S(()=>K.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),gD$=S(()=>K.enum(["stdio","sse","sse-ide","http","ws","sdk"])),ls=S(()=>K.object({type:K.literal("stdio").optional(),command:K.string().min(1,"Command cannot be empty"),args:K.array(K.string()).default([]),env:K.record(K.string(),K.string()).optional(),alwaysLoad:K.boolean().optional()})),cs=S(()=>K.boolean()),RE=S(()=>K.object({clientId:K.string().optional(),callbackPort:K.number().int().positive().optional(),authServerMetadataUrl:K.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:K.string().min(1).optional(),xaa:cs().optional()})),ps=S(()=>K.object({type:K.literal("sse"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),oauth:RE().optional(),alwaysLoad:K.boolean().optional()})),ds=S(()=>K.object({type:K.literal("sse-ide"),url:K.string(),ideName:K.string(),ideRunningInWindows:K.boolean().optional(),alwaysLoad:K.boolean().optional()})),is=S(()=>K.object({type:K.literal("ws-ide"),url:K.string(),ideName:K.string(),authToken:K.string().optional(),ideRunningInWindows:K.boolean().optional(),alwaysLoad:K.boolean().optional()})),ns=S(()=>K.object({type:K.enum(["http","streamable-http"]).transform(()=>"http"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),oauth:RE().optional(),alwaysLoad:K.boolean().optional()})),rs=S(()=>K.object({type:K.literal("ws"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),alwaysLoad:K.boolean().optional()})),os=S(()=>K.object({type:K.literal("sdk"),name:K.string(),alwaysLoad:K.boolean().optional()})),ts=S(()=>K.enum(["allow","ask","blocked"])),as=S(()=>K.object({type:K.literal("claudeai-proxy"),url:K.string(),id:K.string(),alwaysLoad:K.boolean().optional(),toolPermissions:K.record(K.string(),ts()).optional()})),WG=S(()=>K.union([ls(),ps(),ds(),is(),ns(),rs(),os(),as()])),hD$=S(()=>K.object({mcpServers:K.record(K.string(),WG())}));var SE=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","life-sciences","knowledge-work-plugins"]);var ss=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,es=/[^\u0020-\u007E]/;function $e($){if(SE.has($.toLowerCase()))return!1;if(es.test($))return!0;return ss.test($)}var M4=S(()=>K.string().startsWith("./")),p0=S(()=>M4().endsWith(".json")),PE=S(()=>K.union([M4().refine(($)=>$.endsWith(".mcpb")||$.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),K.string().url().refine(($)=>$.endsWith(".mcpb")||$.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),Sz=S(()=>M4().endsWith(".md")),_z=S(()=>K.union([Sz(),M4()])),_E=S(()=>K.string().min(1,"Marketplace must have a name").refine(($)=>!$.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine(($)=>!$.includes("/")&&!$.includes("\\")&&!$.includes("..")&&$!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine(($)=>!$e($),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine(($)=>$.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine(($)=>$.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'})),kz=S(()=>K.object({name:K.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:K.string().optional().describe("Contact email for support or feedback"),url:K.string().optional().describe("Website, GitHub profile, or organization URL")})),Qe=S(()=>K.object({$schema:K.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:K.string().min(1,"Plugin name cannot be empty").refine(($)=>!$.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),version:K.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:K.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:kz().optional().describe("Information about the plugin creator or maintainer"),homepage:K.string().url().optional().describe("Plugin homepage or documentation URL"),repository:K.string().optional().describe("Source code repository URL"),license:K.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:K.array(K.string()).optional().describe("Tags for plugin discovery and categorization"),dependencies:K.array(Ie()).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.`)})),nD$=S(()=>K.object({description:K.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:K.lazy(()=>c0()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),Xe=S(()=>K.object({hooks:K.union([p0().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),K.lazy(()=>c0()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),K.array(K.union([p0().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),K.lazy(()=>c0()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),Je=S(()=>K.object({source:_z().optional().describe("Path to command markdown file, relative to plugin root"),content:K.string().optional().describe("Inline markdown content for the command"),description:K.string().optional().describe("Command description override"),argumentHint:K.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:K.string().optional().describe("Default model for this command"),allowedTools:K.array(K.string()).optional().describe("Tools allowed when command runs")}).refine(($)=>$.source&&!$.content||!$.source&&$.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),Ye=S(()=>K.object({commands:K.union([_z().describe("Path to additional command file or skill directory (in addition to those in the commands/ directory, if it exists), relative to the plugin root"),K.array(_z().describe("Path to additional command file or skill directory (in addition to those in the commands/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional command files or skill directories"),K.record(K.string(),Je()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),We=S(()=>K.object({agents:K.union([Sz().describe("Path to additional agent file (in addition to those in the agents/ directory, if it exists), relative to the plugin root"),K.array(Sz().describe("Path to additional agent file (in addition to those in the agents/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional agent files")])})),Ge=S(()=>K.object({skills:K.union([M4().describe("Path to additional skill directory (in addition to those in the skills/ directory, if it exists), relative to the plugin root"),K.array(M4().describe("Path to additional skill directory (in addition to those in the skills/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional skill directories")])})),Ue=S(()=>K.object({outputStyles:K.union([M4().describe("Path to additional output styles directory or file (in addition to those in the output-styles/ directory, if it exists), relative to the plugin root"),K.array(M4().describe("Path to additional output styles directory or file (in addition to those in the output-styles/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional output styles directories or files")])})),kE=S(()=>K.object({themes:K.union([M4().describe("Path to additional themes directory or file (in addition to those in the themes/ directory, if it exists), relative to the plugin root"),K.array(M4().describe("Path to additional themes directory or file (in addition to those in the themes/ directory, if it exists), relative to the plugin root")).describe("List of paths to additional themes directories or files")])})),He=S(()=>K.object({})),EE=S(()=>K.string().min(1)),Ke=S(()=>K.string().min(2).refine(($)=>$.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),qe=S(()=>K.object({mcpServers:K.union([p0().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),PE().describe("Path or URL to MCPB file containing MCP server configuration"),K.record(K.string(),WG()).describe("MCP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to MCP servers configuration file"),PE().describe("Path or URL to MCPB file"),K.record(K.string(),WG()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),vE=S(()=>K.object({type:K.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:K.string().describe("Human-readable label shown in the config dialog"),description:K.string().describe("Help text shown beneath the field in the config dialog"),required:K.boolean().optional().describe("If true, validation fails when this field is empty"),default:K.union([K.string(),K.number(),K.boolean(),K.array(K.string())]).optional().describe("Default value used when the user provides nothing"),multiple:K.boolean().optional().describe("For string type: allow an array of strings"),sensitive:K.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:K.number().optional().describe("Minimum value (number type only)"),max:K.number().optional().describe("Maximum value (number type only)")}).strict()),Ve=S(()=>K.object({userConfig:K.record(K.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"),vE()).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.")})),Be=S(()=>K.object({channels:K.array(K.object({server:K.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:K.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:K.record(K.string(),vE()).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.")})),bE=S(()=>K.strictObject({command:K.string().min(1).refine(($)=>{if($.includes(" ")&&!$.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:K.array(EE()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:K.record(Ke(),EE()).refine(($)=>Object.keys($).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:K.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:K.record(K.string(),K.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:K.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:K.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:K.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:K.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:K.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:K.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:K.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up")})),ze=S(()=>K.strictObject({name:K.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:K.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:K.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:K.union([K.literal("always"),K.string().startsWith("on-skill-invoke:").refine(($)=>$.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).')})),Ne=S(()=>K.array(ze()).refine(($)=>new Set($.map((Q)=>Q.name)).size===$.length,{message:"Monitor names must be unique within a plugin"})),CE=S(()=>K.object({monitors:K.union([p0().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Ne()]).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.")})),we=S(()=>K.object({lspServers:K.union([p0().describe("Path to .lsp.json configuration file relative to plugin root"),K.record(K.string(),bE()).describe("LSP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to LSP configuration file"),K.record(K.string(),bE()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),TE=S(()=>K.string().refine(($)=>!$.includes("..")&&!$.includes("//"),"Package name cannot contain path traversal patterns").refine(($)=>{let Q=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,X=/^[a-z0-9][a-z0-9-._]*$/;return Q.test($)||X.test($)},"Invalid npm package name format")),Oe=S(()=>K.object({settings:K.record(K.string(),K.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),De=S(()=>K.object({experimental:K.preprocess(($)=>typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0,K.object({...kE().partial().shape,...CE().partial().shape}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),Fe=S(()=>K.object({...Qe().shape,...Xe().partial().shape,...Ye().partial().shape,...We().partial().shape,...Ge().partial().shape,...Ue().partial().shape,...kE().partial().shape,...He().shape,...Be().partial().shape,...qe().partial().shape,...we().partial().shape,...CE().partial().shape,...Oe().partial().shape,...Ve().partial().shape,...De().partial().shape})),QJ=S(()=>K.discriminatedUnion("source",[K.object({source:K.literal("url"),url:K.string().url().describe("Direct URL to marketplace.json file"),headers:K.record(K.string(),K.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),K.object({source:K.literal("github"),repo:K.string().describe("GitHub repository in owner/repo format"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:K.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:K.array(K.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.')}),K.object({source:K.literal("git"),url:K.string().describe("Full git repository URL"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:K.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:K.array(K.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.')}),K.object({source:K.literal("npm"),package:TE().describe("NPM package containing marketplace.json")}),K.object({source:K.literal("file"),path:K.string().describe("Local file path to marketplace.json")}),K.object({source:K.literal("directory"),path:K.string().describe("Local directory containing .claude-plugin/marketplace.json")}),K.object({source:K.literal("hostPattern"),hostPattern:K.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$").')}),K.object({source:K.literal("pathPattern"),pathPattern:K.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.')}),K.object({source:K.literal("settings"),name:_E().refine(($)=>!SE.has($.toLowerCase()),{message:"Reserved official marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation "+"as PluginMarketplaceSchema plus reserved-name rejection — "+"validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:K.array(Ze()).describe("Plugin entries declared inline in settings.json"),owner:kz().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).")])),bz=S(()=>K.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),xE=S(()=>K.union([M4().describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),K.object({source:K.literal("npm"),package:TE().or(K.string().refine(($)=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test($)||!$.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:K.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:K.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),K.object({source:K.literal("url"),url:K.string().describe("Full git repository URL (https:// or git@)"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:bz().optional().describe("Specific commit SHA to use")}),K.object({source:K.literal("github"),repo:K.string().describe("GitHub repository in owner/repo format"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:bz().optional().describe("Specific commit SHA to use")}),K.object({source:K.literal("git-subdir"),url:K.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:K.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:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:bz().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."),K.object({source:K.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.')])),Ze=S(()=>K.object({name:K.string().min(1,"Plugin name cannot be empty").refine(($)=>!$.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:xE().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:K.string().optional(),version:K.string().optional(),strict:K.boolean().optional()}).refine(($)=>typeof $.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(($)=>typeof $.source==="string"||$.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 Me=S(()=>Fe().partial().extend({name:K.string().min(1,"Plugin name cannot be empty").refine(($)=>!$.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:xE().describe("Where to fetch the plugin from"),category:K.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:K.array(K.string()).optional().describe("Tags for searchability and discovery"),strict:K.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest.")})),Le=S(()=>K.object({name:K.string().min(1).refine(($)=>!$.includes(" "))}));function je($){let Q=Me();return $.flatMap((X,Y)=>{let J=Q.safeParse(X);if(J.success)return[J.data];let W=Le().safeParse(X).data?.name,G=J.error.issues.map((U)=>`${U.path.join(".")}: ${U.message}`).join(", ");if(W)return K$(`Stubbing unparseable marketplace plugin entry (${W}): ${G}`,{level:"warn"}),[{name:W,source:{source:"unsupported"},strict:!0}];return K$(`Dropping unparseable marketplace plugin entry (index ${Y}): ${G}`,{level:"warn"}),[]})}var rD$=S(()=>K.object({$schema:K.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:_E(),version:K.string().optional().describe("Marketplace manifest version"),description:K.string().optional().describe("Human-readable description of this marketplace"),owner:kz().describe("Marketplace maintainer or curator information"),plugins:K.array(K.unknown()).transform(je).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:K.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:K.object({pluginRoot:K.string().optional().describe("Base path for relative plugin sources"),version:K.string().optional().describe("Marketplace version"),description:K.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:K.array(K.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust.")})),yE=S(()=>K.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")),Ae=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,Ie=S(()=>K.union([K.string().regex(Ae,"Dependency must be a plugin name, optionally qualified with @marketplace").transform(($)=>$.replace(/@\^[^@]*$/,"")),K.object({name:K.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:K.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform(($)=>$.marketplace?`${$.name}@${$.marketplace}`:$.name)])),Re=S(()=>K.object({version:K.string().describe("Currently installed version"),installedAt:K.string().describe("ISO 8601 timestamp of installation"),lastUpdated:K.string().optional().describe("ISO 8601 timestamp of last update"),installPath:K.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:K.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:K.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:K.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).")})),Pe=S(()=>K.object({version:K.literal(1).describe("Schema version 1"),plugins:K.record(yE(),Re()).describe("Map of plugin IDs to their installation metadata")})),Ee=S(()=>K.enum(["managed","user","project","local"])),be=S(()=>K.object({scope:Ee().describe("Installation scope"),projectPath:K.string().optional().describe("Project path (required for project/local scopes)"),installPath:K.string().describe("Absolute path to the versioned plugin directory"),version:K.string().optional().describe("Currently installed version"),installedAt:K.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:K.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:K.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:K.string().optional().describe("Tag-derived semver this install resolved to"),auto:K.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),Se=S(()=>K.object({version:K.literal(2).describe("Schema version 2"),plugins:K.record(yE(),K.array(be())).describe("Map of plugin IDs to arrays of installation entries")})),oD$=S(()=>K.union([Pe(),Se()])),_e=S(()=>K.object({source:QJ().describe("Where to fetch the marketplace from"),installLocation:K.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:K.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:K.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),tD$=S(()=>K.record(K.string(),_e()));var ke=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var vz;function GG(){let $=z5();if(vz?.allowed===$)return vz.result;let Q=new Set($);Q.add("flagSettings"),Q.add("policySettings");let X=ke.filter((Y)=>Q.has(Y));return vz={allowed:$,result:X},X}var fE="https://json.schemastore.org/claude-code-settings.json";var ve=["autoMode","deepLink","voice","assistant","briefView"],UG={},HG={autoMode:{buildGate:()=>!1,shape:()=>UG,permissionsShape:()=>UG,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:K.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>UG},assistant:{buildGate:()=>!1,shape:()=>UG},briefView:{buildGate:()=>!0,shape:()=>({defaultView:K.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})}};function Cz(){return ve.filter(($)=>HG[$].buildGate())}function gE($){let Q={};for(let X of $)Q={...Q,...HG[X].shape()};return Q}function hE($){let Q={};for(let X of $)Q={...Q,...HG[X].permissionsShape?.()};return Q}function uE($){let Q=[];for(let X of $)Q.push(...HG[X].permissionModes?.()??[]);return Q}function mE($){let Q=$.split("__"),[X,Y,...J]=Q;if(X!=="mcp"||!Y)return null;let W=J.length>0?J.join("__"):void 0;return{serverName:Y,toolName:W}}var lE={Task:"Agent",KillShell:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage"};function S9($){return Object.hasOwn(lE,$)?lE[$]:$}var cE="workspace",KF$=`mcp__${cE}__bash`,qF$=`mcp__${cE}__web_fetch`;function Ce($){return $.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function pE($){let Q=Te($,"(");if(Q===-1)return{toolName:S9($)};let X=xe($,")");if(X===-1||X<=Q)return{toolName:S9($)};if(X!==$.length-1)return{toolName:S9($)};let Y=$.substring(0,Q),J=$.substring(Q+1,X);if(!Y)return{toolName:S9($)};if(J===""||J==="*")return{toolName:S9(Y)};let W=Ce(J);return{toolName:S9(Y),ruleContent:W}}function Te($,Q){for(let X=0;X<$.length;X++)if($[X]===Q){let Y=0,J=X-1;while(J>=0&&$[J]==="\\")Y++,J--;if(Y%2===0)return X}return-1}function xe($,Q){for(let X=$.length-1;X>=0;X--)if($[X]===Q){let Y=0,J=X-1;while(J>=0&&$[J]==="\\")Y++,J--;if(Y%2===0)return X}return-1}var KG={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit"],bashPrefixTools:["Bash"],customValidation:{WebSearch:($)=>{if($.includes("*")||$.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:($)=>{if($.includes("://")||$.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(!$.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 dE($){return KG.filePatternTools.includes($)}function iE($){return KG.bashPrefixTools.includes($)}function nE($){return Object.hasOwn(KG.customValidation,$)?KG.customValidation[$]:void 0}function rE($,Q){let X=0,Y=Q-1;while(Y>=0&&$[Y]==="\\")X++,Y--;return X%2!==0}function Tz($,Q){let X=0;for(let Y=0;Y<$.length;Y++)if($[Y]===Q&&!rE($,Y))X++;return X}function ye($){for(let Q=0;Q<$.length-1;Q++)if($[Q]==="("&&$[Q+1]===")"){if(!rE($,Q))return!0}return!1}function xz($){if(!$||$.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let Q=Tz($,"("),X=Tz($,")");if(Q!==X)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(ye($)){let G=$.substring(0,$.indexOf("("));if(!G)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 "${G}" without parentheses`,examples:[`${G}`,`${G}(some-pattern)`]}}let Y=pE($),J=mE(Y.toolName);if(J){if(Y.ruleContent!==void 0||Tz($,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${Y.toolName}" without parentheses, or use "mcp__${J.serverName}__*" for all tools`,examples:[`mcp__${J.serverName}`,`mcp__${J.serverName}__*`,J.toolName&&J.toolName!=="*"?`mcp__${J.serverName}__${J.toolName}`:void 0].filter(Boolean)};return{valid:!0}}if(!Y.toolName||Y.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(!Y.toolName.includes("_")&&Y.toolName[0]!==Y.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${jU(String(Y.toolName))}"`};let W=nE(Y.toolName);if(W&&Y.ruleContent!==void 0){let G=W(Y.ruleContent);if(!G.valid)return G}if(iE(Y.toolName)&&Y.ruleContent!==void 0){let G=Y.ruleContent;if(G.includes(":*")&&!G.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(G===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(dE(Y.toolName)&&Y.ruleContent!==void 0){let G=Y.ruleContent;if(G.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${Y.toolName}(*.ts) - matches .ts files`,`${Y.toolName}(src/**) - matches all files in src`,`${Y.toolName}(**/*.test.ts) - matches test files`]};if(G.includes("*")&&!G.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!G.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${Y.toolName}(*.js) - all .js files`,`${Y.toolName}(src/*) - all files directly in src`,`${Y.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}var qG=S(()=>K.string().superRefine(($,Q)=>{let X=xz($);if(!X.valid){let Y=X.error;if(X.suggestion)Y+=`. ${X.suggestion}`;if(X.examples&&X.examples.length>0)Y+=`. Examples: ${X.examples.join(", ")}`;Q.addIssue({code:K.ZodIssueCode.custom,message:Y,params:{received:$}})}}));var fe=S(()=>K.record(K.string(),K.coerce.string()));function tE($){return K.object({allow:K.array(qG()).optional().describe("List of permission rules for allowed operations"),deny:K.array(qG()).optional().describe("List of permission rules for denied operations"),ask:K.array(qG()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:K.enum([...eX,...uE($)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:K.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...hE($),additionalDirectories:K.array(K.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var vF$=S(()=>tE(Cz())),ge=S(()=>K.object({source:QJ().describe("Where to fetch the marketplace from"),installLocation:K.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:K.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),he=S(()=>K.object({serverName:K.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:K.array(K.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:K.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(($)=>{return uH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),ue=S(()=>K.object({serverName:K.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:K.array(K.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:K.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(($)=>{return uH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),me=S(()=>K.object({path:K.string().describe("Absolute path to the helper executable"),timeoutMs:K.number().int().min(1000).optional(),refreshIntervalMs:K.union([K.literal(0),K.number().int().min(60000)]).optional()})),oE=["skills","agents","hooks","mcp"];function aE($){return K.object({$schema:K.literal(fE).optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:K.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:K.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:K.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:K.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:K.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:me().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...R$(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:K.object({issuer:K.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:K.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:K.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:K.object({type:K.literal("command"),command:K.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:K.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:K.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:K.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:K.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:K.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:fe().optional().describe("Environment variables to set for Claude Code sessions"),attribution:K.object({commit:K.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:K.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:K.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:K.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:tE($).optional().describe("Tool usage permissions configuration"),model:K.string().optional().describe("Override the default model used by Claude Code"),availableModels:K.array(K.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:K.record(K.string(),K.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:K.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:K.array(K.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:K.array(K.string()).optional().describe("List of rejected MCP servers from .mcp.json"),skillOverrides:K.record(K.string(),K.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),allowedMcpServers:K.array(he()).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:K.array(ue()).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:c0().optional().describe("Custom commands to run before/after tool executions"),worktree:K.object({symlinkDirectories:K.array(K.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:K.array(K.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:K.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:K.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:K.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:K.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableSkillShellExecution:K.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:K.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:K.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:K.array(K.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:K.array(K.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:K.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:K.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:K.preprocess((Q)=>Array.isArray(Q)?Q.filter((X)=>oE.includes(X)):Q,K.union([K.boolean(),K.array(K.enum(oE))])).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:K.object({type:K.literal("command"),command:K.string(),padding:K.number().optional(),refreshInterval:K.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:K.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:K.string().optional().describe('URL template for PR links in the footer badge and inline messages. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),subagentStatusLine:K.object({type:K.literal("command"),command:K.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:K.record(K.string(),K.union([K.array(K.string()),K.boolean(),K.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:K.record(K.string(),ge()).check((Q)=>{for(let[X,Y]of Object.entries(Q.value))if(Y.source.source==="settings"&&Y.source.name!==X)Q.issues.push({code:"custom",input:Y.source.name,path:[X,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${X}" but source.name "${Y.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:K.array(QJ()).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:K.array(QJ()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),forceLoginMethod:K.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),parentSettingsBehavior:K.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:K.union([K.string(),K.array(K.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:K.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:K.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:K.string().optional().describe("Controls the output style for assistant responses"),viewMode:K.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:K.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:K.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:OE().optional(),feedbackSurveyRate:K.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:K.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:K.object({mode:K.enum(["append","replace"]),verbs:K.array(K.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:K.object({excludeDefault:K.boolean().optional(),tips:K.array(K.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:K.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:K.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:K.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:K.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),autoCompactWindow:K.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:K.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:K.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:K.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:K.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:K.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:K.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:K.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:K.array(K.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:K.record(K.string(),K.object({mcpServers:K.record(K.string(),K.record(K.string(),K.union([K.string(),K.number(),K.boolean(),K.array(K.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:K.record(K.string(),K.union([K.string(),K.number(),K.boolean(),K.array(K.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:K.object({defaultEnvironmentId:K.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:K.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:K.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:K.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:K.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:K.object({enabled:K.boolean().optional(),mode:K.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:K.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:K.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:K.array(K.object({marketplace:K.string(),plugin:K.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:K.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:K.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),autoMemoryEnabled:K.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:K.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:K.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:K.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:K.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),disableAutoMode:K.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:K.array(K.object({id:K.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:K.string().describe("Display name for the SSH connection"),sshHost:K.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:K.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:K.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:K.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:K.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:K.array(K.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:K.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:K.union([K.enum(ME),K.string().startsWith("custom:").transform((Q)=>Q)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:K.enum(FE).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:K.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:K.enum(DE).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:K.boolean().optional().describe("Automatically compact conversation when context fills"),autoScrollEnabled:K.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),fileCheckpointingEnabled:K.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:K.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:K.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:K.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:K.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:K.enum(ZE).optional().catch(void 0).describe("How spawned teammates execute (tmux, in-process, auto)"),remoteControlAtStartup:K.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:K.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:K.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:K.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:K.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:K.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...gE($)}).passthrough()}var C4=S(()=>aE(Cz()));var le=[{matches:($)=>$.path==="permissions.defaultMode"&&$.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:"https://code.claude.com/docs/en/iam#permission-modes"}},{matches:($)=>$.path==="apiKeyHelper"&&$.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:($)=>$.path==="cleanupPeriodDays"&&$.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:($)=>$.path.startsWith("env.")&&$.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:"https://code.claude.com/docs/en/settings#environment-variables"}},{matches:($)=>($.path==="permissions.allow"||$.path==="permissions.deny")&&$.code==="invalid_type"&&$.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:($)=>$.path.startsWith("hooks.")&&$.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:"https://code.claude.com/docs/en/hooks"}},{matches:($)=>$.path.includes("hooks")&&$.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:($)=>$.code==="invalid_type"&&$.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:($)=>$.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:"https://code.claude.com/docs/en/settings"}},{matches:($)=>$.code==="invalid_value"&&$.enumValues!==void 0,tip:{suggestion:void 0}},{matches:($)=>$.code==="invalid_type"&&$.expected==="object"&&$.received===null&&$.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:($)=>$.path==="permissions.additionalDirectories"&&$.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:"https://code.claude.com/docs/en/iam#working-directories"}}],ce={permissions:"https://code.claude.com/docs/en/iam#configuring-permissions",env:"https://code.claude.com/docs/en/settings#environment-variables",hooks:"https://code.claude.com/docs/en/hooks"};function sE($){let Q=le.find((Y)=>Y.matches($));if(!Q)return null;let X={...Q.tip};if($.code==="invalid_value"&&$.enumValues&&!X.suggestion)X.suggestion=`Valid values: ${$.enumValues.map((Y)=>`"${Y}"`).join(", ")}`;if(!X.docLink&&$.path){let Y=$.path.split(".")[0];if(Y)X.docLink=ce[Y]}return X}var rF$=S(()=>C4().strict());function eE($){return $.code==="invalid_type"}function $b($){return $.code==="invalid_value"}function pe($){return $.code==="unrecognized_keys"}function Qb($){return $.code==="too_small"}function XJ($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";return typeof $}function Xb($){let Q=$.match(/received (\w+)/);return Q?Q[1]:void 0}function i0($,Q){return $.issues.map((X)=>{let Y=X.path.map(String).join("."),J=X.message,W,G,U,H,q;if($b(X))G=X.values.map((B)=>String(B)),U=G.join(" | "),H=void 0,q=void 0;else if(eE(X)){U=X.expected;let B=Xb(X.message);H=B??XJ(X.input),q=B??XJ(X.input)}else if(Qb(X))U=String(X.minimum);else if(X.code==="custom"&&"params"in X)H=X.params.received,q=H;let V=sE({path:Y,code:X.code,expected:U,received:H,enumValues:G,message:X.message,value:H});if($b(X))W=G?.map((B)=>`"${B}"`).join(", "),J=`Invalid value. Expected one of: ${W}`;else if(eE(X)){let B=Xb(X.message)??XJ(X.input);if(X.expected==="object"&&B==="null"&&Y==="")J="Invalid or malformed JSON";else J=`Expected ${X.expected}, but received ${B}`}else if(pe(X)){let B=X.keys.join(", ");J=`Unrecognized ${rO(X.keys.length,"field")}: ${B}`}else if(Qb(X))J=`Number must be greater than or equal to ${X.minimum}`,W=String(X.minimum);return{file:Q,path:Y,message:J,expected:W,invalidValue:q,suggestion:V?.suggestion,docLink:V?.docLink}})}function de($,Q){if(!$||typeof $!=="object")return[];let X=$;if(!X.permissions||typeof X.permissions!=="object")return[];let Y=X.permissions,J=[];for(let W of["allow","deny","ask"]){let G=Y[W];if(!Array.isArray(G))continue;Y[W]=G.filter((U)=>{if(typeof U!=="string")return J.push({file:Q,path:`permissions.${W}`,message:`Non-string value in ${W} array was removed`,severity:"warning",invalidValue:U}),!1;let H=xz(U);if(!H.valid){let q=`Invalid permission rule "${U}" was skipped: ${H.error}`;if(H.suggestion)q+=`. ${H.suggestion}`;return J.push({file:Q,path:`permissions.${W}`,message:q,severity:"warning",invalidValue:U}),!1}return!0})}return J}var ie=new Set(s0);function ne($,Q){if(!$||typeof $!=="object")return[];let X=$;if(!("hooks"in X))return[];if(X.hooks===null||typeof X.hooks!=="object"||Array.isArray(X.hooks)){let W=XJ(X.hooks);return delete X.hooks,[{file:Q,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${W}. This field was ignored.`,severity:"warning",invalidValue:W,docLink:"https://code.claude.com/docs/en/hooks"}]}let Y=X.hooks,J=[];for(let W of Object.keys(Y)){if(!ie.has(W)){delete Y[W],J.push({file:Q,path:`hooks.${W}`,message:`Unknown hook event "${W}" was ignored. Valid events: ${s0.join(", ")}`,severity:"warning",invalidValue:W,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(Y[W])){let G=XJ(Y[W]);delete Y[W],J.push({file:Q,path:`hooks.${W}`,message:`Hook event "${W}" must be an array of matchers; received ${G}. This entry was ignored.`,severity:"warning",invalidValue:G,docLink:"https://code.claude.com/docs/en/hooks"})}}if(J.length>0&&Object.keys(Y).length===0)delete X.hooks;return J}function i1($,Q){return[...de($,Q),...ne($,Q)]}import{userInfo as re}from"os";var Jb="com.anthropic.claudecode",JJ="HKLM\\SOFTWARE\\Policies\\ClaudeCode",YJ="HKCU\\SOFTWARE\\Policies\\ClaudeCode",n1="Settings",Yb="/usr/bin/plutil",Wb=["-convert","json","-o","-","--"],Gb=5000,yz="/mnt/c/Windows/System32/reg.exe",_9="/mnt/c/Program Files/ClaudeCode";function VG(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let $=S6("fs").readFileSync("/proc/version","utf8").toLowerCase();return $.includes("microsoft")||$.includes("wsl")}catch{return!1}}function Ub(){let $="";try{$=re().username}catch{}let Q=[];if($)Q.push({path:`/Library/Managed Preferences/${$}/${Jb}.plist`,label:"per-user managed preferences"});return Q.push({path:`/Library/Managed Preferences/${Jb}.plist`,label:"device-level managed preferences"}),Q}import{execFile as oe}from"child_process";import{existsSync as te}from"fs";var ae=null;function WJ($,Q){return new Promise((X)=>{try{oe($,Q,{encoding:"utf-8",timeout:Gb},(Y,J)=>{X({stdout:J??"",code:Y?1:0})})}catch{X({stdout:"",code:1})}})}function Hb(){return(async()=>{if(process.platform==="darwin"){let $=Ub(),X=(await Promise.all($.map(async({path:Y,label:J})=>{if(!te(Y))return{stdout:"",label:J,ok:!1};let{stdout:W,code:G}=await WJ(Yb,[...Wb,Y]);return{stdout:W,label:J,ok:G===0&&!!W}}))).find((Y)=>Y.ok);return{plistStdouts:X?[{stdout:X.stdout,label:X.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let Q=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[X,Y]=await Promise.all([WJ(Q,["query",JJ,"/v",n1]),WJ(Q,["query",YJ,"/v",n1])]);return{plistStdouts:null,hklmStdout:X.code===0?X.stdout:null,hkcuStdout:Y.code===0?Y.stdout:null}}if(VG()){let[$,Q]=await Promise.all([WJ(yz,["query",JJ,"/v",n1]),WJ(yz,["query",YJ,"/v",n1])]);return{plistStdouts:null,hklmStdout:$.code===0?$.stdout:null,hkcuStdout:Q.code===0?Q.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function Kb(){return ae}var r1=Object.freeze({settings:{},errors:[]}),zb=null,Nb=null,wb=!1,BG=null;function se(){if(BG)return;BG=(async()=>{let $=Date.now(),Q=Kb()??Hb(),{mdm:X,hkcu:Y,wslInherits:J}=ee(await Q);zb=X,Nb=Y,wb=J;let W=Date.now()-$;if(K$(`MDM settings load completed in ${W}ms`),Object.keys(X.settings).length>0){K$(`MDM settings found: ${Object.keys(X.settings).join(", ")}`);try{aX("info","mdm_settings_loaded",{duration_ms:W,key_count:Object.keys(X.settings).length,error_count:X.errors.length})}catch{}}})()}async function Ob(){if(!BG)se();await BG}function Db(){return zb??r1}function Fb(){return Nb??r1}function Zb(){return wb}function fz($,Q){let X=P4(b9($,!1));if(!X||typeof X!=="object")return{settings:{},errors:[]};let Y=i1(X,Q),J=C4().safeParse(X);if(!J.success){let W=i0(J.error,Q);return{settings:{},errors:[...Y,...W]}}return{settings:J.data,errors:Y}}function qb($,Q="Settings"){let X=$.split(/\r?\n/),Y=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),J=new RegExp(`^\\s+${Y}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let W of X){let G=W.match(J);if(G&&G[1])return G[1].trimEnd()}return null}function ee($){let Q=[];if($.plistStdouts&&$.plistStdouts.length>0){let{stdout:G,label:U}=$.plistStdouts[0],H=fz(G,U),{wslInheritsWindowsSettings:q,...V}=H.settings;if(Object.keys(V).length>0)return{mdm:H,hkcu:r1,wslInherits:!1};Q.push(...H.errors)}let X=null;if($.hklmStdout){let G=qb($.hklmStdout);if(G)X=fz(G,`Registry: ${JJ}\\${n1}`)}if(X)Q.push(...X.errors);let Y=Q.length>0?{settings:{},errors:Q}:r1,J=VG(),W=!1;if(J){if(W=X?.settings.wslInheritsWindowsSettings===!0||Q$$(),!W)return{mdm:Y,hkcu:r1,wslInherits:!1}}if(X){let{wslInheritsWindowsSettings:G,...U}=X.settings;if(Object.keys(U).length>0)return{mdm:X,hkcu:r1,wslInherits:W}}if($$$(W))return{mdm:Y,hkcu:r1,wslInherits:W};if($.hkcuStdout){let G=qb($.hkcuStdout);if(G){let U=fz(G,`Registry: ${YJ}\\${n1}`);if(!J||U.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:H,...q}=U.settings;return{mdm:Y,hkcu:{settings:q,errors:U.errors},wslInherits:W}}if(U.errors.length>0)return{mdm:Y,hkcu:{settings:{},errors:U.errors},wslInherits:W}}}return{mdm:Y,hkcu:r1,wslInherits:W}}function $$$($){if($&&Bb(_9))return!0;return Bb(l0())}function Vb($){let Q=P4(b9(u0($),!1));if(!Q||typeof Q!=="object")return!1;i1(Q,$);let{wslInheritsWindowsSettings:X,...Y}=Q;return Object.keys(Y).length>0}function Q$$(){function $(Q){try{let X=b9(u0(Q),!1);return!!X&&typeof X==="object"&&"wslInheritsWindowsSettings"in X&&X.wslInheritsWindowsSettings===!0}catch{return!1}}if($(k9(_9,"managed-settings.json")))return!0;try{let Q=k9(_9,"managed-settings.d");for(let X of m$().readdirSync(Q))if((X.isFile()||X.isSymbolicLink())&&X.name.endsWith(".json")&&!X.name.startsWith(".")&&$(k9(Q,X.name)))return!0}catch{}return!1}function Bb($){try{if(Vb(k9($,"managed-settings.json")))return!0}catch{}try{let Q=k9($,"managed-settings.d"),X=m$().readdirSync(Q);for(let Y of X){if(!(Y.isFile()||Y.isSymbolicLink())||!Y.name.endsWith(".json")||Y.name.startsWith("."))continue;try{if(Vb(k9(Q,Y.name)))return!0}catch{}}}catch{}return!1}function X$$($,Q,X){if(X!==void 0&&!q1($[Q],X)||X===void 0&&!(Q in $))A8($,Q,X)}var GJ=X$$;function J$$($){return function(Q,X,Y){var J=-1,W=Object(Q),G=Y(Q),U=G.length;while(U--){var H=G[$?U:++J];if(X(W[H],H,W)===!1)break}return Q}}var Mb=J$$;var Y$$=Mb(),Lb=Y$$;function W$$($){return r6($)&&R8($)}var jb=W$$;var G$$="[object Object]",U$$=Function.prototype,H$$=Object.prototype,Ab=U$$.toString,K$$=H$$.hasOwnProperty,q$$=Ab.call(Object);function V$$($){if(!r6($)||A4($)!=G$$)return!1;var Q=H5($);if(Q===null)return!0;var X=K$$.call(Q,"constructor")&&Q.constructor;return typeof X=="function"&&X instanceof X&&Ab.call(X)==q$$}var Ib=V$$;function B$$($,Q){if(Q==="constructor"&&typeof $[Q]==="function")return;if(Q=="__proto__")return;return $[Q]}var UJ=B$$;function z$$($){return pw($,W5($))}var Rb=z$$;function N$$($,Q,X,Y,J,W,G){var U=UJ($,X),H=UJ(Q,X),q=G.get(H);if(q){GJ($,X,q);return}var V=W?W(U,H,X+"",$,Q,G):void 0,B=V===void 0;if(B){var z=q6(H),N=!z&&T7(H),w=!z&&!N&&J5(H);if(V=H,z||N||w)if(q6(U))V=U;else if(jb(U))V=KO(U);else if(N)B=!1,V=BU(H,!0);else if(w)B=!1,V=BO(H,!0);else V=[];else if(Ib(H)||l4(H)){if(V=U,l4(U))V=Rb(U);else if(!e$(U)||$8(U))V=wO(H)}else B=!1}if(B)G.set(H,V),J(V,H,Y,W,G),G.delete(H);GJ($,X,V)}var Pb=N$$;function Eb($,Q,X,Y,J){if($===Q)return;Lb(Q,function(W,G){if(J||(J=new cw),e$(W))Pb($,Q,G,X,Eb,Y,J);else{var U=Y?Y(UJ($,G),W,G+"",$,Q,J):void 0;if(U===void 0)U=W;GJ($,G,U)}},W5)}var bb=Eb;function w$$($,Q,X){switch(X.length){case 0:return $.call(Q);case 1:return $.call(Q,X[0]);case 2:return $.call(Q,X[0],X[1]);case 3:return $.call(Q,X[0],X[1],X[2])}return $.apply(Q,X)}var Sb=w$$;var _b=Math.max;function O$$($,Q,X){return Q=_b(Q===void 0?$.length-1:Q,0),function(){var Y=arguments,J=-1,W=_b(Y.length-Q,0),G=Array(W);while(++J<W)G[J]=Y[Q+J];J=-1;var U=Array(Q+1);while(++J<Q)U[J]=Y[J];return U[Q]=X(G),Sb($,this,U)}}var zG=O$$;function D$$($){return function(){return $}}var kb=D$$;var F$$=!j8?K5:function($,Q){return j8($,"toString",{configurable:!0,enumerable:!1,value:kb(Q),writable:!0})},vb=F$$;var Z$$=800,M$$=16,L$$=Date.now;function j$$($){var Q=0,X=0;return function(){var Y=L$$(),J=M$$-(Y-X);if(X=Y,J>0){if(++Q>=Z$$)return arguments[0]}else Q=0;return $.apply(void 0,arguments)}}var Cb=j$$;var A$$=Cb(vb),NG=A$$;function I$$($,Q){return NG(zG($,Q,K5),$+"")}var Tb=I$$;function R$$($,Q,X){if(!e$(X))return!1;var Y=typeof Q;if(Y=="number"?R8(X)&&Z1(Q,X.length):Y=="string"&&(Q in X))return q1(X[Q],$);return!1}var xb=R$$;function P$$($){return Tb(function(Q,X){var Y=-1,J=X.length,W=J>1?X[J-1]:void 0,G=J>2?X[2]:void 0;if(W=$.length>3&&typeof W=="function"?(J--,W):void 0,G&&xb(X[0],X[1],G))W=J<3?void 0:W,J=1;Q=Object(Q);while(++Y<J){var U=X[Y];if(U)$(Q,U,Y,W)}return Q})}var yb=P$$;var E$$=yb(function($,Q,X,Y){bb($,Q,X,Y)}),U1=E$$;function b$$($,Q,X,Y){if(!e$($))return $;Q=M1(Q,$);var J=-1,W=Q.length,G=W-1,U=$;while(U!=null&&++J<W){var H=E8(Q[J]),q=X;if(H==="__proto__"||H==="constructor"||H==="prototype")return $;if(J!=G){var V=U[H];if(q=Y?Y(V,H,U):void 0,q===void 0)q=e$(V)?V:Z1(Q[J+1])?[]:{}}aJ(U,H,q),U=U[H]}return $}var fb=b$$;function S$$($,Q,X){var Y=-1,J=Q.length,W={};while(++Y<J){var G=Q[Y],U=RO($,G);if(X(U,G))fb(W,M1(G,$),U)}return W}var gb=S$$;function _$$($,Q){return gb($,Q,function(X,Y){return bO($,Y)})}var hb=_$$;var ub=c6?c6.isConcatSpreadable:void 0;function k$$($){return q6($)||l4($)||!!(ub&&$&&$[ub])}var mb=k$$;function lb($,Q,X,Y,J){var W=-1,G=$.length;X||(X=mb),J||(J=[]);while(++W<G){var U=$[W];if(Q>0&&X(U))if(Q>1)lb(U,Q-1,X,Y,J);else qO(J,U);else if(!Y)J[J.length]=U}return J}var cb=lb;function v$$($){var Q=$==null?0:$.length;return Q?cb($,1):[]}var pb=v$$;function C$$($){return NG(zG($,void 0,pb),$+"")}var db=C$$;var T$$=db(function($,Q){return $==null?{}:hb($,Q)}),wG=T$$;import{dirname as u$$,join as t1,resolve as HJ}from"path";import{join as x$$}from"path";var y$$="remote-settings.json",gz=null,f$$;function ib(){return}function g$$(){return ib()??x$$(p6(),y$$)}function h$$(){try{let $=u0(g$$()),Q=l$(XG($));if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;return Q}catch{return null}}function nb(){if(!ib()&&f$$!==!0)return null;if(gz)return gz;let $=h$$();if($)return gz=$,B0(),$;return null}function m$$(){return t1(l0(),"managed-settings.json")}function ob($){if(m0()==="wsl"&&$.wslInherits?.()){let Q=hz(_9,$);if(Q.settings)return Q;let X=hz(l0(),$);return{settings:X.settings,errors:[...Q.errors,...X.errors]}}return hz(l0(),$)}function hz($,Q){let X=[],Y={},J=!1,{settings:W,errors:G}=OG(t1($,"managed-settings.json"),Q);if(X.push(...G),W&&Object.keys(W).length>0)Y=U1(Y,W,o1),J=!0;let U=t1($,"managed-settings.d");try{let V=m$().readdirSync(U).filter((B)=>(B.isFile()||B.isSymbolicLink())&&B.name.endsWith(".json")&&!B.name.startsWith(".")).map((B)=>B.name).sort();for(let B of V){let{settings:z,errors:N}=OG(t1(U,B),Q);if(X.push(...N),z&&Object.keys(z).length>0)Y=U1(Y,z,o1),J=!0}}catch(V){let B=T6(V);if(B!=="ENOENT"&&B!=="ENOTDIR")if(Q?.onFsError)Q.onFsError(V);else K$(`managed-settings.d read failed: ${V}`,{level:"error"})}let{wslInheritsWindowsSettings:H,...q}=Y;return{settings:J&&Object.keys(q).length>0?Y:null,errors:X}}function l$$($,Q,X){if(R4($))K$(`Broken symlink or missing file encountered for settings.json at path: ${Q}`);else if(X?.onFsError)X.onFsError($);else K$(`settings file read failed at ${Q}: ${$}`,{level:"error"})}function OG($,Q){let X=CO($);if(X)return{settings:X.settings?P4(X.settings):null,errors:X.errors};let Y=c$$($,Q);return TO($,Y),{settings:Y.settings?P4(Y.settings):null,errors:Y.errors}}function tb($){if(!$.mdm)return{settings:null,errors:[]};let Q=$.mdm();return{settings:Object.keys(Q.settings).length>0?Q.settings:null,errors:Q.errors}}function ab($){let Q=$?.remote?$.remote():nb();if(!Q||Object.keys(Q).length===0)return{settings:null,errors:[]};let X=P4(Q),Y=i1(X,"remote managed settings"),J=C4().safeParse(X);if(!J.success)return{settings:null,errors:[...Y,...i0(J.error,"remote managed settings")]};return{settings:Object.keys(J.data).length>0?J.data:null,errors:Y}}function sb(){let $=B5();if(!$||Object.keys($).length===0)return{settings:null,errors:[]};let Q=P4($),X=i1(Q,"parent managed settings"),Y=C4().safeParse(Q);if(!Y.success)return{settings:null,errors:[...X,...i0(Y.error,"parent managed settings")]};return Object.keys(Y.data).length>0?{settings:Y.data,errors:X}:{settings:null,errors:X}}function eb(){let $=V5();if(!$)return{settings:null,errors:[]};let Q=P4($),X=i1(Q,"SDK inline settings"),Y=C4().safeParse(Q);if(!Y.success)return{settings:null,errors:[...X,...i0(Y.error,"SDK inline settings")]};return{settings:Y.data,errors:X}}function c$$($,Q){try{let{resolvedPath:X}=N5(m$(),$),Y=u0(X);if(Y.trim()==="")return{settings:{},errors:[]};let J=P4(b9(Y,!1)),W=i1(J,$),G=C4().safeParse(J);if(!G.success){let U=i0(G.error,$);return{settings:null,errors:[...W,...U]}}return{settings:G.data,errors:W}}catch(X){return l$$(X,$,Q),{settings:null,errors:[]}}}function rb($){switch($){case"userSettings":return HJ(p6());case"policySettings":case"projectSettings":case"localSettings":return HJ(f7());case"flagSettings":{let Q=g7();return Q?u$$(HJ(Q)):HJ(f7())}}}function p$$(){if(hO()||R$(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function KJ($){switch($){case"userSettings":return t1(rb($),p$$());case"projectSettings":case"localSettings":return t1(rb($),d$$($));case"policySettings":return m$$();case"flagSettings":return g7()}}function d$$($){switch($){case"projectSettings":return t1(".claude","settings.json");case"localSettings":return t1(".claude","settings.local.json")}}function $S($,Q){let X=kO($);if(X!==void 0)return X;let Y=o$$($,Q);return vO($,Y),Y}function i$$($){return!$||$.parentSettingsBehavior==="merge"}function n$$($,Q){let X={};if($.allowManagedHooksOnly===!0)X.allowManagedHooksOnly=!0;if($.allowManagedMcpServersOnly===!0)X.allowManagedMcpServersOnly=!0;if($.allowManagedPermissionRulesOnly===!0)X.allowManagedPermissionRulesOnly=!0;let Y=$.strictPluginOnlyCustomization;if(Y===!0||Array.isArray(Y)&&Y.length>0)X.strictPluginOnlyCustomization=Y;if($.deniedMcpServers)X.deniedMcpServers=$.deniedMcpServers;if(Q.forceLoginOrgUUID===void 0&&$.forceLoginOrgUUID)X.forceLoginOrgUUID=$.forceLoginOrgUUID;if(Q.allowedMcpServers===void 0&&$.allowedMcpServers)X.allowedMcpServers=$.allowedMcpServers;if($.permissions){let J=wG($.permissions,["deny","ask"]);if($.permissions.disableBypassPermissionsMode==="disable")J.disableBypassPermissionsMode="disable";if(Q.allowManagedPermissionRulesOnly!==!0){let{allow:W,additionalDirectories:G}=$.permissions;if(W&&Q.sandbox?.network?.allowManagedDomainsOnly!==!0)J.allow=W;if(G)J.additionalDirectories=G}if(Object.keys(J).length>0)X.permissions=J}if($.sandbox){let{network:J,filesystem:W}=$.sandbox,G={};if($.sandbox.enabled===!0)G.enabled=!0;if($.sandbox.failIfUnavailable===!0)G.failIfUnavailable=!0;if($.sandbox.allowUnsandboxedCommands===!1)G.allowUnsandboxedCommands=!1;if($.sandbox.autoAllowBashIfSandboxed===!1)G.autoAllowBashIfSandboxed=!1;if(J){let U=wG(J,["deniedDomains"]);if(J.allowManagedDomainsOnly===!0)U.allowManagedDomainsOnly=!0;if(Q.sandbox?.network?.allowManagedDomainsOnly!==!0&&J.allowedDomains)U.allowedDomains=J.allowedDomains;if(Object.keys(U).length>0)G.network=U}if(W){let U=wG(W,["denyRead","denyWrite"]);if(W.allowManagedReadPathsOnly===!0)U.allowManagedReadPathsOnly=!0;if(Q.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&W.allowRead)U.allowRead=W.allowRead;if(Object.keys(U).length>0)G.filesystem=U}if(Object.keys(G).length>0)X.sandbox=G}return X}function QS($){if($.helper?.())return"helper";if(ab($).settings)return"remote";if(tb($).settings)return m0()==="macos"?"plist":"hklm";if(($.file?.()??ob($)).settings)return"file";if(sb().settings)return"parent";let Q=$.hkcu?.();return Q&&Object.keys(Q.settings).length>0?"hkcu":null}function r$$($){let Q=[],{settings:X,errors:Y}=ab($);Q.push(...Y);let{settings:J,errors:W}=tb($);Q.push(...W);let{settings:G,errors:U}=$.file?.()??ob($);Q.push(...U);let{settings:H,errors:q}=sb();Q.push(...q);let V=[X,J,G].filter((w)=>w!==null),B=V[0]??null,z={allowManagedPermissionRulesOnly:V.some((w)=>w.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:V.find((w)=>w.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:V.find((w)=>w.allowedMcpServers!==void 0)?.allowedMcpServers,sandbox:{network:{allowManagedDomainsOnly:V.some((w)=>w.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:V.some((w)=>w.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},N=H&&i$$(B)?n$$(H,z):null;return{tiers:V,admin:B,parentSlice:N,errors:Q}}function XS($){let Q=$.helper?.();if(Q)return{settings:Q,errors:$.helperWarnings?.()??[]};let{admin:X,parentSlice:Y,errors:J}=r$$($);if(!X&&!Y){let W=$.hkcu?.();if(W&&Object.keys(W.settings).length>0)return{settings:W.settings,errors:[...J,...W.errors]};return{settings:null,errors:[...J,...W?.errors??[]]}}return{settings:U1({},Y??{},X??{},o1),errors:J}}function o$$($,Q){if($==="policySettings")return XS(Q).settings;let X=KJ($),{settings:Y}=X?OG(X,Q):{settings:null};if($==="flagSettings"){let{settings:J}=eb();if(J)return U1(Y||{},J,o1)}return Y}function t$$($,Q){return y5([...$,...Q])}function o1($,Q){if(Array.isArray($)&&Array.isArray(Q))return t$$($,Q);return}var uz=!1;function a$$($){if(uz)return{settings:{},errors:[]};let Q=Date.now();aX("info","settings_load_started"),uz=!0;try{let X=xO(),Y={};if(X)Y=U1(Y,X,o1);let J=[],W=new Set,G=new Set;for(let U of GG()){if(U==="policySettings"){let{settings:q,errors:V}=XS($);if(q)Y=U1(Y,q,o1);for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),J.push(B)}continue}let H=KJ(U);if(H){let q=HJ(H);if(!G.has(q)){G.add(q);let{settings:V,errors:B}=OG(H,$);for(let z of B){let N=`${z.file}:${z.path}:${z.message}`;if(!W.has(N))W.add(N),J.push(z)}if(V)Y=U1(Y,V,o1)}}if(U==="flagSettings"){let{settings:q,errors:V}=eb();for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),J.push(B)}if(q)Y=U1(Y,q,o1)}}return aX("info","settings_load_completed",{duration_ms:Date.now()-Q,source_count:G.size,error_count:J.length}),{settings:Y,errors:J}}finally{uz=!1}}function s$$($){let Q=SO();if(Q!==null)return Q;let X=a$$($);return _O(X),X}function e$$($){let{settings:Q}=s$$($);return Q||{}}function JS($){B0();let Q=[];for(let X of GG()){let Y=$S(X,$);if(Y&&Object.keys(Y).length>0)Q.push({source:X,settings:Y})}return{effective:e$$($),sources:Q}}function YS($,Q){let X=GG();for(let Y=X.length-1;Y>=0;Y--){let J=X[Y];if($S(J,Q)?.[$]!==void 0)return J}return null}var Q6$={user:"userSettings",project:"projectSettings",local:"localSettings"},WS={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},X6$=["user","project","local"],J6$=new Set(["bypassPermissions","auto","acceptEdits"]),Y6$=new Set(["project"]);function W6$($){let Q=$.effective.permissions?.defaultMode;if(!Q||!J6$.has(Q))return $.effective;for(let X=$.sources.length-1;X>=0;X--){let Y=$.sources[X];if(Y.settings.permissions?.defaultMode!==void 0){if(Y6$.has(Y.source)){let{defaultMode:J,...W}=$.effective.permissions??{};return{...$.effective,permissions:W}}return $.effective}}return $.effective}async function GS($={}){await Ob();let Q=f7(),X=z5(),Y=B5(),J=V5(),W=g7();try{DU($6$($.cwd??m$().cwd())),LU(($.settingSources??X6$).map((z)=>Q6$[z])),MU($.managedSettings??null),ZU(null),FU(void 0);let G={mdm:Db,hkcu:Fb,wslInherits:Zb,...$.serverManagedSettings!==void 0&&{remote:()=>$.serverManagedSettings}},{effective:U,sources:H}=JS(G),q=QS(G)??void 0,V=H.map(({source:z,settings:N})=>({source:WS[z],settings:N,path:z==="policySettings"?void 0:KJ(z),...z==="policySettings"&&{policyOrigin:q}})),B={};for(let z of Object.keys(U)){let N=YS(z,G);if(N)B[z]={source:WS[N],path:N==="policySettings"?void 0:KJ(N),...N==="policySettings"&&{policyOrigin:q}}}return{effective:U,provenance:B,sources:V}}finally{DU(Q),LU(X),MU(Y),ZU(J),FU(W),B0()}}async function Mj$($){return GS($)}async function O6$($,Q){try{await K6$($,Q)}catch(X){if(!R4(X))throw X}}async function D6$($,Q){if(!$)return;let X=$;try{let Y=l$($);if(Y?.claudeAiOauth?.refreshToken)delete Y.claudeAiOauth.refreshToken,X=B$(Y)}catch{}await zS(Q,X,{mode:384})}function F6$(){if(process.platform!=="darwin")return Promise.resolve(void 0);let $=hZ(gZ);return new Promise((Q)=>{G6$("security",["find-generic-password","-a",uZ(),"-w","-s",$],{encoding:"utf-8",timeout:5000},(X,Y)=>Q(X?void 0:Y.trim()||void 0))})}async function OS($,Q,X,Y,J=60000){if(!L$(Q))return;let W=X4(X),G=await x4($.load({projectKey:W,sessionId:Q}),J,`SessionStore.load() timed out after ${J}ms for session ${Q}`);if(!G||G.length===0)return;let U=h6(z6$(),`claude-resume-${dz()}`);try{let H=h6(U,"projects",W);await mz(H,{recursive:!0});let q=h6(H,`${Q}.jsonl`);await s7(q,G);let V=Y?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,B=V??h6(lz(),".claude"),z;try{z=await BS(h6(B,".credentials.json"),"utf-8")}catch(N){if(!R4(N))throw N}if(!V&&!(Y??process.env).ANTHROPIC_API_KEY&&!(Y??process.env).CLAUDE_CODE_OAUTH_TOKEN)z=await F6$()??z;if(await D6$(z,h6(U,".credentials.json")),await O6$(h6(V??lz(),".claude.json"),h6(U,".claude.json")),$.listSubkeys){let N=h6(H,Q),w=await x4($.listSubkeys({projectKey:W,sessionId:Q}),J,`SessionStore.listSubkeys() timed out after ${J}ms for session ${Q}`);for(let O of w){let D=qJ(N,O+".jsonl");if(!O||NS(O)||O.split(/[\\/]/).includes("..")||!D.startsWith(N+iz)){K$(`[SessionStore] skipping unsafe subpath from listSubkeys: ${O}`,{level:"warn"});continue}let M=await x4($.load({projectKey:W,sessionId:Q,subpath:O}),J,`SessionStore.load() timed out after ${J}ms for session ${Q} subpath ${O}`);if(!M||M.length===0)continue;let R=[],P=[];for(let k of M)if(ZS(k))R.push(k);else P.push(k);if(P.length>0)await mz(US(D),{recursive:!0}),await s7(D,P);if(R.length>0){let k=R.at(-1),u=qJ(N,O+".meta.json");await mz(US(u),{recursive:!0});let{type:W$,...h$}=k;await zS(u,B$(h$),{mode:384})}}}return U}catch(H){throw await DG(U),H}}function cz($,Q,X,Y){let{systemPrompt:J,settings:W,managedSettings:G,settingSources:U,sandbox:H,...q}=$??{},V,B,z;if(J===void 0)V="";else if(typeof J==="string")V=J;else if(Array.isArray(J))V=J;else if(J.type==="preset")B=J.append,z=J.excludeDynamicSections;let N=q.pathToClaudeCodeExecutable;if(!N){let b6=w6$(import.meta.url),m6=B6$(b6),s1=F5((t0)=>m6.resolve(t0));if(s1)N=s1;else try{N=m6.resolve("./cli.js")}catch{throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`)}}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.139";let{abortController:w=a0(),additionalDirectories:O=[],agent:D,agents:M,allowedTools:R=[],betas:P,canUseTool:k,continue:u,cwd:W$,debug:h$,debugFile:a$,disallowedTools:u6=[],tools:T4,env:L4,executable:n0=e0()?"bun":"node",executableArgs:H1=[],extraArgs:r0={},fallbackModel:a1,enableFileCheckpointing:i,toolConfig:v9,forkSession:ZG,hooks:o0,includeHookEvents:C9,includePartialMessages:T9,forwardSubagentText:VJ,onElicitation:d$,persistSession:J4,sessionStore:s$,sessionStoreFlush:jS,thinking:x9,effort:AS,maxThinkingTokens:MG,maxTurns:IS,maxBudgetUsd:RS,taskBudget:PS,mcpServers:nz,model:ES,outputFormat:rz,permissionMode:bS="default",allowDangerouslySkipPermissions:SS=!1,permissionPromptToolName:_S,plugins:kS,getOAuthToken:oz,workload:tz,resume:az,resumeSessionAt:vS,sessionId:CS,skills:sz,stderr:TS,strictMcpConfig:xS}=q;if(s$&&J4===!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(s$&&u&&!az&&!s$.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(s$&&i)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(s$&&q.spawnClaudeCodeProcess)K$("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 ez=rz?.type==="json_schema"?rz.schema:void 0,Y4=L4?{...L4}:{...process.env};if(!Y4.CLAUDE_CODE_ENTRYPOINT)Y4.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(i)Y4.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(oz)Y4.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(v9?.askUserQuestion?.previewFormat)Y4.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=v9.askUserQuestion.previewFormat;let LG={};if(FG.propagation.inject(FG.context.active(),LG),"traceparent"in LG){for(let b6 of["TRACEPARENT","TRACESTATE"])if(!(b6 in(L4??{})))delete Y4[b6]}for(let[b6,m6]of Object.entries(LG)){let s1=b6.toUpperCase();if(!(s1 in(L4??{})))Y4[s1]=m6}let $N={},QN=new Map;if(nz)for(let[b6,m6]of Object.entries(nz))if(m6.type==="sdk"&&m6.instance)QN.set(b6,m6.instance);else $N[b6]=m6;let y9;if(x9)switch(x9.type){case"adaptive":y9={type:"adaptive",display:x9.display};break;case"enabled":y9={type:"enabled",budgetTokens:x9.budgetTokens,display:x9.display};break;case"disabled":y9={type:"disabled"};break}else if(MG!==void 0)y9=MG===0?{type:"disabled"}:{type:"enabled",budgetTokens:MG};if(X)Y4.CLAUDE_CONFIG_DIR=X;let XN=new u7({abortController:w,additionalDirectories:O,agent:D,betas:P,cwd:W$,debug:h$,debugFile:a$,executable:n0,executableArgs:H1,extraArgs:tz?{...r0,workload:tz}:r0,pathToClaudeCodeExecutable:N,env:Y4,forkSession:ZG,stderr:TS,thinkingConfig:y9,effort:AS,maxTurns:IS,maxBudgetUsd:RS,taskBudget:PS,model:ES,fallbackModel:a1,jsonSchema:ez,permissionMode:bS,allowDangerouslySkipPermissions:SS,permissionPromptToolName:_S,continueConversation:s$?void 0:u,resume:az,resumeSessionAt:vS,sessionId:CS,settings:typeof W==="object"?B$(W):W,managedSettings:G?B$(G):void 0,settingSources:U,skills:sz,allowedTools:R,disallowedTools:u6,tools:T4,mcpServers:$N,strictMcpConfig:xS,canUseTool:!!k,hooks:!!o0,includeHookEvents:C9,includePartialMessages:T9,persistSession:J4,sessionMirror:!!s$,plugins:kS,sandbox:H,spawnClaudeCodeProcess:q.spawnClaudeCodeProcess,deferSpawn:Y}),yS={systemPrompt:V,appendSystemPrompt:B,planModeInstructions:q.planModeInstructions,appendSubagentSystemPrompt:q.appendSubagentSystemPrompt,excludeDynamicSections:z,agents:M,title:q.title,skills:sz,webSearchIsolationExemptMcpServers:q.webSearchIsolationExemptMcpServers,promptSuggestions:q.promptSuggestions,agentProgressSummaries:q.agentProgressSummaries,forwardSubagentText:VJ},jG=new c7(XN,Q,k,o0,w,QN,ez,yS,d$,oz);if(s$){let b6=()=>h6(Y4.CLAUDE_CONFIG_DIR??h6(lz(),".claude"),"projects"),m6=jS==="eager",s1=new vU(async(t0,AG)=>{let f9=VS(t0,b6());if(f9)await s$.append(f9,AG);else K$(`[SessionStore] dropping mirror frame: filePath ${t0} is not under ${b6()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(t0,AG)=>{let f9=VS(t0,b6());if(f9)jG.reportMirrorError(f9,AG.message)},m6?0:M5,m6?0:L5);jG.setTranscriptMirrorBatcher(s1)}return{queryInstance:jG,transport:XN,abortController:w,processEnv:Y4}}function pz($,Q,X,Y){if(typeof X==="string")Q.write(B$({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:X}]},parent_tool_use_id:null})+`
115
+ `)){let Y=X.match(/^(ID|VERSION_ID)=(.*)$/);if(Y&&Y[1]&&Y[2]){let J=Y[2].replace(/^"|"$/g,"");if(Y[1]==="ID")$.linuxDistroId=J;else $.linuxDistroVersion=J}}}catch{}return $});var WD$=v$(()=>{if(process.platform!=="darwin")return;let Q=NE().match(/^(\d+)\./);if(!Q||!Q[1])return;return parseInt(Q[1],10)-9});var l0=v$(function(){switch(m0()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),qD$=v$(function(){return ys(l0(),"managed-settings.d")});import{isAbsolute as wE}from"path";var fs=S(()=>K.object({allowedDomains:K.array(K.string()).optional(),deniedDomains:K.array(K.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:K.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:K.array(K.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:K.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:K.boolean().optional(),allowMachLookup:K.array(K.string().refine(($)=>{return!($.endsWith("*")?$.slice(0,-1):$).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:K.number().optional(),socksProxyPort:K.number().optional(),tlsTerminate:K.object({caCertPath:K.string().min(1).optional(),caKeyPath:K.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()),gs=S(()=>K.object({allowWrite:K.array(K.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:K.array(K.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:K.array(K.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:K.array(K.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:K.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),OE=S(()=>K.object({enabled:K.boolean().optional(),failIfUnavailable:K.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:K.boolean().optional(),allowUnsandboxedCommands:K.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:fs(),filesystem:gs(),ignoreViolations:K.record(K.string(),K.array(K.string())).optional(),enableWeakerNestedSandbox:K.boolean().optional(),enableWeakerNetworkIsolation:K.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:K.array(K.string()).optional(),ripgrep:K.object({command:K.string(),args:K.array(K.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:K.preprocess(($)=>typeof $==="string"&&wE($)?$:void 0,K.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:K.preprocess(($)=>typeof $==="string"&&wE($)?$:void 0,K.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 DE=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],FE=["normal","vim"],ZE=["auto","tmux","in-process"],hs=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],ME=["auto",...hs];var FD$=m0()==="macos"?"⏺":"●";var eX=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],us=[...eX,"bubble"],LE=us;var PD$=S(()=>mV.enum(LE)),ED$=S(()=>mV.enum(eX));var jE=["bash","powershell"];var $J=S(()=>K.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 ms(){let $=K.object({type:K.literal("command").describe("Shell command hook type"),command:K.string().describe("Shell command to execute"),args:K.array(K.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:$J(),shell:K.enum(jE).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:K.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:K.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:K.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:K.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".')}),Q=K.object({type:K.literal("prompt").describe("LLM prompt hook type"),prompt:K.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:K.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:K.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:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")}),X=K.object({type:K.literal("mcp_tool").describe("MCP tool hook type"),server:K.string().describe("Name of an already-configured MCP server to invoke"),tool:K.string().describe("Name of the tool on that server to call"),input:K.record(K.string(),K.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:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")}),Y=K.object({type:K.literal("http").describe("HTTP hook type"),url:K.string().url().describe("URL to POST the hook input JSON to"),if:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:K.record(K.string(),K.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:K.array(K.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:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")}),J=K.object({type:K.literal("agent").describe("Agentic verifier hook type"),prompt:K.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:$J(),timeout:K.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:K.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:K.string().optional().describe("Custom status message to display in spinner while hook runs"),once:K.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:$,PromptHookSchema:Q,HttpHookSchema:Y,AgentHookSchema:J,McpToolHookSchema:X}}var AE=S(()=>{let{BashCommandHookSchema:$,PromptHookSchema:Q,AgentHookSchema:X,HttpHookSchema:Y,McpToolHookSchema:J}=ms();return K.discriminatedUnion("type",[$,Q,X,Y,J])}),IE=S(()=>K.object({matcher:K.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:K.array(AE()).describe("List of hooks to execute when the matcher matches")})),c0=S(()=>K.partialRecord(K.enum(s0),K.array(IE())));var fD$=S(()=>K.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),gD$=S(()=>K.enum(["stdio","sse","sse-ide","http","ws","sdk"])),ls=S(()=>K.object({type:K.literal("stdio").optional(),command:K.string().min(1,"Command cannot be empty"),args:K.array(K.string()).default([]),env:K.record(K.string(),K.string()).optional(),alwaysLoad:K.boolean().optional()})),cs=S(()=>K.boolean()),RE=S(()=>K.object({clientId:K.string().optional(),callbackPort:K.number().int().positive().optional(),authServerMetadataUrl:K.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:K.string().min(1).optional(),xaa:cs().optional()})),ps=S(()=>K.object({type:K.literal("sse"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),oauth:RE().optional(),alwaysLoad:K.boolean().optional()})),ds=S(()=>K.object({type:K.literal("sse-ide"),url:K.string(),ideName:K.string(),ideRunningInWindows:K.boolean().optional(),alwaysLoad:K.boolean().optional()})),is=S(()=>K.object({type:K.literal("ws-ide"),url:K.string(),ideName:K.string(),authToken:K.string().optional(),ideRunningInWindows:K.boolean().optional(),alwaysLoad:K.boolean().optional()})),ns=S(()=>K.object({type:K.enum(["http","streamable-http"]).transform(()=>"http"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),oauth:RE().optional(),alwaysLoad:K.boolean().optional()})),rs=S(()=>K.object({type:K.literal("ws"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),alwaysLoad:K.boolean().optional()})),os=S(()=>K.object({type:K.literal("sdk"),name:K.string(),alwaysLoad:K.boolean().optional()})),ts=S(()=>K.enum(["allow","ask","blocked"])),as=S(()=>K.object({type:K.literal("claudeai-proxy"),url:K.string(),id:K.string(),alwaysLoad:K.boolean().optional(),toolPermissions:K.record(K.string(),ts()).optional()})),WG=S(()=>K.union([ls(),ps(),ds(),is(),ns(),rs(),os(),as()])),hD$=S(()=>K.object({mcpServers:K.record(K.string(),WG())}));var SE=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"]);var ss=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,es=/[^\u0020-\u007E]/;function $e($){if(SE.has($.toLowerCase()))return!1;if(es.test($))return!0;return ss.test($)}var M4=S(()=>K.string().startsWith("./")),p0=S(()=>M4().endsWith(".json")),PE=S(()=>K.union([M4().refine(($)=>$.endsWith(".mcpb")||$.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),K.string().url().refine(($)=>$.endsWith(".mcpb")||$.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),Sz=S(()=>M4().endsWith(".md")),_z=S(()=>K.union([Sz(),M4()])),_E=S(()=>K.string().min(1,"Marketplace must have a name").refine(($)=>!$.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine(($)=>!$.includes("/")&&!$.includes("\\")&&!$.includes("..")&&$!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine(($)=>!$e($),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine(($)=>$.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine(($)=>$.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine(($)=>$.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),kz=S(()=>K.object({name:K.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:K.string().optional().describe("Contact email for support or feedback"),url:K.string().optional().describe("Website, GitHub profile, or organization URL")})),Qe=S(()=>K.object({$schema:K.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:K.string().min(1,"Plugin name cannot be empty").refine(($)=>!$.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),version:K.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:K.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:kz().optional().describe("Information about the plugin creator or maintainer"),homepage:K.string().url().optional().describe("Plugin homepage or documentation URL"),repository:K.string().optional().describe("Source code repository URL"),license:K.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:K.array(K.string()).optional().describe("Tags for plugin discovery and categorization"),dependencies:K.array(Ie()).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.`)})),nD$=S(()=>K.object({description:K.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:K.lazy(()=>c0()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),Xe=S(()=>K.object({hooks:K.union([p0().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),K.lazy(()=>c0()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),K.array(K.union([p0().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),K.lazy(()=>c0()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),Je=S(()=>K.object({source:_z().optional().describe("Path to command markdown file, relative to plugin root"),content:K.string().optional().describe("Inline markdown content for the command"),description:K.string().optional().describe("Command description override"),argumentHint:K.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:K.string().optional().describe("Default model for this command"),allowedTools:K.array(K.string()).optional().describe("Tools allowed when command runs")}).refine(($)=>$.source&&!$.content||!$.source&&$.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),Ye=S(()=>K.object({commands:K.union([_z().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."),K.array(_z().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."),K.record(K.string(),Je()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),We=S(()=>K.object({agents:K.union([Sz().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."),K.array(Sz().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.")])})),Ge=S(()=>K.object({skills:K.union([M4().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory."),K.array(M4().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.")])})),Ue=S(()=>K.object({outputStyles:K.union([M4().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."),K.array(M4().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.")])})),kE=S(()=>K.object({themes:K.union([M4().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."),K.array(M4().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.")])})),He=S(()=>K.object({})),EE=S(()=>K.string().min(1)),Ke=S(()=>K.string().min(2).refine(($)=>$.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),qe=S(()=>K.object({mcpServers:K.union([p0().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),PE().describe("Path or URL to MCPB file containing MCP server configuration"),K.record(K.string(),WG()).describe("MCP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to MCP servers configuration file"),PE().describe("Path or URL to MCPB file"),K.record(K.string(),WG()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),vE=S(()=>K.object({type:K.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:K.string().describe("Human-readable label shown in the config dialog"),description:K.string().describe("Help text shown beneath the field in the config dialog"),required:K.boolean().optional().describe("If true, validation fails when this field is empty"),default:K.union([K.string(),K.number(),K.boolean(),K.array(K.string())]).optional().describe("Default value used when the user provides nothing"),multiple:K.boolean().optional().describe("For string type: allow an array of strings"),sensitive:K.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:K.number().optional().describe("Minimum value (number type only)"),max:K.number().optional().describe("Maximum value (number type only)")}).strict()),Ve=S(()=>K.object({userConfig:K.record(K.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"),vE()).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.")})),Be=S(()=>K.object({channels:K.array(K.object({server:K.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:K.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:K.record(K.string(),vE()).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.")})),bE=S(()=>K.strictObject({command:K.string().min(1).refine(($)=>{if($.includes(" ")&&!$.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:K.array(EE()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:K.record(Ke(),EE()).refine(($)=>Object.keys($).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:K.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:K.record(K.string(),K.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:K.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:K.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:K.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:K.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:K.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:K.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:K.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up")})),ze=S(()=>K.strictObject({name:K.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:K.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:K.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:K.union([K.literal("always"),K.string().startsWith("on-skill-invoke:").refine(($)=>$.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).')})),Ne=S(()=>K.array(ze()).refine(($)=>new Set($.map((Q)=>Q.name)).size===$.length,{message:"Monitor names must be unique within a plugin"})),CE=S(()=>K.object({monitors:K.union([p0().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Ne()]).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.")})),we=S(()=>K.object({lspServers:K.union([p0().describe("Path to .lsp.json configuration file relative to plugin root"),K.record(K.string(),bE()).describe("LSP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to LSP configuration file"),K.record(K.string(),bE()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),TE=S(()=>K.string().refine(($)=>!$.includes("..")&&!$.includes("//"),"Package name cannot contain path traversal patterns").refine(($)=>{let Q=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,X=/^[a-z0-9][a-z0-9-._]*$/;return Q.test($)||X.test($)},"Invalid npm package name format")),Oe=S(()=>K.object({settings:K.record(K.string(),K.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),De=S(()=>K.object({experimental:K.preprocess(($)=>typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0,K.object({...kE().partial().shape,...CE().partial().shape}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),Fe=S(()=>K.object({...Qe().shape,...Xe().partial().shape,...Ye().partial().shape,...We().partial().shape,...Ge().partial().shape,...Ue().partial().shape,...kE().partial().shape,...He().shape,...Be().partial().shape,...qe().partial().shape,...we().partial().shape,...CE().partial().shape,...Oe().partial().shape,...Ve().partial().shape,...De().partial().shape})),QJ=S(()=>K.discriminatedUnion("source",[K.object({source:K.literal("url"),url:K.string().url().describe("Direct URL to marketplace.json file"),headers:K.record(K.string(),K.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),K.object({source:K.literal("github"),repo:K.string().describe("GitHub repository in owner/repo format"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:K.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:K.array(K.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.')}),K.object({source:K.literal("git"),url:K.string().describe("Full git repository URL"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:K.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:K.array(K.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.')}),K.object({source:K.literal("npm"),package:TE().describe("NPM package containing marketplace.json")}),K.object({source:K.literal("file"),path:K.string().describe("Local file path to marketplace.json")}),K.object({source:K.literal("directory"),path:K.string().describe("Local directory containing .claude-plugin/marketplace.json")}),K.object({source:K.literal("hostPattern"),hostPattern:K.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$").')}),K.object({source:K.literal("pathPattern"),pathPattern:K.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.')}),K.object({source:K.literal("settings"),name:_E().refine(($)=>!SE.has($.toLowerCase()),{message:"Reserved official marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation "+"as PluginMarketplaceSchema plus reserved-name rejection — "+"validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:K.array(Ze()).describe("Plugin entries declared inline in settings.json"),owner:kz().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).")])),bz=S(()=>K.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),xE=S(()=>K.union([M4().describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),K.object({source:K.literal("npm"),package:TE().or(K.string().refine(($)=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test($)||!$.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:K.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:K.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),K.object({source:K.literal("url"),url:K.string().describe("Full git repository URL (https:// or git@)"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:bz().optional().describe("Specific commit SHA to use")}),K.object({source:K.literal("github"),repo:K.string().describe("GitHub repository in owner/repo format"),ref:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:bz().optional().describe("Specific commit SHA to use")}),K.object({source:K.literal("git-subdir"),url:K.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:K.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:K.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:bz().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."),K.object({source:K.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.')])),Ze=S(()=>K.object({name:K.string().min(1,"Plugin name cannot be empty").refine(($)=>!$.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:xE().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:K.string().optional(),version:K.string().optional(),strict:K.boolean().optional()}).refine(($)=>typeof $.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(($)=>typeof $.source==="string"||$.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 Me=S(()=>Fe().partial().extend({name:K.string().min(1,"Plugin name cannot be empty").refine(($)=>!$.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:xE().describe("Where to fetch the plugin from"),category:K.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:K.array(K.string()).optional().describe("Tags for searchability and discovery"),strict:K.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest.")})),Le=S(()=>K.object({name:K.string().min(1).refine(($)=>!$.includes(" "))}));function je($){let Q=Me();return $.flatMap((X,Y)=>{let J=Q.safeParse(X);if(J.success)return[J.data];let W=Le().safeParse(X).data?.name,G=J.error.issues.map((U)=>`${U.path.join(".")}: ${U.message}`).join(", ");if(W)return K$(`Stubbing unparseable marketplace plugin entry (${W}): ${G}`,{level:"warn"}),[{name:W,source:{source:"unsupported"},strict:!0}];return K$(`Dropping unparseable marketplace plugin entry (index ${Y}): ${G}`,{level:"warn"}),[]})}var rD$=S(()=>K.object({$schema:K.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:_E(),version:K.string().optional().describe("Marketplace manifest version"),description:K.string().optional().describe("Human-readable description of this marketplace"),owner:kz().describe("Marketplace maintainer or curator information"),plugins:K.array(K.unknown()).transform(je).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:K.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:K.object({pluginRoot:K.string().optional().describe("Base path for relative plugin sources"),version:K.string().optional().describe("Marketplace version"),description:K.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:K.array(K.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust.")})),yE=S(()=>K.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")),Ae=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,Ie=S(()=>K.union([K.string().regex(Ae,"Dependency must be a plugin name, optionally qualified with @marketplace").transform(($)=>$.replace(/@\^[^@]*$/,"")),K.object({name:K.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:K.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform(($)=>$.marketplace?`${$.name}@${$.marketplace}`:$.name)])),Re=S(()=>K.object({version:K.string().describe("Currently installed version"),installedAt:K.string().describe("ISO 8601 timestamp of installation"),lastUpdated:K.string().optional().describe("ISO 8601 timestamp of last update"),installPath:K.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:K.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:K.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:K.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).")})),Pe=S(()=>K.object({version:K.literal(1).describe("Schema version 1"),plugins:K.record(yE(),Re()).describe("Map of plugin IDs to their installation metadata")})),Ee=S(()=>K.enum(["managed","user","project","local"])),be=S(()=>K.object({scope:Ee().describe("Installation scope"),projectPath:K.string().optional().describe("Project path (required for project/local scopes)"),installPath:K.string().describe("Absolute path to the versioned plugin directory"),version:K.string().optional().describe("Currently installed version"),installedAt:K.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:K.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:K.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:K.string().optional().describe("Tag-derived semver this install resolved to"),auto:K.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),Se=S(()=>K.object({version:K.literal(2).describe("Schema version 2"),plugins:K.record(yE(),K.array(be())).describe("Map of plugin IDs to arrays of installation entries")})),oD$=S(()=>K.union([Pe(),Se()])),_e=S(()=>K.object({source:QJ().describe("Where to fetch the marketplace from"),installLocation:K.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:K.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:K.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),tD$=S(()=>K.record(K.string(),_e()));var ke=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var vz;function GG(){let $=z5();if(vz?.allowed===$)return vz.result;let Q=new Set($);Q.add("flagSettings"),Q.add("policySettings");let X=ke.filter((Y)=>Q.has(Y));return vz={allowed:$,result:X},X}var fE="https://json.schemastore.org/claude-code-settings.json";var ve=["autoMode","deepLink","voice","assistant","briefView"],UG={},HG={autoMode:{buildGate:()=>!1,shape:()=>UG,permissionsShape:()=>UG,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:K.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>UG},assistant:{buildGate:()=>!1,shape:()=>UG},briefView:{buildGate:()=>!0,shape:()=>({defaultView:K.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})}};function Cz(){return ve.filter(($)=>HG[$].buildGate())}function gE($){let Q={};for(let X of $)Q={...Q,...HG[X].shape()};return Q}function hE($){let Q={};for(let X of $)Q={...Q,...HG[X].permissionsShape?.()};return Q}function uE($){let Q=[];for(let X of $)Q.push(...HG[X].permissionModes?.()??[]);return Q}function mE($){let Q=$.split("__"),[X,Y,...J]=Q;if(X!=="mcp"||!Y)return null;let W=J.length>0?J.join("__"):void 0;return{serverName:Y,toolName:W}}var lE={Task:"Agent",KillShell:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage"};function S9($){return Object.hasOwn(lE,$)?lE[$]:$}var cE="workspace",KF$=`mcp__${cE}__bash`,qF$=`mcp__${cE}__web_fetch`;function Ce($){return $.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function pE($){let Q=Te($,"(");if(Q===-1)return{toolName:S9($)};let X=xe($,")");if(X===-1||X<=Q)return{toolName:S9($)};if(X!==$.length-1)return{toolName:S9($)};let Y=$.substring(0,Q),J=$.substring(Q+1,X);if(!Y)return{toolName:S9($)};if(J===""||J==="*")return{toolName:S9(Y)};let W=Ce(J);return{toolName:S9(Y),ruleContent:W}}function Te($,Q){for(let X=0;X<$.length;X++)if($[X]===Q){let Y=0,J=X-1;while(J>=0&&$[J]==="\\")Y++,J--;if(Y%2===0)return X}return-1}function xe($,Q){for(let X=$.length-1;X>=0;X--)if($[X]===Q){let Y=0,J=X-1;while(J>=0&&$[J]==="\\")Y++,J--;if(Y%2===0)return X}return-1}var KG={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit"],bashPrefixTools:["Bash"],customValidation:{WebSearch:($)=>{if($.includes("*")||$.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:($)=>{if($.includes("://")||$.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(!$.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 dE($){return KG.filePatternTools.includes($)}function iE($){return KG.bashPrefixTools.includes($)}function nE($){return Object.hasOwn(KG.customValidation,$)?KG.customValidation[$]:void 0}function rE($,Q){let X=0,Y=Q-1;while(Y>=0&&$[Y]==="\\")X++,Y--;return X%2!==0}function Tz($,Q){let X=0;for(let Y=0;Y<$.length;Y++)if($[Y]===Q&&!rE($,Y))X++;return X}function ye($){for(let Q=0;Q<$.length-1;Q++)if($[Q]==="("&&$[Q+1]===")"){if(!rE($,Q))return!0}return!1}function xz($){if(!$||$.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let Q=Tz($,"("),X=Tz($,")");if(Q!==X)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(ye($)){let G=$.substring(0,$.indexOf("("));if(!G)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 "${G}" without parentheses`,examples:[`${G}`,`${G}(some-pattern)`]}}let Y=pE($),J=mE(Y.toolName);if(J){if(Y.ruleContent!==void 0||Tz($,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${Y.toolName}" without parentheses, or use "mcp__${J.serverName}__*" for all tools`,examples:[`mcp__${J.serverName}`,`mcp__${J.serverName}__*`,J.toolName&&J.toolName!=="*"?`mcp__${J.serverName}__${J.toolName}`:void 0].filter(Boolean)};return{valid:!0}}if(!Y.toolName||Y.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(!Y.toolName.includes("_")&&Y.toolName[0]!==Y.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${jU(String(Y.toolName))}"`};let W=nE(Y.toolName);if(W&&Y.ruleContent!==void 0){let G=W(Y.ruleContent);if(!G.valid)return G}if(iE(Y.toolName)&&Y.ruleContent!==void 0){let G=Y.ruleContent;if(G.includes(":*")&&!G.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(G===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(dE(Y.toolName)&&Y.ruleContent!==void 0){let G=Y.ruleContent;if(G.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${Y.toolName}(*.ts) - matches .ts files`,`${Y.toolName}(src/**) - matches all files in src`,`${Y.toolName}(**/*.test.ts) - matches test files`]};if(G.includes("*")&&!G.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!G.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${Y.toolName}(*.js) - all .js files`,`${Y.toolName}(src/*) - all files directly in src`,`${Y.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}var qG=S(()=>K.string().superRefine(($,Q)=>{let X=xz($);if(!X.valid){let Y=X.error;if(X.suggestion)Y+=`. ${X.suggestion}`;if(X.examples&&X.examples.length>0)Y+=`. Examples: ${X.examples.join(", ")}`;Q.addIssue({code:K.ZodIssueCode.custom,message:Y,params:{received:$}})}}));var fe=S(()=>K.record(K.string(),K.coerce.string()));function tE($){return K.object({allow:K.array(qG()).optional().describe("List of permission rules for allowed operations"),deny:K.array(qG()).optional().describe("List of permission rules for denied operations"),ask:K.array(qG()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:K.enum([...eX,...uE($)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:K.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...hE($),additionalDirectories:K.array(K.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var vF$=S(()=>tE(Cz())),ge=S(()=>K.object({source:QJ().describe("Where to fetch the marketplace from"),installLocation:K.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:K.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),he=S(()=>K.object({serverName:K.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:K.array(K.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:K.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(($)=>{return uH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),ue=S(()=>K.object({serverName:K.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:K.array(K.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:K.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(($)=>{return uH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),me=S(()=>K.object({path:K.string().describe("Absolute path to the helper executable"),timeoutMs:K.number().int().min(1000).optional(),refreshIntervalMs:K.union([K.literal(0),K.number().int().min(60000)]).optional()})),oE=["skills","agents","hooks","mcp"];function aE($){return K.object({$schema:K.literal(fE).optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:K.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:K.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:K.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:K.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:K.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:me().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...R$(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:K.object({issuer:K.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:K.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:K.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:K.object({type:K.literal("command"),command:K.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:K.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:K.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:K.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:K.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:K.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:fe().optional().describe("Environment variables to set for Claude Code sessions"),attribution:K.object({commit:K.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:K.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:K.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:K.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:tE($).optional().describe("Tool usage permissions configuration"),model:K.string().optional().describe("Override the default model used by Claude Code"),availableModels:K.array(K.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:K.record(K.string(),K.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:K.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:K.array(K.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:K.array(K.string()).optional().describe("List of rejected MCP servers from .mcp.json"),skillOverrides:K.record(K.string(),K.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),allowedMcpServers:K.array(he()).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:K.array(ue()).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:c0().optional().describe("Custom commands to run before/after tool executions"),worktree:K.object({symlinkDirectories:K.array(K.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:K.array(K.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:K.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:K.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:K.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:K.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableSkillShellExecution:K.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:K.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:K.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:K.array(K.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:K.array(K.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:K.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:K.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:K.preprocess((Q)=>Array.isArray(Q)?Q.filter((X)=>oE.includes(X)):Q,K.union([K.boolean(),K.array(K.enum(oE))])).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:K.object({type:K.literal("command"),command:K.string(),padding:K.number().optional(),refreshInterval:K.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:K.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:K.string().optional().describe('URL template for PR links in the footer badge and inline messages. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),subagentStatusLine:K.object({type:K.literal("command"),command:K.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:K.record(K.string(),K.union([K.array(K.string()),K.boolean(),K.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:K.record(K.string(),ge()).check((Q)=>{for(let[X,Y]of Object.entries(Q.value))if(Y.source.source==="settings"&&Y.source.name!==X)Q.issues.push({code:"custom",input:Y.source.name,path:[X,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${X}" but source.name "${Y.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:K.array(QJ()).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:K.array(QJ()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),forceLoginMethod:K.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),parentSettingsBehavior:K.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:K.union([K.string(),K.array(K.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:K.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:K.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:K.string().optional().describe("Controls the output style for assistant responses"),viewMode:K.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:K.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:K.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:OE().optional(),feedbackSurveyRate:K.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:K.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:K.object({mode:K.enum(["append","replace"]),verbs:K.array(K.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:K.object({excludeDefault:K.boolean().optional(),tips:K.array(K.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:K.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:K.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:K.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:K.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),autoCompactWindow:K.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:K.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:K.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:K.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:K.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:K.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:K.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:K.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:K.array(K.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:K.record(K.string(),K.object({mcpServers:K.record(K.string(),K.record(K.string(),K.union([K.string(),K.number(),K.boolean(),K.array(K.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:K.record(K.string(),K.union([K.string(),K.number(),K.boolean(),K.array(K.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:K.object({defaultEnvironmentId:K.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:K.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:K.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:K.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:K.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:K.object({enabled:K.boolean().optional(),mode:K.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:K.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:K.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:K.array(K.object({marketplace:K.string(),plugin:K.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:K.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:K.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),autoMemoryEnabled:K.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:K.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:K.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:K.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:K.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),disableAutoMode:K.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:K.array(K.object({id:K.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:K.string().describe("Display name for the SSH connection"),sshHost:K.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:K.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:K.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:K.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:K.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:K.array(K.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:K.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:K.union([K.enum(ME),K.string().startsWith("custom:").transform((Q)=>Q)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:K.enum(FE).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:K.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:K.enum(DE).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:K.boolean().optional().describe("Automatically compact conversation when context fills"),autoScrollEnabled:K.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),fileCheckpointingEnabled:K.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:K.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:K.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:K.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:K.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:K.enum(ZE).optional().catch(void 0).describe("How spawned teammates execute (tmux, in-process, auto)"),remoteControlAtStartup:K.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:K.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:K.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:K.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:K.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:K.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...gE($)}).passthrough()}var C4=S(()=>aE(Cz()));var le=[{matches:($)=>$.path==="permissions.defaultMode"&&$.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:"https://code.claude.com/docs/en/iam#permission-modes"}},{matches:($)=>$.path==="apiKeyHelper"&&$.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:($)=>$.path==="cleanupPeriodDays"&&$.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:($)=>$.path.startsWith("env.")&&$.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:"https://code.claude.com/docs/en/settings#environment-variables"}},{matches:($)=>($.path==="permissions.allow"||$.path==="permissions.deny")&&$.code==="invalid_type"&&$.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:($)=>$.path.startsWith("hooks.")&&$.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:"https://code.claude.com/docs/en/hooks"}},{matches:($)=>$.path.includes("hooks")&&$.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:($)=>$.code==="invalid_type"&&$.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:($)=>$.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:"https://code.claude.com/docs/en/settings"}},{matches:($)=>$.code==="invalid_value"&&$.enumValues!==void 0,tip:{suggestion:void 0}},{matches:($)=>$.code==="invalid_type"&&$.expected==="object"&&$.received===null&&$.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:($)=>$.path==="permissions.additionalDirectories"&&$.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:"https://code.claude.com/docs/en/iam#working-directories"}}],ce={permissions:"https://code.claude.com/docs/en/iam#configuring-permissions",env:"https://code.claude.com/docs/en/settings#environment-variables",hooks:"https://code.claude.com/docs/en/hooks"};function sE($){let Q=le.find((Y)=>Y.matches($));if(!Q)return null;let X={...Q.tip};if($.code==="invalid_value"&&$.enumValues&&!X.suggestion)X.suggestion=`Valid values: ${$.enumValues.map((Y)=>`"${Y}"`).join(", ")}`;if(!X.docLink&&$.path){let Y=$.path.split(".")[0];if(Y)X.docLink=ce[Y]}return X}var rF$=S(()=>C4().strict());function eE($){return $.code==="invalid_type"}function $b($){return $.code==="invalid_value"}function pe($){return $.code==="unrecognized_keys"}function Qb($){return $.code==="too_small"}function XJ($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";return typeof $}function Xb($){let Q=$.match(/received (\w+)/);return Q?Q[1]:void 0}function i0($,Q){return $.issues.map((X)=>{let Y=X.path.map(String).join("."),J=X.message,W,G,U,H,q;if($b(X))G=X.values.map((B)=>String(B)),U=G.join(" | "),H=void 0,q=void 0;else if(eE(X)){U=X.expected;let B=Xb(X.message);H=B??XJ(X.input),q=B??XJ(X.input)}else if(Qb(X))U=String(X.minimum);else if(X.code==="custom"&&"params"in X)H=X.params.received,q=H;let V=sE({path:Y,code:X.code,expected:U,received:H,enumValues:G,message:X.message,value:H});if($b(X))W=G?.map((B)=>`"${B}"`).join(", "),J=`Invalid value. Expected one of: ${W}`;else if(eE(X)){let B=Xb(X.message)??XJ(X.input);if(X.expected==="object"&&B==="null"&&Y==="")J="Invalid or malformed JSON";else J=`Expected ${X.expected}, but received ${B}`}else if(pe(X)){let B=X.keys.join(", ");J=`Unrecognized ${rO(X.keys.length,"field")}: ${B}`}else if(Qb(X))J=`Number must be greater than or equal to ${X.minimum}`,W=String(X.minimum);return{file:Q,path:Y,message:J,expected:W,invalidValue:q,suggestion:V?.suggestion,docLink:V?.docLink}})}function de($,Q){if(!$||typeof $!=="object")return[];let X=$;if(!X.permissions||typeof X.permissions!=="object")return[];let Y=X.permissions,J=[];for(let W of["allow","deny","ask"]){let G=Y[W];if(!Array.isArray(G))continue;Y[W]=G.filter((U)=>{if(typeof U!=="string")return J.push({file:Q,path:`permissions.${W}`,message:`Non-string value in ${W} array was removed`,severity:"warning",invalidValue:U}),!1;let H=xz(U);if(!H.valid){let q=`Invalid permission rule "${U}" was skipped: ${H.error}`;if(H.suggestion)q+=`. ${H.suggestion}`;return J.push({file:Q,path:`permissions.${W}`,message:q,severity:"warning",invalidValue:U}),!1}return!0})}return J}var ie=new Set(s0);function ne($,Q){if(!$||typeof $!=="object")return[];let X=$;if(!("hooks"in X))return[];if(X.hooks===null||typeof X.hooks!=="object"||Array.isArray(X.hooks)){let W=XJ(X.hooks);return delete X.hooks,[{file:Q,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${W}. This field was ignored.`,severity:"warning",invalidValue:W,docLink:"https://code.claude.com/docs/en/hooks"}]}let Y=X.hooks,J=[];for(let W of Object.keys(Y)){if(!ie.has(W)){delete Y[W],J.push({file:Q,path:`hooks.${W}`,message:`Unknown hook event "${W}" was ignored. Valid events: ${s0.join(", ")}`,severity:"warning",invalidValue:W,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(Y[W])){let G=XJ(Y[W]);delete Y[W],J.push({file:Q,path:`hooks.${W}`,message:`Hook event "${W}" must be an array of matchers; received ${G}. This entry was ignored.`,severity:"warning",invalidValue:G,docLink:"https://code.claude.com/docs/en/hooks"})}}if(J.length>0&&Object.keys(Y).length===0)delete X.hooks;return J}function i1($,Q){return[...de($,Q),...ne($,Q)]}import{userInfo as re}from"os";var Jb="com.anthropic.claudecode",JJ="HKLM\\SOFTWARE\\Policies\\ClaudeCode",YJ="HKCU\\SOFTWARE\\Policies\\ClaudeCode",n1="Settings",Yb="/usr/bin/plutil",Wb=["-convert","json","-o","-","--"],Gb=5000,yz="/mnt/c/Windows/System32/reg.exe",_9="/mnt/c/Program Files/ClaudeCode";function VG(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let $=S6("fs").readFileSync("/proc/version","utf8").toLowerCase();return $.includes("microsoft")||$.includes("wsl")}catch{return!1}}function Ub(){let $="";try{$=re().username}catch{}let Q=[];if($)Q.push({path:`/Library/Managed Preferences/${$}/${Jb}.plist`,label:"per-user managed preferences"});return Q.push({path:`/Library/Managed Preferences/${Jb}.plist`,label:"device-level managed preferences"}),Q}import{execFile as oe}from"child_process";import{existsSync as te}from"fs";var ae=null;function WJ($,Q){return new Promise((X)=>{try{oe($,Q,{encoding:"utf-8",timeout:Gb},(Y,J)=>{X({stdout:J??"",code:Y?1:0})})}catch{X({stdout:"",code:1})}})}function Hb(){return(async()=>{if(process.platform==="darwin"){let $=Ub(),X=(await Promise.all($.map(async({path:Y,label:J})=>{if(!te(Y))return{stdout:"",label:J,ok:!1};let{stdout:W,code:G}=await WJ(Yb,[...Wb,Y]);return{stdout:W,label:J,ok:G===0&&!!W}}))).find((Y)=>Y.ok);return{plistStdouts:X?[{stdout:X.stdout,label:X.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let Q=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[X,Y]=await Promise.all([WJ(Q,["query",JJ,"/v",n1]),WJ(Q,["query",YJ,"/v",n1])]);return{plistStdouts:null,hklmStdout:X.code===0?X.stdout:null,hkcuStdout:Y.code===0?Y.stdout:null}}if(VG()){let[$,Q]=await Promise.all([WJ(yz,["query",JJ,"/v",n1]),WJ(yz,["query",YJ,"/v",n1])]);return{plistStdouts:null,hklmStdout:$.code===0?$.stdout:null,hkcuStdout:Q.code===0?Q.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function Kb(){return ae}var r1=Object.freeze({settings:{},errors:[]}),zb=null,Nb=null,wb=!1,BG=null;function se(){if(BG)return;BG=(async()=>{let $=Date.now(),Q=Kb()??Hb(),{mdm:X,hkcu:Y,wslInherits:J}=ee(await Q);zb=X,Nb=Y,wb=J;let W=Date.now()-$;if(K$(`MDM settings load completed in ${W}ms`),Object.keys(X.settings).length>0){K$(`MDM settings found: ${Object.keys(X.settings).join(", ")}`);try{aX("info","mdm_settings_loaded",{duration_ms:W,key_count:Object.keys(X.settings).length,error_count:X.errors.length})}catch{}}})()}async function Ob(){if(!BG)se();await BG}function Db(){return zb??r1}function Fb(){return Nb??r1}function Zb(){return wb}function fz($,Q){let X=P4(b9($,!1));if(!X||typeof X!=="object")return{settings:{},errors:[]};let Y=i1(X,Q),J=C4().safeParse(X);if(!J.success){let W=i0(J.error,Q);return{settings:{},errors:[...Y,...W]}}return{settings:J.data,errors:Y}}function qb($,Q="Settings"){let X=$.split(/\r?\n/),Y=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),J=new RegExp(`^\\s+${Y}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let W of X){let G=W.match(J);if(G&&G[1])return G[1].trimEnd()}return null}function ee($){let Q=[];if($.plistStdouts&&$.plistStdouts.length>0){let{stdout:G,label:U}=$.plistStdouts[0],H=fz(G,U),{wslInheritsWindowsSettings:q,...V}=H.settings;if(Object.keys(V).length>0)return{mdm:H,hkcu:r1,wslInherits:!1};Q.push(...H.errors)}let X=null;if($.hklmStdout){let G=qb($.hklmStdout);if(G)X=fz(G,`Registry: ${JJ}\\${n1}`)}if(X)Q.push(...X.errors);let Y=Q.length>0?{settings:{},errors:Q}:r1,J=VG(),W=!1;if(J){if(W=X?.settings.wslInheritsWindowsSettings===!0||Q$$(),!W)return{mdm:Y,hkcu:r1,wslInherits:!1}}if(X){let{wslInheritsWindowsSettings:G,...U}=X.settings;if(Object.keys(U).length>0)return{mdm:X,hkcu:r1,wslInherits:W}}if($$$(W))return{mdm:Y,hkcu:r1,wslInherits:W};if($.hkcuStdout){let G=qb($.hkcuStdout);if(G){let U=fz(G,`Registry: ${YJ}\\${n1}`);if(!J||U.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:H,...q}=U.settings;return{mdm:Y,hkcu:{settings:q,errors:U.errors},wslInherits:W}}if(U.errors.length>0)return{mdm:Y,hkcu:{settings:{},errors:U.errors},wslInherits:W}}}return{mdm:Y,hkcu:r1,wslInherits:W}}function $$$($){if($&&Bb(_9))return!0;return Bb(l0())}function Vb($){let Q=P4(b9(u0($),!1));if(!Q||typeof Q!=="object")return!1;i1(Q,$);let{wslInheritsWindowsSettings:X,...Y}=Q;return Object.keys(Y).length>0}function Q$$(){function $(Q){try{let X=b9(u0(Q),!1);return!!X&&typeof X==="object"&&"wslInheritsWindowsSettings"in X&&X.wslInheritsWindowsSettings===!0}catch{return!1}}if($(k9(_9,"managed-settings.json")))return!0;try{let Q=k9(_9,"managed-settings.d");for(let X of m$().readdirSync(Q))if((X.isFile()||X.isSymbolicLink())&&X.name.endsWith(".json")&&!X.name.startsWith(".")&&$(k9(Q,X.name)))return!0}catch{}return!1}function Bb($){try{if(Vb(k9($,"managed-settings.json")))return!0}catch{}try{let Q=k9($,"managed-settings.d"),X=m$().readdirSync(Q);for(let Y of X){if(!(Y.isFile()||Y.isSymbolicLink())||!Y.name.endsWith(".json")||Y.name.startsWith("."))continue;try{if(Vb(k9(Q,Y.name)))return!0}catch{}}}catch{}return!1}function X$$($,Q,X){if(X!==void 0&&!q1($[Q],X)||X===void 0&&!(Q in $))A8($,Q,X)}var GJ=X$$;function J$$($){return function(Q,X,Y){var J=-1,W=Object(Q),G=Y(Q),U=G.length;while(U--){var H=G[$?U:++J];if(X(W[H],H,W)===!1)break}return Q}}var Mb=J$$;var Y$$=Mb(),Lb=Y$$;function W$$($){return r6($)&&R8($)}var jb=W$$;var G$$="[object Object]",U$$=Function.prototype,H$$=Object.prototype,Ab=U$$.toString,K$$=H$$.hasOwnProperty,q$$=Ab.call(Object);function V$$($){if(!r6($)||A4($)!=G$$)return!1;var Q=H5($);if(Q===null)return!0;var X=K$$.call(Q,"constructor")&&Q.constructor;return typeof X=="function"&&X instanceof X&&Ab.call(X)==q$$}var Ib=V$$;function B$$($,Q){if(Q==="constructor"&&typeof $[Q]==="function")return;if(Q=="__proto__")return;return $[Q]}var UJ=B$$;function z$$($){return pw($,W5($))}var Rb=z$$;function N$$($,Q,X,Y,J,W,G){var U=UJ($,X),H=UJ(Q,X),q=G.get(H);if(q){GJ($,X,q);return}var V=W?W(U,H,X+"",$,Q,G):void 0,B=V===void 0;if(B){var z=q6(H),N=!z&&T7(H),w=!z&&!N&&J5(H);if(V=H,z||N||w)if(q6(U))V=U;else if(jb(U))V=KO(U);else if(N)B=!1,V=BU(H,!0);else if(w)B=!1,V=BO(H,!0);else V=[];else if(Ib(H)||l4(H)){if(V=U,l4(U))V=Rb(U);else if(!e$(U)||$8(U))V=wO(H)}else B=!1}if(B)G.set(H,V),J(V,H,Y,W,G),G.delete(H);GJ($,X,V)}var Pb=N$$;function Eb($,Q,X,Y,J){if($===Q)return;Lb(Q,function(W,G){if(J||(J=new cw),e$(W))Pb($,Q,G,X,Eb,Y,J);else{var U=Y?Y(UJ($,G),W,G+"",$,Q,J):void 0;if(U===void 0)U=W;GJ($,G,U)}},W5)}var bb=Eb;function w$$($,Q,X){switch(X.length){case 0:return $.call(Q);case 1:return $.call(Q,X[0]);case 2:return $.call(Q,X[0],X[1]);case 3:return $.call(Q,X[0],X[1],X[2])}return $.apply(Q,X)}var Sb=w$$;var _b=Math.max;function O$$($,Q,X){return Q=_b(Q===void 0?$.length-1:Q,0),function(){var Y=arguments,J=-1,W=_b(Y.length-Q,0),G=Array(W);while(++J<W)G[J]=Y[Q+J];J=-1;var U=Array(Q+1);while(++J<Q)U[J]=Y[J];return U[Q]=X(G),Sb($,this,U)}}var zG=O$$;function D$$($){return function(){return $}}var kb=D$$;var F$$=!j8?K5:function($,Q){return j8($,"toString",{configurable:!0,enumerable:!1,value:kb(Q),writable:!0})},vb=F$$;var Z$$=800,M$$=16,L$$=Date.now;function j$$($){var Q=0,X=0;return function(){var Y=L$$(),J=M$$-(Y-X);if(X=Y,J>0){if(++Q>=Z$$)return arguments[0]}else Q=0;return $.apply(void 0,arguments)}}var Cb=j$$;var A$$=Cb(vb),NG=A$$;function I$$($,Q){return NG(zG($,Q,K5),$+"")}var Tb=I$$;function R$$($,Q,X){if(!e$(X))return!1;var Y=typeof Q;if(Y=="number"?R8(X)&&Z1(Q,X.length):Y=="string"&&(Q in X))return q1(X[Q],$);return!1}var xb=R$$;function P$$($){return Tb(function(Q,X){var Y=-1,J=X.length,W=J>1?X[J-1]:void 0,G=J>2?X[2]:void 0;if(W=$.length>3&&typeof W=="function"?(J--,W):void 0,G&&xb(X[0],X[1],G))W=J<3?void 0:W,J=1;Q=Object(Q);while(++Y<J){var U=X[Y];if(U)$(Q,U,Y,W)}return Q})}var yb=P$$;var E$$=yb(function($,Q,X,Y){bb($,Q,X,Y)}),U1=E$$;function b$$($,Q,X,Y){if(!e$($))return $;Q=M1(Q,$);var J=-1,W=Q.length,G=W-1,U=$;while(U!=null&&++J<W){var H=E8(Q[J]),q=X;if(H==="__proto__"||H==="constructor"||H==="prototype")return $;if(J!=G){var V=U[H];if(q=Y?Y(V,H,U):void 0,q===void 0)q=e$(V)?V:Z1(Q[J+1])?[]:{}}aJ(U,H,q),U=U[H]}return $}var fb=b$$;function S$$($,Q,X){var Y=-1,J=Q.length,W={};while(++Y<J){var G=Q[Y],U=RO($,G);if(X(U,G))fb(W,M1(G,$),U)}return W}var gb=S$$;function _$$($,Q){return gb($,Q,function(X,Y){return bO($,Y)})}var hb=_$$;var ub=c6?c6.isConcatSpreadable:void 0;function k$$($){return q6($)||l4($)||!!(ub&&$&&$[ub])}var mb=k$$;function lb($,Q,X,Y,J){var W=-1,G=$.length;X||(X=mb),J||(J=[]);while(++W<G){var U=$[W];if(Q>0&&X(U))if(Q>1)lb(U,Q-1,X,Y,J);else qO(J,U);else if(!Y)J[J.length]=U}return J}var cb=lb;function v$$($){var Q=$==null?0:$.length;return Q?cb($,1):[]}var pb=v$$;function C$$($){return NG(zG($,void 0,pb),$+"")}var db=C$$;var T$$=db(function($,Q){return $==null?{}:hb($,Q)}),wG=T$$;import{dirname as u$$,join as t1,resolve as HJ}from"path";import{join as x$$}from"path";var y$$="remote-settings.json",gz=null,f$$;function ib(){return}function g$$(){return ib()??x$$(p6(),y$$)}function h$$(){try{let $=u0(g$$()),Q=l$(XG($));if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;return Q}catch{return null}}function nb(){if(!ib()&&f$$!==!0)return null;if(gz)return gz;let $=h$$();if($)return gz=$,B0(),$;return null}function m$$(){return t1(l0(),"managed-settings.json")}function ob($){if(m0()==="wsl"&&$.wslInherits?.()){let Q=hz(_9,$);if(Q.settings)return Q;let X=hz(l0(),$);return{settings:X.settings,errors:[...Q.errors,...X.errors]}}return hz(l0(),$)}function hz($,Q){let X=[],Y={},J=!1,{settings:W,errors:G}=OG(t1($,"managed-settings.json"),Q);if(X.push(...G),W&&Object.keys(W).length>0)Y=U1(Y,W,o1),J=!0;let U=t1($,"managed-settings.d");try{let V=m$().readdirSync(U).filter((B)=>(B.isFile()||B.isSymbolicLink())&&B.name.endsWith(".json")&&!B.name.startsWith(".")).map((B)=>B.name).sort();for(let B of V){let{settings:z,errors:N}=OG(t1(U,B),Q);if(X.push(...N),z&&Object.keys(z).length>0)Y=U1(Y,z,o1),J=!0}}catch(V){let B=T6(V);if(B!=="ENOENT"&&B!=="ENOTDIR")if(Q?.onFsError)Q.onFsError(V);else K$(`managed-settings.d read failed: ${V}`,{level:"error"})}let{wslInheritsWindowsSettings:H,...q}=Y;return{settings:J&&Object.keys(q).length>0?Y:null,errors:X}}function l$$($,Q,X){if(R4($))K$(`Broken symlink or missing file encountered for settings.json at path: ${Q}`);else if(X?.onFsError)X.onFsError($);else K$(`settings file read failed at ${Q}: ${$}`,{level:"error"})}function OG($,Q){let X=CO($);if(X)return{settings:X.settings?P4(X.settings):null,errors:X.errors};let Y=c$$($,Q);return TO($,Y),{settings:Y.settings?P4(Y.settings):null,errors:Y.errors}}function tb($){if(!$.mdm)return{settings:null,errors:[]};let Q=$.mdm();return{settings:Object.keys(Q.settings).length>0?Q.settings:null,errors:Q.errors}}function ab($){let Q=$?.remote?$.remote():nb();if(!Q||Object.keys(Q).length===0)return{settings:null,errors:[]};let X=P4(Q),Y=i1(X,"remote managed settings"),J=C4().safeParse(X);if(!J.success)return{settings:null,errors:[...Y,...i0(J.error,"remote managed settings")]};return{settings:Object.keys(J.data).length>0?J.data:null,errors:Y}}function sb(){let $=B5();if(!$||Object.keys($).length===0)return{settings:null,errors:[]};let Q=P4($),X=i1(Q,"parent managed settings"),Y=C4().safeParse(Q);if(!Y.success)return{settings:null,errors:[...X,...i0(Y.error,"parent managed settings")]};return Object.keys(Y.data).length>0?{settings:Y.data,errors:X}:{settings:null,errors:X}}function eb(){let $=V5();if(!$)return{settings:null,errors:[]};let Q=P4($),X=i1(Q,"SDK inline settings"),Y=C4().safeParse(Q);if(!Y.success)return{settings:null,errors:[...X,...i0(Y.error,"SDK inline settings")]};return{settings:Y.data,errors:X}}function c$$($,Q){try{let{resolvedPath:X}=N5(m$(),$),Y=u0(X);if(Y.trim()==="")return{settings:{},errors:[]};let J=P4(b9(Y,!1)),W=i1(J,$),G=C4().safeParse(J);if(!G.success){let U=i0(G.error,$);return{settings:null,errors:[...W,...U]}}return{settings:G.data,errors:W}}catch(X){return l$$(X,$,Q),{settings:null,errors:[]}}}function rb($){switch($){case"userSettings":return HJ(p6());case"policySettings":case"projectSettings":case"localSettings":return HJ(f7());case"flagSettings":{let Q=g7();return Q?u$$(HJ(Q)):HJ(f7())}}}function p$$(){if(hO()||R$(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function KJ($){switch($){case"userSettings":return t1(rb($),p$$());case"projectSettings":case"localSettings":return t1(rb($),d$$($));case"policySettings":return m$$();case"flagSettings":return g7()}}function d$$($){switch($){case"projectSettings":return t1(".claude","settings.json");case"localSettings":return t1(".claude","settings.local.json")}}function $S($,Q){let X=kO($);if(X!==void 0)return X;let Y=o$$($,Q);return vO($,Y),Y}function i$$($){return!$||$.parentSettingsBehavior==="merge"}function n$$($,Q){let X={};if($.allowManagedHooksOnly===!0)X.allowManagedHooksOnly=!0;if($.allowManagedMcpServersOnly===!0)X.allowManagedMcpServersOnly=!0;if($.allowManagedPermissionRulesOnly===!0)X.allowManagedPermissionRulesOnly=!0;let Y=$.strictPluginOnlyCustomization;if(Y===!0||Array.isArray(Y)&&Y.length>0)X.strictPluginOnlyCustomization=Y;if($.deniedMcpServers)X.deniedMcpServers=$.deniedMcpServers;if(Q.forceLoginOrgUUID===void 0&&$.forceLoginOrgUUID)X.forceLoginOrgUUID=$.forceLoginOrgUUID;if(Q.allowedMcpServers===void 0&&$.allowedMcpServers)X.allowedMcpServers=$.allowedMcpServers;if($.permissions){let J=wG($.permissions,["deny","ask"]);if($.permissions.disableBypassPermissionsMode==="disable")J.disableBypassPermissionsMode="disable";if(Q.allowManagedPermissionRulesOnly!==!0){let{allow:W,additionalDirectories:G}=$.permissions;if(W&&Q.sandbox?.network?.allowManagedDomainsOnly!==!0)J.allow=W;if(G)J.additionalDirectories=G}if(Object.keys(J).length>0)X.permissions=J}if($.sandbox){let{network:J,filesystem:W}=$.sandbox,G={};if($.sandbox.enabled===!0)G.enabled=!0;if($.sandbox.failIfUnavailable===!0)G.failIfUnavailable=!0;if($.sandbox.allowUnsandboxedCommands===!1)G.allowUnsandboxedCommands=!1;if($.sandbox.autoAllowBashIfSandboxed===!1)G.autoAllowBashIfSandboxed=!1;if(J){let U=wG(J,["deniedDomains"]);if(J.allowManagedDomainsOnly===!0)U.allowManagedDomainsOnly=!0;if(Q.sandbox?.network?.allowManagedDomainsOnly!==!0&&J.allowedDomains)U.allowedDomains=J.allowedDomains;if(Object.keys(U).length>0)G.network=U}if(W){let U=wG(W,["denyRead","denyWrite"]);if(W.allowManagedReadPathsOnly===!0)U.allowManagedReadPathsOnly=!0;if(Q.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&W.allowRead)U.allowRead=W.allowRead;if(Object.keys(U).length>0)G.filesystem=U}if(Object.keys(G).length>0)X.sandbox=G}return X}function QS($){if($.helper?.())return"helper";if(ab($).settings)return"remote";if(tb($).settings)return m0()==="macos"?"plist":"hklm";if(($.file?.()??ob($)).settings)return"file";if(sb().settings)return"parent";let Q=$.hkcu?.();return Q&&Object.keys(Q.settings).length>0?"hkcu":null}function r$$($){let Q=[],{settings:X,errors:Y}=ab($);Q.push(...Y);let{settings:J,errors:W}=tb($);Q.push(...W);let{settings:G,errors:U}=$.file?.()??ob($);Q.push(...U);let{settings:H,errors:q}=sb();Q.push(...q);let V=[X,J,G].filter((w)=>w!==null),B=V[0]??null,z={allowManagedPermissionRulesOnly:V.some((w)=>w.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:V.find((w)=>w.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:V.find((w)=>w.allowedMcpServers!==void 0)?.allowedMcpServers,sandbox:{network:{allowManagedDomainsOnly:V.some((w)=>w.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:V.some((w)=>w.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},N=H&&i$$(B)?n$$(H,z):null;return{tiers:V,admin:B,parentSlice:N,errors:Q}}function XS($){let Q=$.helper?.();if(Q)return{settings:Q,errors:$.helperWarnings?.()??[]};let{admin:X,parentSlice:Y,errors:J}=r$$($);if(!X&&!Y){let W=$.hkcu?.();if(W&&Object.keys(W.settings).length>0)return{settings:W.settings,errors:[...J,...W.errors]};return{settings:null,errors:[...J,...W?.errors??[]]}}return{settings:U1({},Y??{},X??{},o1),errors:J}}function o$$($,Q){if($==="policySettings")return XS(Q).settings;let X=KJ($),{settings:Y}=X?OG(X,Q):{settings:null};if($==="flagSettings"){let{settings:J}=eb();if(J)return U1(Y||{},J,o1)}return Y}function t$$($,Q){return y5([...$,...Q])}function o1($,Q){if(Array.isArray($)&&Array.isArray(Q))return t$$($,Q);return}var uz=!1;function a$$($){if(uz)return{settings:{},errors:[]};let Q=Date.now();aX("info","settings_load_started"),uz=!0;try{let X=xO(),Y={};if(X)Y=U1(Y,X,o1);let J=[],W=new Set,G=new Set;for(let U of GG()){if(U==="policySettings"){let{settings:q,errors:V}=XS($);if(q)Y=U1(Y,q,o1);for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),J.push(B)}continue}let H=KJ(U);if(H){let q=HJ(H);if(!G.has(q)){G.add(q);let{settings:V,errors:B}=OG(H,$);for(let z of B){let N=`${z.file}:${z.path}:${z.message}`;if(!W.has(N))W.add(N),J.push(z)}if(V)Y=U1(Y,V,o1)}}if(U==="flagSettings"){let{settings:q,errors:V}=eb();for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),J.push(B)}if(q)Y=U1(Y,q,o1)}}return aX("info","settings_load_completed",{duration_ms:Date.now()-Q,source_count:G.size,error_count:J.length}),{settings:Y,errors:J}}finally{uz=!1}}function s$$($){let Q=SO();if(Q!==null)return Q;let X=a$$($);return _O(X),X}function e$$($){let{settings:Q}=s$$($);return Q||{}}function JS($){B0();let Q=[];for(let X of GG()){let Y=$S(X,$);if(Y&&Object.keys(Y).length>0)Q.push({source:X,settings:Y})}return{effective:e$$($),sources:Q}}function YS($,Q){let X=GG();for(let Y=X.length-1;Y>=0;Y--){let J=X[Y];if($S(J,Q)?.[$]!==void 0)return J}return null}var Q6$={user:"userSettings",project:"projectSettings",local:"localSettings"},WS={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},X6$=["user","project","local"],J6$=new Set(["bypassPermissions","auto","acceptEdits"]),Y6$=new Set(["project"]);function W6$($){let Q=$.effective.permissions?.defaultMode;if(!Q||!J6$.has(Q))return $.effective;for(let X=$.sources.length-1;X>=0;X--){let Y=$.sources[X];if(Y.settings.permissions?.defaultMode!==void 0){if(Y6$.has(Y.source)){let{defaultMode:J,...W}=$.effective.permissions??{};return{...$.effective,permissions:W}}return $.effective}}return $.effective}async function GS($={}){await Ob();let Q=f7(),X=z5(),Y=B5(),J=V5(),W=g7();try{DU($6$($.cwd??m$().cwd())),LU(($.settingSources??X6$).map((z)=>Q6$[z])),MU($.managedSettings??null),ZU(null),FU(void 0);let G={mdm:Db,hkcu:Fb,wslInherits:Zb,...$.serverManagedSettings!==void 0&&{remote:()=>$.serverManagedSettings}},{effective:U,sources:H}=JS(G),q=QS(G)??void 0,V=H.map(({source:z,settings:N})=>({source:WS[z],settings:N,path:z==="policySettings"?void 0:KJ(z),...z==="policySettings"&&{policyOrigin:q}})),B={};for(let z of Object.keys(U)){let N=YS(z,G);if(N)B[z]={source:WS[N],path:N==="policySettings"?void 0:KJ(N),...N==="policySettings"&&{policyOrigin:q}}}return{effective:U,provenance:B,sources:V}}finally{DU(Q),LU(X),MU(Y),ZU(J),FU(W),B0()}}async function Mj$($){return GS($)}async function O6$($,Q){try{await K6$($,Q)}catch(X){if(!R4(X))throw X}}async function D6$($,Q){if(!$)return;let X=$;try{let Y=l$($);if(Y?.claudeAiOauth?.refreshToken)delete Y.claudeAiOauth.refreshToken,X=B$(Y)}catch{}await zS(Q,X,{mode:384})}function F6$(){if(process.platform!=="darwin")return Promise.resolve(void 0);let $=hZ(gZ);return new Promise((Q)=>{G6$("security",["find-generic-password","-a",uZ(),"-w","-s",$],{encoding:"utf-8",timeout:5000},(X,Y)=>Q(X?void 0:Y.trim()||void 0))})}async function OS($,Q,X,Y,J=60000){if(!L$(Q))return;let W=X4(X),G=await x4($.load({projectKey:W,sessionId:Q}),J,`SessionStore.load() timed out after ${J}ms for session ${Q}`);if(!G||G.length===0)return;let U=h6(z6$(),`claude-resume-${dz()}`);try{let H=h6(U,"projects",W);await mz(H,{recursive:!0});let q=h6(H,`${Q}.jsonl`);await s7(q,G);let V=Y?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,B=V??h6(lz(),".claude"),z;try{z=await BS(h6(B,".credentials.json"),"utf-8")}catch(N){if(!R4(N))throw N}if(!V&&!(Y??process.env).ANTHROPIC_API_KEY&&!(Y??process.env).CLAUDE_CODE_OAUTH_TOKEN)z=await F6$()??z;if(await D6$(z,h6(U,".credentials.json")),await O6$(h6(V??lz(),".claude.json"),h6(U,".claude.json")),$.listSubkeys){let N=h6(H,Q),w=await x4($.listSubkeys({projectKey:W,sessionId:Q}),J,`SessionStore.listSubkeys() timed out after ${J}ms for session ${Q}`);for(let O of w){let D=qJ(N,O+".jsonl");if(!O||NS(O)||O.split(/[\\/]/).includes("..")||!D.startsWith(N+iz)){K$(`[SessionStore] skipping unsafe subpath from listSubkeys: ${O}`,{level:"warn"});continue}let M=await x4($.load({projectKey:W,sessionId:Q,subpath:O}),J,`SessionStore.load() timed out after ${J}ms for session ${Q} subpath ${O}`);if(!M||M.length===0)continue;let R=[],P=[];for(let k of M)if(ZS(k))R.push(k);else P.push(k);if(P.length>0)await mz(US(D),{recursive:!0}),await s7(D,P);if(R.length>0){let k=R.at(-1),u=qJ(N,O+".meta.json");await mz(US(u),{recursive:!0});let{type:W$,...h$}=k;await zS(u,B$(h$),{mode:384})}}}return U}catch(H){throw await DG(U),H}}function cz($,Q,X,Y){let{systemPrompt:J,settings:W,managedSettings:G,settingSources:U,sandbox:H,...q}=$??{},V,B,z;if(J===void 0)V="";else if(typeof J==="string")V=J;else if(Array.isArray(J))V=J;else if(J.type==="preset")B=J.append,z=J.excludeDynamicSections;let N=q.pathToClaudeCodeExecutable;if(!N){let b6=w6$(import.meta.url),m6=B6$(b6),s1=F5((t0)=>m6.resolve(t0));if(s1)N=s1;else try{N=m6.resolve("./cli.js")}catch{throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`)}}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.140";let{abortController:w=a0(),additionalDirectories:O=[],agent:D,agents:M,allowedTools:R=[],betas:P,canUseTool:k,continue:u,cwd:W$,debug:h$,debugFile:a$,disallowedTools:u6=[],tools:T4,env:L4,executable:n0=e0()?"bun":"node",executableArgs:H1=[],extraArgs:r0={},fallbackModel:a1,enableFileCheckpointing:i,toolConfig:v9,forkSession:ZG,hooks:o0,includeHookEvents:C9,includePartialMessages:T9,forwardSubagentText:VJ,onElicitation:d$,persistSession:J4,sessionStore:s$,sessionStoreFlush:jS,thinking:x9,effort:AS,maxThinkingTokens:MG,maxTurns:IS,maxBudgetUsd:RS,taskBudget:PS,mcpServers:nz,model:ES,outputFormat:rz,permissionMode:bS="default",allowDangerouslySkipPermissions:SS=!1,permissionPromptToolName:_S,plugins:kS,getOAuthToken:oz,workload:tz,resume:az,resumeSessionAt:vS,sessionId:CS,skills:sz,stderr:TS,strictMcpConfig:xS}=q;if(s$&&J4===!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(s$&&u&&!az&&!s$.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(s$&&i)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(s$&&q.spawnClaudeCodeProcess)K$("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 ez=rz?.type==="json_schema"?rz.schema:void 0,Y4=L4?{...L4}:{...process.env};if(!Y4.CLAUDE_CODE_ENTRYPOINT)Y4.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(i)Y4.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(oz)Y4.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(v9?.askUserQuestion?.previewFormat)Y4.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=v9.askUserQuestion.previewFormat;let LG={};if(FG.propagation.inject(FG.context.active(),LG),"traceparent"in LG){for(let b6 of["TRACEPARENT","TRACESTATE"])if(!(b6 in(L4??{})))delete Y4[b6]}for(let[b6,m6]of Object.entries(LG)){let s1=b6.toUpperCase();if(!(s1 in(L4??{})))Y4[s1]=m6}let $N={},QN=new Map;if(nz)for(let[b6,m6]of Object.entries(nz))if(m6.type==="sdk"&&m6.instance)QN.set(b6,m6.instance);else $N[b6]=m6;let y9;if(x9)switch(x9.type){case"adaptive":y9={type:"adaptive",display:x9.display};break;case"enabled":y9={type:"enabled",budgetTokens:x9.budgetTokens,display:x9.display};break;case"disabled":y9={type:"disabled"};break}else if(MG!==void 0)y9=MG===0?{type:"disabled"}:{type:"enabled",budgetTokens:MG};if(X)Y4.CLAUDE_CONFIG_DIR=X;let XN=new u7({abortController:w,additionalDirectories:O,agent:D,betas:P,cwd:W$,debug:h$,debugFile:a$,executable:n0,executableArgs:H1,extraArgs:tz?{...r0,workload:tz}:r0,pathToClaudeCodeExecutable:N,env:Y4,forkSession:ZG,stderr:TS,thinkingConfig:y9,effort:AS,maxTurns:IS,maxBudgetUsd:RS,taskBudget:PS,model:ES,fallbackModel:a1,jsonSchema:ez,permissionMode:bS,allowDangerouslySkipPermissions:SS,permissionPromptToolName:_S,continueConversation:s$?void 0:u,resume:az,resumeSessionAt:vS,sessionId:CS,settings:typeof W==="object"?B$(W):W,managedSettings:G?B$(G):void 0,settingSources:U,skills:sz,allowedTools:R,disallowedTools:u6,tools:T4,mcpServers:$N,strictMcpConfig:xS,canUseTool:!!k,hooks:!!o0,includeHookEvents:C9,includePartialMessages:T9,persistSession:J4,sessionMirror:!!s$,plugins:kS,sandbox:H,spawnClaudeCodeProcess:q.spawnClaudeCodeProcess,deferSpawn:Y}),yS={systemPrompt:V,appendSystemPrompt:B,planModeInstructions:q.planModeInstructions,appendSubagentSystemPrompt:q.appendSubagentSystemPrompt,excludeDynamicSections:z,agents:M,title:q.title,skills:sz,webSearchIsolationExemptMcpServers:q.webSearchIsolationExemptMcpServers,promptSuggestions:q.promptSuggestions,agentProgressSummaries:q.agentProgressSummaries,forwardSubagentText:VJ},jG=new c7(XN,Q,k,o0,w,QN,ez,yS,d$,oz);if(s$){let b6=()=>h6(Y4.CLAUDE_CONFIG_DIR??h6(lz(),".claude"),"projects"),m6=jS==="eager",s1=new vU(async(t0,AG)=>{let f9=VS(t0,b6());if(f9)await s$.append(f9,AG);else K$(`[SessionStore] dropping mirror frame: filePath ${t0} is not under ${b6()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(t0,AG)=>{let f9=VS(t0,b6());if(f9)jG.reportMirrorError(f9,AG.message)},m6?0:M5,m6?0:L5);jG.setTranscriptMirrorBatcher(s1)}return{queryInstance:jG,transport:XN,abortController:w,processEnv:Y4}}function pz($,Q,X,Y){if(typeof X==="string")Q.write(B$({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:X}]},parent_tool_use_id:null})+`
116
116
  `);else $.streamInput(X).catch((J)=>Y.abort(J))}var Z6$=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function DG($){for(let Q=0;;Q++)try{return await V6$($,{recursive:!0,force:!0})}catch(X){if(Q>=4||!Z6$.has(T6(X)??""))return;await zJ((Q+1)*100)}}function M6$($,Q){$.waitForExit().catch(()=>{}).finally(()=>DG(Q))}function Lj$({prompt:$,options:Q}){if((Q?.resume||Q?.continue)&&Q?.sessionStore){let{queryInstance:W,transport:G,abortController:U,processEnv:H}=cz({...Q},typeof $==="string",void 0,!0),q=qJ(Q.cwd??"."),V=Q.sessionStore,B=Q.loadTimeoutMs??60000,z=Q.resume;return(async()=>{if(!z)z=(await x4(V.listSessions(X4(q)),B,`SessionStore.listSessions() timed out after ${B}ms`)).slice().sort((O,D)=>D.mtime-O.mtime)[0]?.sessionId;if(!z)return;return OS(V,z,q,Q.env,Q.loadTimeoutMs)})().then((w)=>{if(w)G.updateResume(z),G.updateEnv({CLAUDE_CONFIG_DIR:w}),H.CLAUDE_CONFIG_DIR=w,W.addCleanupCallback(()=>M6$(G,w));if(!W.isClosed())G.spawn()}).catch((w)=>{let O=I4(w);G.spawnAbort(O),W.setError(O)}),pz(W,G,$,U),W}let{queryInstance:X,transport:Y,abortController:J}=cz(Q,typeof $==="string");return pz(X,Y,$,J),X}async function jj$({options:$,initializeTimeoutMs:Q=60000}={}){let X,Y=$?.resume;if((Y||$?.continue)&&$?.sessionStore){let U=qJ($.cwd??".");if(!Y){if(!$.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let H=$.loadTimeoutMs??60000;Y=(await x4($.sessionStore.listSessions(X4(U)),H,`SessionStore.listSessions() timed out after ${H}ms`)).slice().sort((V,B)=>B.mtime-V.mtime)[0]?.sessionId}if(Y)X=await OS($.sessionStore,Y,U,$.env,$.loadTimeoutMs)}let J,W,G;try{let z=function(){if(B)return;B=!0,V.close()},U=cz(X&&Y&&Y!==$?.resume?{...$,resume:Y}:$,!1,X);J=U.queryInstance;let{transport:H,abortController:q}=U;W=H;let V=U.queryInstance;if(X){let N=X;V.addCleanupCallback(()=>{G=H.waitForExit().catch(()=>{}).then(()=>DG(N))})}await x4(V.initializationResult(),Q,`Subprocess initialization did not complete within ${Q}ms — check authentication and network connectivity`);let B=!1;return{query(N){if(B)throw Error("WarmQuery.query() can only be called once");B=!0;try{pz(V,H,N,q)}catch(w){throw V.close(),w}if(typeof N==="string")V.setIsSingleUserTurn(!0);return V},close:z,async[Symbol.asyncDispose](){B=!0,V.close(),await G}}}catch(U){if(J?.close(),X&&!G){let H=W;G=(H?H.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>DG(X))}throw await G,U}}function Aj$($){return bH($)}function Ij$($,Q){return GZ($,Q)}async function Rj$($,Q){let Y=[];try{const X=F$(Y,bH(Q),1);await X.send($);for await(let H of X.stream())if(H.type==="result")return H;throw Error("Session ended without result message")}catch(J){var W=J,G=1}finally{var U=Z$(Y,W,G);U&&await U}}async function Pj$($,Q){if(Q?.sessionStore)return I6$(Q.sessionStore,$,Q);return OZ($,Q)}async function Ej$($){if($?.sessionStore)return j6$($.sessionStore,$);return FZ($)}async function bj$($,Q){if(Q?.sessionStore)return R6$(Q.sessionStore,$,Q);return ZZ($,Q)}async function Sj$($,Q,X){if(X?.sessionStore)return P6$(X.sessionStore,$,Q,X.dir);return AZ($,Q,X)}async function _j$($,Q,X){if(X?.sessionStore)return E6$(X.sessionStore,$,Q,X.dir);return IZ($,Q,X)}async function kj$($,Q){if(!L$($))throw Error(`Invalid sessionId: ${$}`);if(Q?.sessionStore){if(!Q.sessionStore.delete)return;let X=X4(Q.dir);await Q.sessionStore.delete({projectKey:X,sessionId:$});return}return RZ($,Q)}async function vj$($,Q){if(Q?.sessionStore)return b6$(Q.sessionStore,$,Q);return bZ($,Q)}async function Cj$($,Q,X){if(!L$($))throw Error(`Invalid sessionId: ${$}`);let Y=await j1($,X?.dir);if(!Y)throw Error(`Session ${$} not found`);let J=X4(X?.dir),W=X?.batchSize&&X.batchSize>0?X.batchSize:M5;if(await HS(Y.filePath,{projectKey:J,sessionId:$},Q,W),X?.includeSubagents===!1)return;let G=Y.filePath.replace(/\.jsonl$/,""),U=h6(G,"subagents");for(let H of await L6$(U)){let q=wS(G,H).split(iz);q[q.length-1]=q.at(-1).replace(/\.jsonl$/,"");let V={projectKey:J,sessionId:$,subpath:q.join("/")};await HS(H,V,Q,W);let B=H.replace(/\.jsonl$/,".meta.json");try{let z=l$(await BS(B,"utf8"));await Q.append(V,[{type:"agent_metadata",...z}])}catch(z){if(!R4(z))throw z}}}async function HS($,Q,X,Y){let J=N6$({input:U6$($,{encoding:"utf8"}),crlfDelay:1/0}),W=[],G=0;for await(let U of J){if(!U)continue;if(W.push(l$(U)),G+=U.length,W.length>=Y||G>=L5)await X.append(Q,W),W=[],G=0}if(W.length>0)await X.append(Q,W)}async function L6$($){let Q=[];async function X(Y){let J;try{J=await q6$(Y,{withFileTypes:!0})}catch{return}for(let W of J){let G=h6(Y,W.name);if(W.isDirectory())await X(G);else if(W.isFile()&&W.name.endsWith(".jsonl"))Q.push(G)}}return await X($),Q}async function Tj$($,Q){if(Q?.sessionStore)return S6$(Q.sessionStore,$,Q.dir);return CZ($,Q)}async function xj$($,Q,X){if(X?.sessionStore)return _6$(X.sessionStore,$,Q,X);return TZ($,Q,X)}function DS($){let Q=qJ($??"."),X;try{X=H6$(Q)}catch{X=Q}return X.normalize("NFC")}function X4($){return M0(DS($))}function FS($){return $.map((Q)=>B$(Q)).join(`
117
117
  `)+`
118
118
  `}function KS($,Q,X){if(Q!==void 0&&Q>0)return $.slice(X,X+Q);if(X>0)return $.slice(X);return $}function ZS($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="agent_metadata"}async function j6$($,Q){let X=DS(Q.dir),Y=M0(X),J=Q.offset??0,W=Q.limit;if($.listSessionSummaries){let q=await $.listSessionSummaries(Y),V=$.listSessions?new Map((await $.listSessions(Y)).map((w)=>[w.sessionId,w])):void 0,B=[];for(let w of q){let O=V?.get(w.sessionId);if(V&&!O)continue;let D=O!==void 0&&w.mtime<O.mtime;B.push({sessionId:w.sessionId,mtime:D?O.mtime:w.mtime,info:D?void 0:JN(w,X)})}if(V){let w=new Set(q.map((O)=>O.sessionId));for(let[O,D]of V)if(!w.has(O))B.push({sessionId:O,mtime:D.mtime})}else K$("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");B.sort((w,O)=>O.mtime-w.mtime);let z=KS(B,W,J),N=z.filter((w)=>w.info===void 0);if(N.length>0){let w=await qS($,N,Q.dir,X),O=new Map(w.map((D)=>[D.sessionId,D]));for(let D of z)if(D.info===void 0)D.info=O.get(D.sessionId)??null}return z.flatMap((w)=>w.info?[w.info]:[])}if(!$.listSessions)throw Error("sessionStore.listSessions is not implemented -- cannot list sessions. Provide a store with a listSessions() method.");let U=(await $.listSessions(Y)).slice().sort((q,V)=>V.mtime-q.mtime),H=KS(U,W,J);return qS($,H,Q.dir,X)}async function qS($,Q,X,Y){return(await Promise.allSettled(Q.map(async(W)=>{let G=await LS($,W.sessionId,X);if(!G)return null;let U=C8(W.sessionId,MS(G,W.mtime),Y);return U?{...U,lastModified:W.mtime}:null}))).flatMap((W,G)=>{let U=Q[G];if(W.status==="fulfilled")return W.value?[W.value]:[];return[{sessionId:U.sessionId,summary:"",lastModified:U.mtime}]})}function MS($,Q){let X=Buffer.from($,"utf-8"),Y=X.length,J=X.subarray(0,U4).toString("utf-8"),W=Y>U4?X.subarray(Y-U4).toString("utf-8"):J;return{mtime:Q,size:Y,head:J,tail:W}}function A6$($){let Q=$.trimEnd(),X=Q.slice(Q.lastIndexOf(`