@anthropic-ai/claude-agent-sdk 0.3.147 → 0.3.148
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/assistant.mjs +3 -3
- package/bridge.mjs +2 -2
- package/browser-sdk.js +1 -1
- package/manifest.json +13 -13
- package/manifest.zst.json +23 -23
- package/package.json +10 -10
- package/sdk.mjs +2 -2
package/sdk.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
|
|
3
3
|
|
|
4
|
-
// Version: 0.3.
|
|
4
|
+
// Version: 0.3.148
|
|
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 eP;(function($){$.DEFAULT={allowTrailingComma:!1}})(eP||(eP={}));var $E;(function($){$[$.None=0]="None",$[$.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",$[$.UnexpectedEndOfString=2]="UnexpectedEndOfString",$[$.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",$[$.InvalidUnicode=4]="InvalidUnicode",$[$.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",$[$.InvalidCharacter=6]="InvalidCharacter"})($E||($E={}));var QE;(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"})(QE||(QE={}));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 rW($){return $.startsWith("\uFEFF")?$.slice(1):$}import y$ from"node:path";import XE from"node:os";import Nz from"node:process";var d1=XE.homedir(),wz=XE.tmpdir(),{env:j9}=Nz,gs=($)=>{let Q=y$.join(d1,"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(wz,$)}},hs=($)=>{let Q=j9.APPDATA||y$.join(d1,"AppData","Roaming"),J=j9.LOCALAPPDATA||y$.join(d1,"AppData","Local");return{data:y$.join(J,$,"Data"),config:y$.join(Q,$,"Config"),cache:y$.join(J,$,"Cache"),log:y$.join(J,$,"Log"),temp:y$.join(wz,$)}},us=($)=>{let Q=y$.basename(d1);return{data:y$.join(j9.XDG_DATA_HOME||y$.join(d1,".local","share"),$),config:y$.join(j9.XDG_CONFIG_HOME||y$.join(d1,".config"),$),cache:y$.join(j9.XDG_CACHE_HOME||y$.join(d1,".cache"),$),log:y$.join(j9.XDG_STATE_HOME||y$.join(d1,".local","state"),$),temp:y$.join(wz,Q,$)}};function Oz($,{suffix:Q="nodejs"}={}){if(typeof $!=="string")throw TypeError(`Expected a string, got ${typeof $}`);if(Q)$+=`-${Q}`;if(Nz.platform==="darwin")return gs($);if(Nz.platform==="win32")return hs($);return us($)}var A2$=Oz("claude-cli");function ms(){if(process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return"essential-traffic";if(process.env.DISABLE_TELEMETRY)return"no-telemetry";if(A$(process.env.DO_NOT_TRACK))return"no-telemetry";return"default"}function YE(){return ms()==="essential-traffic"}var ls=100,Dz=[];function cs($){if(Dz.length>=ls)Dz.shift();Dz.push($)}var ps=[],WE=null;var r2$=v$(()=>{return process.argv.includes("--hard-fail")});function oW($){let Q=j4($);try{if(A$(process.env.CLAUDE_CODE_USE_BEDROCK)||A$(process.env.CLAUDE_CODE_USE_VERTEX)||A$(process.env.CLAUDE_CODE_USE_FOUNDRY)||A$(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||A$(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||YE())return;let Y={error:Q.stack||Q.message,timestamp:new Date().toISOString()};if(cs(Y),WE===null){ps.push({type:"error",error:Q});return}WE.logError(Q)}catch{}}var A9=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,UE=new Set,Fz=typeof process==="object"&&!!process?process:{},HE=($,Q,J,Y)=>{typeof Fz.emitWarning==="function"?Fz.emitWarning($,Q,J,Y):console.error(`[${J}] ${Q}: ${$}`)},tW=globalThis.AbortController,GE=globalThis.AbortSignal;if(typeof tW>"u"){GE=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(Y,X){this._onabort.push(X)}},tW=class{constructor(){Q()}signal=new GE;abort(Y){if(this.signal.aborted)return;this.signal.reason=Y,this.signal.aborted=!0;for(let X of this.signal._onabort)X(Y);this.signal.onabort?.(Y)}};let $=Fz.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!$)return;$=!1,HE("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 ds=($)=>!UE.has($),t2$=Symbol("type"),i1=($)=>$&&$===Math.floor($)&&$>0&&isFinite($),KE=($)=>!i1($)?null:$<=Math.pow(2,8)?Uint8Array:$<=Math.pow(2,16)?Uint16Array:$<=Math.pow(2,32)?Uint32Array:$<=Number.MAX_SAFE_INTEGER?nJ:null;class nJ extends Array{constructor($){super($);this.fill(0)}}class I9{heap;length;static#X=!1;static create($){let Q=KE($);if(!Q)return[];I9.#X=!0;let J=new I9($,Q);return I9.#X=!1,J}constructor($,Q){if(!I9.#X)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 aW{#X;#V;#w;#O;#S;#k;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#W;#D;#Y;#J;#$;#K;#B;#H;#G;#F;#U;#Z;#M;#z;#L;#P;#q;static unsafeExposeInternals($){return{starts:$.#M,ttls:$.#z,sizes:$.#Z,keyMap:$.#Y,keyList:$.#J,valList:$.#$,next:$.#K,prev:$.#B,get head(){return $.#H},get tail(){return $.#G},free:$.#F,isBackgroundFetch:(Q)=>$.#Q(Q),backgroundFetch:(Q,J,Y,X)=>$.#T(Q,J,Y,X),moveToTail:(Q)=>$.#_(Q),indexes:(Q)=>$.#j(Q),rindexes:(Q)=>$.#A(Q),isStale:(Q)=>$.#N(Q)}}get max(){return this.#X}get maxSize(){return this.#V}get calculatedSize(){return this.#D}get size(){return this.#W}get fetchMethod(){return this.#S}get memoMethod(){return this.#k}get dispose(){return this.#w}get disposeAfter(){return this.#O}constructor($){let{max:Q=0,ttl:J,ttlResolution:Y=1,ttlAutopurge:X,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:j,allowStaleOnFetchRejection:A,allowStaleOnFetchAbort:k,ignoreFetchAbort:u}=$;if(Q!==0&&!i1(Q))throw TypeError("max option must be a nonnegative integer");let G$=Q?KE(Q):Array;if(!G$)throw Error("invalid max value: "+Q);if(this.#X=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.#S=O,this.#P=!!O,this.#Y=new Map,this.#J=Array(Q).fill(void 0),this.#$=Array(Q).fill(void 0),this.#K=new G$(Q),this.#B=new G$(Q),this.#H=0,this.#G=0,this.#F=I9.create(Q),this.#W=0,this.#D=0,typeof H==="function")this.#w=H;if(typeof q==="function")this.#O=q,this.#U=[];else this.#O=void 0,this.#U=void 0;if(this.#L=!!this.#w,this.#q=!!this.#O,this.noDisposeOnSet=!!V,this.noUpdateTTL=!!B,this.noDeleteOnFetchRejection=!!M,this.allowStaleOnFetchRejection=!!A,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!u,this.maxEntrySize!==0){if(this.#V!==0){if(!i1(this.#V))throw TypeError("maxSize must be a positive integer if specified")}if(!i1(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!U,this.noDeleteOnStaleGet=!!j,this.updateAgeOnGet=!!W,this.updateAgeOnHas=!!G,this.ttlResolution=i1(Y)||Y===0?Y:1,this.ttlAutopurge=!!X,this.ttl=J||0,this.ttl){if(!i1(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#x()}if(this.#X===0&&this.ttl===0&&this.#V===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#X&&!this.#V){if(ds("LRU_CACHE_UNBOUNDED"))UE.add("LRU_CACHE_UNBOUNDED"),HE("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",aW)}}getRemainingTTL($){return this.#Y.has($)?1/0:0}#x(){let $=new nJ(this.#X),Q=new nJ(this.#X);this.#z=$,this.#M=Q,this.#y=(X,W,G=A9.now())=>{if(Q[X]=W!==0?G:0,$[X]=W,W!==0&&this.ttlAutopurge){let U=setTimeout(()=>{if(this.#N(X))this.#I(this.#J[X],"expire")},W+1);if(U.unref)U.unref()}},this.#E=(X)=>{Q[X]=$[X]!==0?A9.now():0},this.#R=(X,W)=>{if($[W]){let G=$[W],U=Q[W];if(!G||!U)return;X.ttl=G,X.start=U,X.now=J||Y();let H=X.now-U;X.remainingTTL=G-H}};let J=0,Y=()=>{let X=A9.now();if(this.ttlResolution>0){J=X;let W=setTimeout(()=>J=0,this.ttlResolution);if(W.unref)W.unref()}return X};this.getRemainingTTL=(X)=>{let W=this.#Y.get(X);if(W===void 0)return 0;let G=$[W],U=Q[W];if(!G||!U)return 1/0;let H=(J||Y())-U;return G-H},this.#N=(X)=>{let W=Q[X],G=$[X];return!!G&&!!W&&(J||Y())-W>G}}#E=()=>{};#R=()=>{};#y=()=>{};#N=()=>!1;#m(){let $=new nJ(this.#X);this.#D=0,this.#Z=$,this.#b=(Q)=>{this.#D-=$[Q],$[Q]=0},this.#f=(Q,J,Y,X)=>{if(this.#Q(J))return 0;if(!i1(Y))if(X){if(typeof X!=="function")throw TypeError("sizeCalculation must be a function");if(Y=X(J,Q),!i1(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,J,Y)=>{if($[Q]=J,this.#V){let X=this.#V-$[Q];while(this.#D>X)this.#C(!0)}if(this.#D+=$[Q],Y)Y.entrySize=J,Y.totalCalculatedSize=this.#D}}#b=($)=>{};#v=($,Q,J)=>{};#f=($,Q,J,Y)=>{if(J||Y)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:$=this.allowStale}={}){if(this.#W)for(let Q=this.#G;;){if(!this.#g(Q))break;if($||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#B[Q]}}*#A({allowStale:$=this.allowStale}={}){if(this.#W)for(let Q=this.#H;;){if(!this.#g(Q))break;if($||!this.#N(Q))yield Q;if(Q===this.#G)break;else Q=this.#K[Q]}}#g($){return $!==void 0&&this.#Y.get(this.#J[$])===$}*entries(){for(let $ of this.#j())if(this.#$[$]!==void 0&&this.#J[$]!==void 0&&!this.#Q(this.#$[$]))yield[this.#J[$],this.#$[$]]}*rentries(){for(let $ of this.#A())if(this.#$[$]!==void 0&&this.#J[$]!==void 0&&!this.#Q(this.#$[$]))yield[this.#J[$],this.#$[$]]}*keys(){for(let $ of this.#j()){let Q=this.#J[$];if(Q!==void 0&&!this.#Q(this.#$[$]))yield Q}}*rkeys(){for(let $ of this.#A()){let Q=this.#J[$];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 J of this.#j()){let Y=this.#$[J],X=this.#Q(Y)?Y.__staleWhileFetching:Y;if(X===void 0)continue;if($(X,this.#J[J],this))return this.get(this.#J[J],Q)}}forEach($,Q=this){for(let J of this.#j()){let Y=this.#$[J],X=this.#Q(Y)?Y.__staleWhileFetching:Y;if(X===void 0)continue;$.call(Q,X,this.#J[J],this)}}rforEach($,Q=this){for(let J of this.#A()){let Y=this.#$[J],X=this.#Q(Y)?Y.__staleWhileFetching:Y;if(X===void 0)continue;$.call(Q,X,this.#J[J],this)}}purgeStale(){let $=!1;for(let Q of this.#A({allowStale:!0}))if(this.#N(Q))this.#I(this.#J[Q],"expire"),$=!0;return $}info($){let Q=this.#Y.get($);if(Q===void 0)return;let J=this.#$[Q],Y=this.#Q(J)?J.__staleWhileFetching:J;if(Y===void 0)return;let X={value:Y};if(this.#z&&this.#M){let W=this.#z[Q],G=this.#M[Q];if(W&&G){let U=W-(A9.now()-G);X.ttl=U,X.start=Date.now()}}if(this.#Z)X.size=this.#Z[Q];return X}dump(){let $=[];for(let Q of this.#j({allowStale:!0})){let J=this.#J[Q],Y=this.#$[Q],X=this.#Q(Y)?Y.__staleWhileFetching:Y;if(X===void 0||J===void 0)continue;let W={value:X};if(this.#z&&this.#M){W.ttl=this.#z[Q];let G=A9.now()-this.#M[Q];W.start=Math.floor(Date.now()-G)}if(this.#Z)W.size=this.#Z[Q];$.unshift([J,W])}return $}load($){this.clear();for(let[Q,J]of $){if(J.start){let Y=Date.now()-J.start;J.start=A9.now()-Y}this.set(Q,J.value,J)}}set($,Q,J={}){if(Q===void 0)return this.delete($),this;let{ttl:Y=this.ttl,start:X,noDisposeOnSet:W=this.noDisposeOnSet,sizeCalculation:G=this.sizeCalculation,status:U}=J,{noUpdateTTL:H=this.noUpdateTTL}=J,q=this.#f($,Q,J.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.#W===0?void 0:this.#Y.get($);if(V===void 0){if(V=this.#W===0?this.#G:this.#F.length!==0?this.#F.pop():this.#W===this.#X?this.#C(!1):this.#W,this.#J[V]=$,this.#$[V]=Q,this.#Y.set($,V),this.#K[this.#G]=V,this.#B[V]=this.#G,this.#G=V,this.#W++,this.#v(V,q,U),U)U.set="add";H=!1}else{this.#_(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.#U?.push([z,$,"set"])}}else if(!W){if(this.#L)this.#w?.(B,$,"set");if(this.#q)this.#U?.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,X);if(U)this.#R(U,V)}if(!W&&this.#q&&this.#U){let B=this.#U,z;while(z=B?.shift())this.#O?.(...z)}return this}pop(){try{while(this.#W){let $=this.#$[this.#H];if(this.#C(!0),this.#Q($)){if($.__staleWhileFetching)return $.__staleWhileFetching}else if($!==void 0)return $}}finally{if(this.#q&&this.#U){let $=this.#U,Q;while(Q=$?.shift())this.#O?.(...Q)}}}#C($){let Q=this.#H,J=this.#J[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,J,"evict");if(this.#q)this.#U?.push([Y,J,"evict"])}if(this.#b(Q),$)this.#J[Q]=void 0,this.#$[Q]=void 0,this.#F.push(Q);if(this.#W===1)this.#H=this.#G=0,this.#F.length=0;else this.#H=this.#K[Q];return this.#Y.delete(J),this.#W--,Q}has($,Q={}){let{updateAgeOnHas:J=this.updateAgeOnHas,status:Y}=Q,X=this.#Y.get($);if(X!==void 0){let W=this.#$[X];if(this.#Q(W)&&W.__staleWhileFetching===void 0)return!1;if(!this.#N(X)){if(J)this.#E(X);if(Y)Y.has="hit",this.#R(Y,X);return!0}else if(Y)Y.has="stale",this.#R(Y,X)}else if(Y)Y.has="miss";return!1}peek($,Q={}){let{allowStale:J=this.allowStale}=Q,Y=this.#Y.get($);if(Y===void 0||!J&&this.#N(Y))return;let X=this.#$[Y];return this.#Q(X)?X.__staleWhileFetching:X}#T($,Q,J,Y){let X=Q===void 0?void 0:this.#$[Q];if(this.#Q(X))return X;let W=new tW,{signal:G}=J;G?.addEventListener("abort",()=>W.abort(G.reason),{signal:W.signal});let U={signal:W.signal,options:J,context:Y},H=(w,O=!1)=>{let{aborted:D}=W.signal,M=J.ignoreFetchAbort&&w!==void 0;if(J.status)if(D&&!O){if(J.status.fetchAborted=!0,J.status.fetchError=W.signal.reason,M)J.status.fetchAbortIgnored=!0}else J.status.fetchResolved=!0;if(D&&!M&&!O)return V(W.signal.reason);let j=z;if(this.#$[Q]===z)if(w===void 0)if(j.__staleWhileFetching)this.#$[Q]=j.__staleWhileFetching;else this.#I($,"fetch");else{if(J.status)J.status.fetchUpdated=!0;this.set($,w,U.options)}return w},q=(w)=>{if(J.status)J.status.fetchRejected=!0,J.status.fetchError=w;return V(w)},V=(w)=>{let{aborted:O}=W.signal,D=O&&J.allowStaleOnFetchAbort,M=D||J.allowStaleOnFetchRejection,j=M||J.noDeleteOnFetchRejection,A=z;if(this.#$[Q]===z){if(!j||A.__staleWhileFetching===void 0)this.#I($,"fetch");else if(!D)this.#$[Q]=A.__staleWhileFetching}if(M){if(J.status&&A.__staleWhileFetching!==void 0)J.status.returnedStale=!0;return A.__staleWhileFetching}else if(A.__returned===A)throw w},B=(w,O)=>{let D=this.#S?.($,X,U);if(D&&D instanceof Promise)D.then((M)=>w(M===void 0?void 0:M),O);W.signal.addEventListener("abort",()=>{if(!J.ignoreFetchAbort||J.allowStaleOnFetchAbort){if(w(void 0),J.allowStaleOnFetchAbort)w=(M)=>H(M,!0)}})};if(J.status)J.status.fetchDispatched=!0;let z=new Promise(B).then(H,q),N=Object.assign(z,{__abortController:W,__staleWhileFetching:X,__returned:void 0});if(Q===void 0)this.set($,N,{...U.options,status:void 0}),Q=this.#Y.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 tW}async fetch($,Q={}){let{allowStale:J=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:X=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:J,updateAgeOnGet:Y,noDeleteOnStaleGet:X,status:D})}let j={allowStale:J,updateAgeOnGet:Y,noDeleteOnStaleGet:X,ttl:W,noDisposeOnSet:G,size:U,sizeCalculation:H,noUpdateTTL:q,noDeleteOnFetchRejection:V,allowStaleOnFetchRejection:B,allowStaleOnFetchAbort:N,ignoreFetchAbort:z,status:D,signal:M},A=this.#Y.get($);if(A===void 0){if(D)D.fetch="miss";let k=this.#T($,A,j,w);return k.__returned=k}else{let k=this.#$[A];if(this.#Q(k)){let m6=J&&k.__staleWhileFetching!==void 0;if(D){if(D.fetch="inflight",m6)D.returnedStale=!0}return m6?k.__staleWhileFetching:k.__returned=k}let u=this.#N(A);if(!O&&!u){if(D)D.fetch="hit";if(this.#_(A),Y)this.#E(A);if(D)this.#R(D,A);return k}let G$=this.#T($,A,j,w),e$=G$.__staleWhileFetching!==void 0&&J;if(D){if(D.fetch=u?"stale":"refresh",e$&&u)D.returnedStale=!0}return e$?G$.__staleWhileFetching:G$.__returned=G$}}async forceFetch($,Q={}){let J=await this.fetch($,Q);if(J===void 0)throw Error("fetch() returned undefined");return J}memo($,Q={}){let J=this.#k;if(!J)throw Error("no memoMethod provided to constructor");let{context:Y,forceRefresh:X,...W}=Q,G=this.get($,W);if(!X&&G!==void 0)return G;let U=J($,G,{options:W,context:Y});return this.set($,U,W),U}get($,Q={}){let{allowStale:J=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:X=this.noDeleteOnStaleGet,status:W}=Q,G=this.#Y.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(!X)this.#I($,"expire");if(W&&J)W.returnedStale=!0;return J?U:void 0}else{if(W&&J&&U.__staleWhileFetching!==void 0)W.returnedStale=!0;return J?U.__staleWhileFetching:void 0}}else{if(W)W.get="hit";if(H)return U.__staleWhileFetching;if(this.#_(G),Y)this.#E(G);return U}}else if(W)W.get="miss"}#h($,Q){this.#B[Q]=$,this.#K[$]=Q}#_($){if($!==this.#G){if($===this.#H)this.#H=this.#K[$];else this.#h(this.#B[$],this.#K[$]);this.#h(this.#G,$),this.#G=$}}delete($){return this.#I($,"delete")}#I($,Q){let J=!1;if(this.#W!==0){let Y=this.#Y.get($);if(Y!==void 0)if(J=!0,this.#W===1)this.#u(Q);else{this.#b(Y);let X=this.#$[Y];if(this.#Q(X))X.__abortController.abort(Error("deleted"));else if(this.#L||this.#q){if(this.#L)this.#w?.(X,$,Q);if(this.#q)this.#U?.push([X,$,Q])}if(this.#Y.delete($),this.#J[Y]=void 0,this.#$[Y]=void 0,Y===this.#G)this.#G=this.#B[Y];else if(Y===this.#H)this.#H=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.#W--,this.#F.push(Y)}}if(this.#q&&this.#U?.length){let Y=this.#U,X;while(X=Y?.shift())this.#O?.(...X)}return J}clear(){return this.#u("delete")}#u($){for(let Q of this.#A({allowStale:!0})){let J=this.#$[Q];if(this.#Q(J))J.__abortController.abort(Error("deleted"));else{let Y=this.#J[Q];if(this.#L)this.#w?.(J,Y,$);if(this.#q)this.#U?.push([J,Y,$])}}if(this.#Y.clear(),this.#$.fill(void 0),this.#J.fill(void 0),this.#z&&this.#M)this.#z.fill(0),this.#M.fill(0);if(this.#Z)this.#Z.fill(0);if(this.#H=0,this.#G=0,this.#F.length=0,this.#D=0,this.#W=0,this.#q&&this.#U){let Q=this.#U,J;while(J=Q?.shift())this.#O?.(...J)}}}function qE($,Q,J=100){let Y=new aW({max:J}),X=(...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 X.cache={clear:()=>Y.clear(),size:()=>Y.size,delete:(W)=>Y.delete(W),get:(W)=>Y.peek(W),has:(W)=>Y.has(W)},X}var is=8192;function BE($,Q){try{return{ok:!0,value:JSON.parse(rW($))}}catch(J){if(Q)oW(J);return{ok:!1}}}var VE=qE(BE,($)=>$,50);var R9=Object.assign(function(Q,J=!0){if(!Q)return null;let Y=Q.length>is?BE(Q,J):VE(Q,J);return Y.ok?Y.value:null},{cache:VE.cache});import{join as rs}from"path";import{readdir as ND$,readFile as ns}from"fs/promises";import{release as zE}from"os";var m0=v$(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){try{let $=c$().readFileSync("/proc/version",{encoding:"utf8"});if($.toLowerCase().includes("microsoft")||$.toLowerCase().includes("wsl"))return"wsl"}catch($){X$(`Failed to read /proc/version for WSL detection: ${$}`,{level:"error"})}return"linux"}return"unknown"}catch($){return oW($),"unknown"}}),MD$=v$(()=>{if(process.platform!=="linux")return;try{let $=c$().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($){X$(`Failed to read /proc/version for WSL detection: ${$}`,{level:"error"});return}}),LD$=v$(async()=>{if(process.platform!=="linux")return;let $={linuxKernel:zE()};try{let Q=await ns("/etc/os-release","utf8");for(let J of Q.split(`
|
|
115
|
-
`)){let Y=J.match(/^(ID|VERSION_ID)=(.*)$/);if(Y&&Y[1]&&Y[2]){let X=Y[2].replace(/^"|"$/g,"");if(Y[1]==="ID")$.linuxDistroId=X;else $.linuxDistroVersion=X}}}catch{}return $});var jD$=v$(()=>{if(process.platform!=="darwin")return;let Q=zE().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"}}),ED$=v$(function(){return rs(l0(),"managed-settings.d")});import{isAbsolute as NE}from"path";var os=b(()=>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()),ts=b(()=>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()),wE=b(()=>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:os(),filesystem:ts(),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"&&NE($)?$: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"&&NE($)?$: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 OE=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],DE=["normal","vim"],FE=["auto","tmux","in-process"],as=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],ZE=["auto",...as];var xD$=m0()==="macos"?"⏺":"●";var rJ=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],ss=[...rJ,"bubble"],ME=ss;var cD$=b(()=>vV.enum(ME)),pD$=b(()=>vV.enum(rJ));var LE=["bash","powershell"];var oJ=b(()=>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 es(){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:oJ(),shell:K.enum(LE).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:oJ(),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")}),J=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:oJ(),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:oJ(),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")}),X=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:oJ(),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:X,McpToolHookSchema:J}}var jE=b(()=>{let{BashCommandHookSchema:$,PromptHookSchema:Q,AgentHookSchema:J,HttpHookSchema:Y,McpToolHookSchema:X}=es();return K.discriminatedUnion("type",[$,Q,J,Y,X])}),AE=b(()=>K.object({matcher:K.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:K.array(jE()).describe("List of hooks to execute when the matcher matches")})),c0=b(()=>K.partialRecord(K.enum(o0),K.array(AE())));var $F$=b(()=>K.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),QF$=b(()=>K.enum(["stdio","sse","sse-ide","http","ws","sdk"])),P9=b(()=>K.literal("comms").optional().catch(void 0)),n1=b(()=>K.number().int().positive()),$e=b(()=>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(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Qe=b(()=>K.boolean()),IE=b(()=>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:Qe().optional()})),Je=b(()=>K.object({type:K.literal("sse"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),oauth:IE().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Xe=b(()=>K.object({type:K.literal("sse-ide"),url:K.string(),ideName:K.string(),ideRunningInWindows:K.boolean().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Ye=b(()=>K.object({type:K.literal("ws-ide"),url:K.string(),ideName:K.string(),authToken:K.string().optional(),ideRunningInWindows:K.boolean().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),We=b(()=>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:IE().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Ge=b(()=>K.object({type:K.literal("ws"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Ue=b(()=>K.object({type:K.literal("sdk"),name:K.string(),timeout:n1().optional(),alwaysLoad:K.boolean().optional()})),He=b(()=>K.enum(["allow","ask","blocked"])),Ke=b(()=>K.object({type:K.literal("claudeai-proxy"),url:K.string(),id:K.string(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),toolPermissions:K.record(K.string(),He()).optional()})),sW=b(()=>K.union([$e(),Je(),Xe(),Ye(),We(),Ge(),Ue(),Ke()])),JF$=b(()=>K.object({mcpServers:K.record(K.string(),sW())}));var bE=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins"]);var qe=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,Ve=/[^\u0020-\u007E]/;function Be($){if(bE.has($.toLowerCase()))return!1;if(Ve.test($))return!0;return qe.test($)}var Z4=b(()=>K.string().startsWith("./")),p0=b(()=>Z4().endsWith(".json")),RE=b(()=>K.union([Z4().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")])),Mz=b(()=>Z4().endsWith(".md")),Lz=b(()=>K.union([Mz(),Z4()])),_E=b(()=>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(($)=>!Be($),{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/'})),jz=b(()=>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")})),ze=b(()=>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)"),displayName:K.string().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version: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:jz().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(fe()).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.`)})),qF$=b(()=>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")})),Ne=b(()=>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)")]))])})),we=b(()=>K.object({source:Lz().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'})),Oe=b(()=>K.object({commands:K.union([Lz().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(Lz().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(),we()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),De=b(()=>K.object({agents:K.union([Mz().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(Mz().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.")])})),Fe=b(()=>K.object({skills:K.union([Z4().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory."),K.array(Z4().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.")])})),SE=b(()=>K.object({outputStyles:K.union([Z4().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(Z4().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=b(()=>K.object({themes:K.union([Z4().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(Z4().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.")])})),Ze=b(()=>K.object({})),PE=b(()=>K.string().min(1)),Me=b(()=>K.string().min(2).refine(($)=>$.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),Le=b(()=>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)"),RE().describe("Path or URL to MCPB file containing MCP server configuration"),K.record(K.string(),sW()).describe("MCP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to MCP servers configuration file"),RE().describe("Path or URL to MCPB file"),K.record(K.string(),sW()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),vE=b(()=>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()),je=b(()=>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.")})),Ae=b(()=>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.")})),EE=b(()=>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(PE()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:K.record(Me(),PE()).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")})),Ie=b(()=>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).')})),Re=b(()=>K.array(Ie()).refine(($)=>new Set($.map((Q)=>Q.name)).size===$.length,{message:"Monitor names must be unique within a plugin"})),CE=b(()=>K.object({monitors:K.union([p0().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Re()]).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.")})),Pe=b(()=>K.object({lspServers:K.union([p0().describe("Path to .lsp.json configuration file relative to plugin root"),K.record(K.string(),EE()).describe("LSP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to LSP configuration file"),K.record(K.string(),EE()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),TE=b(()=>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-._]*$/,J=/^[a-z0-9][a-z0-9-._]*$/;return Q.test($)||J.test($)},"Invalid npm package name format")),Ee=b(()=>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.")})),be=b(()=>K.object({experimental:K.preprocess(($)=>typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0,K.object({...kE().partial().shape,...CE().partial().shape,...SE().partial().shape,evals:K.union([K.string(),K.array(K.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),_e=b(()=>K.object({...ze().shape,...Ne().partial().shape,...Oe().partial().shape,...De().partial().shape,...Fe().partial().shape,...SE().partial().shape,...kE().partial().shape,...Ze().shape,...Ae().partial().shape,...Le().partial().shape,...Pe().partial().shape,...CE().partial().shape,...Ee().partial().shape,...je().partial().shape,...be().partial().shape})),tJ=b(()=>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("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),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(($)=>!bE.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(Se()).describe("Plugin entries declared inline in settings.json"),owner:jz().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).")])),Zz=b(()=>K.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),xE=b(()=>K.union([Z4().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:Zz().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:Zz().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:Zz().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.')])),Se=b(()=>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 ke=b(()=>K.object({cli:K.array(K.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:K.array(K.string().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) — exact, case-insensitive match against '+"hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path."),filePath:K.string().max(256).optional().describe("RegExp source matched (case-insensitive) against file paths read this session, or present in cwd at session start."),manifestDeps:K.array(K.object({file:K.string().max(256),pattern:K.string().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: "+"`file` matches the manifest filename (package.json, go.mod, requirements.txt, …); "+"`pattern` matches the dependency declaration inside that file. Evaluated against files read this session, or present in cwd at session start.")})),ve=b(()=>K.object({topic:K.string().max(64).optional().describe('What the user is working with when this plugin is relevant — fills "Working with {topic}?". '+'Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:ke().optional().describe("Matchers that determine when the plugin is relevant.")})),Ce=b(()=>_e().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."),relevance:K.preprocess(($)=>typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0,ve().optional()).describe(`Declares when this plugin is relevant to the user's work. Consumed by the spinner tip ("Working with {topic}?"), session-start auto-suggest, and marketplace browse ranking.`)})),Te=b(()=>K.object({name:K.string().min(1).refine(($)=>!$.includes(" "))}));function xe($){let Q=Ce();return $.flatMap((J,Y)=>{let X=Q.safeParse(J);if(X.success)return[X.data];let W=Te().safeParse(J).data?.name,G=X.error.issues.map((U)=>`${U.path.join(".")}: ${U.message}`).join(", ");if(W)return X$(`Stubbing unparseable marketplace plugin entry (${W}): ${G}`,{level:"warn"}),[{name:W,source:{source:"unsupported"},strict:!0}];return X$(`Dropping unparseable marketplace plugin entry (index ${Y}): ${G}`,{level:"warn"}),[]})}var VF$=b(()=>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:jz().describe("Marketplace maintainer or curator information"),plugins:K.array(K.unknown()).transform(xe).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=b(()=>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")),ye=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,fe=b(()=>K.union([K.string().regex(ye,"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)])),ge=b(()=>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).")})),he=b(()=>K.object({version:K.literal(1).describe("Schema version 1"),plugins:K.record(yE(),ge()).describe("Map of plugin IDs to their installation metadata")})),ue=b(()=>K.enum(["managed","user","project","local"])),me=b(()=>K.object({scope:ue().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.")})),le=b(()=>K.object({version:K.literal(2).describe("Schema version 2"),plugins:K.record(yE(),K.array(me())).describe("Map of plugin IDs to arrays of installation entries")})),BF$=b(()=>K.union([he(),le()])),ce=b(()=>K.object({source:tJ().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")})),zF$=b(()=>K.record(K.string(),ce()));var fE=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var gE="https://json.schemastore.org/claude-code-settings.json";var pe=["autoMode","deepLink","voice","assistant","briefView"],eW={},$G={autoMode:{buildGate:()=>!1,shape:()=>eW,permissionsShape:()=>eW,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:K.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>eW},assistant:{buildGate:()=>!1,shape:()=>eW},briefView:{buildGate:()=>!0,shape:()=>({defaultView:K.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})}};function Az(){return pe.filter(($)=>$G[$].buildGate())}function hE($){let Q={};for(let J of $)Q={...Q,...$G[J].shape()};return Q}function uE($){let Q={};for(let J of $)Q={...Q,...$G[J].permissionsShape?.()};return Q}function mE($){let Q=[];for(let J of $)Q.push(...$G[J].permissionModes?.()??[]);return Q}function lE($){let Q=$.split("__"),[J,Y,...X]=Q;if(J!=="mcp"||!Y)return null;let W=X.length>0?X.join("__"):void 0;return{serverName:Y,toolName:W}}var cE={Task:"Agent",KillShell:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage"};function E9($){return Object.hasOwn(cE,$)?cE[$]:$}var pE="workspace",EF$=`mcp__${pE}__bash`,bF$=`mcp__${pE}__web_fetch`;function de($){return $.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function dE($){let Q=ie($,"(");if(Q===-1)return{toolName:E9($)};let J=ne($,")");if(J===-1||J<=Q)return{toolName:E9($)};if(J!==$.length-1)return{toolName:E9($)};let Y=$.substring(0,Q),X=$.substring(Q+1,J);if(!Y)return{toolName:E9($)};if(X===""||X==="*")return{toolName:E9(Y)};let W=de(X);return{toolName:E9(Y),ruleContent:W}}function ie($,Q){for(let J=0;J<$.length;J++)if($[J]===Q){let Y=0,X=J-1;while(X>=0&&$[X]==="\\")Y++,X--;if(Y%2===0)return J}return-1}function ne($,Q){for(let J=$.length-1;J>=0;J--)if($[J]===Q){let Y=0,X=J-1;while(X>=0&&$[X]==="\\")Y++,X--;if(Y%2===0)return J}return-1}var QG={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 iE($){return QG.filePatternTools.includes($)}function nE($){return QG.bashPrefixTools.includes($)}function rE($){return Object.hasOwn(QG.customValidation,$)?QG.customValidation[$]:void 0}function oE($,Q){let J=0,Y=Q-1;while(Y>=0&&$[Y]==="\\")J++,Y--;return J%2!==0}function Iz($,Q){let J=0;for(let Y=0;Y<$.length;Y++)if($[Y]===Q&&!oE($,Y))J++;return J}function re($){for(let Q=0;Q<$.length-1;Q++)if($[Q]==="("&&$[Q+1]===")"){if(!oE($,Q))return!0}return!1}function Rz($){if(!$||$.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let Q=Iz($,"("),J=Iz($,")");if(Q!==J)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(re($)){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=dE($),X=lE(Y.toolName);if(X){if(Y.ruleContent!==void 0||Iz($,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${Y.toolName}" without parentheses, or use "mcp__${X.serverName}__*" for all tools`,examples:[`mcp__${X.serverName}`,`mcp__${X.serverName}__*`,X.toolName&&X.toolName!=="*"?`mcp__${X.serverName}__${X.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 "${BU(String(Y.toolName))}"`};let W=rE(Y.toolName);if(W&&Y.ruleContent!==void 0){let G=W(Y.ruleContent);if(!G.valid)return G}if(nE(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(iE(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 JG=b(()=>K.string().superRefine(($,Q)=>{let J=Rz($);if(!J.valid){let Y=J.error;if(J.suggestion)Y+=`. ${J.suggestion}`;if(J.examples&&J.examples.length>0)Y+=`. Examples: ${J.examples.join(", ")}`;Q.addIssue({code:K.ZodIssueCode.custom,message:Y,params:{received:$}})}}));var oe=b(()=>K.record(K.string(),K.coerce.string()));function aE($){return K.object({allow:K.array(JG()).optional().describe("List of permission rules for allowed operations"),deny:K.array(JG()).optional().describe("List of permission rules for denied operations"),ask:K.array(JG()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:K.enum([...rJ,...mE($)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:K.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...uE($),additionalDirectories:K.array(K.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var tF$=b(()=>aE(Az())),te=b(()=>K.object({source:tJ().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")})),ae=b(()=>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 kH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),se=b(()=>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 kH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),ee=b(()=>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()})),tE=["skills","agents","hooks","mcp"];function sE($){return K.object({$schema:K.literal(gE).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:ee().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...A$(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:oe().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:aE($).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(ae()).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(se()).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."),bgIsolation:K.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks: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((J)=>tE.includes(J)):Q,K.union([K.boolean(),K.array(K.enum(tE))])).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(),te()).check((Q)=>{for(let[J,Y]of Object.entries(Q.value))if(Y.source.source==="settings"&&Y.source.name!==J)Q.issues.push({code:"custom",input:Y.source.name,path:[J,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${J}" 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(tJ()).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(tJ()).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:wE().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(ZE),K.string().startsWith("custom:").transform((Q)=>Q)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:K.enum(DE).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(OE).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(FE).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"),...hE($)}).passthrough()}var S4=b(()=>sE(Az()));var W1="https://code.claude.com/docs/en",$$$=[{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:`${W1}/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:`${W1}/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:`${W1}/hooks`}},{matches:($)=>/\.hooks\.\d+\.command$/.test($.path)&&$.code==="invalid_type"&&$.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${W1}/hooks#exec-form-and-shell-form`}},{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:`${W1}/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:`${W1}/iam#working-directories`}}],Q$$={permissions:`${W1}/iam#configuring-permissions`,env:`${W1}/settings#environment-variables`,hooks:`${W1}/hooks`};function eE($){let Q=$$$.find((Y)=>Y.matches($));if(!Q)return null;let J={...Q.tip};if($.code==="invalid_value"&&$.enumValues&&!J.suggestion)J.suggestion=`Valid values: ${$.enumValues.map((Y)=>`"${Y}"`).join(", ")}`;if(!J.docLink&&$.path)J.docLink=Q$$[dO($.path,".")];return J}var zZ$=b(()=>S4().strict());function $b($){return $.code==="invalid_type"}function Qb($){return $.code==="invalid_value"}function J$$($){return $.code==="unrecognized_keys"}function Jb($){return $.code==="too_small"}function aJ($){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((J)=>{let Y=J.path.map(String).join("."),X=J.message,W,G,U,H,q;if(Qb(J))G=J.values.map((B)=>String(B)),U=G.join(" | "),H=void 0,q=void 0;else if($b(J)){U=J.expected;let B=Xb(J.message);H=B??aJ(J.input),q=B??aJ(J.input)}else if(Jb(J))U=String(J.minimum);else if(J.code==="custom"&&"params"in J)H=J.params.received,q=H;let V=eE({path:Y,code:J.code,expected:U,received:H,enumValues:G,message:J.message,value:H});if(Qb(J))W=G?.map((B)=>`"${B}"`).join(", "),X=`Invalid value. Expected one of: ${W}`;else if($b(J)){let B=Xb(J.message)??aJ(J.input);if(J.expected==="object"&&B==="null"&&Y==="")X="Invalid or malformed JSON";else X=`Expected ${J.expected}, but received ${B}`}else if(J$$(J)){let B=J.keys.join(", ");X=`Unrecognized ${pO(J.keys.length,"field")}: ${B}`}else if(Jb(J))X=`Number must be greater than or equal to ${J.minimum}`,W=String(J.minimum);return{file:Q,path:Y,message:X,expected:W,invalidValue:q,suggestion:V?.suggestion,docLink:V?.docLink}})}function X$$($,Q){if(!$||typeof $!=="object")return[];let J=$;if(!J.permissions||typeof J.permissions!=="object")return[];let Y=J.permissions,X=[];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 X.push({file:Q,path:`permissions.${W}`,message:`Non-string value in ${W} array was removed`,severity:"warning",invalidValue:U}),!1;let H=Rz(U);if(!H.valid){let q=`Invalid permission rule "${U}" was skipped: ${H.error}`;if(H.suggestion)q+=`. ${H.suggestion}`;return X.push({file:Q,path:`permissions.${W}`,message:q,severity:"warning",invalidValue:U}),!1}return!0})}return X}var Y$$=new Set(o0);function W$$($,Q){if(!$||typeof $!=="object")return[];let J=$;if(!("hooks"in J))return[];if(J.hooks===null||typeof J.hooks!=="object"||Array.isArray(J.hooks)){let W=aJ(J.hooks);return delete J.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=J.hooks,X=[];for(let W of Object.keys(Y)){if(!Y$$.has(W)){delete Y[W],X.push({file:Q,path:`hooks.${W}`,message:`Unknown hook event "${W}" was ignored. Valid events: ${o0.join(", ")}`,severity:"warning",invalidValue:W,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(Y[W])){let G=aJ(Y[W]);delete Y[W],X.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(X.length>0&&Object.keys(Y).length===0)delete J.hooks;return X}function r1($,Q){return[...X$$($,Q),...W$$($,Q)]}import{userInfo as G$$}from"os";var Yb="com.anthropic.claudecode",sJ="HKLM\\SOFTWARE\\Policies\\ClaudeCode",eJ="HKCU\\SOFTWARE\\Policies\\ClaudeCode",o1="Settings",Wb="/usr/bin/plutil",Gb=["-convert","json","-o","-","--"],Ub=5000,Pz="/mnt/c/Windows/System32/reg.exe",b9="/mnt/c/Program Files/ClaudeCode";function XG(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let $=v6("fs").readFileSync("/proc/version","utf8").toLowerCase();return $.includes("microsoft")||$.includes("wsl")}catch{return!1}}function Hb(){let $="";try{$=G$$().username}catch{}let Q=[];if($)Q.push({path:`/Library/Managed Preferences/${$}/${Yb}.plist`,label:"per-user managed preferences"});return Q.push({path:`/Library/Managed Preferences/${Yb}.plist`,label:"device-level managed preferences"}),Q}import{execFile as U$$}from"child_process";import{existsSync as H$$}from"fs";var K$$=null;function $X($,Q){return new Promise((J)=>{try{U$$($,Q,{encoding:"utf-8",timeout:Ub},(Y,X)=>{J({stdout:X??"",code:Y?1:0})})}catch{J({stdout:"",code:1})}})}function Kb(){return(async()=>{if(process.platform==="darwin"){let $=Hb(),J=(await Promise.all($.map(async({path:Y,label:X})=>{if(!H$$(Y))return{stdout:"",label:X,ok:!1};let{stdout:W,code:G}=await $X(Wb,[...Gb,Y]);return{stdout:W,label:X,ok:G===0&&!!W}}))).find((Y)=>Y.ok);return{plistStdouts:J?[{stdout:J.stdout,label:J.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let Q=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[J,Y]=await Promise.all([$X(Q,["query",sJ,"/v",o1]),$X(Q,["query",eJ,"/v",o1])]);return{plistStdouts:null,hklmStdout:J.code===0?J.stdout:null,hkcuStdout:Y.code===0?Y.stdout:null}}if(XG()){let[$,Q]=await Promise.all([$X(Pz,["query",sJ,"/v",o1]),$X(Pz,["query",eJ,"/v",o1])]);return{plistStdouts:null,hklmStdout:$.code===0?$.stdout:null,hkcuStdout:Q.code===0?Q.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function qb(){return K$$}var t1=Object.freeze({settings:{},errors:[]}),Nb=null,wb=null,Ob=!1,YG=null;function q$$(){if(YG)return;YG=(async()=>{let $=Date.now(),Q=qb()??Kb(),{mdm:J,hkcu:Y,wslInherits:X}=V$$(await Q);Nb=J,wb=Y,Ob=X;let W=Date.now()-$;if(X$(`MDM settings load completed in ${W}ms`),Object.keys(J.settings).length>0){X$(`MDM settings found: ${Object.keys(J.settings).join(", ")}`);try{iJ("info","mdm_settings_loaded",{duration_ms:W,key_count:Object.keys(J.settings).length,error_count:J.errors.length})}catch{}}})()}async function Db(){if(!YG)q$$();await YG}function Fb(){return Nb??t1}function Zb(){return wb??t1}function Mb(){return Ob}function Ez($,Q){let J=A4(R9($,!1));if(!J||typeof J!=="object")return{settings:{},errors:[]};let Y=r1(J,Q),X=S4().safeParse(J);if(!X.success){let W=i0(X.error,Q);return{settings:{},errors:[...Y,...W]}}return{settings:X.data,errors:Y}}function Vb($,Q="Settings"){let J=$.split(/\r?\n/),Y=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=new RegExp(`^\\s+${Y}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let W of J){let G=W.match(X);if(G&&G[1])return G[1].trimEnd()}return null}function V$$($){let Q=[];if($.plistStdouts&&$.plistStdouts.length>0){let{stdout:G,label:U}=$.plistStdouts[0],H=Ez(G,U),{wslInheritsWindowsSettings:q,...V}=H.settings;if(Object.keys(V).length>0)return{mdm:H,hkcu:t1,wslInherits:!1};Q.push(...H.errors)}let J=null;if($.hklmStdout){let G=Vb($.hklmStdout);if(G)J=Ez(G,`Registry: ${sJ}\\${o1}`)}if(J)Q.push(...J.errors);let Y=Q.length>0?{settings:{},errors:Q}:t1,X=XG(),W=!1;if(X){if(W=J?.settings.wslInheritsWindowsSettings===!0||z$$(),!W)return{mdm:Y,hkcu:t1,wslInherits:!1}}if(J){let{wslInheritsWindowsSettings:G,...U}=J.settings;if(Object.keys(U).length>0)return{mdm:J,hkcu:t1,wslInherits:W}}if(B$$(W))return{mdm:Y,hkcu:t1,wslInherits:W};if($.hkcuStdout){let G=Vb($.hkcuStdout);if(G){let U=Ez(G,`Registry: ${eJ}\\${o1}`);if(!X||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:t1,wslInherits:W}}function B$$($){if($&&zb(b9))return!0;return zb(l0())}function Bb($){let Q=A4(R9(u0($),!1));if(!Q||typeof Q!=="object")return!1;r1(Q,$);let{wslInheritsWindowsSettings:J,...Y}=Q;return Object.keys(Y).length>0}function z$$(){function $(Q){try{let J=R9(u0(Q),!1);return!!J&&typeof J==="object"&&"wslInheritsWindowsSettings"in J&&J.wslInheritsWindowsSettings===!0}catch{return!1}}if($(_9(b9,"managed-settings.json")))return!0;try{let Q=_9(b9,"managed-settings.d");for(let J of c$().readdirSync(Q))if((J.isFile()||J.isSymbolicLink())&&J.name.endsWith(".json")&&!J.name.startsWith(".")&&$(_9(Q,J.name)))return!0}catch{}return!1}function zb($){try{if(Bb(_9($,"managed-settings.json")))return!0}catch{}try{let Q=_9($,"managed-settings.d"),J=c$().readdirSync(Q);for(let Y of J){if(!(Y.isFile()||Y.isSymbolicLink())||!Y.name.endsWith(".json")||Y.name.startsWith("."))continue;try{if(Bb(_9(Q,Y.name)))return!0}catch{}}}catch{}return!1}function N$$($,Q,J){if(J!==void 0&&!q1($[Q],J)||J===void 0&&!(Q in $))M8($,Q,J)}var QX=N$$;function w$$($){return function(Q,J,Y){var X=-1,W=Object(Q),G=Y(Q),U=G.length;while(U--){var H=G[$?U:++X];if(J(W[H],H,W)===!1)break}return Q}}var Lb=w$$;var O$$=Lb(),jb=O$$;function D$$($){return r6($)&&j8($)}var Ab=D$$;var F$$="[object Object]",Z$$=Function.prototype,M$$=Object.prototype,Ib=Z$$.toString,L$$=M$$.hasOwnProperty,j$$=Ib.call(Object);function A$$($){if(!r6($)||L4($)!=F$$)return!1;var Q=W5($);if(Q===null)return!0;var J=L$$.call(Q,"constructor")&&Q.constructor;return typeof J=="function"&&J instanceof J&&Ib.call(J)==j$$}var Rb=A$$;function I$$($,Q){if(Q==="constructor"&&typeof $[Q]==="function")return;if(Q=="__proto__")return;return $[Q]}var JX=I$$;function R$$($){return lw($,J5($))}var Pb=R$$;function P$$($,Q,J,Y,X,W,G){var U=JX($,J),H=JX(Q,J),q=G.get(H);if(q){QX($,J,q);return}var V=W?W(U,H,J+"",$,Q,G):void 0,B=V===void 0;if(B){var z=V6(H),N=!z&&T7(H),w=!z&&!N&&$5(H);if(V=H,z||N||w)if(V6(U))V=U;else if(Ab(U))V=UO(U);else if(N)B=!1,V=UU(H,!0);else if(w)B=!1,V=qO(H,!0);else V=[];else if(Rb(H)||u4(H)){if(V=U,u4(U))V=Pb(U);else if(!$6(U)||t0(U))V=zO(H)}else B=!1}if(B)G.set(H,V),X(V,H,Y,W,G),G.delete(H);QX($,J,V)}var Eb=P$$;function bb($,Q,J,Y,X){if($===Q)return;jb(Q,function(W,G){if(X||(X=new mw),$6(W))Eb($,Q,G,J,bb,Y,X);else{var U=Y?Y(JX($,G),W,G+"",$,Q,X):void 0;if(U===void 0)U=W;QX($,G,U)}},J5)}var _b=bb;function E$$($,Q,J){switch(J.length){case 0:return $.call(Q);case 1:return $.call(Q,J[0]);case 2:return $.call(Q,J[0],J[1]);case 3:return $.call(Q,J[0],J[1],J[2])}return $.apply(Q,J)}var Sb=E$$;var kb=Math.max;function b$$($,Q,J){return Q=kb(Q===void 0?$.length-1:Q,0),function(){var Y=arguments,X=-1,W=kb(Y.length-Q,0),G=Array(W);while(++X<W)G[X]=Y[Q+X];X=-1;var U=Array(Q+1);while(++X<Q)U[X]=Y[X];return U[Q]=J(G),Sb($,this,U)}}var WG=b$$;function _$$($){return function(){return $}}var vb=_$$;var S$$=!Z8?G5:function($,Q){return Z8($,"toString",{configurable:!0,enumerable:!1,value:vb(Q),writable:!0})},Cb=S$$;var k$$=800,v$$=16,C$$=Date.now;function T$$($){var Q=0,J=0;return function(){var Y=C$$(),X=v$$-(Y-J);if(J=Y,X>0){if(++Q>=k$$)return arguments[0]}else Q=0;return $.apply(void 0,arguments)}}var Tb=T$$;var x$$=Tb(Cb),GG=x$$;function y$$($,Q){return GG(WG($,Q,G5),$+"")}var xb=y$$;function f$$($,Q,J){if(!$6(J))return!1;var Y=typeof Q;if(Y=="number"?j8(J)&&M1(Q,J.length):Y=="string"&&(Q in J))return q1(J[Q],$);return!1}var yb=f$$;function g$$($){return xb(function(Q,J){var Y=-1,X=J.length,W=X>1?J[X-1]:void 0,G=X>2?J[2]:void 0;if(W=$.length>3&&typeof W=="function"?(X--,W):void 0,G&&yb(J[0],J[1],G))W=X<3?void 0:W,X=1;Q=Object(Q);while(++Y<X){var U=J[Y];if(U)$(Q,U,Y,W)}return Q})}var fb=g$$;var h$$=fb(function($,Q,J,Y){_b($,Q,J,Y)}),G1=h$$;function u$$($,Q,J,Y){if(!$6($))return $;Q=L1(Q,$);var X=-1,W=Q.length,G=W-1,U=$;while(U!=null&&++X<W){var H=I8(Q[X]),q=J;if(H==="__proto__"||H==="constructor"||H==="prototype")return $;if(X!=G){var V=U[H];if(q=Y?Y(V,H,U):void 0,q===void 0)q=$6(V)?V:M1(Q[X+1])?[]:{}}rX(U,H,q),U=U[H]}return $}var gb=u$$;function m$$($,Q,J){var Y=-1,X=Q.length,W={};while(++Y<X){var G=Q[Y],U=AO($,G);if(J(U,G))gb(W,L1(G,$),U)}return W}var hb=m$$;function l$$($,Q){return hb($,Q,function(J,Y){return PO($,Y)})}var ub=l$$;var mb=c6?c6.isConcatSpreadable:void 0;function c$$($){return V6($)||u4($)||!!(mb&&$&&$[mb])}var lb=c$$;function cb($,Q,J,Y,X){var W=-1,G=$.length;J||(J=lb),X||(X=[]);while(++W<G){var U=$[W];if(Q>0&&J(U))if(Q>1)cb(U,Q-1,J,Y,X);else HO(X,U);else if(!Y)X[X.length]=U}return X}var pb=cb;function p$$($){var Q=$==null?0:$.length;return Q?pb($,1):[]}var db=p$$;function d$$($){return GG(WG($,void 0,db),$+"")}var ib=d$$;var i$$=ib(function($,Q){return $==null?{}:ub($,Q)}),UG=i$$;import{dirname as s$$,join as s1,resolve as XX}from"path";import{join as n$$}from"path";var r$$="remote-settings.json",bz=null,o$$;function nb(){return}function t$$(){return nb()??n$$(p6(),r$$)}function a$$(){try{let $=u0(t$$()),Q=g$(rW($));if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;return Q}catch{return null}}function rb(){if(!nb()&&o$$!==!0)return null;if(bz)return bz;let $=a$$();if($)return bz=$,z0(),$;return null}function kz($){let Q=new Set($.allowedSources);return Q.add("flagSettings"),Q.add("policySettings"),fE.filter((J)=>Q.has(J))}function e$$(){return s1(l0(),"managed-settings.json")}function tb($){if(m0()==="wsl"&&$.wslInherits?.()){let Q=_z(b9);if(Q.settings)return Q;let J=_z(l0());return{settings:J.settings,errors:[...Q.errors,...J.errors]}}return _z(l0())}function _z($){let Q=[],J={},Y=!1,{settings:X,errors:W}=HG(s1($,"managed-settings.json"));if(Q.push(...W),X&&Object.keys(X).length>0)J=G1(J,X,a1),Y=!0;let G=s1($,"managed-settings.d");try{let q=c$().readdirSync(G).filter((V)=>(V.isFile()||V.isSymbolicLink())&&V.name.endsWith(".json")&&!V.name.startsWith(".")).map((V)=>V.name).sort();for(let V of q){let{settings:B,errors:z}=HG(s1(G,V));if(Q.push(...z),B&&Object.keys(B).length>0)J=G1(J,B,a1),Y=!0}}catch(q){let V=o$(q);if(V!=="ENOENT"&&V!=="ENOTDIR")X$(`managed-settings.d read failed: ${q}`,{level:"error"})}let{wslInheritsWindowsSettings:U,...H}=J;return{settings:Y&&Object.keys(H).length>0?J:null,errors:Q}}function $6$($,Q){if(Z1($))X$(`Broken symlink or missing file encountered for settings.json at path: ${Q}`);else X$(`settings file read failed at ${Q}: ${$}`,{level:"error"})}function HG($){let Q=kO($);if(Q)return{settings:Q.settings?A4(Q.settings):null,errors:Q.errors};let J=Q6$($);return vO($,J),{settings:J.settings?A4(J.settings):null,errors:J.errors}}function ab($){if(!$.mdm)return{settings:null,errors:[]};let Q=$.mdm();return{settings:Object.keys(Q.settings).length>0?Q.settings:null,errors:Q.errors}}function sb($){let Q=$?.remote?$.remote():rb();if(!Q||Object.keys(Q).length===0)return{settings:null,errors:[]};let J=A4(Q),Y=r1(J,"remote managed settings"),X=S4().safeParse(J);if(!X.success)return{settings:null,errors:[...Y,...i0(X.error,"remote managed settings")]};return{settings:Object.keys(X.data).length>0?X.data:null,errors:Y}}function eb($){let Q=$.parentManaged;if(!Q||Object.keys(Q).length===0)return{settings:null,errors:[]};let J=A4(Q),Y=r1(J,"parent managed settings"),X=S4().safeParse(J);if(!X.success)return{settings:null,errors:[...Y,...i0(X.error,"parent managed settings")]};return Object.keys(X.data).length>0?{settings:X.data,errors:Y}:{settings:null,errors:Y}}function $_($){let Q=$.flagInline;if(!Q)return{settings:null,errors:[]};let J=A4(Q),Y=r1(J,"SDK inline settings"),X=S4().safeParse(J);if(!X.success)return{settings:null,errors:[...Y,...i0(X.error,"SDK inline settings")]};return{settings:X.data,errors:Y}}function Q6$($){try{let{resolvedPath:Q}=H5(c$(),$),J=u0(Q);if(J.trim()==="")return{settings:{},errors:[]};let Y=A4(R9(J,!1)),X=r1(Y,$),W=S4().safeParse(Y);if(!W.success){let G=i0(W.error,$);return{settings:null,errors:[...X,...G]}}return{settings:W.data,errors:X}}catch(Q){return $6$(Q,$),{settings:null,errors:[]}}}function ob($,Q){switch($){case"userSettings":return XX(p6());case"policySettings":case"projectSettings":case"localSettings":return XX(Q.cwd);case"flagSettings":return Q.flagPath?s$$(XX(Q.flagPath)):XX(Q.cwd)}}function J6$($){if($.coworkPlugins||A$(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function YX($,Q){switch($){case"userSettings":return s1(ob($,Q),J6$(Q));case"projectSettings":case"localSettings":return s1(ob($,Q),X6$($));case"policySettings":return e$$();case"flagSettings":return Q.flagPath}}function X6$($){switch($){case"projectSettings":return s1(".claude","settings.json");case"localSettings":return s1(".claude","settings.local.json")}}function Q_($,Q){let J=_O($);if(J!==void 0)return J;let Y=U6$($,Q);return SO($,Y),Y}function Y6$($){return!$||$.parentSettingsBehavior==="merge"}function W6$($,Q){let J={};if($.allowManagedHooksOnly===!0)J.allowManagedHooksOnly=!0;if($.allowManagedMcpServersOnly===!0)J.allowManagedMcpServersOnly=!0;if($.allowManagedPermissionRulesOnly===!0)J.allowManagedPermissionRulesOnly=!0;let Y=$.strictPluginOnlyCustomization;if(Y===!0||Array.isArray(Y)&&Y.length>0)J.strictPluginOnlyCustomization=Y;if($.deniedMcpServers)J.deniedMcpServers=$.deniedMcpServers;if(Q.forceLoginOrgUUID===void 0&&$.forceLoginOrgUUID)J.forceLoginOrgUUID=$.forceLoginOrgUUID;if(Q.allowedMcpServers===void 0&&$.allowedMcpServers)J.allowedMcpServers=$.allowedMcpServers;if($.permissions){let X=UG($.permissions,["deny","ask"]);if($.permissions.disableBypassPermissionsMode==="disable")X.disableBypassPermissionsMode="disable";if(Q.allowManagedPermissionRulesOnly!==!0){let{allow:W,additionalDirectories:G}=$.permissions;if(W&&Q.sandbox?.network?.allowManagedDomainsOnly!==!0)X.allow=W;if(G)X.additionalDirectories=G}if(Object.keys(X).length>0)J.permissions=X}if($.sandbox){let{network:X,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(X){let U=UG(X,["deniedDomains"]);if(X.allowManagedDomainsOnly===!0)U.allowManagedDomainsOnly=!0;if(Q.sandbox?.network?.allowManagedDomainsOnly!==!0&&X.allowedDomains)U.allowedDomains=X.allowedDomains;if(Object.keys(U).length>0)G.network=U}if(W){let U=UG(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)J.sandbox=G}return J}function J_($){if($.helper?.())return"helper";if(sb($).settings)return"remote";if(ab($).settings)return m0()==="macos"?"plist":"hklm";if(($.file?.()??tb($)).settings)return"file";if(eb($).settings)return"parent";let Q=$.hkcu?.();return Q&&Object.keys(Q.settings).length>0?"hkcu":null}function G6$($){let Q=[],{settings:J,errors:Y}=sb($);Q.push(...Y);let{settings:X,errors:W}=ab($);Q.push(...W);let{settings:G,errors:U}=$.file?.()??tb($);Q.push(...U);let{settings:H,errors:q}=eb($);Q.push(...q);let V=[J,X,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&&Y6$(B)?W6$(H,z):null;return{tiers:V,admin:B,parentSlice:N,errors:Q}}function X_($){let Q=$.helper?.();if(Q)return{settings:Q,errors:$.helperWarnings?.()??[]};let{admin:J,parentSlice:Y,errors:X}=G6$($);if(!J&&!Y){let W=$.hkcu?.();if(W&&Object.keys(W.settings).length>0)return{settings:W.settings,errors:[...X,...W.errors]};return{settings:null,errors:[...X,...W?.errors??[]]}}return{settings:G1({},Y??{},J??{},a1),errors:X}}function U6$($,Q){if($==="policySettings")return X_(Q).settings;let J=YX($,Q),{settings:Y}=J?HG(J):{settings:null};if($==="flagSettings"){let{settings:X}=$_(Q);if(X)return G1(Y||{},X,a1)}return Y}function H6$($,Q){return b5([...$,...Q])}function a1($,Q){if(Array.isArray($)&&Array.isArray(Q))return H6$($,Q);return}var Sz=!1;function K6$($){if(Sz)return{settings:{},errors:[]};let Q=Date.now();iJ("info","settings_load_started"),Sz=!0;try{let J=CO(),Y={};if(J)Y=G1(Y,J,a1);let X=[],W=new Set,G=new Set;for(let U of kz($)){if(U==="policySettings"){let{settings:q,errors:V}=X_($);if(q)Y=G1(Y,q,a1);for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),X.push(B)}continue}let H=YX(U,$);if(H){let q=XX(H);if(!G.has(q)){G.add(q);let{settings:V,errors:B}=HG(H);for(let z of B){let N=`${z.file}:${z.path}:${z.message}`;if(!W.has(N))W.add(N),X.push(z)}if(V)Y=G1(Y,V,a1)}}if(U==="flagSettings"){let{settings:q,errors:V}=$_($);for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),X.push(B)}if(q)Y=G1(Y,q,a1)}}return iJ("info","settings_load_completed",{duration_ms:Date.now()-Q,source_count:G.size,error_count:X.length}),{settings:Y,errors:X}}finally{Sz=!1}}function q6$($){let Q=EO();if(Q!==null)return Q;let J=K6$($);return bO(J),J}function V6$($){let{settings:Q}=q6$($);return Q||{}}function Y_($){z0();let Q=[];for(let J of kz($)){let Y=Q_(J,$);if(Y&&Object.keys(Y).length>0)Q.push({source:J,settings:Y})}return{effective:V6$($),sources:Q}}function W_($,Q){let J=kz(Q);for(let Y=J.length-1;Y>=0;Y--){let X=J[Y];if(Q_(X,Q)?.[$]!==void 0)return X}return null}var z6$={user:"userSettings",project:"projectSettings",local:"localSettings"},G_={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},N6$=["user","project","local"],w6$=new Set(["bypassPermissions","auto","acceptEdits"]),O6$=new Set(["project"]);function D6$($){let Q=$.effective.permissions?.defaultMode;if(!Q||!w6$.has(Q))return $.effective;for(let J=$.sources.length-1;J>=0;J--){let Y=$.sources[J];if(Y.settings.permissions?.defaultMode!==void 0){if(O6$.has(Y.source)){let{defaultMode:X,...W}=$.effective.permissions??{};return{...$.effective,permissions:W}}return $.effective}}return $.effective}async function U_($={}){await Db();let Q={cwd:B6$($.cwd??c$().cwd()),allowedSources:($.settingSources??N6$).map((J)=>z6$[J]),parentManaged:$.managedSettings??null,flagInline:null,flagPath:void 0,mdm:Fb,hkcu:Zb,wslInherits:Mb,...$.serverManagedSettings!==void 0&&{remote:()=>$.serverManagedSettings}};try{let{effective:J,sources:Y}=Y_(Q),X=J_(Q)??void 0,W=Y.map(({source:U,settings:H})=>({source:G_[U],settings:H,path:U==="policySettings"?void 0:YX(U,Q),...U==="policySettings"&&{policyOrigin:X}})),G={};for(let U of Object.keys(J)){let H=W_(U,Q);if(H)G[U]={source:G_[H],path:H==="policySettings"?void 0:YX(H,Q),...H==="policySettings"&&{policyOrigin:X}}}return{effective:J,provenance:G,sources:W}}finally{z0()}}async function yj$($){return U_($)}async function b6$($,Q){try{await L6$($,Q)}catch(J){if(!Z1(J))throw J}}async function _6$($,Q){if(!$)return;let J=$;try{let Y=g$($);if(Y?.claudeAiOauth?.refreshToken)delete Y.claudeAiOauth.refreshToken,J=B$(Y)}catch{}await N_(Q,J,{mode:384})}function S6$(){if(process.platform!=="darwin")return Promise.resolve(void 0);let $=gZ(fZ);return new Promise((Q)=>{F6$("security",["find-generic-password","-a",hZ(),"-w","-s",$],{encoding:"utf-8",timeout:5000},(J,Y)=>Q(J?void 0:Y.trim()||void 0))})}async function D_($,Q,J,Y,X=60000){if(!Z$(Q))return;let W=J4(J),G=await C4($.load({projectKey:W,sessionId:Q}),X,`SessionStore.load() timed out after ${X}ms for session ${Q}`);if(!G||G.length===0)return;let U=u6(R6$(),`claude-resume-${fz()}`);try{let H=u6(U,"projects",W);await vz(H,{recursive:!0});let q=u6(H,`${Q}.jsonl`);await n7(q,G);let V=Y?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,B=V??u6(Cz(),".claude"),z;try{z=await z_(u6(B,".credentials.json"),"utf-8")}catch(N){if(!Z1(N))throw N}if(!V&&!(Y??process.env).ANTHROPIC_API_KEY&&!(Y??process.env).CLAUDE_CODE_OAUTH_TOKEN)z=await S6$()??z;if(await _6$(z,u6(U,".credentials.json")),await b6$(u6(V??Cz(),".claude.json"),u6(U,".claude.json")),$.listSubkeys){let N=u6(H,Q),w=await C4($.listSubkeys({projectKey:W,sessionId:Q}),X,`SessionStore.listSubkeys() timed out after ${X}ms for session ${Q}`);for(let O of w){let D=WX(N,O+".jsonl");if(!O||w_(O)||O.split(/[\\/]/).includes("..")||!D.startsWith(N+gz)){X$(`[SessionStore] skipping unsafe subpath from listSubkeys: ${O}`,{level:"warn"});continue}let M=await C4($.load({projectKey:W,sessionId:Q,subpath:O}),X,`SessionStore.load() timed out after ${X}ms for session ${Q} subpath ${O}`);if(!M||M.length===0)continue;let j=[],A=[];for(let k of M)if(yz(k))j.push(k);else A.push(k);if(A.length>0)await vz(H_(D),{recursive:!0}),await n7(D,A);if(j.length>0){let k=j.at(-1),u=WX(N,O+".meta.json");await vz(H_(u),{recursive:!0});let{type:G$,...u$}=k;await N_(u,B$(u$),{mode:384})}}}return U}catch(H){throw await KG(U),H}}function Tz($,Q,J,Y){let{systemPrompt:X,settings:W,managedSettings:G,settingSources:U,sandbox:H,...q}=$??{},V,B,z;if(X===void 0)V="";else if(typeof X==="string")V=X;else if(Array.isArray(X))V=X;else if(X.type==="preset")B=X.append,z=X.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.147";let{abortController:N=f9(),additionalDirectories:w=[],agent:O,agents:D,allowedTools:M=[],betas:j,canUseTool:A,continue:k,cwd:u,debug:G$,debugFile:u$,disallowedTools:e$=[],tools:m6,env:D6,executable:e1=VX()?"bun":"node",executableArgs:n0=[],extraArgs:k4={},fallbackModel:S9,enableFileCheckpointing:U1,toolConfig:i,forkSession:GX,hooks:UX,includeHookEvents:k9,includePartialMessages:v9,forwardSubagentText:C9,onElicitation:HX,persistSession:m$,sessionStore:s$,sessionStoreFlush:v4,thinking:T9,effort:j_,maxThinkingTokens:VG,maxTurns:A_,maxBudgetUsd:I_,taskBudget:R_,mcpServers:hz,model:P_,outputFormat:uz,permissionMode:E_="default",allowDangerouslySkipPermissions:b_=!1,permissionPromptToolName:__,plugins:S_,getOAuthToken:mz,getHostAuthToken:lz,workload:cz,resume:pz,resumeSessionAt:k_,sessionId:v_,skills:dz,stderr:C_,strictMcpConfig:T_}=q;if(s$&&m$===!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$&&k&&!pz&&!s$.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(s$&&U1)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)X$("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 BG=q.pathToClaudeCodeExecutable;if(!BG){let k6=E6$(import.meta.url),X4=I6$(k6),$0=U2((r0)=>X4.resolve(r0));if(!$0)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.`);BG=$0}let iz=uz?.type==="json_schema"?uz.schema:void 0,S6=D6?{...D6}:{...process.env};if(!S6.CLAUDE_CODE_ENTRYPOINT)S6.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(U1)S6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(mz)S6.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(lz)S6.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(i?.askUserQuestion?.previewFormat)S6.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=i.askUserQuestion.previewFormat;let zG={};if(qG.propagation.inject(qG.context.active(),zG),"traceparent"in zG){for(let k6 of["TRACEPARENT","TRACESTATE"])if(!(k6 in(D6??{})))delete S6[k6]}for(let[k6,X4]of Object.entries(zG)){let $0=k6.toUpperCase();if(!($0 in(D6??{})))S6[$0]=X4}let nz={},rz=new Map;if(hz)for(let[k6,X4]of Object.entries(hz))if(X4.type==="sdk"&&X4.instance)rz.set(k6,X4.instance);else nz[k6]=X4;let x9;if(T9)switch(T9.type){case"adaptive":x9={type:"adaptive",display:T9.display};break;case"enabled":x9={type:"enabled",budgetTokens:T9.budgetTokens,display:T9.display};break;case"disabled":x9={type:"disabled"};break}else if(VG!==void 0)x9=VG===0?{type:"disabled"}:{type:"enabled",budgetTokens:VG};if(J){if(S6.CLAUDE_CONFIG_DIR=J,process.platform==="win32")S6.CLAUDE_SECURESTORAGE_CONFIG_DIR=D6?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??D6?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let oz=new LU({abortController:N,additionalDirectories:w,agent:O,betas:j,cwd:u,debug:G$,debugFile:u$,executable:e1,executableArgs:n0,extraArgs:cz?{...k4,workload:cz}:k4,pathToClaudeCodeExecutable:BG,env:S6,forkSession:GX,stderr:C_,thinkingConfig:x9,effort:j_,maxTurns:A_,maxBudgetUsd:I_,taskBudget:R_,model:P_,fallbackModel:S9,jsonSchema:iz,permissionMode:E_,allowDangerouslySkipPermissions:b_,permissionPromptToolName:__,continueConversation:s$?void 0:k,resume:pz,resumeSessionAt:k_,sessionId:v_,settings:typeof W==="object"?B$(W):W,managedSettings:G?B$(G):void 0,settingSources:U,skills:dz,allowedTools:M,disallowedTools:e$,tools:m6,mcpServers:nz,strictMcpConfig:T_,canUseTool:!!A,hooks:!!UX,includeHookEvents:k9,includePartialMessages:v9,persistSession:m$,sessionMirror:!!s$,plugins:S_,sandbox:H,spawnClaudeCodeProcess:q.spawnClaudeCodeProcess,deferSpawn:Y}),x_={systemPrompt:V,appendSystemPrompt:B,planModeInstructions:q.planModeInstructions,appendSubagentSystemPrompt:q.appendSubagentSystemPrompt,toolAliases:q.toolAliases,excludeDynamicSections:z,agents:D,title:q.title,skills:dz,webSearchIsolationExemptMcpServers:q.webSearchIsolationExemptMcpServers,promptSuggestions:q.promptSuggestions,agentProgressSummaries:q.agentProgressSummaries,forwardSubagentText:C9},NG=new RU(oz,Q,A,UX,N,rz,iz,x_,HX,mz,lz);if(s$){let k6=()=>u6(S6.CLAUDE_CONFIG_DIR??u6(Cz(),".claude"),"projects"),X4=v4==="eager",$0=new PU(async(r0,wG)=>{let y9=B_(r0,k6());if(y9)await s$.append(y9,wG);else X$(`[SessionStore] dropping mirror frame: filePath ${r0} is not under ${k6()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(r0,wG)=>{let y9=B_(r0,k6());if(y9)NG.reportMirrorError(y9,wG.message)},X4?0:z5,X4?0:N5);NG.setTranscriptMirrorBatcher($0)}return{queryInstance:NG,transport:oz,abortController:N,processEnv:S6}}function xz($,Q,J,Y){if(typeof J==="string")Q.write(B$({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:J}]},parent_tool_use_id:null})+`
|
|
115
|
+
`)){let Y=J.match(/^(ID|VERSION_ID)=(.*)$/);if(Y&&Y[1]&&Y[2]){let X=Y[2].replace(/^"|"$/g,"");if(Y[1]==="ID")$.linuxDistroId=X;else $.linuxDistroVersion=X}}}catch{}return $});var jD$=v$(()=>{if(process.platform!=="darwin")return;let Q=zE().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"}}),ED$=v$(function(){return rs(l0(),"managed-settings.d")});import{isAbsolute as NE}from"path";var os=b(()=>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()),ts=b(()=>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()),wE=b(()=>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:os(),filesystem:ts(),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"&&NE($)?$: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"&&NE($)?$: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 OE=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],DE=["normal","vim"],FE=["auto","tmux","in-process"],as=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],ZE=["auto",...as];var xD$=m0()==="macos"?"⏺":"●";var rJ=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],ss=[...rJ,"bubble"],ME=ss;var cD$=b(()=>vV.enum(ME)),pD$=b(()=>vV.enum(rJ));var LE=["bash","powershell"];var oJ=b(()=>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 es(){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:oJ(),shell:K.enum(LE).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:oJ(),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")}),J=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:oJ(),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:oJ(),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")}),X=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:oJ(),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:X,McpToolHookSchema:J}}var jE=b(()=>{let{BashCommandHookSchema:$,PromptHookSchema:Q,AgentHookSchema:J,HttpHookSchema:Y,McpToolHookSchema:X}=es();return K.discriminatedUnion("type",[$,Q,J,Y,X])}),AE=b(()=>K.object({matcher:K.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:K.array(jE()).describe("List of hooks to execute when the matcher matches")})),c0=b(()=>K.partialRecord(K.enum(o0),K.array(AE())));var $F$=b(()=>K.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),QF$=b(()=>K.enum(["stdio","sse","sse-ide","http","ws","sdk"])),P9=b(()=>K.literal("comms").optional().catch(void 0)),n1=b(()=>K.number().int().positive()),$e=b(()=>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(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Qe=b(()=>K.boolean()),IE=b(()=>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:Qe().optional()})),Je=b(()=>K.object({type:K.literal("sse"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),oauth:IE().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Xe=b(()=>K.object({type:K.literal("sse-ide"),url:K.string(),ideName:K.string(),ideRunningInWindows:K.boolean().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Ye=b(()=>K.object({type:K.literal("ws-ide"),url:K.string(),ideName:K.string(),authToken:K.string().optional(),ideRunningInWindows:K.boolean().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),We=b(()=>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:IE().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Ge=b(()=>K.object({type:K.literal("ws"),url:K.string(),headers:K.record(K.string(),K.string()).optional(),headersHelper:K.string().optional(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),role:P9()})),Ue=b(()=>K.object({type:K.literal("sdk"),name:K.string(),timeout:n1().optional(),alwaysLoad:K.boolean().optional()})),He=b(()=>K.enum(["allow","ask","blocked"])),Ke=b(()=>K.object({type:K.literal("claudeai-proxy"),url:K.string(),id:K.string(),timeout:n1().optional(),alwaysLoad:K.boolean().optional(),toolPermissions:K.record(K.string(),He()).optional()})),sW=b(()=>K.union([$e(),Je(),Xe(),Ye(),We(),Ge(),Ue(),Ke()])),JF$=b(()=>K.object({mcpServers:K.record(K.string(),sW())}));var bE=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins"]);var qe=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,Ve=/[^\u0020-\u007E]/;function Be($){if(bE.has($.toLowerCase()))return!1;if(Ve.test($))return!0;return qe.test($)}var Z4=b(()=>K.string().startsWith("./")),p0=b(()=>Z4().endsWith(".json")),RE=b(()=>K.union([Z4().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")])),Mz=b(()=>Z4().endsWith(".md")),Lz=b(()=>K.union([Mz(),Z4()])),_E=b(()=>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(($)=>!Be($),{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/'})),jz=b(()=>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")})),ze=b(()=>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)"),displayName:K.string().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version: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:jz().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(fe()).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.`)})),qF$=b(()=>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")})),Ne=b(()=>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)")]))])})),we=b(()=>K.object({source:Lz().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'})),Oe=b(()=>K.object({commands:K.union([Lz().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(Lz().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(),we()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),De=b(()=>K.object({agents:K.union([Mz().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(Mz().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.")])})),Fe=b(()=>K.object({skills:K.union([Z4().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory."),K.array(Z4().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.")])})),SE=b(()=>K.object({outputStyles:K.union([Z4().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(Z4().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=b(()=>K.object({themes:K.union([Z4().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(Z4().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.")])})),Ze=b(()=>K.object({})),PE=b(()=>K.string().min(1)),Me=b(()=>K.string().min(2).refine(($)=>$.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),Le=b(()=>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)"),RE().describe("Path or URL to MCPB file containing MCP server configuration"),K.record(K.string(),sW()).describe("MCP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to MCP servers configuration file"),RE().describe("Path or URL to MCPB file"),K.record(K.string(),sW()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),vE=b(()=>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()),je=b(()=>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.")})),Ae=b(()=>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.")})),EE=b(()=>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(PE()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:K.record(Me(),PE()).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")})),Ie=b(()=>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).')})),Re=b(()=>K.array(Ie()).refine(($)=>new Set($.map((Q)=>Q.name)).size===$.length,{message:"Monitor names must be unique within a plugin"})),CE=b(()=>K.object({monitors:K.union([p0().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Re()]).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.")})),Pe=b(()=>K.object({lspServers:K.union([p0().describe("Path to .lsp.json configuration file relative to plugin root"),K.record(K.string(),EE()).describe("LSP server configurations keyed by server name"),K.array(K.union([p0().describe("Path to LSP configuration file"),K.record(K.string(),EE()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),TE=b(()=>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-._]*$/,J=/^[a-z0-9][a-z0-9-._]*$/;return Q.test($)||J.test($)},"Invalid npm package name format")),Ee=b(()=>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.")})),be=b(()=>K.object({experimental:K.preprocess(($)=>typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0,K.object({...kE().partial().shape,...CE().partial().shape,...SE().partial().shape,evals:K.union([K.string(),K.array(K.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),_e=b(()=>K.object({...ze().shape,...Ne().partial().shape,...Oe().partial().shape,...De().partial().shape,...Fe().partial().shape,...SE().partial().shape,...kE().partial().shape,...Ze().shape,...Ae().partial().shape,...Le().partial().shape,...Pe().partial().shape,...CE().partial().shape,...Ee().partial().shape,...je().partial().shape,...be().partial().shape})),tJ=b(()=>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("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),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(($)=>!bE.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(Se()).describe("Plugin entries declared inline in settings.json"),owner:jz().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).")])),Zz=b(()=>K.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),xE=b(()=>K.union([Z4().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:Zz().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:Zz().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:Zz().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.')])),Se=b(()=>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 ke=b(()=>K.object({cli:K.array(K.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:K.array(K.string().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) — exact, case-insensitive match against '+"hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path."),filePath:K.string().max(256).optional().describe("RegExp source matched (case-insensitive) against file paths read this session, or present in cwd at session start."),manifestDeps:K.array(K.object({file:K.string().max(256),pattern:K.string().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: "+"`file` matches the manifest filename (package.json, go.mod, requirements.txt, …); "+"`pattern` matches the dependency declaration inside that file. Evaluated against files read this session, or present in cwd at session start.")})),ve=b(()=>K.object({topic:K.string().max(64).optional().describe('What the user is working with when this plugin is relevant — fills "Working with {topic}?". '+'Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:ke().optional().describe("Matchers that determine when the plugin is relevant.")})),Ce=b(()=>_e().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."),relevance:K.preprocess(($)=>typeof $==="object"&&$!==null&&!Array.isArray($)?$:void 0,ve().optional()).describe(`Declares when this plugin is relevant to the user's work. Consumed by the spinner tip ("Working with {topic}?"), session-start auto-suggest, and marketplace browse ranking.`)})),Te=b(()=>K.object({name:K.string().min(1).refine(($)=>!$.includes(" "))}));function xe($){let Q=Ce();return $.flatMap((J,Y)=>{let X=Q.safeParse(J);if(X.success)return[X.data];let W=Te().safeParse(J).data?.name,G=X.error.issues.map((U)=>`${U.path.join(".")}: ${U.message}`).join(", ");if(W)return X$(`Stubbing unparseable marketplace plugin entry (${W}): ${G}`,{level:"warn"}),[{name:W,source:{source:"unsupported"},strict:!0}];return X$(`Dropping unparseable marketplace plugin entry (index ${Y}): ${G}`,{level:"warn"}),[]})}var VF$=b(()=>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:jz().describe("Marketplace maintainer or curator information"),plugins:K.array(K.unknown()).transform(xe).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=b(()=>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")),ye=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,fe=b(()=>K.union([K.string().regex(ye,"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)])),ge=b(()=>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).")})),he=b(()=>K.object({version:K.literal(1).describe("Schema version 1"),plugins:K.record(yE(),ge()).describe("Map of plugin IDs to their installation metadata")})),ue=b(()=>K.enum(["managed","user","project","local"])),me=b(()=>K.object({scope:ue().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.")})),le=b(()=>K.object({version:K.literal(2).describe("Schema version 2"),plugins:K.record(yE(),K.array(me())).describe("Map of plugin IDs to arrays of installation entries")})),BF$=b(()=>K.union([he(),le()])),ce=b(()=>K.object({source:tJ().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")})),zF$=b(()=>K.record(K.string(),ce()));var fE=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var gE="https://json.schemastore.org/claude-code-settings.json";var pe=["autoMode","deepLink","voice","assistant","briefView"],eW={},$G={autoMode:{buildGate:()=>!1,shape:()=>eW,permissionsShape:()=>eW,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:K.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>eW},assistant:{buildGate:()=>!1,shape:()=>eW},briefView:{buildGate:()=>!0,shape:()=>({defaultView:K.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})}};function Az(){return pe.filter(($)=>$G[$].buildGate())}function hE($){let Q={};for(let J of $)Q={...Q,...$G[J].shape()};return Q}function uE($){let Q={};for(let J of $)Q={...Q,...$G[J].permissionsShape?.()};return Q}function mE($){let Q=[];for(let J of $)Q.push(...$G[J].permissionModes?.()??[]);return Q}function lE($){let Q=$.split("__"),[J,Y,...X]=Q;if(J!=="mcp"||!Y)return null;let W=X.length>0?X.join("__"):void 0;return{serverName:Y,toolName:W}}var cE={Task:"Agent",KillShell:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage"};function E9($){return Object.hasOwn(cE,$)?cE[$]:$}var pE="workspace",EF$=`mcp__${pE}__bash`,bF$=`mcp__${pE}__web_fetch`;function de($){return $.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function dE($){let Q=ie($,"(");if(Q===-1)return{toolName:E9($)};let J=ne($,")");if(J===-1||J<=Q)return{toolName:E9($)};if(J!==$.length-1)return{toolName:E9($)};let Y=$.substring(0,Q),X=$.substring(Q+1,J);if(!Y)return{toolName:E9($)};if(X===""||X==="*")return{toolName:E9(Y)};let W=de(X);return{toolName:E9(Y),ruleContent:W}}function ie($,Q){for(let J=0;J<$.length;J++)if($[J]===Q){let Y=0,X=J-1;while(X>=0&&$[X]==="\\")Y++,X--;if(Y%2===0)return J}return-1}function ne($,Q){for(let J=$.length-1;J>=0;J--)if($[J]===Q){let Y=0,X=J-1;while(X>=0&&$[X]==="\\")Y++,X--;if(Y%2===0)return J}return-1}var QG={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 iE($){return QG.filePatternTools.includes($)}function nE($){return QG.bashPrefixTools.includes($)}function rE($){return Object.hasOwn(QG.customValidation,$)?QG.customValidation[$]:void 0}function oE($,Q){let J=0,Y=Q-1;while(Y>=0&&$[Y]==="\\")J++,Y--;return J%2!==0}function Iz($,Q){let J=0;for(let Y=0;Y<$.length;Y++)if($[Y]===Q&&!oE($,Y))J++;return J}function re($){for(let Q=0;Q<$.length-1;Q++)if($[Q]==="("&&$[Q+1]===")"){if(!oE($,Q))return!0}return!1}function Rz($){if(!$||$.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let Q=Iz($,"("),J=Iz($,")");if(Q!==J)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(re($)){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=dE($),X=lE(Y.toolName);if(X){if(Y.ruleContent!==void 0||Iz($,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${Y.toolName}" without parentheses, or use "mcp__${X.serverName}__*" for all tools`,examples:[`mcp__${X.serverName}`,`mcp__${X.serverName}__*`,X.toolName&&X.toolName!=="*"?`mcp__${X.serverName}__${X.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 "${BU(String(Y.toolName))}"`};let W=rE(Y.toolName);if(W&&Y.ruleContent!==void 0){let G=W(Y.ruleContent);if(!G.valid)return G}if(nE(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(iE(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 JG=b(()=>K.string().superRefine(($,Q)=>{let J=Rz($);if(!J.valid){let Y=J.error;if(J.suggestion)Y+=`. ${J.suggestion}`;if(J.examples&&J.examples.length>0)Y+=`. Examples: ${J.examples.join(", ")}`;Q.addIssue({code:K.ZodIssueCode.custom,message:Y,params:{received:$}})}}));var oe=b(()=>K.record(K.string(),K.coerce.string()));function aE($){return K.object({allow:K.array(JG()).optional().describe("List of permission rules for allowed operations"),deny:K.array(JG()).optional().describe("List of permission rules for denied operations"),ask:K.array(JG()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:K.enum([...rJ,...mE($)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:K.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...uE($),additionalDirectories:K.array(K.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var tF$=b(()=>aE(Az())),te=b(()=>K.object({source:tJ().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")})),ae=b(()=>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 kH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),se=b(()=>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 kH([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),ee=b(()=>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()})),tE=["skills","agents","hooks","mcp"];function sE($){return K.object({$schema:K.literal(gE).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:ee().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...A$(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:oe().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:aE($).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(ae()).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(se()).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."),bgIsolation:K.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks: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((J)=>tE.includes(J)):Q,K.union([K.boolean(),K.array(K.enum(tE))])).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(),te()).check((Q)=>{for(let[J,Y]of Object.entries(Q.value))if(Y.source.source==="settings"&&Y.source.name!==J)Q.issues.push({code:"custom",input:Y.source.name,path:[J,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${J}" 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(tJ()).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(tJ()).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:wE().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(ZE),K.string().startsWith("custom:").transform((Q)=>Q)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:K.enum(DE).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(OE).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(FE).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"),...hE($)}).passthrough()}var S4=b(()=>sE(Az()));var W1="https://code.claude.com/docs/en",$$$=[{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:`${W1}/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:`${W1}/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:`${W1}/hooks`}},{matches:($)=>/\.hooks\.\d+\.command$/.test($.path)&&$.code==="invalid_type"&&$.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${W1}/hooks#exec-form-and-shell-form`}},{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:`${W1}/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:`${W1}/iam#working-directories`}}],Q$$={permissions:`${W1}/iam#configuring-permissions`,env:`${W1}/settings#environment-variables`,hooks:`${W1}/hooks`};function eE($){let Q=$$$.find((Y)=>Y.matches($));if(!Q)return null;let J={...Q.tip};if($.code==="invalid_value"&&$.enumValues&&!J.suggestion)J.suggestion=`Valid values: ${$.enumValues.map((Y)=>`"${Y}"`).join(", ")}`;if(!J.docLink&&$.path)J.docLink=Q$$[dO($.path,".")];return J}var zZ$=b(()=>S4().strict());function $b($){return $.code==="invalid_type"}function Qb($){return $.code==="invalid_value"}function J$$($){return $.code==="unrecognized_keys"}function Jb($){return $.code==="too_small"}function aJ($){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((J)=>{let Y=J.path.map(String).join("."),X=J.message,W,G,U,H,q;if(Qb(J))G=J.values.map((B)=>String(B)),U=G.join(" | "),H=void 0,q=void 0;else if($b(J)){U=J.expected;let B=Xb(J.message);H=B??aJ(J.input),q=B??aJ(J.input)}else if(Jb(J))U=String(J.minimum);else if(J.code==="custom"&&"params"in J)H=J.params.received,q=H;let V=eE({path:Y,code:J.code,expected:U,received:H,enumValues:G,message:J.message,value:H});if(Qb(J))W=G?.map((B)=>`"${B}"`).join(", "),X=`Invalid value. Expected one of: ${W}`;else if($b(J)){let B=Xb(J.message)??aJ(J.input);if(J.expected==="object"&&B==="null"&&Y==="")X="Invalid or malformed JSON";else X=`Expected ${J.expected}, but received ${B}`}else if(J$$(J)){let B=J.keys.join(", ");X=`Unrecognized ${pO(J.keys.length,"field")}: ${B}`}else if(Jb(J))X=`Number must be greater than or equal to ${J.minimum}`,W=String(J.minimum);return{file:Q,path:Y,message:X,expected:W,invalidValue:q,suggestion:V?.suggestion,docLink:V?.docLink}})}function X$$($,Q){if(!$||typeof $!=="object")return[];let J=$;if(!J.permissions||typeof J.permissions!=="object")return[];let Y=J.permissions,X=[];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 X.push({file:Q,path:`permissions.${W}`,message:`Non-string value in ${W} array was removed`,severity:"warning",invalidValue:U}),!1;let H=Rz(U);if(!H.valid){let q=`Invalid permission rule "${U}" was skipped: ${H.error}`;if(H.suggestion)q+=`. ${H.suggestion}`;return X.push({file:Q,path:`permissions.${W}`,message:q,severity:"warning",invalidValue:U}),!1}return!0})}return X}var Y$$=new Set(o0);function W$$($,Q){if(!$||typeof $!=="object")return[];let J=$;if(!("hooks"in J))return[];if(J.hooks===null||typeof J.hooks!=="object"||Array.isArray(J.hooks)){let W=aJ(J.hooks);return delete J.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=J.hooks,X=[];for(let W of Object.keys(Y)){if(!Y$$.has(W)){delete Y[W],X.push({file:Q,path:`hooks.${W}`,message:`Unknown hook event "${W}" was ignored. Valid events: ${o0.join(", ")}`,severity:"warning",invalidValue:W,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(Y[W])){let G=aJ(Y[W]);delete Y[W],X.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(X.length>0&&Object.keys(Y).length===0)delete J.hooks;return X}function r1($,Q){return[...X$$($,Q),...W$$($,Q)]}import{userInfo as G$$}from"os";var Yb="com.anthropic.claudecode",sJ="HKLM\\SOFTWARE\\Policies\\ClaudeCode",eJ="HKCU\\SOFTWARE\\Policies\\ClaudeCode",o1="Settings",Wb="/usr/bin/plutil",Gb=["-convert","json","-o","-","--"],Ub=5000,Pz="/mnt/c/Windows/System32/reg.exe",b9="/mnt/c/Program Files/ClaudeCode";function XG(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let $=v6("fs").readFileSync("/proc/version","utf8").toLowerCase();return $.includes("microsoft")||$.includes("wsl")}catch{return!1}}function Hb(){let $="";try{$=G$$().username}catch{}let Q=[];if($)Q.push({path:`/Library/Managed Preferences/${$}/${Yb}.plist`,label:"per-user managed preferences"});return Q.push({path:`/Library/Managed Preferences/${Yb}.plist`,label:"device-level managed preferences"}),Q}import{execFile as U$$}from"child_process";import{existsSync as H$$}from"fs";var K$$=null;function $X($,Q){return new Promise((J)=>{try{U$$($,Q,{encoding:"utf-8",timeout:Ub},(Y,X)=>{J({stdout:X??"",code:Y?1:0})})}catch{J({stdout:"",code:1})}})}function Kb(){return(async()=>{if(process.platform==="darwin"){let $=Hb(),J=(await Promise.all($.map(async({path:Y,label:X})=>{if(!H$$(Y))return{stdout:"",label:X,ok:!1};let{stdout:W,code:G}=await $X(Wb,[...Gb,Y]);return{stdout:W,label:X,ok:G===0&&!!W}}))).find((Y)=>Y.ok);return{plistStdouts:J?[{stdout:J.stdout,label:J.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let Q=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[J,Y]=await Promise.all([$X(Q,["query",sJ,"/v",o1]),$X(Q,["query",eJ,"/v",o1])]);return{plistStdouts:null,hklmStdout:J.code===0?J.stdout:null,hkcuStdout:Y.code===0?Y.stdout:null}}if(XG()){let[$,Q]=await Promise.all([$X(Pz,["query",sJ,"/v",o1]),$X(Pz,["query",eJ,"/v",o1])]);return{plistStdouts:null,hklmStdout:$.code===0?$.stdout:null,hkcuStdout:Q.code===0?Q.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function qb(){return K$$}var t1=Object.freeze({settings:{},errors:[]}),Nb=null,wb=null,Ob=!1,YG=null;function q$$(){if(YG)return;YG=(async()=>{let $=Date.now(),Q=qb()??Kb(),{mdm:J,hkcu:Y,wslInherits:X}=V$$(await Q);Nb=J,wb=Y,Ob=X;let W=Date.now()-$;if(X$(`MDM settings load completed in ${W}ms`),Object.keys(J.settings).length>0){X$(`MDM settings found: ${Object.keys(J.settings).join(", ")}`);try{iJ("info","mdm_settings_loaded",{duration_ms:W,key_count:Object.keys(J.settings).length,error_count:J.errors.length})}catch{}}})()}async function Db(){if(!YG)q$$();await YG}function Fb(){return Nb??t1}function Zb(){return wb??t1}function Mb(){return Ob}function Ez($,Q){let J=A4(R9($,!1));if(!J||typeof J!=="object")return{settings:{},errors:[]};let Y=r1(J,Q),X=S4().safeParse(J);if(!X.success){let W=i0(X.error,Q);return{settings:{},errors:[...Y,...W]}}return{settings:X.data,errors:Y}}function Vb($,Q="Settings"){let J=$.split(/\r?\n/),Y=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=new RegExp(`^\\s+${Y}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let W of J){let G=W.match(X);if(G&&G[1])return G[1].trimEnd()}return null}function V$$($){let Q=[];if($.plistStdouts&&$.plistStdouts.length>0){let{stdout:G,label:U}=$.plistStdouts[0],H=Ez(G,U),{wslInheritsWindowsSettings:q,...V}=H.settings;if(Object.keys(V).length>0)return{mdm:H,hkcu:t1,wslInherits:!1};Q.push(...H.errors)}let J=null;if($.hklmStdout){let G=Vb($.hklmStdout);if(G)J=Ez(G,`Registry: ${sJ}\\${o1}`)}if(J)Q.push(...J.errors);let Y=Q.length>0?{settings:{},errors:Q}:t1,X=XG(),W=!1;if(X){if(W=J?.settings.wslInheritsWindowsSettings===!0||z$$(),!W)return{mdm:Y,hkcu:t1,wslInherits:!1}}if(J){let{wslInheritsWindowsSettings:G,...U}=J.settings;if(Object.keys(U).length>0)return{mdm:J,hkcu:t1,wslInherits:W}}if(B$$(W))return{mdm:Y,hkcu:t1,wslInherits:W};if($.hkcuStdout){let G=Vb($.hkcuStdout);if(G){let U=Ez(G,`Registry: ${eJ}\\${o1}`);if(!X||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:t1,wslInherits:W}}function B$$($){if($&&zb(b9))return!0;return zb(l0())}function Bb($){let Q=A4(R9(u0($),!1));if(!Q||typeof Q!=="object")return!1;r1(Q,$);let{wslInheritsWindowsSettings:J,...Y}=Q;return Object.keys(Y).length>0}function z$$(){function $(Q){try{let J=R9(u0(Q),!1);return!!J&&typeof J==="object"&&"wslInheritsWindowsSettings"in J&&J.wslInheritsWindowsSettings===!0}catch{return!1}}if($(_9(b9,"managed-settings.json")))return!0;try{let Q=_9(b9,"managed-settings.d");for(let J of c$().readdirSync(Q))if((J.isFile()||J.isSymbolicLink())&&J.name.endsWith(".json")&&!J.name.startsWith(".")&&$(_9(Q,J.name)))return!0}catch{}return!1}function zb($){try{if(Bb(_9($,"managed-settings.json")))return!0}catch{}try{let Q=_9($,"managed-settings.d"),J=c$().readdirSync(Q);for(let Y of J){if(!(Y.isFile()||Y.isSymbolicLink())||!Y.name.endsWith(".json")||Y.name.startsWith("."))continue;try{if(Bb(_9(Q,Y.name)))return!0}catch{}}}catch{}return!1}function N$$($,Q,J){if(J!==void 0&&!q1($[Q],J)||J===void 0&&!(Q in $))M8($,Q,J)}var QX=N$$;function w$$($){return function(Q,J,Y){var X=-1,W=Object(Q),G=Y(Q),U=G.length;while(U--){var H=G[$?U:++X];if(J(W[H],H,W)===!1)break}return Q}}var Lb=w$$;var O$$=Lb(),jb=O$$;function D$$($){return r6($)&&j8($)}var Ab=D$$;var F$$="[object Object]",Z$$=Function.prototype,M$$=Object.prototype,Ib=Z$$.toString,L$$=M$$.hasOwnProperty,j$$=Ib.call(Object);function A$$($){if(!r6($)||L4($)!=F$$)return!1;var Q=W5($);if(Q===null)return!0;var J=L$$.call(Q,"constructor")&&Q.constructor;return typeof J=="function"&&J instanceof J&&Ib.call(J)==j$$}var Rb=A$$;function I$$($,Q){if(Q==="constructor"&&typeof $[Q]==="function")return;if(Q=="__proto__")return;return $[Q]}var JX=I$$;function R$$($){return lw($,J5($))}var Pb=R$$;function P$$($,Q,J,Y,X,W,G){var U=JX($,J),H=JX(Q,J),q=G.get(H);if(q){QX($,J,q);return}var V=W?W(U,H,J+"",$,Q,G):void 0,B=V===void 0;if(B){var z=V6(H),N=!z&&T7(H),w=!z&&!N&&$5(H);if(V=H,z||N||w)if(V6(U))V=U;else if(Ab(U))V=UO(U);else if(N)B=!1,V=UU(H,!0);else if(w)B=!1,V=qO(H,!0);else V=[];else if(Rb(H)||u4(H)){if(V=U,u4(U))V=Pb(U);else if(!$6(U)||t0(U))V=zO(H)}else B=!1}if(B)G.set(H,V),X(V,H,Y,W,G),G.delete(H);QX($,J,V)}var Eb=P$$;function bb($,Q,J,Y,X){if($===Q)return;jb(Q,function(W,G){if(X||(X=new mw),$6(W))Eb($,Q,G,J,bb,Y,X);else{var U=Y?Y(JX($,G),W,G+"",$,Q,X):void 0;if(U===void 0)U=W;QX($,G,U)}},J5)}var _b=bb;function E$$($,Q,J){switch(J.length){case 0:return $.call(Q);case 1:return $.call(Q,J[0]);case 2:return $.call(Q,J[0],J[1]);case 3:return $.call(Q,J[0],J[1],J[2])}return $.apply(Q,J)}var Sb=E$$;var kb=Math.max;function b$$($,Q,J){return Q=kb(Q===void 0?$.length-1:Q,0),function(){var Y=arguments,X=-1,W=kb(Y.length-Q,0),G=Array(W);while(++X<W)G[X]=Y[Q+X];X=-1;var U=Array(Q+1);while(++X<Q)U[X]=Y[X];return U[Q]=J(G),Sb($,this,U)}}var WG=b$$;function _$$($){return function(){return $}}var vb=_$$;var S$$=!Z8?G5:function($,Q){return Z8($,"toString",{configurable:!0,enumerable:!1,value:vb(Q),writable:!0})},Cb=S$$;var k$$=800,v$$=16,C$$=Date.now;function T$$($){var Q=0,J=0;return function(){var Y=C$$(),X=v$$-(Y-J);if(J=Y,X>0){if(++Q>=k$$)return arguments[0]}else Q=0;return $.apply(void 0,arguments)}}var Tb=T$$;var x$$=Tb(Cb),GG=x$$;function y$$($,Q){return GG(WG($,Q,G5),$+"")}var xb=y$$;function f$$($,Q,J){if(!$6(J))return!1;var Y=typeof Q;if(Y=="number"?j8(J)&&M1(Q,J.length):Y=="string"&&(Q in J))return q1(J[Q],$);return!1}var yb=f$$;function g$$($){return xb(function(Q,J){var Y=-1,X=J.length,W=X>1?J[X-1]:void 0,G=X>2?J[2]:void 0;if(W=$.length>3&&typeof W=="function"?(X--,W):void 0,G&&yb(J[0],J[1],G))W=X<3?void 0:W,X=1;Q=Object(Q);while(++Y<X){var U=J[Y];if(U)$(Q,U,Y,W)}return Q})}var fb=g$$;var h$$=fb(function($,Q,J,Y){_b($,Q,J,Y)}),G1=h$$;function u$$($,Q,J,Y){if(!$6($))return $;Q=L1(Q,$);var X=-1,W=Q.length,G=W-1,U=$;while(U!=null&&++X<W){var H=I8(Q[X]),q=J;if(H==="__proto__"||H==="constructor"||H==="prototype")return $;if(X!=G){var V=U[H];if(q=Y?Y(V,H,U):void 0,q===void 0)q=$6(V)?V:M1(Q[X+1])?[]:{}}rX(U,H,q),U=U[H]}return $}var gb=u$$;function m$$($,Q,J){var Y=-1,X=Q.length,W={};while(++Y<X){var G=Q[Y],U=AO($,G);if(J(U,G))gb(W,L1(G,$),U)}return W}var hb=m$$;function l$$($,Q){return hb($,Q,function(J,Y){return PO($,Y)})}var ub=l$$;var mb=c6?c6.isConcatSpreadable:void 0;function c$$($){return V6($)||u4($)||!!(mb&&$&&$[mb])}var lb=c$$;function cb($,Q,J,Y,X){var W=-1,G=$.length;J||(J=lb),X||(X=[]);while(++W<G){var U=$[W];if(Q>0&&J(U))if(Q>1)cb(U,Q-1,J,Y,X);else HO(X,U);else if(!Y)X[X.length]=U}return X}var pb=cb;function p$$($){var Q=$==null?0:$.length;return Q?pb($,1):[]}var db=p$$;function d$$($){return GG(WG($,void 0,db),$+"")}var ib=d$$;var i$$=ib(function($,Q){return $==null?{}:ub($,Q)}),UG=i$$;import{dirname as s$$,join as s1,resolve as XX}from"path";import{join as n$$}from"path";var r$$="remote-settings.json",bz=null,o$$;function nb(){return}function t$$(){return nb()??n$$(p6(),r$$)}function a$$(){try{let $=u0(t$$()),Q=g$(rW($));if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;return Q}catch{return null}}function rb(){if(!nb()&&o$$!==!0)return null;if(bz)return bz;let $=a$$();if($)return bz=$,z0(),$;return null}function kz($){let Q=new Set($.allowedSources);return Q.add("flagSettings"),Q.add("policySettings"),fE.filter((J)=>Q.has(J))}function e$$(){return s1(l0(),"managed-settings.json")}function tb($){if(m0()==="wsl"&&$.wslInherits?.()){let Q=_z(b9);if(Q.settings)return Q;let J=_z(l0());return{settings:J.settings,errors:[...Q.errors,...J.errors]}}return _z(l0())}function _z($){let Q=[],J={},Y=!1,{settings:X,errors:W}=HG(s1($,"managed-settings.json"));if(Q.push(...W),X&&Object.keys(X).length>0)J=G1(J,X,a1),Y=!0;let G=s1($,"managed-settings.d");try{let q=c$().readdirSync(G).filter((V)=>(V.isFile()||V.isSymbolicLink())&&V.name.endsWith(".json")&&!V.name.startsWith(".")).map((V)=>V.name).sort();for(let V of q){let{settings:B,errors:z}=HG(s1(G,V));if(Q.push(...z),B&&Object.keys(B).length>0)J=G1(J,B,a1),Y=!0}}catch(q){let V=o$(q);if(V!=="ENOENT"&&V!=="ENOTDIR")X$(`managed-settings.d read failed: ${q}`,{level:"error"})}let{wslInheritsWindowsSettings:U,...H}=J;return{settings:Y&&Object.keys(H).length>0?J:null,errors:Q}}function $6$($,Q){if(Z1($))X$(`Broken symlink or missing file encountered for settings.json at path: ${Q}`);else X$(`settings file read failed at ${Q}: ${$}`,{level:"error"})}function HG($){let Q=kO($);if(Q)return{settings:Q.settings?A4(Q.settings):null,errors:Q.errors};let J=Q6$($);return vO($,J),{settings:J.settings?A4(J.settings):null,errors:J.errors}}function ab($){if(!$.mdm)return{settings:null,errors:[]};let Q=$.mdm();return{settings:Object.keys(Q.settings).length>0?Q.settings:null,errors:Q.errors}}function sb($){let Q=$?.remote?$.remote():rb();if(!Q||Object.keys(Q).length===0)return{settings:null,errors:[]};let J=A4(Q),Y=r1(J,"remote managed settings"),X=S4().safeParse(J);if(!X.success)return{settings:null,errors:[...Y,...i0(X.error,"remote managed settings")]};return{settings:Object.keys(X.data).length>0?X.data:null,errors:Y}}function eb($){let Q=$.parentManaged;if(!Q||Object.keys(Q).length===0)return{settings:null,errors:[]};let J=A4(Q),Y=r1(J,"parent managed settings"),X=S4().safeParse(J);if(!X.success)return{settings:null,errors:[...Y,...i0(X.error,"parent managed settings")]};return Object.keys(X.data).length>0?{settings:X.data,errors:Y}:{settings:null,errors:Y}}function $_($){let Q=$.flagInline;if(!Q)return{settings:null,errors:[]};let J=A4(Q),Y=r1(J,"SDK inline settings"),X=S4().safeParse(J);if(!X.success)return{settings:null,errors:[...Y,...i0(X.error,"SDK inline settings")]};return{settings:X.data,errors:Y}}function Q6$($){try{let{resolvedPath:Q}=H5(c$(),$),J=u0(Q);if(J.trim()==="")return{settings:{},errors:[]};let Y=A4(R9(J,!1)),X=r1(Y,$),W=S4().safeParse(Y);if(!W.success){let G=i0(W.error,$);return{settings:null,errors:[...X,...G]}}return{settings:W.data,errors:X}}catch(Q){return $6$(Q,$),{settings:null,errors:[]}}}function ob($,Q){switch($){case"userSettings":return XX(p6());case"policySettings":case"projectSettings":case"localSettings":return XX(Q.cwd);case"flagSettings":return Q.flagPath?s$$(XX(Q.flagPath)):XX(Q.cwd)}}function J6$($){if($.coworkPlugins||A$(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function YX($,Q){switch($){case"userSettings":return s1(ob($,Q),J6$(Q));case"projectSettings":case"localSettings":return s1(ob($,Q),X6$($));case"policySettings":return e$$();case"flagSettings":return Q.flagPath}}function X6$($){switch($){case"projectSettings":return s1(".claude","settings.json");case"localSettings":return s1(".claude","settings.local.json")}}function Q_($,Q){let J=_O($);if(J!==void 0)return J;let Y=U6$($,Q);return SO($,Y),Y}function Y6$($){return!$||$.parentSettingsBehavior==="merge"}function W6$($,Q){let J={};if($.allowManagedHooksOnly===!0)J.allowManagedHooksOnly=!0;if($.allowManagedMcpServersOnly===!0)J.allowManagedMcpServersOnly=!0;if($.allowManagedPermissionRulesOnly===!0)J.allowManagedPermissionRulesOnly=!0;let Y=$.strictPluginOnlyCustomization;if(Y===!0||Array.isArray(Y)&&Y.length>0)J.strictPluginOnlyCustomization=Y;if($.deniedMcpServers)J.deniedMcpServers=$.deniedMcpServers;if(Q.forceLoginOrgUUID===void 0&&$.forceLoginOrgUUID)J.forceLoginOrgUUID=$.forceLoginOrgUUID;if(Q.allowedMcpServers===void 0&&$.allowedMcpServers)J.allowedMcpServers=$.allowedMcpServers;if($.permissions){let X=UG($.permissions,["deny","ask"]);if($.permissions.disableBypassPermissionsMode==="disable")X.disableBypassPermissionsMode="disable";if(Q.allowManagedPermissionRulesOnly!==!0){let{allow:W,additionalDirectories:G}=$.permissions;if(W&&Q.sandbox?.network?.allowManagedDomainsOnly!==!0)X.allow=W;if(G)X.additionalDirectories=G}if(Object.keys(X).length>0)J.permissions=X}if($.sandbox){let{network:X,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(X){let U=UG(X,["deniedDomains"]);if(X.allowManagedDomainsOnly===!0)U.allowManagedDomainsOnly=!0;if(Q.sandbox?.network?.allowManagedDomainsOnly!==!0&&X.allowedDomains)U.allowedDomains=X.allowedDomains;if(Object.keys(U).length>0)G.network=U}if(W){let U=UG(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)J.sandbox=G}return J}function J_($){if($.helper?.())return"helper";if(sb($).settings)return"remote";if(ab($).settings)return m0()==="macos"?"plist":"hklm";if(($.file?.()??tb($)).settings)return"file";if(eb($).settings)return"parent";let Q=$.hkcu?.();return Q&&Object.keys(Q.settings).length>0?"hkcu":null}function G6$($){let Q=[],{settings:J,errors:Y}=sb($);Q.push(...Y);let{settings:X,errors:W}=ab($);Q.push(...W);let{settings:G,errors:U}=$.file?.()??tb($);Q.push(...U);let{settings:H,errors:q}=eb($);Q.push(...q);let V=[J,X,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&&Y6$(B)?W6$(H,z):null;return{tiers:V,admin:B,parentSlice:N,errors:Q}}function X_($){let Q=$.helper?.();if(Q)return{settings:Q,errors:$.helperWarnings?.()??[]};let{admin:J,parentSlice:Y,errors:X}=G6$($);if(!J&&!Y){let W=$.hkcu?.();if(W&&Object.keys(W.settings).length>0)return{settings:W.settings,errors:[...X,...W.errors]};return{settings:null,errors:[...X,...W?.errors??[]]}}return{settings:G1({},Y??{},J??{},a1),errors:X}}function U6$($,Q){if($==="policySettings")return X_(Q).settings;let J=YX($,Q),{settings:Y}=J?HG(J):{settings:null};if($==="flagSettings"){let{settings:X}=$_(Q);if(X)return G1(Y||{},X,a1)}return Y}function H6$($,Q){return b5([...$,...Q])}function a1($,Q){if(Array.isArray($)&&Array.isArray(Q))return H6$($,Q);return}var Sz=!1;function K6$($){if(Sz)return{settings:{},errors:[]};let Q=Date.now();iJ("info","settings_load_started"),Sz=!0;try{let J=CO(),Y={};if(J)Y=G1(Y,J,a1);let X=[],W=new Set,G=new Set;for(let U of kz($)){if(U==="policySettings"){let{settings:q,errors:V}=X_($);if(q)Y=G1(Y,q,a1);for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),X.push(B)}continue}let H=YX(U,$);if(H){let q=XX(H);if(!G.has(q)){G.add(q);let{settings:V,errors:B}=HG(H);for(let z of B){let N=`${z.file}:${z.path}:${z.message}`;if(!W.has(N))W.add(N),X.push(z)}if(V)Y=G1(Y,V,a1)}}if(U==="flagSettings"){let{settings:q,errors:V}=$_($);for(let B of V){let z=`${B.file}:${B.path}:${B.message}`;if(!W.has(z))W.add(z),X.push(B)}if(q)Y=G1(Y,q,a1)}}return iJ("info","settings_load_completed",{duration_ms:Date.now()-Q,source_count:G.size,error_count:X.length}),{settings:Y,errors:X}}finally{Sz=!1}}function q6$($){let Q=EO();if(Q!==null)return Q;let J=K6$($);return bO(J),J}function V6$($){let{settings:Q}=q6$($);return Q||{}}function Y_($){z0();let Q=[];for(let J of kz($)){let Y=Q_(J,$);if(Y&&Object.keys(Y).length>0)Q.push({source:J,settings:Y})}return{effective:V6$($),sources:Q}}function W_($,Q){let J=kz(Q);for(let Y=J.length-1;Y>=0;Y--){let X=J[Y];if(Q_(X,Q)?.[$]!==void 0)return X}return null}var z6$={user:"userSettings",project:"projectSettings",local:"localSettings"},G_={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},N6$=["user","project","local"],w6$=new Set(["bypassPermissions","auto","acceptEdits"]),O6$=new Set(["project"]);function D6$($){let Q=$.effective.permissions?.defaultMode;if(!Q||!w6$.has(Q))return $.effective;for(let J=$.sources.length-1;J>=0;J--){let Y=$.sources[J];if(Y.settings.permissions?.defaultMode!==void 0){if(O6$.has(Y.source)){let{defaultMode:X,...W}=$.effective.permissions??{};return{...$.effective,permissions:W}}return $.effective}}return $.effective}async function U_($={}){await Db();let Q={cwd:B6$($.cwd??c$().cwd()),allowedSources:($.settingSources??N6$).map((J)=>z6$[J]),parentManaged:$.managedSettings??null,flagInline:null,flagPath:void 0,mdm:Fb,hkcu:Zb,wslInherits:Mb,...$.serverManagedSettings!==void 0&&{remote:()=>$.serverManagedSettings}};try{let{effective:J,sources:Y}=Y_(Q),X=J_(Q)??void 0,W=Y.map(({source:U,settings:H})=>({source:G_[U],settings:H,path:U==="policySettings"?void 0:YX(U,Q),...U==="policySettings"&&{policyOrigin:X}})),G={};for(let U of Object.keys(J)){let H=W_(U,Q);if(H)G[U]={source:G_[H],path:H==="policySettings"?void 0:YX(H,Q),...H==="policySettings"&&{policyOrigin:X}}}return{effective:J,provenance:G,sources:W}}finally{z0()}}async function yj$($){return U_($)}async function b6$($,Q){try{await L6$($,Q)}catch(J){if(!Z1(J))throw J}}async function _6$($,Q){if(!$)return;let J=$;try{let Y=g$($);if(Y?.claudeAiOauth?.refreshToken)delete Y.claudeAiOauth.refreshToken,J=B$(Y)}catch{}await N_(Q,J,{mode:384})}function S6$(){if(process.platform!=="darwin")return Promise.resolve(void 0);let $=gZ(fZ);return new Promise((Q)=>{F6$("security",["find-generic-password","-a",hZ(),"-w","-s",$],{encoding:"utf-8",timeout:5000},(J,Y)=>Q(J?void 0:Y.trim()||void 0))})}async function D_($,Q,J,Y,X=60000){if(!Z$(Q))return;let W=J4(J),G=await C4($.load({projectKey:W,sessionId:Q}),X,`SessionStore.load() timed out after ${X}ms for session ${Q}`);if(!G||G.length===0)return;let U=u6(R6$(),`claude-resume-${fz()}`);try{let H=u6(U,"projects",W);await vz(H,{recursive:!0});let q=u6(H,`${Q}.jsonl`);await n7(q,G);let V=Y?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,B=V??u6(Cz(),".claude"),z;try{z=await z_(u6(B,".credentials.json"),"utf-8")}catch(N){if(!Z1(N))throw N}if(!V&&!(Y??process.env).ANTHROPIC_API_KEY&&!(Y??process.env).CLAUDE_CODE_OAUTH_TOKEN)z=await S6$()??z;if(await _6$(z,u6(U,".credentials.json")),await b6$(u6(V??Cz(),".claude.json"),u6(U,".claude.json")),$.listSubkeys){let N=u6(H,Q),w=await C4($.listSubkeys({projectKey:W,sessionId:Q}),X,`SessionStore.listSubkeys() timed out after ${X}ms for session ${Q}`);for(let O of w){let D=WX(N,O+".jsonl");if(!O||w_(O)||O.split(/[\\/]/).includes("..")||!D.startsWith(N+gz)){X$(`[SessionStore] skipping unsafe subpath from listSubkeys: ${O}`,{level:"warn"});continue}let M=await C4($.load({projectKey:W,sessionId:Q,subpath:O}),X,`SessionStore.load() timed out after ${X}ms for session ${Q} subpath ${O}`);if(!M||M.length===0)continue;let j=[],A=[];for(let k of M)if(yz(k))j.push(k);else A.push(k);if(A.length>0)await vz(H_(D),{recursive:!0}),await n7(D,A);if(j.length>0){let k=j.at(-1),u=WX(N,O+".meta.json");await vz(H_(u),{recursive:!0});let{type:G$,...u$}=k;await N_(u,B$(u$),{mode:384})}}}return U}catch(H){throw await KG(U),H}}function Tz($,Q,J,Y){let{systemPrompt:X,settings:W,managedSettings:G,settingSources:U,sandbox:H,...q}=$??{},V,B,z;if(X===void 0)V="";else if(typeof X==="string")V=X;else if(Array.isArray(X))V=X;else if(X.type==="preset")B=X.append,z=X.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.148";let{abortController:N=f9(),additionalDirectories:w=[],agent:O,agents:D,allowedTools:M=[],betas:j,canUseTool:A,continue:k,cwd:u,debug:G$,debugFile:u$,disallowedTools:e$=[],tools:m6,env:D6,executable:e1=VX()?"bun":"node",executableArgs:n0=[],extraArgs:k4={},fallbackModel:S9,enableFileCheckpointing:U1,toolConfig:i,forkSession:GX,hooks:UX,includeHookEvents:k9,includePartialMessages:v9,forwardSubagentText:C9,onElicitation:HX,persistSession:m$,sessionStore:s$,sessionStoreFlush:v4,thinking:T9,effort:j_,maxThinkingTokens:VG,maxTurns:A_,maxBudgetUsd:I_,taskBudget:R_,mcpServers:hz,model:P_,outputFormat:uz,permissionMode:E_="default",allowDangerouslySkipPermissions:b_=!1,permissionPromptToolName:__,plugins:S_,getOAuthToken:mz,getHostAuthToken:lz,workload:cz,resume:pz,resumeSessionAt:k_,sessionId:v_,skills:dz,stderr:C_,strictMcpConfig:T_}=q;if(s$&&m$===!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$&&k&&!pz&&!s$.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(s$&&U1)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)X$("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 BG=q.pathToClaudeCodeExecutable;if(!BG){let k6=E6$(import.meta.url),X4=I6$(k6),$0=U2((r0)=>X4.resolve(r0));if(!$0)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.`);BG=$0}let iz=uz?.type==="json_schema"?uz.schema:void 0,S6=D6?{...D6}:{...process.env};if(!S6.CLAUDE_CODE_ENTRYPOINT)S6.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(U1)S6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(mz)S6.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(lz)S6.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(i?.askUserQuestion?.previewFormat)S6.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=i.askUserQuestion.previewFormat;let zG={};if(qG.propagation.inject(qG.context.active(),zG),"traceparent"in zG){for(let k6 of["TRACEPARENT","TRACESTATE"])if(!(k6 in(D6??{})))delete S6[k6]}for(let[k6,X4]of Object.entries(zG)){let $0=k6.toUpperCase();if(!($0 in(D6??{})))S6[$0]=X4}let nz={},rz=new Map;if(hz)for(let[k6,X4]of Object.entries(hz))if(X4.type==="sdk"&&X4.instance)rz.set(k6,X4.instance);else nz[k6]=X4;let x9;if(T9)switch(T9.type){case"adaptive":x9={type:"adaptive",display:T9.display};break;case"enabled":x9={type:"enabled",budgetTokens:T9.budgetTokens,display:T9.display};break;case"disabled":x9={type:"disabled"};break}else if(VG!==void 0)x9=VG===0?{type:"disabled"}:{type:"enabled",budgetTokens:VG};if(J){if(S6.CLAUDE_CONFIG_DIR=J,process.platform==="win32")S6.CLAUDE_SECURESTORAGE_CONFIG_DIR=D6?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??D6?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let oz=new LU({abortController:N,additionalDirectories:w,agent:O,betas:j,cwd:u,debug:G$,debugFile:u$,executable:e1,executableArgs:n0,extraArgs:cz?{...k4,workload:cz}:k4,pathToClaudeCodeExecutable:BG,env:S6,forkSession:GX,stderr:C_,thinkingConfig:x9,effort:j_,maxTurns:A_,maxBudgetUsd:I_,taskBudget:R_,model:P_,fallbackModel:S9,jsonSchema:iz,permissionMode:E_,allowDangerouslySkipPermissions:b_,permissionPromptToolName:__,continueConversation:s$?void 0:k,resume:pz,resumeSessionAt:k_,sessionId:v_,settings:typeof W==="object"?B$(W):W,managedSettings:G?B$(G):void 0,settingSources:U,skills:dz,allowedTools:M,disallowedTools:e$,tools:m6,mcpServers:nz,strictMcpConfig:T_,canUseTool:!!A,hooks:!!UX,includeHookEvents:k9,includePartialMessages:v9,persistSession:m$,sessionMirror:!!s$,plugins:S_,sandbox:H,spawnClaudeCodeProcess:q.spawnClaudeCodeProcess,deferSpawn:Y}),x_={systemPrompt:V,appendSystemPrompt:B,planModeInstructions:q.planModeInstructions,appendSubagentSystemPrompt:q.appendSubagentSystemPrompt,toolAliases:q.toolAliases,excludeDynamicSections:z,agents:D,title:q.title,skills:dz,webSearchIsolationExemptMcpServers:q.webSearchIsolationExemptMcpServers,promptSuggestions:q.promptSuggestions,agentProgressSummaries:q.agentProgressSummaries,forwardSubagentText:C9},NG=new RU(oz,Q,A,UX,N,rz,iz,x_,HX,mz,lz);if(s$){let k6=()=>u6(S6.CLAUDE_CONFIG_DIR??u6(Cz(),".claude"),"projects"),X4=v4==="eager",$0=new PU(async(r0,wG)=>{let y9=B_(r0,k6());if(y9)await s$.append(y9,wG);else X$(`[SessionStore] dropping mirror frame: filePath ${r0} is not under ${k6()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(r0,wG)=>{let y9=B_(r0,k6());if(y9)NG.reportMirrorError(y9,wG.message)},X4?0:z5,X4?0:N5);NG.setTranscriptMirrorBatcher($0)}return{queryInstance:NG,transport:oz,abortController:N,processEnv:S6}}function xz($,Q,J,Y){if(typeof J==="string")Q.write(B$({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:J}]},parent_tool_use_id:null})+`
|
|
116
116
|
`);else $.streamInput(J).catch((X)=>Y.abort(X))}var k6$=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function KG($){for(let Q=0;;Q++)try{return await A6$($,{recursive:!0,force:!0})}catch(J){if(Q>=4||!k6$.has(o$(J)??""))return;await KX((Q+1)*100)}}function v6$($,Q){$.waitForExit().catch(()=>{}).finally(()=>KG(Q))}function fj$({prompt:$,options:Q}){if((Q?.resume||Q?.continue)&&Q?.sessionStore){let{queryInstance:W,transport:G,abortController:U,processEnv:H}=Tz({...Q},typeof $==="string",void 0,!0),q=WX(Q.cwd??"."),V=Q.sessionStore,B=Q.loadTimeoutMs??60000,z=Q.resume;return(async()=>{if(!z)z=(await C4(V.listSessions(J4(q)),B,`SessionStore.listSessions() timed out after ${B}ms`)).slice().sort((O,D)=>D.mtime-O.mtime)[0]?.sessionId;if(!z)return;return D_(V,z,q,Q.env,Q.loadTimeoutMs)})().then((w)=>{if(w){G.updateResume(z);let O={CLAUDE_CONFIG_DIR:w};if(process.platform==="win32"){let D=Q.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??Q.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";O.CLAUDE_SECURESTORAGE_CONFIG_DIR=D,H.CLAUDE_SECURESTORAGE_CONFIG_DIR=D}G.updateEnv(O),H.CLAUDE_CONFIG_DIR=w,W.addCleanupCallback(()=>v6$(G,w))}if(!W.isClosed())G.spawn()}).catch((w)=>{let O=j4(w);G.spawnAbort(O),W.setError(O)}),xz(W,G,$,U),W}let{queryInstance:J,transport:Y,abortController:X}=Tz(Q,typeof $==="string");return xz(J,Y,$,X),J}async function gj$({options:$,initializeTimeoutMs:Q=60000}={}){let J,Y=$?.resume;if((Y||$?.continue)&&$?.sessionStore){let U=WX($.cwd??".");if(!Y){if(!$.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let H=$.loadTimeoutMs??60000;Y=(await C4($.sessionStore.listSessions(J4(U)),H,`SessionStore.listSessions() timed out after ${H}ms`)).slice().sort((V,B)=>B.mtime-V.mtime)[0]?.sessionId}if(Y)J=await D_($.sessionStore,Y,U,$.env,$.loadTimeoutMs)}let X,W,G;try{let z=function(){if(B)return;B=!0,V.close()},U=Tz(J&&Y&&Y!==$?.resume?{...$,resume:Y}:$,!1,J);X=U.queryInstance;let{transport:H,abortController:q}=U;W=H;let V=U.queryInstance;if(J){let N=J;V.addCleanupCallback(()=>{G=H.waitForExit().catch(()=>{}).then(()=>KG(N))})}await C4(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{xz(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(X?.close(),J&&!G){let H=W;G=(H?H.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>KG(J))}throw await G,U}}async function hj$($,Q){if(Q?.sessionStore)return y6$(Q.sessionStore,$,Q);return NZ($,Q)}async function uj$($){if($?.sessionStore)return T6$($.sessionStore,$);return OZ($)}async function mj$($,Q){if(Q?.sessionStore)return f6$(Q.sessionStore,$,Q);return DZ($,Q)}async function lj$($,Q,J){if(J?.sessionStore)return g6$(J.sessionStore,$,Q,J.dir);return LZ($,Q,J)}async function cj$($,Q,J){if(J?.sessionStore)return h6$(J.sessionStore,$,Q,J.dir);return jZ($,Q,J)}async function pj$($,Q){if(!Z$($))throw Error(`Invalid sessionId: ${$}`);if(Q?.sessionStore){if(!Q.sessionStore.delete)return;let J=J4(Q.dir);await Q.sessionStore.delete({projectKey:J,sessionId:$});return}return AZ($,Q)}async function dj$($,Q){if(Q?.sessionStore)return u6$(Q.sessionStore,$,Q);return PZ($,Q)}async function ij$($,Q,J){if(!Z$($))throw Error(`Invalid sessionId: ${$}`);let Y=await A1($,J?.dir);if(!Y)throw Error(`Session ${$} not found`);let X=J4(J?.dir),W=J?.batchSize&&J.batchSize>0?J.batchSize:z5;if(await K_(Y.filePath,{projectKey:X,sessionId:$},Q,W),J?.includeSubagents===!1)return;let G=Y.filePath.replace(/\.jsonl$/,""),U=u6(G,"subagents");for(let H of await C6$(U)){let q=O_(G,H).split(gz);q[q.length-1]=q.at(-1).replace(/\.jsonl$/,"");let V={projectKey:X,sessionId:$,subpath:q.join("/")};await K_(H,V,Q,W);let B=H.replace(/\.jsonl$/,".meta.json");try{let z=g$(await z_(B,"utf8"));await Q.append(V,[{type:"agent_metadata",...z}])}catch(z){if(!Z1(z))throw z}}}async function K_($,Q,J,Y){let X=P6$({input:Z6$($,{encoding:"utf8"}),crlfDelay:1/0}),W=[],G=0;for await(let U of X){if(!U)continue;if(W.push(g$(U)),G+=U.length,W.length>=Y||G>=N5)await J.append(Q,W),W=[],G=0}if(W.length>0)await J.append(Q,W)}async function C6$($){let Q=[];async function J(Y){let X;try{X=await j6$(Y,{withFileTypes:!0})}catch{return}for(let W of X){let G=u6(Y,W.name);if(W.isDirectory())await J(G);else if(W.isFile()&&W.name.endsWith(".jsonl"))Q.push(G)}}return await J($),Q}async function nj$($,Q){if(Q?.sessionStore)return m6$(Q.sessionStore,$,Q.dir);return vZ($,Q)}async function rj$($,Q,J){if(J?.sessionStore)return l6$(J.sessionStore,$,Q,J);return CZ($,Q,J)}function F_($){let Q=WX($??"."),J;try{J=M6$(Q)}catch{J=Q}return J.normalize("NFC")}function J4($){return M0(F_($))}function Z_($){return $.map((Q)=>B$(Q)).join(`
|
|
117
117
|
`)+`
|
|
118
118
|
`}function q_($,Q,J){if(Q!==void 0&&Q>0)return $.slice(J,J+Q);if(J>0)return $.slice(J);return $}function yz($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="agent_metadata"}async function T6$($,Q){let J=F_(Q.dir),Y=M0(J),X=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:tz(w,J)})}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 X$("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");B.sort((w,O)=>O.mtime-w.mtime);let z=q_(B,W,X),N=z.filter((w)=>w.info===void 0);if(N.length>0){let w=await V_($,N,Q.dir,J),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=q_(U,W,X);return V_($,H,Q.dir,J)}async function V_($,Q,J,Y){return(await Promise.allSettled(Q.map(async(W)=>{let G=await L_($,W.sessionId,J);if(!G)return null;let U=k8(W.sessionId,M_(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 M_($,Q){let J=Buffer.from($,"utf-8"),Y=J.length,X=J.subarray(0,G4).toString("utf-8"),W=Y>G4?J.subarray(Y-G4).toString("utf-8"):X;return{mtime:Q,size:Y,head:X,tail:W}}function x6$($){let Q=$.trimEnd(),J=Q.slice(Q.lastIndexOf(`
|