@anthropic-ai/claude-agent-sdk 0.3.208 → 0.3.209
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bridge.mjs +41 -41
- package/browser-sdk.js +2 -2
- package/manifest.json +21 -20
- package/manifest.zst.json +25 -24
- package/package.json +10 -10
- package/sdk.mjs +3 -3
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.209
|
|
5
5
|
|
|
6
6
|
// Want to see the unminified source? We're hiring!
|
|
7
7
|
// https://job-boards.greenhouse.io/anthropic/jobs/4816199008
|
|
@@ -83,7 +83,7 @@ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
83
83
|
`);this.baseURL=n.baseURL,this._baseURLIsExplicit=o.__baseURLIsExplicit??!!e,this.timeout=n.timeout??Gb.DEFAULT_TIMEOUT,this.logger=n.logger??console;let i="warn";this.logLevel=i,this.logLevel=wb(n.logLevel,"ClientOptions.logLevel",this)??wb(he("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??ET(),N(this,Tf,PT,"f");let s=he("ANTHROPIC_CUSTOM_HEADERS");if(s){let c={};for(let u of s.split(`
|
|
84
84
|
`)){let d=u.indexOf(":");if(d>=0)c[u.substring(0,d).trim()]=u.substring(d+1).trim()}n.defaultHeaders={...c,...n.defaultHeaders}}let a=o.__auth;if(delete n.__auth,delete n.__baseURLIsExplicit,this._options=n,this.apiKey=typeof t==="string"?t:null,this.authToken=r,a){if(this._authState=a,!this._baseURLIsExplicit&&a.baseURL)this.baseURL=a.baseURL}else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let c=n.credentials??null;if(c)this._authState.provider=c,this._authState.tokenCache=this._makeTokenCache(c);else if(n.config!=null){let u=Tb(n.config,this._credentialResolverOptions());this._authState.provider=u.provider,this._authState.tokenCache=this._makeTokenCache(u.provider),this._authState.extraHeaders=u.extraHeaders,this._applyCredentialBaseURL(u.baseURL)}else if(n.profile!=null)this._authState.resolution=this._resolveDefaultCredentials(n.profile);else this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL(e){if(!e)return;let t=e.replace(/\/+$/,"");if(this._authState.baseURL=t,!this._baseURLIsExplicit)this.baseURL=t}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this.fetch,userAgent:this.getUserAgent(),onCacheWriteError:(e)=>{He(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:(e)=>{He(this).warn(e)}}}_makeTokenCache(e){return new vb(e,(t)=>{He(this).debug("advisory token refresh failed; serving cached token",t)})}withOptions(e){let t="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||t,o={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(o)}async _resolveDefaultCredentials(e){try{let t=await WT(this._credentialResolverOptions(),e);if(t)this._authState.provider=t.provider,this._authState.tokenCache=this._makeTokenCache(t.provider),this._authState.extraHeaders=t.extraHeaders,this._applyCredentialBaseURL(t.baseURL);else if(e!=null)throw new j(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(t){this._authState.error=t}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(e.get("x-api-key")||e.get("authorization"))return;if(this._authState.error)throw this._authState.error;if(this._authState.tokenCache||this._authState.resolution)return;if(this.apiKey&&e.get("x-api-key"))return;if(t.has("x-api-key"))return;if(this.authToken&&e.get("authorization"))return;if(t.has("authorization"))return;throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}_authFlags(e){let t=this._requestAuthFlags.get(e);if(!t)t={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,t);return t}async authHeaders(e){if(this._authState.resolution)await this._authState.resolution;if(this._authState.error)return;if(this._authState.tokenCache&&this.apiKey==null){let t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,T([{Authorization:`Bearer ${t}`}])}return T([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey==null)return;return T([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken==null)return;return T([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return IT(e)}getUserAgent(){return`${this.constructor.name}/JS ${Yt}`}defaultIdempotencyKey(){return`stainless-node-retry-${gb()}`}makeStatusError(e,t,r,o){return Ye.generate(e,t,r,o)}buildURL(e,t,r){let o=!b(this,Zb,"m",SP).call(this)&&r||this.baseURL,n=yT(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),s=Object.fromEntries(n.searchParams);if(!_b(i)||!_b(s))t={...s,...i,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128000>600)throw new j("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){if(this._authState.tokenCache&&this.apiKey==null){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,s]of Object.entries(this._authState.extraHeaders))if(!o.has(i))o.set(i,s);if(!o.get("anthropic-beta")?.split(",").map((i)=>i.trim())?.includes(wo))o.append("anthropic-beta",wo);e.headers=o}}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((o)=>({method:e,path:t,...o})))}request(e,t=null){return new ko(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let o=await e,n=o.maxRetries??this.maxRetries;if(t==null)t=n,this._requestAuthFlags.delete(o);await this.prepareOptions(o);let{req:i,url:s,timeout:a}=await this.buildRequest(o,{retryCount:n-t});await this.prepareRequest(i,{url:s,options:o});let c="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(He(this).debug(`[${c}] sending request`,Kr({retryOfRequestLogID:r,method:o.method,url:s,options:o,headers:i.headers})),o.signal?.aborted)throw new rt;let p=new AbortController,f=await this.fetchWithTimeout(s,i,a,p).catch(vl),m=Date.now();if(f instanceof globalThis.Error){let y=`retrying, ${t} attempts remaining`;if(o.signal?.aborted)throw new rt;let S=Wr(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return He(this).info(`[${c}] connection ${S?"timed out":"failed"} - ${y}`),He(this).debug(`[${c}] connection ${S?"timed out":"failed"} (${y})`,Kr({retryOfRequestLogID:r,url:s,durationMs:m-d,message:f.message})),this.retryRequest(o,t,r??c);if(He(this).info(`[${c}] connection ${S?"timed out":"failed"} - error; no more retries left`),He(this).debug(`[${c}] connection ${S?"timed out":"failed"} (error; no more retries left)`,Kr({retryOfRequestLogID:r,url:s,durationMs:m-d,message:f.message})),S)throw new xl;throw new xo({cause:f})}let g=[...f.headers.entries()].filter(([y])=>y==="request-id").map(([y,S])=>", "+y+": "+JSON.stringify(S)).join(""),h=`[${c}${u}${g}] ${i.method} ${s} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${m-d}ms`;if(!f.ok){let y=await this.shouldRetry(f,o);if(t&&y){let ae=`retrying, ${t} attempts remaining`;return await TT(f.body),He(this).info(`${h} - ${ae}`),He(this).debug(`[${c}] response error (${ae})`,Kr({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),this.retryRequest(o,t,r??c,f.headers)}let S=y?"error; no more retries left":"error; not retryable";He(this).info(`${h} - ${S}`);let x=await f.text().catch((ae)=>vl(ae).message),w=Zp(x),R=w?void 0:x;throw He(this).debug(`[${c}] response error (${S})`,Kr({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:R,durationMs:Date.now()-d})),this.makeStatusError(f.status,w,R,f.headers)}return He(this).info(h),He(this).debug(`[${c}] response start`,Kr({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),{response:f,options:o,controller:p,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((o)=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new af(this,r,e)}async fetchWithTimeout(e,t,r,o){let{signal:n,method:i,...s}=t||{},a=this._makeAbort(o);if(n)n.addEventListener("abort",a,{once:!0});let c=setTimeout(a,r),u=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body==="object"&&s.body!==null&&Symbol.asyncIterator in s.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...s};if(i)d.method=i.toUpperCase();try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e,t){let r=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&r.usedTokenCache&&!r.didRefreshFor401)return r.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let o=e.headers.get("x-should-retry");if(o==="true")return!0;if(o==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,o){let n,i=o?.get("retry-after-ms");if(i){let a=parseFloat(i);if(!Number.isNaN(a))n=a}let s=o?.get("retry-after");if(s&&!n){let a=parseFloat(s);if(!Number.isNaN(a))n=a*1000;else n=Date.parse(s)-Date.now()}if(n===void 0){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await ST(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,i=Math.min(0.5*Math.pow(2,n),8),s=1-Math.random()*0.25;return i*s*1000}calculateNonstreamingTimeout(e,t){if(3600000*e/128000>600000||t!=null&&e>t)throw new j("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:o,path:n,query:i,defaultBaseURL:s}=r;if(this._authState.resolution)await this._authState.resolution;if(!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL)this.baseURL=this._authState.baseURL;let a=this.buildURL(n,i,s);if("timeout"in r)bT("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:t});return{req:{method:o,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:a,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:o}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let i=T([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ol(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=T([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:Gp(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return b(this,Tf,"f").call(this,{body:e,headers:r})}}Gb=Le,Tf=new WeakMap,Zb=new WeakSet,SP=function(){return this.baseURL!=="https://api.anthropic.com"};Le.Anthropic=Gb;Le.HUMAN_PROMPT=vP;Le.AI_PROMPT=xP;Le.DEFAULT_TIMEOUT=600000;Le.AnthropicError=j;Le.APIError=Ye;Le.APIConnectionError=xo;Le.APIConnectionTimeoutError=xl;Le.APIUserAbortError=rt;Le.NotFoundError=Tl;Le.ConflictError=Pl;Le.RateLimitError=Al;Le.BadRequestError=wl;Le.AuthenticationError=kl;Le.InternalServerError=Rl;Le.PermissionDeniedError=El;Le.UnprocessableEntityError=Il;Le.toFile=lf;class Co extends Le{constructor(){super(...arguments);this.completions=new Zi(this),this.messages=new Oo(this),this.models=new Ji(this),this.beta=new ct(this)}}Co.Completions=Zi;Co.Messages=Oo;Co.Models=Ji;Co.Beta=ct;function wP(e){return e}function Jb(e){return wP(e)}function Xi(e){return wP(e)}class ht extends Error{telemetryMessage;constructor(e,t){super(e);this.name="TelemetrySafeError",this.telemetryMessage=t??e}}var kP=(e,t)=>{try{if(e!==null&&typeof e==="object"&&!("telemetryMessage"in e)&&Object.isExtensible(e))Object.assign(e,{telemetryMessage:t})}catch{}return e};function Or(e){return e instanceof Error?e:Error(String(e))}function Yi(e){return e instanceof Error?e.message:String(e)}function Be(e){if(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string")return e.code;return}function Xr(e){return Be(e)==="ENOENT"}function Xb(e){return Be(e)==="EISDIR"}var lq=new Set(["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG","EROFS"]);function Yb(e){let t=Be(e);return t!==void 0&&lq.has(t)}import{randomUUID as Iq}from"crypto";import{join as OP}from"path";import{AsyncLocalStorage as vq}from"async_hooks";import{appendFile as xq,copyFile as wq,mkdir as kq,open as TP,readdir as PP,readFile as IP,stat as Eq,unlink as Tq,writeFile as eS}from"fs/promises";import{randomBytes as cq}from"crypto";import{chmod as uq,copyFile as dq,rename as pq,unlink as Qb,writeFile as fq}from"fs/promises";var mq=new Set(["EXDEV","EPERM","EEXIST","EBUSY"]),gq=new Set(["EPERM","EBUSY","EACCES"]),hq=4,yq=50,hRe=new Int32Array(new SharedArrayBuffer(4));function _q(e,t){if(process.platform!=="win32")return!1;let r=Be(e);return r!==void 0&&gq.has(r)&&t<hq-1}async function bq(e,t,r=pq){let o=!1;for(let n=0;;n++)try{return await r(e,t),o}catch(i){if(_q(i,n)){o=!0,await mn(yq);continue}throw i}}var Sq=new Set(["ENOSPC","EIO","EDQUOT","EFBIG"]);async function EP(e,t,r){let o=`${e}.tmp.${cq(4).toString("hex")}`;try{await fq(o,t,{encoding:"utf8",mode:r});try{await bq(o,e)}catch(n){let i=Be(n);if(i===void 0||!mq.has(i))throw n;try{if(await dq(o,e),r!==void 0)await uq(e,r).catch(()=>{})}catch(s){if(Sq.has(Be(s)??""))await Qb(e).catch(()=>{});throw s}await Qb(o).catch(()=>{})}}catch(n){throw await Qb(o).catch(()=>{}),n}}class RP{read(e){return IP(e,"utf8")}readBytes(e){return IP(e)}write(e,t,r){return eS(e,t,{encoding:"utf8",mode:r})}async mkdir(e){try{await kq(e,{recursive:!0})}catch(t){if(Be(t)!=="EEXIST")throw t}}atomicWrite(e,t,r){return EP(e,t,r)}delete(e){return Tq(e)}list(e){return PP(e)}append(e,t,r){return xq(e,t,{encoding:"utf8",mode:r})}writeExclusive(e,t,r){return eS(e,t,{encoding:"utf8",flag:"wx",mode:r})}writeBytes(e,t){return eS(e,t)}copy(e,t){return wq(e,t)}async stat(e){return{mtimeMs:(await Eq(e)).mtimeMs}}async listEntries(e){return(await PP(e,{withFileTypes:!0})).map((r)=>({name:r.name,isDirectory:r.isDirectory(),isFile:r.isFile()}))}async readRange(e,t,r){tS("readRange","offset",t),tS("readRange","length",r);let o=await TP(e,"r");try{return await AP(o,t,r)}finally{await o.close()}}async readTail(e,t){tS("readTail","maxBytes",t);let r=await TP(e,"r");try{let{size:o}=await r.stat(),n=Math.min(t,o);return await AP(r,o-n,n)}finally{await r.close()}}}function tS(e,t,r){if(!Number.isInteger(r)||r<0)throw RangeError(`${e}: ${t} must be a non-negative integer, got ${r}`)}async function AP(e,t,r){if(r===0)return Buffer.alloc(0);let o=Buffer.alloc(r),n=0;while(n<r){let{bytesRead:i}=await e.read(o,n,r-n,t+n);if(i===0)break;n+=i}return n===r?o:Buffer.from(o.subarray(0,n))}var Pq=new vq;function Qi(){return Pq.getStore()??new RP}var $o,es=null;function CP(){if(es)return es;if(!ve(process.env.DEBUG_CLAUDE_AGENT_SDK))return $o=null,es=Promise.resolve(),es;let e=OP(Xt(),"debug");return $o=OP(e,`sdk-${Iq()}.txt`),process.stderr.write(`SDK debug logs: ${$o}
|
|
85
85
|
`),es=Qi().mkdir(e).catch(()=>{}),es}function $P(){return CP(),$o??null}function yt(e){if($o===null)return;let r=`${new Date().toISOString()} ${e}
|
|
86
|
-
`;CP().then(()=>{if($o)Qi().append($o,r).catch(()=>{})})}function Aq(){this.__data__=new _n,this.size=0}var MP=Aq;function Rq(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var DP=Rq;function Oq(e){return this.__data__.get(e)}var NP=Oq;function Cq(e){return this.__data__.has(e)}var UP=Cq;var $q=200;function Mq(e,t){var r=this.__data__;if(r instanceof _n){var o=r.__data__;if(!bn||o.length<$q-1)return o.push([e,t]),this.size=++r.size,this;r=this.__data__=new po(o)}return r.set(e,t),this.size=r.size,this}var LP=Mq;function ts(e){var t=this.__data__=new _n(e);this.size=t.size}ts.prototype.clear=MP;ts.prototype.delete=DP;ts.prototype.get=NP;ts.prototype.has=UP;ts.prototype.set=LP;var $n=ts;var Dq=function(){try{var e=kt(Object,"defineProperty");return e({},"",{}),e}catch(t){}}(),rs=Dq;function Nq(e,t,r){if(t=="__proto__"&&rs)rs(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0});else e[t]=r}var ns=Nq;var Uq=Object.prototype,Lq=Uq.hasOwnProperty;function jq(e,t,r){var o=e[t];if(!(Lq.call(e,t)&&Rr(o,r))||r===void 0&&!(t in e))ns(e,t,r)}var Pf=jq;function zq(e,t,r,o){var n=!r;r||(r={});var i=-1,s=t.length;while(++i<s){var a=t[i],c=o?o(r[a],e[a],a,r,e):void 0;if(c===void 0)c=e[a];if(n)ns(r,a,c);else Pf(r,a,c)}return r}var jP=zq;function Fq(e,t){var r=-1,o=Array(e);while(++r<e)o[r]=t(r);return o}var zP=Fq;function Hq(e){return e!=null&&typeof e=="object"}var _t=Hq;var Bq="[object Arguments]";function qq(e){return _t(e)&&Lt(e)==Bq}var rS=qq;var FP=Object.prototype,Vq=FP.hasOwnProperty,Wq=FP.propertyIsEnumerable,Kq=rS(function(){return arguments}())?rS:function(e){return _t(e)&&Vq.call(e,"callee")&&!Wq.call(e,"callee")},Yr=Kq;var Zq=Array.isArray,je=Zq;var Af={};Pr(Af,{default:()=>Mn});function Gq(){return!1}var HP=Gq;var VP=typeof Af=="object"&&Af&&!Af.nodeType&&Af,BP=VP&&typeof If=="object"&&If&&!If.nodeType&&If,Jq=BP&&BP.exports===VP,qP=Jq?We.Buffer:void 0,Xq=qP?qP.isBuffer:void 0,Yq=Xq||HP,Mn=Yq;var Qq=9007199254740991,e6=/^(?:0|[1-9]\d*)$/;function t6(e,t){var r=typeof e;return t=t==null?Qq:t,!!t&&(r=="number"||r!="symbol"&&e6.test(e))&&(e>-1&&e%1==0&&e<t)}var Dn=t6;var r6=9007199254740991;function n6(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=r6}var os=n6;var o6="[object Arguments]",i6="[object Array]",s6="[object Boolean]",a6="[object Date]",l6="[object Error]",c6="[object Function]",u6="[object Map]",d6="[object Number]",p6="[object Object]",f6="[object RegExp]",m6="[object Set]",g6="[object String]",h6="[object WeakMap]",y6="[object ArrayBuffer]",_6="[object DataView]",b6="[object Float32Array]",S6="[object Float64Array]",v6="[object Int8Array]",x6="[object Int16Array]",w6="[object Int32Array]",k6="[object Uint8Array]",E6="[object Uint8ClampedArray]",T6="[object Uint16Array]",P6="[object Uint32Array]",Ce={};Ce[b6]=Ce[S6]=Ce[v6]=Ce[x6]=Ce[w6]=Ce[k6]=Ce[E6]=Ce[T6]=Ce[P6]=!0;Ce[o6]=Ce[i6]=Ce[y6]=Ce[s6]=Ce[_6]=Ce[a6]=Ce[l6]=Ce[c6]=Ce[u6]=Ce[d6]=Ce[p6]=Ce[f6]=Ce[m6]=Ce[g6]=Ce[h6]=!1;function I6(e){return _t(e)&&os(e.length)&&!!Ce[Lt(e)]}var WP=I6;function A6(e){return function(t){return e(t)}}var KP=A6;var Of={};Pr(Of,{default:()=>Cf});var ZP=typeof Of=="object"&&Of&&!Of.nodeType&&Of,mc=ZP&&typeof Rf=="object"&&Rf&&!Rf.nodeType&&Rf,R6=mc&&mc.exports===ZP,nS=R6&&Vu.process,O6=function(){try{var e=mc&&mc.require&&mc.require("util").types;if(e)return e;return nS&&nS.binding&&nS.binding("util")}catch(t){}}(),Cf=O6;var GP=Cf&&Cf.isTypedArray,C6=GP?KP(GP):WP,is=C6;var $6=Object.prototype,M6=$6.hasOwnProperty;function D6(e,t){var r=je(e),o=!r&&Yr(e),n=!r&&!o&&Mn(e),i=!r&&!o&&!n&&is(e),s=r||o||n||i,a=s?zP(e.length,String):[],c=a.length;for(var u in e)if((t||M6.call(e,u))&&!(s&&(u=="length"||n&&(u=="offset"||u=="parent")||i&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Dn(u,c))))a.push(u);return a}var $f=D6;var N6=Object.prototype;function U6(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||N6;return e===r}var ss=U6;function L6(e,t){return function(r){return e(t(r))}}var Mf=L6;var j6=Mf(Object.keys,Object),JP=j6;var z6=Object.prototype,F6=z6.hasOwnProperty;function H6(e){if(!ss(e))return JP(e);var t=[];for(var r in Object(e))if(F6.call(e,r)&&r!="constructor")t.push(r);return t}var XP=H6;function B6(e){return e!=null&&os(e.length)&&!mi(e)}var Nn=B6;function q6(e){return Nn(e)?$f(e):XP(e)}var Df=q6;function V6(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var YP=V6;var W6=Object.prototype,K6=W6.hasOwnProperty;function Z6(e){if(!Je(e))return YP(e);var t=ss(e),r=[];for(var o in e)if(!(o=="constructor"&&(t||!K6.call(e,o))))r.push(o);return r}var QP=Z6;function G6(e){return Nn(e)?$f(e,!0):QP(e)}var as=G6;var Uf={};Pr(Uf,{default:()=>oS});var nI=typeof Uf=="object"&&Uf&&!Uf.nodeType&&Uf,eI=nI&&typeof Nf=="object"&&Nf&&!Nf.nodeType&&Nf,J6=eI&&eI.exports===nI,tI=J6?We.Buffer:void 0,rI=tI?tI.allocUnsafe:void 0;function X6(e,t){if(t)return e.slice();var r=e.length,o=rI?rI(r):new e.constructor(r);return e.copy(o),o}var oS=X6;function Y6(e,t){var r=-1,o=e.length;t||(t=Array(o));while(++r<o)t[r]=e[r];return t}var oI=Y6;function Q6(e,t){var r=-1,o=e==null?0:e.length,n=0,i=[];while(++r<o){var s=e[r];if(t(s,r,e))i[n++]=s}return i}var iI=Q6;function eV(){return[]}var Lf=eV;var tV=Object.prototype,rV=tV.propertyIsEnumerable,sI=Object.getOwnPropertySymbols,nV=!sI?Lf:function(e){if(e==null)return[];return e=Object(e),iI(sI(e),function(t){return rV.call(e,t)})},jf=nV;function oV(e,t){var r=-1,o=t.length,n=e.length;while(++r<o)e[n+r]=t[r];return e}var ls=oV;var iV=Mf(Object.getPrototypeOf,Object),cs=iV;var sV=Object.getOwnPropertySymbols,aV=!sV?Lf:function(e){var t=[];while(e)ls(t,jf(e)),e=cs(e);return t},aI=aV;function lV(e,t,r){var o=t(e);return je(e)?o:ls(o,r(e))}var zf=lV;function cV(e){return zf(e,Df,jf)}var iS=cV;function uV(e){return zf(e,as,aI)}var lI=uV;var dV=kt(We,"DataView"),Ff=dV;var pV=kt(We,"Promise"),Hf=pV;var fV=kt(We,"Set"),Bf=fV;var mV=kt(We,"WeakMap"),qf=mV;var cI="[object Map]",gV="[object Object]",uI="[object Promise]",dI="[object Set]",pI="[object WeakMap]",fI="[object DataView]",hV=Lr(Ff),yV=Lr(bn),_V=Lr(Hf),bV=Lr(Bf),SV=Lr(qf),Mo=Lt;if(Ff&&Mo(new Ff(new ArrayBuffer(1)))!=fI||bn&&Mo(new bn)!=cI||Hf&&Mo(Hf.resolve())!=uI||Bf&&Mo(new Bf)!=dI||qf&&Mo(new qf)!=pI)Mo=function(e){var t=Lt(e),r=t==gV?e.constructor:void 0,o=r?Lr(r):"";if(o)switch(o){case hV:return fI;case yV:return cI;case _V:return uI;case bV:return dI;case SV:return pI}return t};var sS=Mo;var vV=We.Uint8Array,us=vV;function xV(e){var t=new e.constructor(e.byteLength);return new us(t).set(new us(e)),t}var mI=xV;function wV(e,t){var r=t?mI(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var gI=wV;var hI=Object.create,kV=function(){function e(){}return function(t){if(!Je(t))return{};if(hI)return hI(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}(),yI=kV;function EV(e){return typeof e.constructor=="function"&&!ss(e)?yI(cs(e)):{}}var _I=EV;import{realpathSync as lA}from"fs";var TV="__lodash_hash_undefined__";function PV(e){return this.__data__.set(e,TV),this}var bI=PV;function IV(e){return this.__data__.has(e)}var SI=IV;function Vf(e){var t=-1,r=e==null?0:e.length;this.__data__=new po;while(++t<r)this.add(e[t])}Vf.prototype.add=Vf.prototype.push=bI;Vf.prototype.has=SI;var vI=Vf;function AV(e,t){var r=-1,o=e==null?0:e.length;while(++r<o)if(t(e[r],r,e))return!0;return!1}var xI=AV;function RV(e,t){return e.has(t)}var wI=RV;var OV=1,CV=2;function $V(e,t,r,o,n,i){var s=r&OV,a=e.length,c=t.length;if(a!=c&&!(s&&c>a))return!1;var u=i.get(e),d=i.get(t);if(u&&d)return u==t&&d==e;var p=-1,f=!0,m=r&CV?new vI:void 0;i.set(e,t),i.set(t,e);while(++p<a){var g=e[p],h=t[p];if(o)var y=s?o(h,g,p,t,e,i):o(g,h,p,e,t,i);if(y!==void 0){if(y)continue;f=!1;break}if(m){if(!xI(t,function(S,x){if(!wI(m,x)&&(g===S||n(g,S,r,o,i)))return m.push(x)})){f=!1;break}}else if(!(g===h||n(g,h,r,o,i))){f=!1;break}}return i.delete(e),i.delete(t),f}var Wf=$V;function MV(e){var t=-1,r=Array(e.size);return e.forEach(function(o,n){r[++t]=[n,o]}),r}var kI=MV;function DV(e){var t=-1,r=Array(e.size);return e.forEach(function(o){r[++t]=o}),r}var EI=DV;var NV=1,UV=2,LV="[object Boolean]",jV="[object Date]",zV="[object Error]",FV="[object Map]",HV="[object Number]",BV="[object RegExp]",qV="[object Set]",VV="[object String]",WV="[object Symbol]",KV="[object ArrayBuffer]",ZV="[object DataView]",TI=mt?mt.prototype:void 0,aS=TI?TI.valueOf:void 0;function GV(e,t,r,o,n,i,s){switch(r){case ZV:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case KV:if(e.byteLength!=t.byteLength||!i(new us(e),new us(t)))return!1;return!0;case LV:case jV:case HV:return Rr(+e,+t);case zV:return e.name==t.name&&e.message==t.message;case BV:case VV:return e==t+"";case FV:var a=kI;case qV:var c=o&NV;if(a||(a=EI),e.size!=t.size&&!c)return!1;var u=s.get(e);if(u)return u==t;o|=UV,s.set(e,t);var d=Wf(a(e),a(t),o,n,i,s);return s.delete(e),d;case WV:if(aS)return aS.call(e)==aS.call(t)}return!1}var PI=GV;var JV=1,XV=Object.prototype,YV=XV.hasOwnProperty;function QV(e,t,r,o,n,i){var s=r&JV,a=iS(e),c=a.length,u=iS(t),d=u.length;if(c!=d&&!s)return!1;var p=c;while(p--){var f=a[p];if(!(s?f in t:YV.call(t,f)))return!1}var m=i.get(e),g=i.get(t);if(m&&g)return m==t&&g==e;var h=!0;i.set(e,t),i.set(t,e);var y=s;while(++p<c){f=a[p];var S=e[f],x=t[f];if(o)var w=s?o(x,S,f,t,e,i):o(S,x,f,e,t,i);if(!(w===void 0?S===x||n(S,x,r,o,i):w)){h=!1;break}y||(y=f=="constructor")}if(h&&!y){var R=e.constructor,U=t.constructor;if(R!=U&&(("constructor"in e)&&("constructor"in t))&&!(typeof R=="function"&&R instanceof R&&typeof U=="function"&&U instanceof U))h=!1}return i.delete(e),i.delete(t),h}var II=QV;var eW=1,AI="[object Arguments]",RI="[object Array]",Kf="[object Object]",tW=Object.prototype,OI=tW.hasOwnProperty;function rW(e,t,r,o,n,i){var s=je(e),a=je(t),c=s?RI:sS(e),u=a?RI:sS(t);c=c==AI?Kf:c,u=u==AI?Kf:u;var d=c==Kf,p=u==Kf,f=c==u;if(f&&Mn(e)){if(!Mn(t))return!1;s=!0,d=!1}if(f&&!d)return i||(i=new $n),s||is(e)?Wf(e,t,r,o,n,i):PI(e,t,c,r,o,n,i);if(!(r&eW)){var m=d&&OI.call(e,"__wrapped__"),g=p&&OI.call(t,"__wrapped__");if(m||g){var h=m?e.value():e,y=g?t.value():t;return i||(i=new $n),n(h,y,r,o,i)}}if(!f)return!1;return i||(i=new $n),II(e,t,r,o,n,i)}var CI=rW;function $I(e,t,r,o,n){if(e===t)return!0;if(e==null||t==null||!_t(e)&&!_t(t))return e!==e&&t!==t;return CI(e,t,r,o,$I,n)}var Zf=$I;var nW=1,oW=2;function iW(e,t,r,o){var n=r.length,i=n,s=!o;if(e==null)return!i;e=Object(e);while(n--){var a=r[n];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}while(++n<i){a=r[n];var c=a[0],u=e[c],d=a[1];if(s&&a[2]){if(u===void 0&&!(c in e))return!1}else{var p=new $n;if(o)var f=o(u,d,c,e,t,p);if(!(f===void 0?Zf(d,u,nW|oW,o,p):f))return!1}}return!0}var MI=iW;function sW(e){return e===e&&!Je(e)}var Gf=sW;function aW(e){var t=Df(e),r=t.length;while(r--){var o=t[r],n=e[o];t[r]=[o,n,Gf(n)]}return t}var DI=aW;function lW(e,t){return function(r){if(r==null)return!1;return r[e]===t&&(t!==void 0||(e in Object(r)))}}var Jf=lW;function cW(e){var t=DI(e);if(t.length==1&&t[0][2])return Jf(t[0][0],t[0][1]);return function(r){return r===e||MI(r,e,t)}}var NI=cW;var uW="[object Symbol]";function dW(e){return typeof e=="symbol"||_t(e)&&Lt(e)==uW}var ds=dW;var pW=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,fW=/^\w*$/;function mW(e,t){if(je(e))return!1;var r=typeof e;if(r=="number"||r=="symbol"||r=="boolean"||e==null||ds(e))return!0;return fW.test(e)||!pW.test(e)||t!=null&&e in Object(t)}var ps=mW;var gW=500;function hW(e){var t=pe(e,function(o){if(r.size===gW)r.clear();return o}),r=t.cache;return t}var UI=hW;var yW=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_W=/\\(\\)?/g,bW=UI(function(e){var t=[];if(e.charCodeAt(0)===46)t.push("");return e.replace(yW,function(r,o,n,i){t.push(n?i.replace(_W,"$1"):o||r)}),t}),LI=bW;function SW(e,t){var r=-1,o=e==null?0:e.length,n=Array(o);while(++r<o)n[r]=t(e[r],r,e);return n}var Xf=SW;var vW=1/0,jI=mt?mt.prototype:void 0,zI=jI?jI.toString:void 0;function FI(e){if(typeof e=="string")return e;if(je(e))return Xf(e,FI)+"";if(ds(e))return zI?zI.call(e):"";var t=e+"";return t=="0"&&1/e==-vW?"-0":t}var HI=FI;function xW(e){return e==null?"":HI(e)}var BI=xW;function wW(e,t){if(je(e))return e;return ps(e,t)?[e]:LI(BI(e))}var Un=wW;var kW=1/0;function EW(e){if(typeof e=="string"||ds(e))return e;var t=e+"";return t=="0"&&1/e==-kW?"-0":t}var Cr=EW;function TW(e,t){t=Un(t,e);var r=0,o=t.length;while(e!=null&&r<o)e=e[Cr(t[r++])];return r&&r==o?e:void 0}var fs=TW;function PW(e,t,r){var o=e==null?void 0:fs(e,t);return o===void 0?r:o}var qI=PW;function IW(e,t){return e!=null&&t in Object(e)}var VI=IW;function AW(e,t,r){t=Un(t,e);var o=-1,n=t.length,i=!1;while(++o<n){var s=Cr(t[o]);if(!(i=e!=null&&r(e,s)))break;e=e[s]}if(i||++o!=n)return i;return n=e==null?0:e.length,!!n&&os(n)&&Dn(s,n)&&(je(e)||Yr(e))}var WI=AW;function RW(e,t){return e!=null&&WI(e,t,VI)}var Yf=RW;var OW=1,CW=2;function $W(e,t){if(ps(e)&&Gf(t))return Jf(Cr(e),t);return function(r){var o=qI(r,e);return o===void 0&&o===t?Yf(r,e):Zf(t,o,OW|CW)}}var KI=$W;function MW(e){return e}var ms=MW;function DW(e){return function(t){return t==null?void 0:t[e]}}var ZI=DW;function NW(e){return function(t){return fs(t,e)}}var GI=NW;function UW(e){return ps(e)?ZI(Cr(e)):GI(e)}var JI=UW;function LW(e){if(typeof e=="function")return e;if(e==null)return ms;if(typeof e=="object")return je(e)?KI(e[0],e[1]):NI(e);return JI(e)}var Qf=LW;import{cwd as ZW}from"process";import{randomUUID as gc}from"crypto";import{createHash as zW,randomBytes as hMe}from"crypto";var XI="[\\w-]{1,63}",jW=new RegExp(`^${XI}$`),fMe=new RegExp(`^a(?:${XI}-)?[0-9a-f]{16}$`);function YI(e,t){let r=Buffer.from(t.replace(/-/g,""),"hex"),o=zW("sha1").update(r).update(Buffer.from(e,"utf8")).digest();o[6]=o[6]&15|80,o[8]=o[8]&63|128;let n=o.subarray(0,16).toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}var FW="3ab19d7e-9f35-45c2-926e-75e271cc60b3";function QI(){let e=process.env.CLAUDE_CODE_REMOTE_SESSION_ID?.trim();return e?YI(e,FW):null}var lS=null;function eA(){return lS}function tA(e){lS=e}var em=new Map;function rA(e){return em.has(e)?em.get(e):void 0}function nA(e,t){em.set(e,t)}var HW;var BW;var qW;var VW;var WW;var cS=new Map;function oA(e){return cS.get(e)}function iA(e,t){cS.set(e,t)}function Do(){lS=null,em.clear(),cS.clear(),WW=void 0,HW=void 0,BW=void 0,qW=void 0,VW=void 0}var KW;function sA(){return KW}function aA(){return{sent:new Set,rejected:new Set}}var GW={renderTarget:"ink",workspace:"local",canDrive:!0,transcriptSource:"local-jsonl",remote:null};function JW(){let e="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof lA==="function"){let r=ZW();try{e=cA(lA(r))}catch{e=cA(r)}}return{originalCwd:e,projectRoot:e,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),sessionLogicalStartTime:void 0,lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:e,modelUsage:{},mainLoopModelOverride:void 0,refusalFallbackOccurred:!1,refusalFallbackModelLatch:void 0,sdkDialogHostActive:!1,sdkSupportedDialogKinds:void 0,sdkSupportedDialogKindsSource:void 0,replConfigArgv:[],settingsEffortAtStartup:void 0,initialMainLoopModel:void 0,resolvedOrgDefault:void 0,modelStrings:null,isInteractive:!1,thinkingDisplayExplicit:!1,permissionPromptToolName:void 0,attacherCaps:null,hasStreamingInput:!1,modelOverrideOptOutForSession:!1,rendererMode:void 0,strictToolResultPairing:!1,memoryToggledOff:!1,teamMemoryServerStatus:void 0,sdkAgentProgressSummariesEnabled:!1,userMsgOptIn:!1,searchToolsOptIn:!1,clientType:"cli",sessionSource:void 0,sessionStartType:"fresh",questionPreviewFormat:void 0,sessionIngressToken:void 0,oauthTokenFromFd:void 0,oauthTokenFromBgSnapshot:!1,oauthScopesFromFd:void 0,apiKeyFromFd:void 0,gatewayAuth:null,gatewayRefreshInFlight:null,startupPolicySnapshot:void 0,flagSettingsPath:void 0,flagSettingsExpectedContent:void 0,flagSettingsInline:null,parentManagedSettings:null,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,statsStore:null,sessionId:QI()??gc(),mainAgentId:null,parentSessionId:void 0,loggerProvider:null,eventLogger:null,pendingOTelEvents:[],meterProvider:null,tracerProvider:null,cachedTelemetryResource:null,cachedOtlpHttpAgentFactory:{direct:null,proxied:null},foundryDeploymentCapabilities:new Map,agentColorMap:new Map,agentColorIndex:0,lastAPIRequest:null,lastCancelledAPIMessageId:null,lastAPIRequestMessages:null,lastClassifierRequests:null,cachedClaudeMdContent:null,inMemoryErrorLog:[],inlinePlugins:[],inlinePluginsNoMcp:[],inlinePluginUrls:[],syncedPluginDirs:[],chromeFlagOverride:void 0,teammateAgentId:void 0,onboardingShownThisSession:!1,useCoworkPlugins:!1,disableSlashCommands:!1,sessionBypassPermissionsMode:!1,scheduledTasksEnabled:!1,sessionPrResolved:!1,sessionCronTasks:[],loopChainStartedAt:Object.create(null),loopTickInFlightPrompt:null,loopConsecutiveKeepalives:0,loopEnded:!1,sessionCreatedTeams:new Set,surfacedHookSpawnFailures:new Set,bareMcpServerMatchersWarned:new Set,inheritedTeamName:void 0,sessionTrustAccepted:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,needsAutoModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0,longContext1mCreditsBlocked:!1,fableCreditsRequired:!1,fableConsentSessionFallback:!1,fableBridgeDialogTimedOut:!1,fableConsentDialogInteracted:!1,sdkOAuthTokenRefreshCallback:null,hostAuthTokenRefreshCallback:null,mainThreadAgentType:void 0,mainThreadAgentHooks:void 0,sessionSkillAllowlist:void 0,caps:GW,replBridgeActive:!1,mainLoopBusy:!1,directConnectServerUrl:void 0,mcpConnectNonBlocking:!1,deferredToolStubGateLatch:null,strictMcpConfig:!1,cliSessionConfigCarried:!1,sessionApprovedMcpServers:[],activeRoutine:void 0,systemPromptSectionCache:new Map,lastEmittedDate:null,additionalDirectoriesForClaudeMd:[],allowedChannels:[],hasDevChannels:!1,sessionProjectDir:null,promptCache1hAllowlist:null,stickyBetas:aA(),thinkingTypeOverrides:new Map,inferenceProfileBackingModels:new Map,promptId:null,promptIndex:0,lastMainRequestId:void 0,lastMainThreadCacheTtlMs:null,lastApiCompletionTimestamp:null,pendingPostCompaction:!1}}var XW=JW(),YW=()=>{return};function uS(){return YW()?.sessionId??XW.sessionId}var QW=hn(),DMe=QW.subscribe;function cA(e){return process.platform==="darwin"?e.normalize("NFC"):e}var eK=hn(),NMe=eK.subscribe;var tK=hn(),UMe=tK.subscribe;var rK=hn();var LMe=rK.subscribe;var nK=hn();var jMe=nK.subscribe;import{appendFile as vA,mkdir as DK,rename as xA,stat as NK,symlink as UK,unlink as mS}from"fs/promises";import{dirname as gS,join as bS,resolve as LK}from"path";function uA({writeFn:e,flushIntervalMs:t=1000,maxBufferSize:r=100,maxBufferBytes:o=1/0,immediateMode:n=!1}){let i=[],s=0,a=null,c=null;function u(){if(a)clearTimeout(a),a=null}function d(g){try{e(g)}catch{}}function p(){if(c)d(c.join("")),c=null;if(i.length===0)return;d(i.join("")),i=[],s=0,u()}function f(){if(!a)a=setTimeout(p,t)}function m(){if(c){c.push(...i),i=[],s=0,u();return}let g=i;i=[],s=0,u(),c=g,setImmediate(()=>{let h=c;if(c=null,h)d(h.join(""))})}return{write(g){if(n){d(g);return}if(i.push(g),s+=g.length,f(),i.length>=r||s>=o)m()},flush:p,dispose(){p()}}}function oK(e){if(typeof e==="function")return e;if(Symbol.asyncDispose in e)return()=>e[Symbol.asyncDispose]();return()=>e[Symbol.dispose]()}class dS{#n=new Set;register(e){let t=oK(e);this.#n.add(t);let r=()=>{this.#n.delete(t)};return Object.assign(r,{[Symbol.dispose]:r})}async drain(){let e=Array.from(this.#n);this.#n.clear(),await Promise.all(e.map(async(t)=>t()))}async[Symbol.asyncDispose](){await this.drain()}get sizeForTesting(){return this.#n.size}}var iK=new dS;function tm(e){return iK.register(e)}var HMe=new dS;var dA=pe((e)=>{if(!e||e.trim()==="")return null;let t=e.split(",").map((i)=>i.trim()).filter(Boolean);if(t.length===0)return null;let r=t.some((i)=>i.startsWith("!")),o=t.some((i)=>!i.startsWith("!"));if(r&&o)return null;let n=t.map((i)=>i.replace(/^!/,"").toLowerCase());return{include:r?[]:n,exclude:r?n:[],isExclusive:r}});function sK(e){let t=[],r=e.match(/^MCP server ["']([^"']+)["']/);if(r&&r[1])t.push("mcp"),t.push(r[1].toLowerCase());else{let i=e.match(/^([^:[]+):/);if(i&&i[1])t.push(i[1].trim().toLowerCase())}let o=e.match(/^\[([^\]]+)]/);if(o&&o[1])t.push(o[1].trim().toLowerCase());if(e.toLowerCase().includes("1p event:"))t.push("1p");let n=e.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(n&&n[1]){let i=n[1].trim().toLowerCase();if(i.length<30&&!i.includes(" "))t.push(i)}return Array.from(new Set(t))}function aK(e,t){if(!t)return!0;if(e.length===0)return!1;if(t.isExclusive)return!e.some((r)=>t.exclude.includes(r));else return e.some((r)=>t.include.includes(r))}function pA(e,t){if(!t)return!0;let r=sK(e);return aK(r,t)}import*as Y from"fs";import{appendFile as lK,chmod as cK,copyFile as uK,link as dK,lstat as pK,mkdir as fK,open as fA,readdir as mK,readFile as mA,readlink as gK,realpath as hK,rename as yK,rmdir as _K,rm as bK,stat as SK,symlink as vK,unlink as xK}from"fs/promises";import*as ut from"path";var rm="→";function wK(e,t){if(fa(t)&&!ga(t)||ma(t))return;let r=ut.resolve(t),o=ut.parse(r).root,n=o,i=r.slice(o.length).split(/[\\/]+/).filter(Boolean),s=0,a=64;while(i.length>0&&s<a){let c=ut.join(n,i[0]);if(ma(c))return i.length===1?c:ut.join(c,...i.slice(1));let u;try{u=e.lstatSync(c)}catch{return}if(!u.isSymbolicLink()){i.shift(),n=c;continue}s++;let d;try{d=e.readlinkSync(c)}catch{return}let p=ut.isAbsolute(d)?d:ut.resolve(n,d);if(fa(p)&&!ga(p)||ma(p))return i.shift(),i.length===0?p:ut.join(p,...i);i.shift();let f=ut.parse(p).root||ut.sep;n=f,i=[...p.slice(f.length).split(/[\\/]+/).filter(Boolean),...i]}return}function nm(e,t){if(fa(t)&&!ga(t)||ma(t))return{resolvedPath:t,isSymlink:!1,isCanonical:!1};let r=wK(e,t);if(r!==void 0)return{resolvedPath:r,isSymlink:!0,isCanonical:!1};try{let o=e.realpathSync(t);return{resolvedPath:o,isSymlink:o!==t,isCanonical:!0}}catch(o){return{resolvedPath:t,isSymlink:!1,isCanonical:!1}}}var kK={cwd(){return process.cwd()},existsSync(e){let r=[];try{const t=Te(r,$e`fs.existsSync(${e})`,0);return Y.existsSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},async stat(e){return SK(e)},async lstat(e){return pK(e)},async readdir(e){return mK(e,{withFileTypes:!0})},async unlink(e){return xK(e)},async rmdir(e){return _K(e)},async rm(e,t){return bK(e,t)},async mkdir(e,t){try{await fK(e,{recursive:!0,...t})}catch(r){if(Be(r)!=="EEXIST")throw r}},async readFile(e,t){return mA(e,{encoding:t.encoding})},async rename(e,t){return yK(e,t)},async realpath(e){return Ir(await hK(e))},async readlink(e){return gK(e)},async copyFile(e,t){return uK(e,t)},async appendFile(e,t,r){if(r?.mode!==void 0)try{let o=await fA(e,"ax",r.mode);try{await o.appendFile(t)}finally{await o.close()}return}catch(o){if(Be(o)!=="EEXIST")throw o}return lK(e,t)},async symlink(e,t,r){return vK(e,t,r)},async link(e,t){return dK(e,t)},async chmod(e,t){return cK(e,t)},statSync(e){let r=[];try{const t=Te(r,$e`fs.statSync(${e})`,0);return Y.statSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},lstatSync(e){let r=[];try{const t=Te(r,$e`fs.lstatSync(${e})`,0);return Y.lstatSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},readFileSync(e,t){let o=[];try{const r=Te(o,$e`fs.readFileSync(${e})`,0);return Y.readFileSync(e,{encoding:t.encoding})}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},readFileBytesSync(e){let r=[];try{const t=Te(r,$e`fs.readFileBytesSync(${e})`,0);return Y.readFileSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},readSync(e,t){let n=[];try{const r=Te(n,$e`fs.readSync(${e}, ${t.length} bytes)`,0);let o=void 0;try{o=Y.openSync(e,"r");let c=Buffer.alloc(t.length),u=Y.readSync(o,c,0,t.length,0);return{buffer:c,bytesRead:u}}finally{if(o)Y.closeSync(o)}}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},appendFileSync(e,t,r){let n=[];try{const o=Te(n,$e`fs.appendFileSync(${e}, ${t.length} chars)`,0);if(r?.mode!==void 0)try{let c=Y.openSync(e,"ax",r.mode);try{Y.appendFileSync(c,t)}finally{Y.closeSync(c)}return}catch(c){if(Be(c)!=="EEXIST")throw c}Y.appendFileSync(e,t)}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},copyFileSync(e,t){let o=[];try{const r=Te(o,$e`fs.copyFileSync(${e} ${rm} ${t})`,0);Y.copyFileSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},unlinkSync(e){let r=[];try{const t=Te(r,$e`fs.unlinkSync(${e})`,0);Y.unlinkSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},renameSync(e,t){let o=[];try{const r=Te(o,$e`fs.renameSync(${e} ${rm} ${t})`,0);Y.renameSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},linkSync(e,t){let o=[];try{const r=Te(o,$e`fs.linkSync(${e} ${rm} ${t})`,0);Y.linkSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},symlinkSync(e,t,r){let n=[];try{const o=Te(n,$e`fs.symlinkSync(${e} ${rm} ${t})`,0);Y.symlinkSync(e,t,r)}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},readlinkSync(e){let r=[];try{const t=Te(r,$e`fs.readlinkSync(${e})`,0);return Y.readlinkSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},realpathSync(e){let r=[];try{const t=Te(r,$e`fs.realpathSync(${e})`,0);return Ir(Y.realpathSync(e))}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},mkdirSync(e,t){let n=[];try{const r=Te(n,$e`fs.mkdirSync(${e})`,0);let o={recursive:!0};if(t?.mode!==void 0)o.mode=t.mode;try{Y.mkdirSync(e,o)}catch(c){if(Be(c)!=="EEXIST")throw c}}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},readdirSync(e){let r=[];try{const t=Te(r,$e`fs.readdirSync(${e})`,0);return Y.readdirSync(e,{withFileTypes:!0})}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},readdirStringSync(e){let r=[];try{const t=Te(r,$e`fs.readdirStringSync(${e})`,0);return Y.readdirSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},rmdirSync(e){let r=[];try{const t=Te(r,$e`fs.rmdirSync(${e})`,0);Y.rmdirSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},rmSync(e,t){let o=[];try{const r=Te(o,$e`fs.rmSync(${e})`,0);Y.rmSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},createWriteStream(e){return Y.createWriteStream(e)},async readFileBytes(e,t){if(t===void 0)return mA(e);let r=await fA(e,"r");try{let{size:o}=await r.stat(),n=Math.min(o,t),i=Buffer.allocUnsafe(n),s=0;while(s<n){let{bytesRead:a}=await r.read(i,s,n-s,s);if(a===0)break;s+=a}return s<n?i.subarray(0,s):i}finally{await r.close()}}},EK=kK;function qe(){return EK}function TK(e,t){if(e.destroyed||e.writableEnded)return;e.write(t)}function gA(e){TK(process.stderr,e)}var PK=/api[_-]?key|secret|token|password|passwd|credential|bearer|authorization|auth[_-]?header|cookie|session[_-]?(?:id|key)|connection[_-]?string|(?:private|ssh|encryption|signing|access|deploy|master|license)[_-]?key|client[_-]?secret/i,hA="[^\\s,;&}\\])]+",bA="-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\\s\\S-]{64,}?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----",IK=`[^\\s-]{0,4}${bA}['"\`]?`,yA=`\\[REDACTED\\]|"[^"]*"|'[^']*'|(?:Bearer|Basic)\\s+(?:\\[REDACTED\\]|${hA})|${IK}|${hA}`,AK=["sk","ant","api"].join("-"),RK=[{id:"url-userinfo",source:":\\/\\/([^/@\\s]+)@",confidence:"low"},{id:"gcp-service-account",source:"\\b([a-z0-9-]+@[a-z0-9-]+\\.iam\\.gserviceaccount\\.com)\\b",flags:"i",confidence:"low"},{id:"loose-anthropic-key",source:"\\b(sk-ant-?[\\w-]{10,})",confidence:"low"},{id:"http-auth-scheme",source:"\\b(?:Bearer|Basic)\\s+([A-Za-z0-9+/=._~-]{20,})",flags:"i",confidence:"low"},{id:"loose-jwt",source:"\\b(eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,})",confidence:"low"},{id:"sensitive-assign",source:`(?:${PK.source})[\\w.-]*["']?\\s*[=:]\\s*(${yA})`,flags:"i",confidence:"low"},{id:"cloud-env-var",source:`\\b(?:AWS|GOOGLE|GCP|GCLOUD|AZURE)_\\w+\\s*[=:]\\s*(${yA})`,flags:"i",confidence:"low"},{id:"aws-access-token",source:"\\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\\b",confidence:"high"},{id:"gcp-api-key",source:"\\b(AIza[\\w-]{35})(?![\\w-])",confidence:"high"},{id:"google-oauth-client-secret",source:"\\bGOCSPX-[\\w-]{28}(?![\\w-])",confidence:"high"},{id:"azure-ad-client-secret",source:`(?:^|[\\\\'"\\x60\\s>=:(,)])([a-zA-Z0-9_~.]{3}\\dQ~[a-zA-Z0-9_~.-]{31,34})(?:$|[\\\\'"\\x60\\s<),])`,confidence:"high"},{id:"digitalocean-pat",source:`\\b(dop_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"digitalocean-access-token",source:`\\b(doo_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-api-key",source:`\\b(${AK}03-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-admin-api-key",source:`\\b(sk-ant-admin01-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"openai-api-key",source:"sk-[A-Za-z0-9_-]{8,200}T3BlbkFJ[A-Za-z0-9_-]{8,200}",confidence:"high"},{id:"openai-legacy-api-key",source:"\\bsk-[a-zA-Z0-9]{48}(?![a-zA-Z0-9])",confidence:"high"},{id:"huggingface-access-token",source:`\\b(hf_[a-zA-Z]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"supabase-secret-key",source:"\\bsb_secret_[A-Za-z0-9_-]{20,}",confidence:"high"},{id:"supabase-access-token",source:"\\bsbp_[a-z0-9]{40,}",confidence:"high"},{id:"github-pat",source:"ghp_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-fine-grained-pat",source:"github_pat_\\w{82}",confidence:"high"},{id:"github-app-token",source:"(?:ghu|ghs)_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-oauth",source:"gho_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-refresh-token",source:"ghr_[0-9a-zA-Z]{36}",confidence:"high"},{id:"gitlab-pat",source:"glpat-[\\w-]{20}",confidence:"high"},{id:"gitlab-deploy-token",source:"gldt-[0-9a-zA-Z_\\-]{20}",confidence:"high"},{id:"slack-bot-token",source:"xoxb-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*",confidence:"high"},{id:"slack-user-token",source:"xox[pe](?:-[0-9]{10,13}){3}-[a-zA-Z0-9-]{28,34}",confidence:"high"},{id:"slack-app-token",source:"xapp-\\d-[A-Z0-9]+-\\d+-[a-z0-9]+",flags:"i",confidence:"high"},{id:"twilio-api-key",source:"SK[0-9a-fA-F]{32}",confidence:"high"},{id:"sendgrid-api-token",source:`\\b(SG\\.[a-zA-Z0-9=_\\-.]{66})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"npm-access-token",source:`\\b(npm_[a-zA-Z0-9]{36})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"pypi-upload-token",source:"pypi-AgEIcHlwaS5vcmc[\\w-]{50,1000}",confidence:"high"},{id:"databricks-api-token",source:`\\b(dapi[a-f0-9]{32}(?:-\\d)?)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"hashicorp-tf-api-token",source:"[a-zA-Z0-9]{14}\\.atlasv1\\.[a-zA-Z0-9\\-_=]{60,70}",confidence:"high"},{id:"pulumi-api-token",source:`\\b(pul-[a-f0-9]{40})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"postman-api-token",source:`\\b(PMAK-[a-fA-F0-9]{24}-[a-fA-F0-9]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-api-key",source:`\\b(eyJrIjoi[A-Za-z0-9+/]{70,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-cloud-api-token",source:`\\b(glc_[A-Za-z0-9+/]{32,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-service-account-token",source:`\\b(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-user-token",source:`\\b(sntryu_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-org-token",source:"\\bsntrys_eyJpYXQiO[a-zA-Z0-9+/]{10,200}(?:LCJyZWdpb25fdXJs|InJlZ2lvbl91cmwi|cmVnaW9uX3VybCI6)[a-zA-Z0-9+/]{10,200}={0,2}_[a-zA-Z0-9+/]{43}",confidence:"high"},{id:"stripe-access-token",source:`\\b((?:sk|rk)_(?:test|live|prod)_[a-zA-Z0-9]{10,99})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"shopify-access-token",source:"shpat_[a-fA-F0-9]{32}",confidence:"high"},{id:"shopify-shared-secret",source:"shpss_[a-fA-F0-9]{32}",confidence:"high"},{id:"private-key",source:bA,flags:"i",confidence:"high"}];var _A=null;function OK(e){return RK.map((t)=>({id:t.id,confidence:t.confidence,re:new RegExp(t.source,e?(t.flags??"").replace("g","")+"g":t.flags??"")}))}function CK(e,t){if(typeof t!=="string")return"[REDACTED]";let r=t.length>=2&&(t[0]==='"'||t[0]==="'")&&t.at(-1)===t[0]?t[0]:"",o=e.lastIndexOf(t);return`${e.slice(0,o)}${r}[REDACTED]${r}${e.slice(o+t.length)}`}var $K=512,MK=512,hc=new Map;function SA(e){let t=e.length<=$K;if(t){let o=hc.get(e);if(o!==void 0)return o}_A??=OK(!0);let r=e;for(let o of _A)r=r.replace(o.re,CK);if(t){if(hc.size>=MK)hc.delete(hc.keys().next().value);hc.set(e,r)}return r}var hS={verbose:0,debug:1,info:2,warn:3,error:4},jK=pe(()=>{let e=process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim();if(e&&Object.hasOwn(hS,e))return e;return"debug"}),zK=!1;function om(){if(typeof process>"u"||!Array.isArray(process.argv))return[];let e=process.argv.indexOf("--");return e===-1?process.argv:process.argv.slice(0,e)}var EA=pe(()=>{let e=om();return zK||ve(process.env.DEBUG)||ve(process.env.DEBUG_SDK)||e.includes("--debug")||e.includes("-d")||TA()||e.some((t)=>t.startsWith("--debug="))||PA()!==null});var FK=pe(()=>{let e=om().find((r)=>r.startsWith("--debug="));if(!e)return null;let t=e.substring(8);return dA(t)}),TA=pe(()=>{let e=om();return e.includes("--debug-to-stderr")||e.includes("-d2e")}),PA=pe(()=>{let e=om();for(let t=0;t<e.length;t++){let r=e[t];if(r.startsWith("--debug-file="))return wA(r.substring(13));if(r==="--debug-file"&&t+1<e.length)return wA(e[t+1])}return null});function wA(e){return Ek(e)?null:LK(e)}function HK(e){if(!EA())return!1;if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let t=FK();return pA(e,t)}var BK=!1;var qK=10485760,yc=null,pS=Promise.resolve(),gs=[],bc=null,kA=null;var _c=-1,fS=!1,yS=null;async function VK(e,t,r=qK){if(_c<0)_c=await NK(e).then((o)=>o.size).catch(()=>0);else _c+=t;if(_c<=r||fS)return;fS=!0;try{let o=e.endsWith(".txt")?`${e.slice(0,-4)}.1.txt`:`${e}.1`;try{await xA(e,o)}catch(n){if(!Xr(n))await mS(o).catch(()=>{}),await xA(e,o).catch(()=>mS(e).catch(()=>{}))}_c=0}finally{fS=!1}}function IA(e){return yS=bS(e,`${uS()}.txt`),yS}async function WK(e,t,r,o){if(e)await DK(t,{recursive:!0}).catch(()=>{});let n=r;try{await vA(r,o)}catch(i){if(!Xb(i))throw i;n=IA(r),await vA(n,o)}await VK(n,Buffer.byteLength(o)).catch(AA),GK()}function AA(){}function KK(){gs.shift()}function ZK(){if(!yc){let e=null;if(yc=uA({writeFn:(t)=>{if(bc){gs.push(t),bc();return}let r=_S(),o=gS(r),n=e!==o;e=o,gs.push(t),pS=pS.then(WK.bind(null,n,o,r,t)).catch(AA).then(KK)},flushIntervalMs:1000,maxBufferSize:100,immediateMode:EA()}),tm(async()=>{yc?.dispose(),await pS}),!kA)process.on("exit",kA=()=>{bc=()=>{if(gs.length===0)return;let t=gs.join("");gs.length=0;let r=_S();try{qe().mkdirSync(gS(r))}catch{}try{qe().appendFileSync(r,t)}catch(o){if(Xb(o))try{qe().appendFileSync(IA(r),t)}catch{}}},yc?.flush(),bc()})}return yc}function Q(e,{level:t}={level:"debug"}){if(hS[t]<hS[jK()])return;if(!HK(e))return;if(BK&&e.includes(`
|
|
86
|
+
`;CP().then(()=>{if($o)Qi().append($o,r).catch(()=>{})})}function Aq(){this.__data__=new _n,this.size=0}var MP=Aq;function Rq(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var DP=Rq;function Oq(e){return this.__data__.get(e)}var NP=Oq;function Cq(e){return this.__data__.has(e)}var UP=Cq;var $q=200;function Mq(e,t){var r=this.__data__;if(r instanceof _n){var o=r.__data__;if(!bn||o.length<$q-1)return o.push([e,t]),this.size=++r.size,this;r=this.__data__=new po(o)}return r.set(e,t),this.size=r.size,this}var LP=Mq;function ts(e){var t=this.__data__=new _n(e);this.size=t.size}ts.prototype.clear=MP;ts.prototype.delete=DP;ts.prototype.get=NP;ts.prototype.has=UP;ts.prototype.set=LP;var $n=ts;var Dq=function(){try{var e=kt(Object,"defineProperty");return e({},"",{}),e}catch(t){}}(),rs=Dq;function Nq(e,t,r){if(t=="__proto__"&&rs)rs(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0});else e[t]=r}var ns=Nq;var Uq=Object.prototype,Lq=Uq.hasOwnProperty;function jq(e,t,r){var o=e[t];if(!(Lq.call(e,t)&&Rr(o,r))||r===void 0&&!(t in e))ns(e,t,r)}var Pf=jq;function zq(e,t,r,o){var n=!r;r||(r={});var i=-1,s=t.length;while(++i<s){var a=t[i],c=o?o(r[a],e[a],a,r,e):void 0;if(c===void 0)c=e[a];if(n)ns(r,a,c);else Pf(r,a,c)}return r}var jP=zq;function Fq(e,t){var r=-1,o=Array(e);while(++r<e)o[r]=t(r);return o}var zP=Fq;function Hq(e){return e!=null&&typeof e=="object"}var _t=Hq;var Bq="[object Arguments]";function qq(e){return _t(e)&&Lt(e)==Bq}var rS=qq;var FP=Object.prototype,Vq=FP.hasOwnProperty,Wq=FP.propertyIsEnumerable,Kq=rS(function(){return arguments}())?rS:function(e){return _t(e)&&Vq.call(e,"callee")&&!Wq.call(e,"callee")},Yr=Kq;var Zq=Array.isArray,je=Zq;var Af={};Pr(Af,{default:()=>Mn});function Gq(){return!1}var HP=Gq;var VP=typeof Af=="object"&&Af&&!Af.nodeType&&Af,BP=VP&&typeof If=="object"&&If&&!If.nodeType&&If,Jq=BP&&BP.exports===VP,qP=Jq?We.Buffer:void 0,Xq=qP?qP.isBuffer:void 0,Yq=Xq||HP,Mn=Yq;var Qq=9007199254740991,e6=/^(?:0|[1-9]\d*)$/;function t6(e,t){var r=typeof e;return t=t==null?Qq:t,!!t&&(r=="number"||r!="symbol"&&e6.test(e))&&(e>-1&&e%1==0&&e<t)}var Dn=t6;var r6=9007199254740991;function n6(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=r6}var os=n6;var o6="[object Arguments]",i6="[object Array]",s6="[object Boolean]",a6="[object Date]",l6="[object Error]",c6="[object Function]",u6="[object Map]",d6="[object Number]",p6="[object Object]",f6="[object RegExp]",m6="[object Set]",g6="[object String]",h6="[object WeakMap]",y6="[object ArrayBuffer]",_6="[object DataView]",b6="[object Float32Array]",S6="[object Float64Array]",v6="[object Int8Array]",x6="[object Int16Array]",w6="[object Int32Array]",k6="[object Uint8Array]",E6="[object Uint8ClampedArray]",T6="[object Uint16Array]",P6="[object Uint32Array]",Ce={};Ce[b6]=Ce[S6]=Ce[v6]=Ce[x6]=Ce[w6]=Ce[k6]=Ce[E6]=Ce[T6]=Ce[P6]=!0;Ce[o6]=Ce[i6]=Ce[y6]=Ce[s6]=Ce[_6]=Ce[a6]=Ce[l6]=Ce[c6]=Ce[u6]=Ce[d6]=Ce[p6]=Ce[f6]=Ce[m6]=Ce[g6]=Ce[h6]=!1;function I6(e){return _t(e)&&os(e.length)&&!!Ce[Lt(e)]}var WP=I6;function A6(e){return function(t){return e(t)}}var KP=A6;var Of={};Pr(Of,{default:()=>Cf});var ZP=typeof Of=="object"&&Of&&!Of.nodeType&&Of,mc=ZP&&typeof Rf=="object"&&Rf&&!Rf.nodeType&&Rf,R6=mc&&mc.exports===ZP,nS=R6&&Vu.process,O6=function(){try{var e=mc&&mc.require&&mc.require("util").types;if(e)return e;return nS&&nS.binding&&nS.binding("util")}catch(t){}}(),Cf=O6;var GP=Cf&&Cf.isTypedArray,C6=GP?KP(GP):WP,is=C6;var $6=Object.prototype,M6=$6.hasOwnProperty;function D6(e,t){var r=je(e),o=!r&&Yr(e),n=!r&&!o&&Mn(e),i=!r&&!o&&!n&&is(e),s=r||o||n||i,a=s?zP(e.length,String):[],c=a.length;for(var u in e)if((t||M6.call(e,u))&&!(s&&(u=="length"||n&&(u=="offset"||u=="parent")||i&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Dn(u,c))))a.push(u);return a}var $f=D6;var N6=Object.prototype;function U6(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||N6;return e===r}var ss=U6;function L6(e,t){return function(r){return e(t(r))}}var Mf=L6;var j6=Mf(Object.keys,Object),JP=j6;var z6=Object.prototype,F6=z6.hasOwnProperty;function H6(e){if(!ss(e))return JP(e);var t=[];for(var r in Object(e))if(F6.call(e,r)&&r!="constructor")t.push(r);return t}var XP=H6;function B6(e){return e!=null&&os(e.length)&&!mi(e)}var Nn=B6;function q6(e){return Nn(e)?$f(e):XP(e)}var Df=q6;function V6(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var YP=V6;var W6=Object.prototype,K6=W6.hasOwnProperty;function Z6(e){if(!Je(e))return YP(e);var t=ss(e),r=[];for(var o in e)if(!(o=="constructor"&&(t||!K6.call(e,o))))r.push(o);return r}var QP=Z6;function G6(e){return Nn(e)?$f(e,!0):QP(e)}var as=G6;var Uf={};Pr(Uf,{default:()=>oS});var nI=typeof Uf=="object"&&Uf&&!Uf.nodeType&&Uf,eI=nI&&typeof Nf=="object"&&Nf&&!Nf.nodeType&&Nf,J6=eI&&eI.exports===nI,tI=J6?We.Buffer:void 0,rI=tI?tI.allocUnsafe:void 0;function X6(e,t){if(t)return e.slice();var r=e.length,o=rI?rI(r):new e.constructor(r);return e.copy(o),o}var oS=X6;function Y6(e,t){var r=-1,o=e.length;t||(t=Array(o));while(++r<o)t[r]=e[r];return t}var oI=Y6;function Q6(e,t){var r=-1,o=e==null?0:e.length,n=0,i=[];while(++r<o){var s=e[r];if(t(s,r,e))i[n++]=s}return i}var iI=Q6;function eV(){return[]}var Lf=eV;var tV=Object.prototype,rV=tV.propertyIsEnumerable,sI=Object.getOwnPropertySymbols,nV=!sI?Lf:function(e){if(e==null)return[];return e=Object(e),iI(sI(e),function(t){return rV.call(e,t)})},jf=nV;function oV(e,t){var r=-1,o=t.length,n=e.length;while(++r<o)e[n+r]=t[r];return e}var ls=oV;var iV=Mf(Object.getPrototypeOf,Object),cs=iV;var sV=Object.getOwnPropertySymbols,aV=!sV?Lf:function(e){var t=[];while(e)ls(t,jf(e)),e=cs(e);return t},aI=aV;function lV(e,t,r){var o=t(e);return je(e)?o:ls(o,r(e))}var zf=lV;function cV(e){return zf(e,Df,jf)}var iS=cV;function uV(e){return zf(e,as,aI)}var lI=uV;var dV=kt(We,"DataView"),Ff=dV;var pV=kt(We,"Promise"),Hf=pV;var fV=kt(We,"Set"),Bf=fV;var mV=kt(We,"WeakMap"),qf=mV;var cI="[object Map]",gV="[object Object]",uI="[object Promise]",dI="[object Set]",pI="[object WeakMap]",fI="[object DataView]",hV=Lr(Ff),yV=Lr(bn),_V=Lr(Hf),bV=Lr(Bf),SV=Lr(qf),Mo=Lt;if(Ff&&Mo(new Ff(new ArrayBuffer(1)))!=fI||bn&&Mo(new bn)!=cI||Hf&&Mo(Hf.resolve())!=uI||Bf&&Mo(new Bf)!=dI||qf&&Mo(new qf)!=pI)Mo=function(e){var t=Lt(e),r=t==gV?e.constructor:void 0,o=r?Lr(r):"";if(o)switch(o){case hV:return fI;case yV:return cI;case _V:return uI;case bV:return dI;case SV:return pI}return t};var sS=Mo;var vV=We.Uint8Array,us=vV;function xV(e){var t=new e.constructor(e.byteLength);return new us(t).set(new us(e)),t}var mI=xV;function wV(e,t){var r=t?mI(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var gI=wV;var hI=Object.create,kV=function(){function e(){}return function(t){if(!Je(t))return{};if(hI)return hI(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}(),yI=kV;function EV(e){return typeof e.constructor=="function"&&!ss(e)?yI(cs(e)):{}}var _I=EV;import{realpathSync as lA}from"fs";var TV="__lodash_hash_undefined__";function PV(e){return this.__data__.set(e,TV),this}var bI=PV;function IV(e){return this.__data__.has(e)}var SI=IV;function Vf(e){var t=-1,r=e==null?0:e.length;this.__data__=new po;while(++t<r)this.add(e[t])}Vf.prototype.add=Vf.prototype.push=bI;Vf.prototype.has=SI;var vI=Vf;function AV(e,t){var r=-1,o=e==null?0:e.length;while(++r<o)if(t(e[r],r,e))return!0;return!1}var xI=AV;function RV(e,t){return e.has(t)}var wI=RV;var OV=1,CV=2;function $V(e,t,r,o,n,i){var s=r&OV,a=e.length,c=t.length;if(a!=c&&!(s&&c>a))return!1;var u=i.get(e),d=i.get(t);if(u&&d)return u==t&&d==e;var p=-1,f=!0,m=r&CV?new vI:void 0;i.set(e,t),i.set(t,e);while(++p<a){var g=e[p],h=t[p];if(o)var y=s?o(h,g,p,t,e,i):o(g,h,p,e,t,i);if(y!==void 0){if(y)continue;f=!1;break}if(m){if(!xI(t,function(S,x){if(!wI(m,x)&&(g===S||n(g,S,r,o,i)))return m.push(x)})){f=!1;break}}else if(!(g===h||n(g,h,r,o,i))){f=!1;break}}return i.delete(e),i.delete(t),f}var Wf=$V;function MV(e){var t=-1,r=Array(e.size);return e.forEach(function(o,n){r[++t]=[n,o]}),r}var kI=MV;function DV(e){var t=-1,r=Array(e.size);return e.forEach(function(o){r[++t]=o}),r}var EI=DV;var NV=1,UV=2,LV="[object Boolean]",jV="[object Date]",zV="[object Error]",FV="[object Map]",HV="[object Number]",BV="[object RegExp]",qV="[object Set]",VV="[object String]",WV="[object Symbol]",KV="[object ArrayBuffer]",ZV="[object DataView]",TI=mt?mt.prototype:void 0,aS=TI?TI.valueOf:void 0;function GV(e,t,r,o,n,i,s){switch(r){case ZV:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case KV:if(e.byteLength!=t.byteLength||!i(new us(e),new us(t)))return!1;return!0;case LV:case jV:case HV:return Rr(+e,+t);case zV:return e.name==t.name&&e.message==t.message;case BV:case VV:return e==t+"";case FV:var a=kI;case qV:var c=o&NV;if(a||(a=EI),e.size!=t.size&&!c)return!1;var u=s.get(e);if(u)return u==t;o|=UV,s.set(e,t);var d=Wf(a(e),a(t),o,n,i,s);return s.delete(e),d;case WV:if(aS)return aS.call(e)==aS.call(t)}return!1}var PI=GV;var JV=1,XV=Object.prototype,YV=XV.hasOwnProperty;function QV(e,t,r,o,n,i){var s=r&JV,a=iS(e),c=a.length,u=iS(t),d=u.length;if(c!=d&&!s)return!1;var p=c;while(p--){var f=a[p];if(!(s?f in t:YV.call(t,f)))return!1}var m=i.get(e),g=i.get(t);if(m&&g)return m==t&&g==e;var h=!0;i.set(e,t),i.set(t,e);var y=s;while(++p<c){f=a[p];var S=e[f],x=t[f];if(o)var w=s?o(x,S,f,t,e,i):o(S,x,f,e,t,i);if(!(w===void 0?S===x||n(S,x,r,o,i):w)){h=!1;break}y||(y=f=="constructor")}if(h&&!y){var R=e.constructor,U=t.constructor;if(R!=U&&(("constructor"in e)&&("constructor"in t))&&!(typeof R=="function"&&R instanceof R&&typeof U=="function"&&U instanceof U))h=!1}return i.delete(e),i.delete(t),h}var II=QV;var eW=1,AI="[object Arguments]",RI="[object Array]",Kf="[object Object]",tW=Object.prototype,OI=tW.hasOwnProperty;function rW(e,t,r,o,n,i){var s=je(e),a=je(t),c=s?RI:sS(e),u=a?RI:sS(t);c=c==AI?Kf:c,u=u==AI?Kf:u;var d=c==Kf,p=u==Kf,f=c==u;if(f&&Mn(e)){if(!Mn(t))return!1;s=!0,d=!1}if(f&&!d)return i||(i=new $n),s||is(e)?Wf(e,t,r,o,n,i):PI(e,t,c,r,o,n,i);if(!(r&eW)){var m=d&&OI.call(e,"__wrapped__"),g=p&&OI.call(t,"__wrapped__");if(m||g){var h=m?e.value():e,y=g?t.value():t;return i||(i=new $n),n(h,y,r,o,i)}}if(!f)return!1;return i||(i=new $n),II(e,t,r,o,n,i)}var CI=rW;function $I(e,t,r,o,n){if(e===t)return!0;if(e==null||t==null||!_t(e)&&!_t(t))return e!==e&&t!==t;return CI(e,t,r,o,$I,n)}var Zf=$I;var nW=1,oW=2;function iW(e,t,r,o){var n=r.length,i=n,s=!o;if(e==null)return!i;e=Object(e);while(n--){var a=r[n];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}while(++n<i){a=r[n];var c=a[0],u=e[c],d=a[1];if(s&&a[2]){if(u===void 0&&!(c in e))return!1}else{var p=new $n;if(o)var f=o(u,d,c,e,t,p);if(!(f===void 0?Zf(d,u,nW|oW,o,p):f))return!1}}return!0}var MI=iW;function sW(e){return e===e&&!Je(e)}var Gf=sW;function aW(e){var t=Df(e),r=t.length;while(r--){var o=t[r],n=e[o];t[r]=[o,n,Gf(n)]}return t}var DI=aW;function lW(e,t){return function(r){if(r==null)return!1;return r[e]===t&&(t!==void 0||(e in Object(r)))}}var Jf=lW;function cW(e){var t=DI(e);if(t.length==1&&t[0][2])return Jf(t[0][0],t[0][1]);return function(r){return r===e||MI(r,e,t)}}var NI=cW;var uW="[object Symbol]";function dW(e){return typeof e=="symbol"||_t(e)&&Lt(e)==uW}var ds=dW;var pW=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,fW=/^\w*$/;function mW(e,t){if(je(e))return!1;var r=typeof e;if(r=="number"||r=="symbol"||r=="boolean"||e==null||ds(e))return!0;return fW.test(e)||!pW.test(e)||t!=null&&e in Object(t)}var ps=mW;var gW=500;function hW(e){var t=pe(e,function(o){if(r.size===gW)r.clear();return o}),r=t.cache;return t}var UI=hW;var yW=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_W=/\\(\\)?/g,bW=UI(function(e){var t=[];if(e.charCodeAt(0)===46)t.push("");return e.replace(yW,function(r,o,n,i){t.push(n?i.replace(_W,"$1"):o||r)}),t}),LI=bW;function SW(e,t){var r=-1,o=e==null?0:e.length,n=Array(o);while(++r<o)n[r]=t(e[r],r,e);return n}var Xf=SW;var vW=1/0,jI=mt?mt.prototype:void 0,zI=jI?jI.toString:void 0;function FI(e){if(typeof e=="string")return e;if(je(e))return Xf(e,FI)+"";if(ds(e))return zI?zI.call(e):"";var t=e+"";return t=="0"&&1/e==-vW?"-0":t}var HI=FI;function xW(e){return e==null?"":HI(e)}var BI=xW;function wW(e,t){if(je(e))return e;return ps(e,t)?[e]:LI(BI(e))}var Un=wW;var kW=1/0;function EW(e){if(typeof e=="string"||ds(e))return e;var t=e+"";return t=="0"&&1/e==-kW?"-0":t}var Cr=EW;function TW(e,t){t=Un(t,e);var r=0,o=t.length;while(e!=null&&r<o)e=e[Cr(t[r++])];return r&&r==o?e:void 0}var fs=TW;function PW(e,t,r){var o=e==null?void 0:fs(e,t);return o===void 0?r:o}var qI=PW;function IW(e,t){return e!=null&&t in Object(e)}var VI=IW;function AW(e,t,r){t=Un(t,e);var o=-1,n=t.length,i=!1;while(++o<n){var s=Cr(t[o]);if(!(i=e!=null&&r(e,s)))break;e=e[s]}if(i||++o!=n)return i;return n=e==null?0:e.length,!!n&&os(n)&&Dn(s,n)&&(je(e)||Yr(e))}var WI=AW;function RW(e,t){return e!=null&&WI(e,t,VI)}var Yf=RW;var OW=1,CW=2;function $W(e,t){if(ps(e)&&Gf(t))return Jf(Cr(e),t);return function(r){var o=qI(r,e);return o===void 0&&o===t?Yf(r,e):Zf(t,o,OW|CW)}}var KI=$W;function MW(e){return e}var ms=MW;function DW(e){return function(t){return t==null?void 0:t[e]}}var ZI=DW;function NW(e){return function(t){return fs(t,e)}}var GI=NW;function UW(e){return ps(e)?ZI(Cr(e)):GI(e)}var JI=UW;function LW(e){if(typeof e=="function")return e;if(e==null)return ms;if(typeof e=="object")return je(e)?KI(e[0],e[1]):NI(e);return JI(e)}var Qf=LW;import{cwd as ZW}from"process";import{randomUUID as gc}from"crypto";import{createHash as zW,randomBytes as hMe}from"crypto";var XI="[\\w-]{1,63}",jW=new RegExp(`^${XI}$`),fMe=new RegExp(`^a(?:${XI}-)?[0-9a-f]{16}$`);function YI(e,t){let r=Buffer.from(t.replace(/-/g,""),"hex"),o=zW("sha1").update(r).update(Buffer.from(e,"utf8")).digest();o[6]=o[6]&15|80,o[8]=o[8]&63|128;let n=o.subarray(0,16).toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}var FW="3ab19d7e-9f35-45c2-926e-75e271cc60b3";function QI(){let e=process.env.CLAUDE_CODE_REMOTE_SESSION_ID?.trim();return e?YI(e,FW):null}var lS=null;function eA(){return lS}function tA(e){lS=e}var em=new Map;function rA(e){return em.has(e)?em.get(e):void 0}function nA(e,t){em.set(e,t)}var HW;var BW;var qW;var VW;var WW;var cS=new Map;function oA(e){return cS.get(e)}function iA(e,t){cS.set(e,t)}function Do(){lS=null,em.clear(),cS.clear(),WW=void 0,HW=void 0,BW=void 0,qW=void 0,VW=void 0}var KW;function sA(){return KW}function aA(){return{sent:new Set,rejected:new Set}}var GW={renderTarget:"ink",workspace:"local",canDrive:!0,transcriptSource:"local-jsonl",remote:null};function JW(){let e="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof lA==="function"){let r=ZW();try{e=cA(lA(r))}catch{e=cA(r)}}return{originalCwd:e,projectRoot:e,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),sessionLogicalStartTime:void 0,lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:e,modelUsage:{},mainLoopModelOverride:void 0,refusalFallbackOccurred:!1,refusalFallbackHeaderArmed:!1,refusalFallbackLatchOriginRequestId:void 0,refusalFallbackModelLatch:void 0,sdkDialogHostActive:!1,sdkSupportedDialogKinds:void 0,sdkSupportedDialogKindsSource:void 0,replConfigArgv:[],settingsEffortAtStartup:void 0,initialMainLoopModel:void 0,resolvedOrgDefault:void 0,modelStrings:null,isInteractive:!1,thinkingDisplayExplicit:!1,permissionPromptToolName:void 0,attacherCaps:null,hasStreamingInput:!1,modelOverrideOptOutForSession:!1,rendererMode:void 0,strictToolResultPairing:!1,memoryToggledOff:!1,teamMemoryServerStatus:void 0,sdkAgentProgressSummariesEnabled:!1,userMsgOptIn:!1,searchToolsOptIn:!1,clientType:"cli",sessionSource:void 0,sessionStartType:"fresh",questionPreviewFormat:void 0,sessionIngressToken:void 0,oauthTokenFromFd:void 0,oauthTokenFromBgSnapshot:!1,oauthScopesFromFd:void 0,apiKeyFromFd:void 0,gatewayAuth:null,gatewayRefreshInFlight:null,startupPolicySnapshot:void 0,flagSettingsPath:void 0,flagSettingsExpectedContent:void 0,flagSettingsInline:null,parentManagedSettings:null,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,statsStore:null,sessionId:QI()??gc(),mainAgentId:null,parentSessionId:void 0,loggerProvider:null,eventLogger:null,pendingOTelEvents:[],meterProvider:null,tracerProvider:null,cachedTelemetryResource:null,cachedOtlpHttpAgentFactory:{direct:null,proxied:null},foundryDeploymentCapabilities:new Map,agentColorMap:new Map,agentColorIndex:0,lastAPIRequest:null,lastCancelledAPIMessageId:null,lastAPIRequestMessages:null,lastClassifierRequests:null,cachedClaudeMdContent:null,inMemoryErrorLog:[],inlinePlugins:[],inlinePluginsNoMcp:[],inlinePluginUrls:[],syncedPluginDirs:[],chromeFlagOverride:void 0,teammateAgentId:void 0,onboardingShownThisSession:!1,useCoworkPlugins:!1,disableSlashCommands:!1,sessionBypassPermissionsMode:!1,scheduledTasksEnabled:!1,sessionPrResolved:!1,sessionCronTasks:[],loopChainStartedAt:Object.create(null),loopTickInFlightPrompt:null,loopConsecutiveKeepalives:0,loopEnded:!1,sessionCreatedTeams:new Set,surfacedHookSpawnFailures:new Set,bareMcpServerMatchersWarned:new Set,inheritedTeamName:void 0,sessionTrustAccepted:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,needsAutoModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0,longContext1mCreditsBlocked:!1,fableCreditsRequired:!1,fableConsentSessionFallback:!1,fableBridgeDialogTimedOut:!1,fableConsentDialogInteracted:!1,sdkOAuthTokenRefreshCallback:null,hostAuthTokenRefreshCallback:null,mainThreadAgentType:void 0,mainThreadAgentHooks:void 0,sessionSkillAllowlist:void 0,caps:GW,replBridgeActive:!1,mainLoopBusy:!1,directConnectServerUrl:void 0,mcpConnectNonBlocking:!1,deferredToolStubGateLatch:null,strictMcpConfig:!1,cliSessionConfigCarried:!1,sessionApprovedMcpServers:[],activeRoutine:void 0,systemPromptSectionCache:new Map,lastEmittedDate:null,additionalDirectoriesForClaudeMd:[],allowedChannels:[],hasDevChannels:!1,sessionProjectDir:null,promptCache1hAllowlist:null,stickyBetas:aA(),thinkingTypeOverrides:new Map,inferenceProfileBackingModels:new Map,promptId:null,promptIndex:0,lastMainRequestId:void 0,lastMainThreadCacheTtlMs:null,lastApiCompletionTimestamp:null,pendingPostCompaction:!1}}var XW=JW(),YW=()=>{return};function uS(){return YW()?.sessionId??XW.sessionId}var QW=hn(),DMe=QW.subscribe;function cA(e){return process.platform==="darwin"?e.normalize("NFC"):e}var eK=hn(),NMe=eK.subscribe;var tK=hn(),UMe=tK.subscribe;var rK=hn();var LMe=rK.subscribe;var nK=hn();var jMe=nK.subscribe;import{appendFile as vA,mkdir as DK,rename as xA,stat as NK,symlink as UK,unlink as mS}from"fs/promises";import{dirname as gS,join as bS,resolve as LK}from"path";function uA({writeFn:e,flushIntervalMs:t=1000,maxBufferSize:r=100,maxBufferBytes:o=1/0,immediateMode:n=!1}){let i=[],s=0,a=null,c=null;function u(){if(a)clearTimeout(a),a=null}function d(g){try{e(g)}catch{}}function p(){if(c)d(c.join("")),c=null;if(i.length===0)return;d(i.join("")),i=[],s=0,u()}function f(){if(!a)a=setTimeout(p,t)}function m(){if(c){c.push(...i),i=[],s=0,u();return}let g=i;i=[],s=0,u(),c=g,setImmediate(()=>{let h=c;if(c=null,h)d(h.join(""))})}return{write(g){if(n){d(g);return}if(i.push(g),s+=g.length,f(),i.length>=r||s>=o)m()},flush:p,dispose(){p()}}}function oK(e){if(typeof e==="function")return e;if(Symbol.asyncDispose in e)return()=>e[Symbol.asyncDispose]();return()=>e[Symbol.dispose]()}class dS{#n=new Set;register(e){let t=oK(e);this.#n.add(t);let r=()=>{this.#n.delete(t)};return Object.assign(r,{[Symbol.dispose]:r})}async drain(){let e=Array.from(this.#n);this.#n.clear(),await Promise.all(e.map(async(t)=>t()))}async[Symbol.asyncDispose](){await this.drain()}get sizeForTesting(){return this.#n.size}}var iK=new dS;function tm(e){return iK.register(e)}var HMe=new dS;var dA=pe((e)=>{if(!e||e.trim()==="")return null;let t=e.split(",").map((i)=>i.trim()).filter(Boolean);if(t.length===0)return null;let r=t.some((i)=>i.startsWith("!")),o=t.some((i)=>!i.startsWith("!"));if(r&&o)return null;let n=t.map((i)=>i.replace(/^!/,"").toLowerCase());return{include:r?[]:n,exclude:r?n:[],isExclusive:r}});function sK(e){let t=[],r=e.match(/^MCP server ["']([^"']+)["']/);if(r&&r[1])t.push("mcp"),t.push(r[1].toLowerCase());else{let i=e.match(/^([^:[]+):/);if(i&&i[1])t.push(i[1].trim().toLowerCase())}let o=e.match(/^\[([^\]]+)]/);if(o&&o[1])t.push(o[1].trim().toLowerCase());if(e.toLowerCase().includes("1p event:"))t.push("1p");let n=e.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(n&&n[1]){let i=n[1].trim().toLowerCase();if(i.length<30&&!i.includes(" "))t.push(i)}return Array.from(new Set(t))}function aK(e,t){if(!t)return!0;if(e.length===0)return!1;if(t.isExclusive)return!e.some((r)=>t.exclude.includes(r));else return e.some((r)=>t.include.includes(r))}function pA(e,t){if(!t)return!0;let r=sK(e);return aK(r,t)}import*as Y from"fs";import{appendFile as lK,chmod as cK,copyFile as uK,link as dK,lstat as pK,mkdir as fK,open as fA,readdir as mK,readFile as mA,readlink as gK,realpath as hK,rename as yK,rmdir as _K,rm as bK,stat as SK,symlink as vK,unlink as xK}from"fs/promises";import*as ut from"path";var rm="→";function wK(e,t){if(fa(t)&&!ga(t)||ma(t))return;let r=ut.resolve(t),o=ut.parse(r).root,n=o,i=r.slice(o.length).split(/[\\/]+/).filter(Boolean),s=0,a=64;while(i.length>0&&s<a){let c=ut.join(n,i[0]);if(ma(c))return i.length===1?c:ut.join(c,...i.slice(1));let u;try{u=e.lstatSync(c)}catch{return}if(!u.isSymbolicLink()){i.shift(),n=c;continue}s++;let d;try{d=e.readlinkSync(c)}catch{return}let p=ut.isAbsolute(d)?d:ut.resolve(n,d);if(fa(p)&&!ga(p)||ma(p))return i.shift(),i.length===0?p:ut.join(p,...i);i.shift();let f=ut.parse(p).root||ut.sep;n=f,i=[...p.slice(f.length).split(/[\\/]+/).filter(Boolean),...i]}return}function nm(e,t){if(fa(t)&&!ga(t)||ma(t))return{resolvedPath:t,isSymlink:!1,isCanonical:!1};let r=wK(e,t);if(r!==void 0)return{resolvedPath:r,isSymlink:!0,isCanonical:!1};try{let o=e.realpathSync(t);return{resolvedPath:o,isSymlink:o!==t,isCanonical:!0}}catch(o){return{resolvedPath:t,isSymlink:!1,isCanonical:!1}}}var kK={cwd(){return process.cwd()},existsSync(e){let r=[];try{const t=Te(r,$e`fs.existsSync(${e})`,0);return Y.existsSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},async stat(e){return SK(e)},async lstat(e){return pK(e)},async readdir(e){return mK(e,{withFileTypes:!0})},async unlink(e){return xK(e)},async rmdir(e){return _K(e)},async rm(e,t){return bK(e,t)},async mkdir(e,t){try{await fK(e,{recursive:!0,...t})}catch(r){if(Be(r)!=="EEXIST")throw r}},async readFile(e,t){return mA(e,{encoding:t.encoding})},async rename(e,t){return yK(e,t)},async realpath(e){return Ir(await hK(e))},async readlink(e){return gK(e)},async copyFile(e,t){return uK(e,t)},async appendFile(e,t,r){if(r?.mode!==void 0)try{let o=await fA(e,"ax",r.mode);try{await o.appendFile(t)}finally{await o.close()}return}catch(o){if(Be(o)!=="EEXIST")throw o}return lK(e,t)},async symlink(e,t,r){return vK(e,t,r)},async link(e,t){return dK(e,t)},async chmod(e,t){return cK(e,t)},statSync(e){let r=[];try{const t=Te(r,$e`fs.statSync(${e})`,0);return Y.statSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},lstatSync(e){let r=[];try{const t=Te(r,$e`fs.lstatSync(${e})`,0);return Y.lstatSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},readFileSync(e,t){let o=[];try{const r=Te(o,$e`fs.readFileSync(${e})`,0);return Y.readFileSync(e,{encoding:t.encoding})}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},readFileBytesSync(e){let r=[];try{const t=Te(r,$e`fs.readFileBytesSync(${e})`,0);return Y.readFileSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},readSync(e,t){let n=[];try{const r=Te(n,$e`fs.readSync(${e}, ${t.length} bytes)`,0);let o=void 0;try{o=Y.openSync(e,"r");let c=Buffer.alloc(t.length),u=Y.readSync(o,c,0,t.length,0);return{buffer:c,bytesRead:u}}finally{if(o)Y.closeSync(o)}}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},appendFileSync(e,t,r){let n=[];try{const o=Te(n,$e`fs.appendFileSync(${e}, ${t.length} chars)`,0);if(r?.mode!==void 0)try{let c=Y.openSync(e,"ax",r.mode);try{Y.appendFileSync(c,t)}finally{Y.closeSync(c)}return}catch(c){if(Be(c)!=="EEXIST")throw c}Y.appendFileSync(e,t)}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},copyFileSync(e,t){let o=[];try{const r=Te(o,$e`fs.copyFileSync(${e} ${rm} ${t})`,0);Y.copyFileSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},unlinkSync(e){let r=[];try{const t=Te(r,$e`fs.unlinkSync(${e})`,0);Y.unlinkSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},renameSync(e,t){let o=[];try{const r=Te(o,$e`fs.renameSync(${e} ${rm} ${t})`,0);Y.renameSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},linkSync(e,t){let o=[];try{const r=Te(o,$e`fs.linkSync(${e} ${rm} ${t})`,0);Y.linkSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},symlinkSync(e,t,r){let n=[];try{const o=Te(n,$e`fs.symlinkSync(${e} ${rm} ${t})`,0);Y.symlinkSync(e,t,r)}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},readlinkSync(e){let r=[];try{const t=Te(r,$e`fs.readlinkSync(${e})`,0);return Y.readlinkSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},realpathSync(e){let r=[];try{const t=Te(r,$e`fs.realpathSync(${e})`,0);return Ir(Y.realpathSync(e))}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},mkdirSync(e,t){let n=[];try{const r=Te(n,$e`fs.mkdirSync(${e})`,0);let o={recursive:!0};if(t?.mode!==void 0)o.mode=t.mode;try{Y.mkdirSync(e,o)}catch(c){if(Be(c)!=="EEXIST")throw c}}catch(i){var s=i,a=1}finally{Pe(n,s,a)}},readdirSync(e){let r=[];try{const t=Te(r,$e`fs.readdirSync(${e})`,0);return Y.readdirSync(e,{withFileTypes:!0})}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},readdirStringSync(e){let r=[];try{const t=Te(r,$e`fs.readdirStringSync(${e})`,0);return Y.readdirSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},rmdirSync(e){let r=[];try{const t=Te(r,$e`fs.rmdirSync(${e})`,0);Y.rmdirSync(e)}catch(o){var n=o,i=1}finally{Pe(r,n,i)}},rmSync(e,t){let o=[];try{const r=Te(o,$e`fs.rmSync(${e})`,0);Y.rmSync(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}},createWriteStream(e){return Y.createWriteStream(e)},async readFileBytes(e,t){if(t===void 0)return mA(e);let r=await fA(e,"r");try{let{size:o}=await r.stat(),n=Math.min(o,t),i=Buffer.allocUnsafe(n),s=0;while(s<n){let{bytesRead:a}=await r.read(i,s,n-s,s);if(a===0)break;s+=a}return s<n?i.subarray(0,s):i}finally{await r.close()}}},EK=kK;function qe(){return EK}function TK(e,t){if(e.destroyed||e.writableEnded)return;e.write(t)}function gA(e){TK(process.stderr,e)}var PK=/api[_-]?key|secret|token|password|passwd|credential|bearer|authorization|auth[_-]?header|cookie|session[_-]?(?:id|key)|connection[_-]?string|(?:private|ssh|encryption|signing|access|deploy|master|license)[_-]?key|client[_-]?secret/i,hA="[^\\s,;&}\\])]+",bA="-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\\s\\S-]{64,}?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----",IK=`[^\\s-]{0,4}${bA}['"\`]?`,yA=`\\[REDACTED\\]|"[^"]*"|'[^']*'|(?:Bearer|Basic)\\s+(?:\\[REDACTED\\]|${hA})|${IK}|${hA}`,AK=["sk","ant","api"].join("-"),RK=[{id:"url-userinfo",source:":\\/\\/([^/@\\s]+)@",confidence:"low"},{id:"gcp-service-account",source:"\\b([a-z0-9-]+@[a-z0-9-]+\\.iam\\.gserviceaccount\\.com)\\b",flags:"i",confidence:"low"},{id:"loose-anthropic-key",source:"\\b(sk-ant-?[\\w-]{10,})",confidence:"low"},{id:"http-auth-scheme",source:"\\b(?:Bearer|Basic)\\s+([A-Za-z0-9+/=._~-]{20,})",flags:"i",confidence:"low"},{id:"loose-jwt",source:"\\b(eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,})",confidence:"low"},{id:"sensitive-assign",source:`(?:${PK.source})[\\w.-]*["']?\\s*[=:]\\s*(${yA})`,flags:"i",confidence:"low"},{id:"cloud-env-var",source:`\\b(?:AWS|GOOGLE|GCP|GCLOUD|AZURE)_\\w+\\s*[=:]\\s*(${yA})`,flags:"i",confidence:"low"},{id:"aws-access-token",source:"\\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\\b",confidence:"high"},{id:"gcp-api-key",source:"\\b(AIza[\\w-]{35})(?![\\w-])",confidence:"high"},{id:"google-oauth-client-secret",source:"\\bGOCSPX-[\\w-]{28}(?![\\w-])",confidence:"high"},{id:"azure-ad-client-secret",source:`(?:^|[\\\\'"\\x60\\s>=:(,)])([a-zA-Z0-9_~.]{3}\\dQ~[a-zA-Z0-9_~.-]{31,34})(?:$|[\\\\'"\\x60\\s<),])`,confidence:"high"},{id:"digitalocean-pat",source:`\\b(dop_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"digitalocean-access-token",source:`\\b(doo_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-api-key",source:`\\b(${AK}03-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-admin-api-key",source:`\\b(sk-ant-admin01-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"openai-api-key",source:"sk-[A-Za-z0-9_-]{8,200}T3BlbkFJ[A-Za-z0-9_-]{8,200}",confidence:"high"},{id:"openai-legacy-api-key",source:"\\bsk-[a-zA-Z0-9]{48}(?![a-zA-Z0-9])",confidence:"high"},{id:"huggingface-access-token",source:`\\b(hf_[a-zA-Z]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"supabase-secret-key",source:"\\bsb_secret_[A-Za-z0-9_-]{20,}",confidence:"high"},{id:"supabase-access-token",source:"\\bsbp_[a-z0-9]{40,}",confidence:"high"},{id:"github-pat",source:"ghp_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-fine-grained-pat",source:"github_pat_\\w{82}",confidence:"high"},{id:"github-app-token",source:"(?:ghu|ghs)_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-oauth",source:"gho_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-refresh-token",source:"ghr_[0-9a-zA-Z]{36}",confidence:"high"},{id:"gitlab-pat",source:"glpat-[\\w-]{20}",confidence:"high"},{id:"gitlab-deploy-token",source:"gldt-[0-9a-zA-Z_\\-]{20}",confidence:"high"},{id:"slack-bot-token",source:"xoxb-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*",confidence:"high"},{id:"slack-user-token",source:"xox[pe](?:-[0-9]{10,13}){3}-[a-zA-Z0-9-]{28,34}",confidence:"high"},{id:"slack-app-token",source:"xapp-\\d-[A-Z0-9]+-\\d+-[a-z0-9]+",flags:"i",confidence:"high"},{id:"twilio-api-key",source:"SK[0-9a-fA-F]{32}",confidence:"high"},{id:"sendgrid-api-token",source:`\\b(SG\\.[a-zA-Z0-9=_\\-.]{66})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"npm-access-token",source:`\\b(npm_[a-zA-Z0-9]{36})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"pypi-upload-token",source:"pypi-AgEIcHlwaS5vcmc[\\w-]{50,1000}",confidence:"high"},{id:"databricks-api-token",source:`\\b(dapi[a-f0-9]{32}(?:-\\d)?)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"hashicorp-tf-api-token",source:"[a-zA-Z0-9]{14}\\.atlasv1\\.[a-zA-Z0-9\\-_=]{60,70}",confidence:"high"},{id:"pulumi-api-token",source:`\\b(pul-[a-f0-9]{40})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"postman-api-token",source:`\\b(PMAK-[a-fA-F0-9]{24}-[a-fA-F0-9]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-api-key",source:`\\b(eyJrIjoi[A-Za-z0-9+/]{70,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-cloud-api-token",source:`\\b(glc_[A-Za-z0-9+/]{32,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-service-account-token",source:`\\b(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-user-token",source:`\\b(sntryu_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-org-token",source:"\\bsntrys_eyJpYXQiO[a-zA-Z0-9+/]{10,200}(?:LCJyZWdpb25fdXJs|InJlZ2lvbl91cmwi|cmVnaW9uX3VybCI6)[a-zA-Z0-9+/]{10,200}={0,2}_[a-zA-Z0-9+/]{43}",confidence:"high"},{id:"stripe-access-token",source:`\\b((?:sk|rk)_(?:test|live|prod)_[a-zA-Z0-9]{10,99})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"shopify-access-token",source:"shpat_[a-fA-F0-9]{32}",confidence:"high"},{id:"shopify-shared-secret",source:"shpss_[a-fA-F0-9]{32}",confidence:"high"},{id:"private-key",source:bA,flags:"i",confidence:"high"}];var _A=null;function OK(e){return RK.map((t)=>({id:t.id,confidence:t.confidence,re:new RegExp(t.source,e?(t.flags??"").replace("g","")+"g":t.flags??"")}))}function CK(e,t){if(typeof t!=="string")return"[REDACTED]";let r=t.length>=2&&(t[0]==='"'||t[0]==="'")&&t.at(-1)===t[0]?t[0]:"",o=e.lastIndexOf(t);return`${e.slice(0,o)}${r}[REDACTED]${r}${e.slice(o+t.length)}`}var $K=512,MK=512,hc=new Map;function SA(e){let t=e.length<=$K;if(t){let o=hc.get(e);if(o!==void 0)return o}_A??=OK(!0);let r=e;for(let o of _A)r=r.replace(o.re,CK);if(t){if(hc.size>=MK)hc.delete(hc.keys().next().value);hc.set(e,r)}return r}var hS={verbose:0,debug:1,info:2,warn:3,error:4},jK=pe(()=>{let e=process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim();if(e&&Object.hasOwn(hS,e))return e;return"debug"}),zK=!1;function om(){if(typeof process>"u"||!Array.isArray(process.argv))return[];let e=process.argv.indexOf("--");return e===-1?process.argv:process.argv.slice(0,e)}var EA=pe(()=>{let e=om();return zK||ve(process.env.DEBUG)||ve(process.env.DEBUG_SDK)||e.includes("--debug")||e.includes("-d")||TA()||e.some((t)=>t.startsWith("--debug="))||PA()!==null});var FK=pe(()=>{let e=om().find((r)=>r.startsWith("--debug="));if(!e)return null;let t=e.substring(8);return dA(t)}),TA=pe(()=>{let e=om();return e.includes("--debug-to-stderr")||e.includes("-d2e")}),PA=pe(()=>{let e=om();for(let t=0;t<e.length;t++){let r=e[t];if(r.startsWith("--debug-file="))return wA(r.substring(13));if(r==="--debug-file"&&t+1<e.length)return wA(e[t+1])}return null});function wA(e){return Ek(e)?null:LK(e)}function HK(e){if(!EA())return!1;if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let t=FK();return pA(e,t)}var BK=!1;var qK=10485760,yc=null,pS=Promise.resolve(),gs=[],bc=null,kA=null;var _c=-1,fS=!1,yS=null;async function VK(e,t,r=qK){if(_c<0)_c=await NK(e).then((o)=>o.size).catch(()=>0);else _c+=t;if(_c<=r||fS)return;fS=!0;try{let o=e.endsWith(".txt")?`${e.slice(0,-4)}.1.txt`:`${e}.1`;try{await xA(e,o)}catch(n){if(!Xr(n))await mS(o).catch(()=>{}),await xA(e,o).catch(()=>mS(e).catch(()=>{}))}_c=0}finally{fS=!1}}function IA(e){return yS=bS(e,`${uS()}.txt`),yS}async function WK(e,t,r,o){if(e)await DK(t,{recursive:!0}).catch(()=>{});let n=r;try{await vA(r,o)}catch(i){if(!Xb(i))throw i;n=IA(r),await vA(n,o)}await VK(n,Buffer.byteLength(o)).catch(AA),GK()}function AA(){}function KK(){gs.shift()}function ZK(){if(!yc){let e=null;if(yc=uA({writeFn:(t)=>{if(bc){gs.push(t),bc();return}let r=_S(),o=gS(r),n=e!==o;e=o,gs.push(t),pS=pS.then(WK.bind(null,n,o,r,t)).catch(AA).then(KK)},flushIntervalMs:1000,maxBufferSize:100,immediateMode:EA()}),tm(async()=>{yc?.dispose(),await pS}),!kA)process.on("exit",kA=()=>{bc=()=>{if(gs.length===0)return;let t=gs.join("");gs.length=0;let r=_S();try{qe().mkdirSync(gS(r))}catch{}try{qe().appendFileSync(r,t)}catch(o){if(Xb(o))try{qe().appendFileSync(IA(r),t)}catch{}}},yc?.flush(),bc()})}return yc}function Q(e,{level:t}={level:"debug"}){if(hS[t]<hS[jK()])return;if(!HK(e))return;if(BK&&e.includes(`
|
|
87
87
|
`))e=me(e);let o=`${new Date().toISOString()} [${t.toUpperCase()}] ${SA(e.trim())}
|
|
88
88
|
`;if(TA()){gA(o);return}let n=ZK();if(n.write(o),bc)n.flush()}function _S(){return PA()??yS??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??bS(Xt(),"debug",`${uS()}.txt`)}var GK=pe(async()=>{try{let e=_S(),t=gS(e),r=bS(t,"latest");await mS(r).catch(()=>{}),await UK(e,r)}catch{}});var kDe=(()=>{let e=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(e!==void 0){let t=Number(e);if(!Number.isNaN(t)&&t>=0)return t}return 1/0})();var JK={[Symbol.dispose](){}};function XK(){return JK}var $e=XK;function me(e,t,r){let n=[];try{const o=Te(n,$e`JSON.stringify(${e})`,0);return JSON.stringify(e,t,r)}catch(i){var s=i,a=1}finally{Pe(n,s,a)}}var Ze=(e,t)=>{let o=[];try{const r=Te(o,$e`JSON.parse(${e})`,0);return typeof t>"u"?JSON.parse(e):JSON.parse(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}};function RA(e){return JSON.parse(e)}function Ln(e,t){let o=[];try{const r=Te(o,$e`structuredClone(${e})`,0);return structuredClone(e,t)}catch(n){var i=n,s=1}finally{Pe(o,i,s)}}function YK(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")}function OA(e,t){let r={...e};if(!t)return r;let o=t.enabled===!0&&t.failIfUnavailable===void 0?{...t,failIfUnavailable:!0}:t,n=r.settings;if(n&&!YK(n))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let i={sandbox:o};if(n)try{i={...Ze(n),sandbox:o}}catch{}return r.settings=me(i),r}function SS(e,t,r){let o=String(r);if(o.length>1&&o.startsWith("-"))e.push(`--${t}=${o}`);else e.push(`--${t}`,o)}var rZ=2000,Sc=new Set,CA=!1;function nZ(){for(let e of Sc)if(!e.killed)if(process.platform==="win32")try{e.stdin.end()}catch{}else e.kill("SIGTERM")}function oZ(e){if(Sc.add(e),!CA)CA=!0,process.on("exit",nZ)}class vS{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitListeners=[];abortHandler;forwardedAbort=pa();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||pa(),e.deferSpawn)this.spawnPromise=new Promise((t,r)=>{this.spawnResolve=t,this.spawnReject=r}),this.spawnPromise.catch(()=>{});else this.initialize()}spawn(){try{this.initialize()}catch(t){throw this.spawnAbort(Or(t)),t}let e=this.pendingWrites;if(this.pendingWrites=[],this.spawnResolve)this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0;for(let t of e)this.write(t);if(this.pendingEndInput)this.pendingEndInput=!1,this.processStdin?.end()}spawnAbort(e){if(this.spawnReject)this.spawnReject(e),this.spawnReject=void 0,this.spawnResolve=void 0,this.pendingWrites=[]}updateEnv(e){if(this.options.env)Object.assign(this.options.env,e);else this.options.env={...e}}updateResume(e){this.options.resume=e}getDefaultExecutable(){return qu()?"bun":"node"}spawnLocalProcess(e){let{command:t,args:r,cwd:o,env:n,signal:i}=e,s=ve(n.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr?"pipe":"ignore",a=QK(t,r,{cwd:o,stdio:["pipe","pipe",s],signal:i,env:n,windowsHide:!0});if(ve(n.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr)a.stderr.on("data",(u)=>{let d=u.toString();if(yt(d),this.options.stderr)this.options.stderr(d)});return{stdin:a.stdin,stdout:a.stdout,get killed(){return a.killed},get exitCode(){return a.exitCode},kill:a.kill.bind(a),on:a.on.bind(a),once:a.once.bind(a),off:a.off.bind(a)}}initialize(){try{let{additionalDirectories:e=[],agent:t,betas:r,cwd:o,executable:n=this.getDefaultExecutable(),executableArgs:i=[],extraArgs:s={},pathToClaudeCodeExecutable:a,env:c={...process.env},thinkingConfig:u,maxTurns:d,maxBudgetUsd:p,taskBudget:f,model:m,fallbackModel:g,jsonSchema:h,permissionMode:y,allowDangerouslySkipPermissions:S,permissionPromptToolName:x,continueConversation:w,resume:R,settingSources:U,skills:ae,disallowedTools:Ge=[],tools:tt,mcpServers:Zt,strictMcpConfig:Ur,canUseTool:Gt,includePartialMessages:li,plugins:fn,sandbox:ci}=this.options,{allowedTools:co=[]}=this.options;if(ae!==void 0){let ye=ae==="all"?["Skill"]:ae.map((lr)=>`Skill(${lr})`),Dt=new Set(co);co=[...co,...ye.filter((lr)=>!Dt.has(lr))]}let W=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(u){switch(u.type){case"enabled":if(u.budgetTokens===void 0)W.push("--thinking","adaptive");else W.push("--max-thinking-tokens",u.budgetTokens.toString());break;case"disabled":W.push("--thinking","disabled");break;case"adaptive":W.push("--thinking","adaptive");break}if(u.type!=="disabled"&&u.display)W.push("--thinking-display",u.display)}if(this.options.effort)W.push("--effort",this.options.effort);if(d)W.push("--max-turns",d.toString());if(p!==void 0)W.push("--max-budget-usd",p.toString());if(f)W.push("--task-budget",f.total.toString());if(m)W.push("--model",m);if(t)W.push("--agent",t);if(r&&r.length>0)W.push("--betas",r.join(","));if(h)W.push("--json-schema",me(h));if(this.options.debugFile)W.push("--debug-file",this.options.debugFile);else if(this.options.debug)W.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let ye=$P();if(ye)W.push("--debug-file",ye)}if(Gt){if(x)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");W.push("--permission-prompt-tool","stdio")}else if(x)W.push("--permission-prompt-tool",x);if(w)W.push("--continue");if(R)W.push(`--resume=${R}`);if(this.options.channels&&this.options.channels.length>0)for(let ye of this.options.channels)SS(W,"channels",ye);if(co.length>0)W.push("--allowedTools",co.join(","));if(Ge.length>0)W.push("--disallowedTools",Ge.join(","));if(tt!==void 0)if(Array.isArray(tt))if(tt.length===0)W.push("--tools","");else W.push("--tools",tt.join(","));else W.push("--tools","default");if(Zt&&Object.keys(Zt).length>0)W.push("--mcp-config",me({mcpServers:Zt}));if(U!==void 0)W.push(`--setting-sources=${U.join(",")}`);if(Ur)W.push("--strict-mcp-config");if(y)W.push("--permission-mode",y);if(S)W.push("--allow-dangerously-skip-permissions");if(g){if(m&&g===m)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");W.push("--fallback-model",g)}if(this.options.includeHookEvents)W.push("--include-hook-events");if(li)W.push("--include-partial-messages");if(this.options.sessionMirror)W.push("--session-mirror");for(let ye of e)W.push("--add-dir",ye);if(fn&&fn.length>0)for(let ye of fn)if(ye.type==="local")W.push(ye.skipMcpDiscovery?"--plugin-dir-no-mcp":"--plugin-dir",ye.path);else throw Error(`Unsupported plugin type: ${ye.type}`);if(this.options.forkSession)W.push("--fork-session");if(this.options.resumeSessionAt)W.push("--resume-session-at",this.options.resumeSessionAt);if(this.options.sessionId)W.push("--session-id",this.options.sessionId);if(this.options.persistSession===!1)W.push("--no-session-persistence");if(this.options.managedSettings)W.push("--managed-settings",this.options.managedSettings);let sa={...s??{}};if(this.options.settings)sa.settings=this.options.settings;let sh=OA(sa,ci);for(let[ye,Dt]of Object.entries(sh))if(Dt===null)W.push(`--${ye}`);else SS(W,ye,Dt);if(!c.CLAUDE_CODE_ENTRYPOINT)c.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete c.NODE_OPTIONS,ve(c.DEBUG_CLAUDE_AGENT_SDK))c.DEBUG="1";else delete c.DEBUG;let ui=iZ(a),aa=ui?a:n,la=ui?[...i,...W]:[...i,a,...W],Hu={command:aa,args:la,cwd:o,env:c,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)yt(`Spawning Claude Code (custom): ${aa} ${la.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(Hu);else yt(`Spawning Claude Code: ${aa} ${la.join(" ")}`),this.process=this.spawnLocalProcess(Hu);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(ye)=>{yt(`[ProcessTransport] stdin write failed (child likely exited): ${ye.code??ye.message}`),this.ready=!1}),oZ(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let di=this.process;di.on("error",(ye)=>{this.ready=!1;let Dt=ye;if((Dt.syscall!==void 0?Dt.syscall.startsWith("spawn"):Yb(ye))&&!di.killed)Sc.delete(di);if(this.abortController.signal.aborted)this.exitError=new st("Claude Code process aborted by user");else if(Yb(ye)){let cr=sZ(a,ui);this.exitError=ReferenceError(cr),yt(this.exitError.message)}else this.exitError=Error(`Failed to spawn Claude Code process: ${ye.message}`),yt(this.exitError.message)}),di.on("exit",(ye,Dt)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new st("Claude Code process aborted by user");else{let lr=this.getProcessExitError(ye,Dt);if(lr)this.exitError=lr,yt(lr.message)}}),this.ready=!this.abortController.signal.aborted}catch(e){throw this.ready=!1,e}}getProcessExitError(e,t){if(e!==0&&e!==null)return Error(`Claude Code process exited with code ${e}`);else if(t)return Error(`Claude Code process terminated by signal ${t}`);return}write(e){if(this.abortController.signal.aborted)throw new st("Operation aborted");if(this.spawnResolve){this.pendingWrites.push(e);return}if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.processStdin.writableEnded){yt("[ProcessTransport] Dropping write to ended stdin stream");return}if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);yt(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{if(!this.processStdin.write(e))yt("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${Yi(t)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?new st("Claude Code process aborted by user"):Error("Query closed before spawn")),this.processStdin)this.processStdin.end(),this.processStdin=void 0;if(this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;for(let{handler:r}of this.exitListeners)this.process?.off("exit",r);this.exitListeners=[];let e=()=>{if(this.abortController.signal.aborted)this.forwardedAbort.abort(this.abortController.signal.reason)},t=this.process;if(t&&!t.killed&&t.exitCode===null)setTimeout((r,o)=>{if(r.exitCode!==null){o();return}if(process.platform==="win32"){setTimeout((n,i)=>{if(n.exitCode===null)n.kill("SIGKILL");i()},5000,r,o).unref();return}r.kill("SIGTERM"),setTimeout((n)=>{if(n.exitCode===null)n.kill("SIGKILL")},5000,r).unref(),o()},rZ,t,e).unref(),t.once("exit",()=>Sc.delete(t));else if(t)Sc.delete(t),e();this.ready=!1}isReady(){return this.ready}async*readMessages(){if(this.spawnPromise)await this.spawnPromise,this.spawnPromise=void 0;if(!this.processStdout)throw Error("ProcessTransport output stream not available");if(this.exitError)throw this.exitError;let e=tZ({input:this.processStdout}),t=this.process?(()=>{let r=this.process,o=()=>e.close();return r.on("error",o),()=>r.off("error",o)})():void 0;if(this.exitError)e.close();try{for await(let r of e)if(r.trim()){let o;try{o=Ze(r)}catch(n){yt(`Non-JSON stdout: ${r}`);continue}yield o}if(this.exitError)throw this.exitError;await this.waitForExit()}finally{t?.(),e.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}if(this.processStdin)this.processStdin.end()}getInputStream(){return this.processStdin}onExit(e){if(!this.process)return()=>{};let t=(r,o)=>{let n=this.getProcessExitError(r,o);e(n)};return this.process.on("exit",t),this.exitListeners.push({callback:e,handler:t}),()=>{if(this.process)this.process.off("exit",t);let r=this.exitListeners.findIndex((o)=>o.handler===t);if(r!==-1)this.exitListeners.splice(r,1)}}async waitForExit(){if(this.exitError)throw this.exitError;if(!this.process||this.process.exitCode!==null||this.process.killed)return;return new Promise((e,t)=>{let r=(n,i)=>{if(this.abortController.signal.aborted){t(new st("Operation aborted"));return}let s=this.getProcessExitError(n,i);if(s)t(s);else e()};this.process.once("exit",r);let o=(n)=>{this.process.off("exit",r),t(n)};this.process.once("error",o),this.process.once("exit",()=>{this.process.off("error",o)})})}}function iZ(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((r)=>e.endsWith(r))}function sZ(e,t){if(eZ(e))return t?`Claude Code native binary at ${e} exists but failed to launch. This usually means the binary does not match this system's libc — e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${e} exists but failed to launch.`;return t?`Claude Code native binary not found at ${e}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${e}. Is options.pathToClaudeCodeExecutable set?`}import{existsSync as aZ}from"fs";var hs="@anthropic-ai/claude-agent-sdk";function lZ(){if(process.platform!=="linux")return!1;let e=typeof process.report?.getReport==="function"?process.report.getReport():null;return e!=null&&e.header?.glibcVersionRuntime===void 0}function $A(e,t={}){let r=t.platform??process.platform,o=t.arch??process.arch,n=t.exists??aZ,i=t.preferMusl??lZ(),s="claude",a=r==="win32"?".exe":"",u=(r==="android"?[`${hs}-linux-${o}-android`]:r==="linux"?i?[`${hs}-linux-${o}-musl`,`${hs}-linux-${o}`]:[`${hs}-linux-${o}`,`${hs}-linux-${o}-musl`]:[`${hs}-${r}-${o}`]).map((d)=>`${d}/claude${a}`);for(let d of u)try{let p=e(d);if(n(p))return p}catch{}return null}class vc{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}var cZ=1000;function uZ(){return{eventQueue:[],sink:null,droppedEventCount:0}}function dZ(e,t){if(e.eventQueue.length>=cZ)e.eventQueue.shift(),e.droppedEventCount++;e.eventQueue.push(t)}var pZ=uZ();function jn(e,t){let r=pZ;if(r.sink===null){dZ(r,{eventName:e,metadata:t,async:!1});return}r.sink.logEvent(e,t)}function xS(e,t){jn("tengu_feature_ok",{feature_name:Xi(e),...t})}function wS(e,t,r){jn("tengu_feature_bad",{...r,feature_name:Xi(e),error_code:t})}function MA(e,t,r){jn("tengu_feature_sad",{...r,feature_name:Xi(e),error_code:t})}async function qt(e,t,r){try{let o=await t();return xS(e),o}catch(o){throw wS(e,r?.(o)??"error"),o}}class kS{sendMcpMessage;isClosed=!1;constructor(e){this.sendMcpMessage=e}onclose;onerror;onmessage;async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var ES=Symbol("suppressControlResponse");class im{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;sdkMessages;inputStream=new vc;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpTransports=new Map;sdkMcpServerInstances=new Map;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;lastErrorResultText;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let r={type:"system",subtype:"mirror_error",error:t,key:e,uuid:gc(),session_id:e.sessionId};this.inputStream.enqueue(r)}addCleanupCallback(e){if(this.cleanupPerformed)e();else this.cleanupCallbacks.push(e)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0}constructor(e,t,r,o,n,i=new Map,s,a,c,u,d,p){this.transport=e;this.isSingleUserTurn=t;this.canUseTool=r;this.hooks=o;this.abortController=n;this.jsonSchema=s;this.initConfig=a;this.onElicitation=c;this.getOAuthToken=u;this.getHostAuthToken=d;this.onUserDialog=p;for(let[f,m]of i)this.connectSdkMcpServer(f,m);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(e){this.inputStream.error(e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let t of this.cleanupCallbacks)try{t()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let r of this.cancelControllers.values())r.abort();this.cancelControllers.clear(),this.transport.close();let t=e??Error("Query closed before response received");for(let{reject:r}of this.pendingControlResponses.values())r(t);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:r}of this.pendingMcpResponses.values())r(t);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let r of this.sdkMcpTransports.values())r.close().catch(()=>{});if(this.sdkMcpTransports.clear(),e)this.inputStream.error(e);else this.inputStream.done()}catch(t){}if(this.transport.waitForExit){let t=new AbortController;try{await Promise.race([this.transport.waitForExit(),mn(2000,t.signal)])}catch{}finally{t.abort()}}}next(...[e]){return this.sdkMessages.next(...[e])}async return(e){return await this.cleanup(),this.sdkMessages.return(e)}async throw(e){return await this.cleanup(),this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let e of this.transport.readMessages()){if(e.type==="control_response"){let t=this.pendingControlResponses.get(e.response.request_id);if(t)t.handler(e.response);else{if(this.unmatchedControlResponses.size>=im.UNMATCHED_CONTROL_RESPONSES_MAX){let r=this.unmatchedControlResponses.keys().next().value;if(r!==void 0)this.unmatchedControlResponses.delete(r)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive")continue;else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=e.is_error?e.subtype==="success"?e.result:e.errors.map((r)=>r.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||void 0,this.firstResultReceived=!0,this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.isSingleUserTurn)Q("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput()}else if(!(e.type==="system"&&e.subtype==="session_state_changed"))this.lastErrorResultText=void 0;this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();if(this.firstResultReceivedResolve)this.firstResultReceivedResolve();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();if(this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.lastErrorResultText!==void 0&&!(e instanceof st)&&e?.name!=="SSEHttpError"){let t=Error(`Claude Code returned an error result: ${this.lastErrorResultText}`);Q(`[Query.readMessages] Replacing exit error with result text. Original: ${Yi(e)}`),this.inputStream.error(t),this.cleanup(t);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cancelControllers.has(e.request_id)){Q(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) — skipping`);return}let t=new AbortController;this.cancelControllers.set(e.request_id,t);try{let r=await this.processControlRequest(e,t.signal);if(this.cleanupPerformed)return;if(r===ES)return;let o={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:r}};await Promise.resolve(this.transport.write(me(o)+`
|
|
89
89
|
`))}catch(r){if(this.cleanupPerformed)return;let o={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:Yi(r)}};try{await Promise.resolve(this.transport.write(me(o)+`
|
|
@@ -114,7 +114,7 @@ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
114
114
|
`+" ".repeat(t))},"\t":{"\n":Array(200).fill(0).map((e,t)=>`
|
|
115
115
|
`+"\t".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+"\t".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
|
|
116
116
|
`+"\t".repeat(t))}};var EL;(function(e){e.DEFAULT={allowTrailingComma:!1}})(EL||(EL={}));var TL;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(TL||(TL={}));var PL;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(PL||(PL={}));var IL;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(IL||(IL={}));function zg(e){return e.startsWith("\uFEFF")?e.slice(1):e}import Ue from"node:path";import AL from"node:os";import ww from"node:process";var ro=AL.homedir(),kw=AL.tmpdir(),{env:Xs}=ww,roe=(e)=>{let t=Ue.join(ro,"Library");return{data:Ue.join(t,"Application Support",e),config:Ue.join(t,"Preferences",e),cache:Ue.join(t,"Caches",e),log:Ue.join(t,"Logs",e),temp:Ue.join(kw,e)}},noe=(e)=>{let t=Xs.APPDATA||Ue.join(ro,"AppData","Roaming"),r=Xs.LOCALAPPDATA||Ue.join(ro,"AppData","Local");return{data:Ue.join(r,e,"Data"),config:Ue.join(t,e,"Config"),cache:Ue.join(r,e,"Cache"),log:Ue.join(r,e,"Log"),temp:Ue.join(kw,e)}},ooe=(e)=>{let t=Ue.basename(ro);return{data:Ue.join(Xs.XDG_DATA_HOME||Ue.join(ro,".local","share"),e),config:Ue.join(Xs.XDG_CONFIG_HOME||Ue.join(ro,".config"),e),cache:Ue.join(Xs.XDG_CACHE_HOME||Ue.join(ro,".cache"),e),log:Ue.join(Xs.XDG_STATE_HOME||Ue.join(ro,".local","state"),e),temp:Ue.join(kw,t,e)}};function Ew(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(ww.platform==="darwin")return roe(e);if(ww.platform==="win32")return noe(e);return ooe(e)}var DBe=Ew("claude-cli");function ioe(){if(process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return"essential-traffic";if(process.env.DISABLE_TELEMETRY)return"no-telemetry";if(ve(process.env.DO_NOT_TRACK))return"no-telemetry";return"default"}function RL(){return ioe()==="essential-traffic"}var soe=100,Tw=[];function aoe(e){if(Tw.length>=soe)Tw.shift();Tw.push(e)}var loe=[],OL=null;var sqe=pe(()=>process.argv.includes("--hard-fail"));function Fg(e){let t=Or(e);try{if(ve(process.env.CLAUDE_CODE_USE_BEDROCK)||ve(process.env.CLAUDE_CODE_USE_VERTEX)||ve(process.env.CLAUDE_CODE_USE_FOUNDRY)||ve(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||ve(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||RL())return;let o={error:t.stack||t.message,timestamp:new Date().toISOString()};if(aoe(o),OL===null){loe.push({type:"error",error:t});return}OL.logError(t)}catch{}}var Ys=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,$L=new Set,Pw=typeof process==="object"&&!!process?process:{},ML=(e,t,r,o)=>{typeof Pw.emitWarning==="function"?Pw.emitWarning(e,t,r,o):console.error(`[${r}] ${t}: ${e}`)},Hg=globalThis.AbortController,CL=globalThis.AbortSignal;if(typeof Hg>"u"){CL=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(o,n){this._onabort.push(n)}},Hg=class{constructor(){t()}signal=new CL;abort(o){if(this.signal.aborted)return;this.signal.reason=o,this.signal.aborted=!0;for(let n of this.signal._onabort)n(o);this.signal.onabort?.(o)}};let e=Pw.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{if(!e)return;e=!1,ML("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t)}}var coe=(e)=>!$L.has(e),lqe=Symbol("type"),no=(e)=>e&&e===Math.floor(e)&&e>0&&isFinite(e),DL=(e)=>!no(e)?null:e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Iu:null;class Iu extends Array{constructor(e){super(e);this.fill(0)}}class Qs{heap;length;static#n=!1;static create(e){let t=DL(e);if(!t)return[];Qs.#n=!0;let r=new Qs(e,t);return Qs.#n=!1,r}constructor(e,t){if(!Qs.#n)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class Bg{#n;#d;#g;#h;#R;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#o;#r;#e;#c;#p;#l;#s;#_;#a;#b;#S;#f;#v;#T;#u;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#f,sizes:e.#b,keyMap:e.#o,keyList:e.#r,valList:e.#e,next:e.#c,prev:e.#p,get head(){return e.#l},get tail(){return e.#s},free:e.#_,isBackgroundFetch:(t)=>e.#t(t),backgroundFetch:(t,r,o,n)=>e.#M(t,r,o,n),moveToTail:(t)=>e.#A(t),indexes:(t)=>e.#x(t),rindexes:(t)=>e.#w(t),isStale:(t)=>e.#m(t)}}get max(){return this.#n}get maxSize(){return this.#d}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#R}get memoMethod(){return this.#O}get dispose(){return this.#g}get disposeAfter(){return this.#h}constructor(e){let{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:n,updateAgeOnGet:i,updateAgeOnHas:s,allowStale:a,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:p,maxSize:f=0,maxEntrySize:m=0,sizeCalculation:g,fetchMethod:h,memoMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:x,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:R,ignoreFetchAbort:U}=e;if(t!==0&&!no(t))throw TypeError("max option must be a nonnegative integer");let ae=t?DL(t):Array;if(!ae)throw Error("invalid max value: "+t);if(this.#n=t,this.#d=f,this.maxEntrySize=m||this.#d,this.sizeCalculation=g,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#O=y,h!==void 0&&typeof h!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#R=h,this.#T=!!h,this.#o=new Map,this.#r=Array(t).fill(void 0),this.#e=Array(t).fill(void 0),this.#c=new ae(t),this.#p=new ae(t),this.#l=0,this.#s=0,this.#_=Qs.create(t),this.#i=0,this.#y=0,typeof c==="function")this.#g=c;if(typeof u==="function")this.#h=u,this.#a=[];else this.#h=void 0,this.#a=void 0;if(this.#v=!!this.#g,this.#u=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!w,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!U,this.maxEntrySize!==0){if(this.#d!==0){if(!no(this.#d))throw TypeError("maxSize must be a positive integer if specified")}if(!no(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!x,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!s,this.ttlResolution=no(o)||o===0?o:1,this.ttlAutopurge=!!n,this.ttl=r||0,this.ttl){if(!no(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#n===0&&this.ttl===0&&this.#d===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#n&&!this.#d){if(coe("LRU_CACHE_UNBOUNDED"))$L.add("LRU_CACHE_UNBOUNDED"),ML("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",Bg)}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#D(){let e=new Iu(this.#n),t=new Iu(this.#n);this.#f=e,this.#S=t,this.#N=(n,i,s=Ys.now())=>{if(t[n]=i!==0?s:0,e[n]=i,i!==0&&this.ttlAutopurge){let a=setTimeout(()=>{if(this.#m(n))this.#k(this.#r[n],"expire")},i+1);if(a.unref)a.unref()}},this.#P=(n)=>{t[n]=e[n]!==0?Ys.now():0},this.#E=(n,i)=>{if(e[i]){let s=e[i],a=t[i];if(!s||!a)return;n.ttl=s,n.start=a,n.now=r||o();let c=n.now-a;n.remainingTTL=s-c}};let r=0,o=()=>{let n=Ys.now();if(this.ttlResolution>0){r=n;let i=setTimeout(()=>r=0,this.ttlResolution);if(i.unref)i.unref()}return n};this.getRemainingTTL=(n)=>{let i=this.#o.get(n);if(i===void 0)return 0;let s=e[i],a=t[i];if(!s||!a)return 1/0;let c=(r||o())-a;return s-c},this.#m=(n)=>{let i=t[n],s=e[n];return!!s&&!!i&&(r||o())-i>s}}#P=()=>{};#E=()=>{};#N=()=>{};#m=()=>!1;#F(){let e=new Iu(this.#n);this.#y=0,this.#b=e,this.#I=(t)=>{this.#y-=e[t],e[t]=0},this.#U=(t,r,o,n)=>{if(this.#t(r))return 0;if(!no(o))if(n){if(typeof n!=="function")throw TypeError("sizeCalculation must be a function");if(o=n(r,t),!no(o))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#C=(t,r,o)=>{if(e[t]=r,this.#d){let n=this.#d-e[t];while(this.#y>n)this.#$(!0)}if(this.#y+=e[t],o)o.entrySize=r,o.totalCalculatedSize=this.#y}}#I=(e)=>{};#C=(e,t,r)=>{};#U=(e,t,r,o)=>{if(r||o)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#x({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#s;;){if(!this.#L(t))break;if(e||!this.#m(t))yield t;if(t===this.#l)break;else t=this.#p[t]}}*#w({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#l;;){if(!this.#L(t))break;if(e||!this.#m(t))yield t;if(t===this.#s)break;else t=this.#c[t]}}#L(e){return e!==void 0&&this.#o.get(this.#r[e])===e}*entries(){for(let e of this.#x())if(this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e]))yield[this.#r[e],this.#e[e]]}*rentries(){for(let e of this.#w())if(this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e]))yield[this.#r[e],this.#e[e]]}*keys(){for(let e of this.#x()){let t=this.#r[e];if(t!==void 0&&!this.#t(this.#e[e]))yield t}}*rkeys(){for(let e of this.#w()){let t=this.#r[e];if(t!==void 0&&!this.#t(this.#e[e]))yield t}}*values(){for(let e of this.#x())if(this.#e[e]!==void 0&&!this.#t(this.#e[e]))yield this.#e[e]}*rvalues(){for(let e of this.#w())if(this.#e[e]!==void 0&&!this.#t(this.#e[e]))yield this.#e[e]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#x()){let o=this.#e[r],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0)continue;if(e(n,this.#r[r],this))return this.get(this.#r[r],t)}}forEach(e,t=this){for(let r of this.#x()){let o=this.#e[r],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0)continue;e.call(t,n,this.#r[r],this)}}rforEach(e,t=this){for(let r of this.#w()){let o=this.#e[r],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0)continue;e.call(t,n,this.#r[r],this)}}purgeStale(){let e=!1;for(let t of this.#w({allowStale:!0}))if(this.#m(t))this.#k(this.#r[t],"expire"),e=!0;return e}info(e){let t=this.#o.get(e);if(t===void 0)return;let r=this.#e[t],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let n={value:o};if(this.#f&&this.#S){let i=this.#f[t],s=this.#S[t];if(i&&s){let a=i-(Ys.now()-s);n.ttl=a,n.start=Date.now()}}if(this.#b)n.size=this.#b[t];return n}dump(){let e=[];for(let t of this.#x({allowStale:!0})){let r=this.#r[t],o=this.#e[t],n=this.#t(o)?o.__staleWhileFetching:o;if(n===void 0||r===void 0)continue;let i={value:n};if(this.#f&&this.#S){i.ttl=this.#f[t];let s=Ys.now()-this.#S[t];i.start=Math.floor(Date.now()-s)}if(this.#b)i.size=this.#b[t];e.unshift([r,i])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Ys.now()-o}this.set(t,r.value,r)}}set(e,t,r={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:n,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,u=this.#U(e,t,r.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize){if(a)a.set="miss",a.maxEntrySizeExceeded=!0;return this.#k(e,"set"),this}let d=this.#i===0?void 0:this.#o.get(e);if(d===void 0){if(d=this.#i===0?this.#s:this.#_.length!==0?this.#_.pop():this.#i===this.#n?this.#$(!1):this.#i,this.#r[d]=e,this.#e[d]=t,this.#o.set(e,d),this.#c[this.#s]=d,this.#p[d]=this.#s,this.#s=d,this.#i++,this.#C(d,u,a),a)a.set="add";c=!1}else{this.#A(d);let p=this.#e[d];if(t!==p){if(this.#T&&this.#t(p)){p.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=p;if(f!==void 0&&!i){if(this.#v)this.#g?.(f,e,"set");if(this.#u)this.#a?.push([f,e,"set"])}}else if(!i){if(this.#v)this.#g?.(p,e,"set");if(this.#u)this.#a?.push([p,e,"set"])}if(this.#I(d),this.#C(d,u,a),this.#e[d]=t,a){a.set="replace";let f=p&&this.#t(p)?p.__staleWhileFetching:p;if(f!==void 0)a.oldValue=f}}else if(a)a.set="update"}if(o!==0&&!this.#f)this.#D();if(this.#f){if(!c)this.#N(d,o,n);if(a)this.#E(a,d)}if(!i&&this.#u&&this.#a){let p=this.#a,f;while(f=p?.shift())this.#h?.(...f)}return this}pop(){try{while(this.#i){let e=this.#e[this.#l];if(this.#$(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#a){let e=this.#a,t;while(t=e?.shift())this.#h?.(...t)}}}#$(e){let t=this.#l,r=this.#r[t],o=this.#e[t];if(this.#T&&this.#t(o))o.__abortController.abort(Error("evicted"));else if(this.#v||this.#u){if(this.#v)this.#g?.(o,r,"evict");if(this.#u)this.#a?.push([o,r,"evict"])}if(this.#I(t),e)this.#r[t]=void 0,this.#e[t]=void 0,this.#_.push(t);if(this.#i===1)this.#l=this.#s=0,this.#_.length=0;else this.#l=this.#c[t];return this.#o.delete(r),this.#i--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,n=this.#o.get(e);if(n!==void 0){let i=this.#e[n];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(!this.#m(n)){if(r)this.#P(n);if(o)o.has="hit",this.#E(o,n);return!0}else if(o)o.has="stale",this.#E(o,n)}else if(o)o.has="miss";return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,o=this.#o.get(e);if(o===void 0||!r&&this.#m(o))return;let n=this.#e[o];return this.#t(n)?n.__staleWhileFetching:n}#M(e,t,r,o){let n=t===void 0?void 0:this.#e[t];if(this.#t(n))return n;let i=new Hg,{signal:s}=r;s?.addEventListener("abort",()=>i.abort(s.reason),{signal:i.signal});let a={signal:i.signal,options:r,context:o},c=(g,h=!1)=>{let{aborted:y}=i.signal,S=r.ignoreFetchAbort&&g!==void 0;if(r.status)if(y&&!h){if(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S)r.status.fetchAbortIgnored=!0}else r.status.fetchResolved=!0;if(y&&!S&&!h)return d(i.signal.reason);let x=f;if(this.#e[t]===f)if(g===void 0)if(x.__staleWhileFetching)this.#e[t]=x.__staleWhileFetching;else this.#k(e,"fetch");else{if(r.status)r.status.fetchUpdated=!0;this.set(e,g,a.options)}return g},u=(g)=>{if(r.status)r.status.fetchRejected=!0,r.status.fetchError=g;return d(g)},d=(g)=>{let{aborted:h}=i.signal,y=h&&r.allowStaleOnFetchAbort,S=y||r.allowStaleOnFetchRejection,x=S||r.noDeleteOnFetchRejection,w=f;if(this.#e[t]===f){if(!x||w.__staleWhileFetching===void 0)this.#k(e,"fetch");else if(!y)this.#e[t]=w.__staleWhileFetching}if(S){if(r.status&&w.__staleWhileFetching!==void 0)r.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw g},p=(g,h)=>{let y=this.#R?.(e,n,a);if(y&&y instanceof Promise)y.then((S)=>g(S===void 0?void 0:S),h);i.signal.addEventListener("abort",()=>{if(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort){if(g(void 0),r.allowStaleOnFetchAbort)g=(S)=>c(S,!0)}})};if(r.status)r.status.fetchDispatched=!0;let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:i,__staleWhileFetching:n,__returned:void 0});if(t===void 0)this.set(e,m,{...a.options,status:void 0}),t=this.#o.get(e);else this.#e[t]=m;return m}#t(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Hg}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:h=!1,status:y,signal:S}=t;if(!this.#T){if(y)y.fetch="get";return this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:n,status:y})}let x={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:n,ttl:i,noDisposeOnSet:s,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:y,signal:S},w=this.#o.get(e);if(w===void 0){if(y)y.fetch="miss";let R=this.#M(e,w,x,g);return R.__returned=R}else{let R=this.#e[w];if(this.#t(R)){let Zt=r&&R.__staleWhileFetching!==void 0;if(y){if(y.fetch="inflight",Zt)y.returnedStale=!0}return Zt?R.__staleWhileFetching:R.__returned=R}let U=this.#m(w);if(!h&&!U){if(y)y.fetch="hit";if(this.#A(w),o)this.#P(w);if(y)this.#E(y,w);return R}let ae=this.#M(e,w,x,g),tt=ae.__staleWhileFetching!==void 0&&r;if(y){if(y.fetch=U?"stale":"refresh",tt&&U)y.returnedStale=!0}return tt?ae.__staleWhileFetching:ae.__returned=ae}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(r===void 0)throw Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#O;if(!r)throw Error("no memoMethod provided to constructor");let{context:o,forceRefresh:n,...i}=t,s=this.get(e,i);if(!n&&s!==void 0)return s;let a=r(e,s,{options:i,context:o});return this.set(e,a,i),a}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:i}=t,s=this.#o.get(e);if(s!==void 0){let a=this.#e[s],c=this.#t(a);if(i)this.#E(i,s);if(this.#m(s)){if(i)i.get="stale";if(!c){if(!n)this.#k(e,"expire");if(i&&r)i.returnedStale=!0;return r?a:void 0}else{if(i&&r&&a.__staleWhileFetching!==void 0)i.returnedStale=!0;return r?a.__staleWhileFetching:void 0}}else{if(i)i.get="hit";if(c)return a.__staleWhileFetching;if(this.#A(s),o)this.#P(s);return a}}else if(i)i.get="miss"}#j(e,t){this.#p[t]=e,this.#c[e]=t}#A(e){if(e!==this.#s){if(e===this.#l)this.#l=this.#c[e];else this.#j(this.#p[e],this.#c[e]);this.#j(this.#s,e),this.#s=e}}delete(e){return this.#k(e,"delete")}#k(e,t){let r=!1;if(this.#i!==0){let o=this.#o.get(e);if(o!==void 0)if(r=!0,this.#i===1)this.#z(t);else{this.#I(o);let n=this.#e[o];if(this.#t(n))n.__abortController.abort(Error("deleted"));else if(this.#v||this.#u){if(this.#v)this.#g?.(n,e,t);if(this.#u)this.#a?.push([n,e,t])}if(this.#o.delete(e),this.#r[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#p[o];else if(o===this.#l)this.#l=this.#c[o];else{let i=this.#p[o];this.#c[i]=this.#c[o];let s=this.#c[o];this.#p[s]=this.#p[o]}this.#i--,this.#_.push(o)}}if(this.#u&&this.#a?.length){let o=this.#a,n;while(n=o?.shift())this.#h?.(...n)}return r}clear(){return this.#z("delete")}#z(e){for(let t of this.#w({allowStale:!0})){let r=this.#e[t];if(this.#t(r))r.__abortController.abort(Error("deleted"));else{let o=this.#r[t];if(this.#v)this.#g?.(r,o,e);if(this.#u)this.#a?.push([r,o,e])}}if(this.#o.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#S)this.#f.fill(0),this.#S.fill(0);if(this.#b)this.#b.fill(0);if(this.#l=0,this.#s=0,this.#_.length=0,this.#y=0,this.#i=0,this.#u&&this.#a){let t=this.#a,r;while(r=t?.shift())this.#h?.(...r)}}}function NL(e,t,r=100){let o=new Bg({max:r}),n=(...i)=>{let s=t(...i),a=o.get(s);if(a!==void 0)return a;let c=e(...i);return o.set(s,c),c};return n.cache={clear:()=>o.clear(),size:()=>o.size,delete:(i)=>o.delete(i),get:(i)=>o.peek(i),has:(i)=>o.has(i)},n}var uoe=8192;function LL(e,t){try{return{ok:!0,value:JSON.parse(zg(e))}}catch(r){if(t)Fg(kP(r,`safeParseJSON: invalid JSON (${r instanceof Error?r.constructor.name:typeof r}, ${e.length} bytes)`));return{ok:!1}}}var UL=NL(LL,(e)=>e,50);var ea=Object.assign(function(t,r=!0){if(!t)return null;let o=t.length>uoe?LL(t,r):UL(t,r);return o.ok?o.value:null},{cache:UL.cache});import{join as poe}from"path";import{readdir as Rqe,readFile as doe}from"fs/promises";import{release as jL}from"os";var Iw=pe(()=>{try{return qe().readFileSync("/proc/version",{encoding:"utf8"}).toLowerCase()}catch{return}});var zL;var ti=pe(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){if(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)return"wsl";let e=zL??Iw();if(e!==void 0&&(e.includes("microsoft")||e.includes("wsl")))return"wsl";return"linux"}return"unknown"}catch(e){return Fg(e),"unknown"}});var Uqe=pe(()=>{if(process.platform!=="linux")return;let e=zL??Iw();if(e===void 0)return;let t=e.match(/wsl(\d+)/);if(t&&t[1])return t[1];if(e.includes("microsoft"))return"1";return}),Lqe=pe(async()=>{if(process.platform!=="linux")return;let e={linuxKernel:jL()};try{let t=await doe("/etc/os-release","utf8");for(let r of t.split(`
|
|
117
|
-
`)){let o=r.match(/^(ID|VERSION_ID)=(.*)$/);if(o&&o[1]&&o[2]){let n=o[2].replace(/^"|"$/g,"");if(o[1]==="ID")e.linuxDistroId=n;else e.linuxDistroVersion=n}}}catch{}return e});var jqe=pe(()=>{if(process.platform!=="darwin")return;let t=jL().match(/^(\d+)\./);if(!t||!t[1])return;return parseInt(t[1],10)-9});var ri=pe(function(){switch(ti()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),qqe=pe(function(){return poe(ri(),"managed-settings.d")});function foe(e,t,r){if(r!==void 0&&!Rr(e[t],r)||r===void 0&&!(t in e))ns(e,t,r)}var Au=foe;function moe(e){return function(t,r,o){var n=-1,i=Object(t),s=o(t),a=s.length;while(a--){var c=s[e?a:++n];if(r(i[c],c,i)===!1)break}return t}}var FL=moe;var goe=FL(),HL=goe;function hoe(e){return _t(e)&&Nn(e)}var BL=hoe;var yoe="[object Object]",_oe=Function.prototype,boe=Object.prototype,qL=_oe.toString,Soe=boe.hasOwnProperty,voe=qL.call(Object);function xoe(e){if(!_t(e)||Lt(e)!=yoe)return!1;var t=cs(e);if(t===null)return!0;var r=Soe.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&qL.call(r)==voe}var VL=xoe;function woe(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var Ru=woe;function koe(e){return jP(e,as(e))}var WL=koe;function Eoe(e,t,r,o,n,i,s){var a=Ru(e,r),c=Ru(t,r),u=s.get(c);if(u){Au(e,r,u);return}var d=i?i(a,c,r+"",e,t,s):void 0,p=d===void 0;if(p){var f=je(c),m=!f&&Mn(c),g=!f&&!m&&is(c);if(d=c,f||m||g)if(je(a))d=a;else if(BL(a))d=oI(a);else if(m)p=!1,d=oS(c,!0);else if(g)p=!1,d=gI(c,!0);else d=[];else if(VL(c)||Yr(c)){if(d=a,Yr(a))d=WL(a);else if(!Je(a)||mi(a))d=_I(c)}else p=!1}if(p)s.set(c,d),n(d,c,o,i,s),s.delete(c);Au(e,r,d)}var KL=Eoe;function ZL(e,t,r,o,n){if(e===t)return;HL(t,function(i,s){if(n||(n=new $n),Je(i))KL(e,t,s,r,ZL,o,n);else{var a=o?o(Ru(e,s),i,s+"",e,t,n):void 0;if(a===void 0)a=i;Au(e,s,a)}},as)}var GL=ZL;function Toe(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var JL=Toe;var XL=Math.max;function Poe(e,t,r){return t=XL(t===void 0?e.length-1:t,0),function(){var o=arguments,n=-1,i=XL(o.length-t,0),s=Array(i);while(++n<i)s[n]=o[t+n];n=-1;var a=Array(t+1);while(++n<t)a[n]=o[n];return a[t]=r(s),JL(e,this,a)}}var qg=Poe;function Ioe(e){return function(){return e}}var YL=Ioe;var Aoe=!rs?ms:function(e,t){return rs(e,"toString",{configurable:!0,enumerable:!1,value:YL(t),writable:!0})},QL=Aoe;var Roe=800,Ooe=16,Coe=Date.now;function $oe(e){var t=0,r=0;return function(){var o=Coe(),n=Ooe-(o-r);if(r=o,n>0){if(++t>=Roe)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var ej=$oe;var Moe=ej(QL),Vg=Moe;function Doe(e,t){return Vg(qg(e,t,ms),e+"")}var tj=Doe;function Noe(e,t,r){if(!Je(r))return!1;var o=typeof t;if(o=="number"?Nn(r)&&Dn(t,r.length):o=="string"&&(t in r))return Rr(r[t],e);return!1}var rj=Noe;function Uoe(e){return tj(function(t,r){var o=-1,n=r.length,i=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;if(i=e.length>3&&typeof i=="function"?(n--,i):void 0,s&&rj(r[0],r[1],s))i=n<3?void 0:i,n=1;t=Object(t);while(++o<n){var a=r[o];if(a)e(t,a,o,i)}return t})}var nj=Uoe;var Loe=nj(function(e,t,r,o){GL(e,t,r,o)}),dn=Loe;function joe(e,t,r,o){if(!Je(e))return e;t=Un(t,e);var n=-1,i=t.length,s=i-1,a=e;while(a!=null&&++n<i){var c=Cr(t[n]),u=r;if(c==="__proto__"||c==="constructor"||c==="prototype")return e;if(n!=s){var d=a[c];if(u=o?o(d,c,a):void 0,u===void 0)u=Je(d)?d:Dn(t[n+1])?[]:{}}Pf(a,c,u),a=a[c]}return e}var oj=joe;function zoe(e,t,r){var o=-1,n=t.length,i={};while(++o<n){var s=t[o],a=fs(e,s);if(r(a,s))oj(i,Un(s,e),a)}return i}var Wg=zoe;function Foe(e,t){return Wg(e,t,function(r,o){return Yf(e,o)})}var ij=Foe;var sj=mt?mt.isConcatSpreadable:void 0;function Hoe(e){return je(e)||Yr(e)||!!(sj&&e&&e[sj])}var aj=Hoe;function lj(e,t,r,o,n){var i=-1,s=e.length;r||(r=aj),n||(n=[]);while(++i<s){var a=e[i];if(t>0&&r(a))if(t>1)lj(a,t-1,r,o,n);else ls(n,a);else if(!o)n[n.length]=a}return n}var cj=lj;function Boe(e){var t=e==null?0:e.length;return t?cj(e,1):[]}var uj=Boe;function qoe(e){return Vg(qg(e,void 0,uj),e+"")}var dj=qoe;var Voe=dj(function(e,t){return e==null?{}:ij(e,t)}),Kg=Voe;import{dirname as Nse,join as ao,resolve as Lu}from"path";var Woe="Expected a function";function Koe(e){if(typeof e!="function")throw TypeError(Woe);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}var pj=Koe;function Zoe(e,t){if(e==null)return{};var r=Xf(lI(e),function(o){return[o]});return t=Qf(t),Wg(e,r,function(o,n){return t(o,n[0])})}var fj=Zoe;function Goe(e,t){return fj(e,pj(Qf(t)))}var mj=Goe;import{join as eie}from"path";var Aw=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","CLOUD_ML_REGION"];var Rw=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_BASE_URL"];var Ow=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_AWS_API_KEY","ANTHROPIC_BEDROCK_MANTLE_API_KEY"],Joe=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],Xoe=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_3P_PROBE_WROTE_SONNET_DEFAULT","CLAUDE_CODE_3P_PROBE_WROTE_OPUS_DEFAULT"];var Yoe=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Qoe=[...Yoe,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var WVe=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...Aw,...Rw,...Ow,...Joe,"CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH","CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS","CLAUDE_CODE_HOST_CREDS_FILE",...Qoe,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT","GCE_METADATA_HOST","GCE_METADATA_IP","METADATA_SERVER_DETECTION","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","AWS_EC2_METADATA_SERVICE_ENDPOINT","AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE","AWS_REGION","AWS_DEFAULT_REGION",...Xoe,"ANTHROPIC_BEDROCK_SERVICE_TIER","CLAUDE_CODE_CERT_STORE","DISABLE_GROWTHBOOK"]);var tie="remote-settings.json",Cw=null,rie;var nie=null,oie=null;function $w(){return}function iie(){return $w()??eie(Xt(),tie)}function sie(){try{let e=ei(iie()),t=Ze(zg(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return t}catch{return null}}var aie=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",...Aw,...Rw,"CLAUDE_CODE_CUSTOM_OAUTH_URL",...Ow,"ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE"].map((e)=>e.toUpperCase()));function lie(e){if(!e?.env)return e;let t=mj(e.env,(r,o)=>aie.has(o.toUpperCase()));return{...e,env:t}}function cie(){if(!$w()&&rie!==!0)return null;if(Cw)return Cw;let e=sie();if(e)return Cw=e,oie??=e,Do(),e;return null}function gj(){let e=cie();if(e===nie||$w())return e;return lie(e)}var hj=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];import{userInfo as uie}from"os";var yj="com.anthropic.claudecode",Ou="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Cu="HKCU\\SOFTWARE\\Policies\\ClaudeCode",oo="Settings",_j="/usr/bin/plutil",bj=["-convert","json","-o","-","--"],Sj=5000,Mw="/mnt/c/Windows/System32/reg.exe",ta="/mnt/c/Program Files/ClaudeCode";function Zg(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Ut("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function vj(){let e="";try{e=uie().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${yj}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${yj}.plist`,label:"device-level managed preferences"}),t}import{isAbsolute as xj}from"path";var die=P(()=>l.object({allowedDomains:l.array(l.string()).optional(),deniedDomains:l.array(l.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:l.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:l.array(l.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:l.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:l.boolean().optional(),allowMachLookup:l.array(l.string().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:l.number().optional(),socksProxyPort:l.number().optional(),tlsTerminate:l.object({caCertPath:l.string().min(1).optional(),caKeyPath:l.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — project settings "+"(.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),pie=P(()=>l.object({allowWrite:l.array(l.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:l.array(l.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:l.array(l.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:l.array(l.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:l.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),Dw=P(()=>l.object({path:l.string().min(1).describe("Path to a credential file or directory. Same resolution as sandbox.filesystem.* paths: absolute, ~ expanded, or relative to the settings file root (project root for project settings, ~/.claude for user settings)."),mode:l.literal("deny").describe("Access mode for this path. Only `deny` is supported.")})),Nw=P(()=>l.object({name:l.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores").describe("Environment variable name."),mode:l.enum(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the "+"host proxy swaps sentinel→real on egress to `injectHosts`."),injectHosts:l.array(l.string()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")})),fie=P(()=>l.object({files:l.array(Dw()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox."),envVars:l.array(Nw()).optional().describe("Environment variables to protect. `deny` unsets the variable for sandboxed commands; `mask` substitutes a sentinel inside the sandbox and injects the real value at the proxy."),allowPlaintextInject:l.boolean().optional().describe("Allow sentinel→real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored.")}).optional()),Uw=P(()=>l.object({enabled:l.boolean().optional(),failIfUnavailable:l.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:l.boolean().optional(),allowUnsandboxedCommands:l.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:die(),filesystem:pie(),credentials:fie(),ignoreViolations:l.record(l.string(),l.array(l.string())).optional(),enableWeakerNestedSandbox:l.boolean().optional(),enableWeakerNetworkIsolation:l.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. "+"**Reduces security** — opens a potential data exfiltration vector through the trustd service. Default: false"),allowAppleEvents:l.boolean().optional().describe("macOS only: Allow sandboxed commands to send Apple Events (and look up the appleeventsd Mach service). Needed for `open`, `osascript`, and browser-based auth flows that open URLs. "+"**Removes code-execution isolation** — sandboxed commands can launch other applications "+"unsandboxed with no user prompt, and can script running apps (e.g. Terminal) subject to the user's per-app TCC automation consent. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. Default: false"),excludedCommands:l.array(l.string()).optional(),ripgrep:l.object({command:l.string(),args:l.array(l.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:l.preprocess((e)=>typeof e==="string"&&xj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:l.preprocess((e)=>typeof e==="string"&&xj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough());var $u=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],mie=[...$u,"bubble"],wj=mie;function Mu(e){return e==="manual"?"default":e}var kj=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"],Ej=["normal","vim"],Tj=["auto","tmux","iterm2","in-process"],gie=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],Pj=["auto",...gie];var hWe=ti()==="macos"?"⏺":"●";var wWe=P(()=>Sl.preprocess(Mu,Sl.enum(wj))),kWe=P(()=>Sl.preprocess(Mu,Sl.enum($u)));var Ij=["bash","powershell"];var Du=P(()=>l.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));function hie(){let e=l.object({type:l.literal("command").describe("Shell command hook type"),command:l.string().describe("Shell command to execute"),args:l.array(l.string()).optional().describe("Argument list for exec form. When present, `command` is resolved as "+"an executable and spawned directly with these arguments — no shell. "+"Path placeholders like ${CLAUDE_PLUGIN_ROOT} are substituted per-element as plain strings, so paths with quotes, $, or backticks never reach a shell parser. When absent, `command` runs through a shell (bash on POSIX, PowerShell on Windows without Git Bash)."),if:Du(),shell:l.enum(Ij).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:l.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:l.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:l.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:l.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),t=l.object({type:l.literal("prompt").describe("LLM prompt hook type"),prompt:l.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:l.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:l.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=l.object({type:l.literal("mcp_tool").describe("MCP tool hook type"),server:l.string().describe("Name of an already-configured MCP server to invoke"),tool:l.string().describe("Name of the tool on that server to call"),input:l.record(l.string(),l.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),o=l.object({type:l.literal("http").describe("HTTP hook type"),url:l.string().url().describe("URL to POST the hook input JSON to"),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:l.record(l.string(),l.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:l.array(l.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=l.object({type:l.literal("agent").describe("Agentic verifier hook type"),prompt:l.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:l.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:o,AgentHookSchema:n,McpToolHookSchema:r}}var Aj=P(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:r,HttpHookSchema:o,McpToolHookSchema:n}=hie();return l.discriminatedUnion("type",[e,t,r,o,n])}),Rj=P(()=>l.object({matcher:l.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:l.array(Aj()).describe("List of hooks to execute when the matcher matches")})),ni=P(()=>l.partialRecord(l.enum(fi),l.array(Rj())));var MWe=P(()=>l.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),DWe=P(()=>l.enum(["stdio","sse","sse-ide","http","ws","sdk"])),ra=P(()=>l.literal("comms").optional().catch(void 0)),io=P(()=>l.number().int().positive()),yie=300000,Oj=P(()=>l.number().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function Cj({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,yie)}}}var _ie=P(()=>l.object({type:l.literal("stdio").optional(),command:l.string().min(1,"Command cannot be empty"),args:l.array(l.string()).default([]),env:l.record(l.string(),l.string()).optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),bie=P(()=>l.boolean()),$j=P(()=>l.object({clientId:l.string().optional(),callbackPort:l.number().int().positive().optional(),authServerMetadataUrl:l.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:l.string().min(1).optional(),xaa:bie().optional()})),Mj=P(()=>l.object({name:l.string(),permission_policy:l.enum(["always_allow","always_ask","always_deny"]).optional()})),Sie=P(()=>l.object({type:l.literal("sse"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:$j().optional(),timeout:io().optional(),request_timeout_ms:Oj(),tools:l.array(Mj()).optional(),alwaysLoad:l.boolean().optional(),role:ra(),toolPermissions:l.record(l.string(),Lw()).optional()}).transform(Cj)),vie=P(()=>l.object({type:l.literal("sse-ide"),url:l.string(),ideName:l.string(),ideRunningInWindows:l.boolean().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),xie=P(()=>l.object({type:l.literal("ws-ide"),url:l.string(),ideName:l.string(),authToken:l.string().optional(),ideRunningInWindows:l.boolean().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),wie=P(()=>l.object({type:l.enum(["http","streamable-http"]).transform(()=>"http"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:$j().optional(),timeout:io().optional(),request_timeout_ms:Oj(),tools:l.array(Mj()).optional(),alwaysLoad:l.boolean().optional(),role:ra(),toolPermissions:l.record(l.string(),Lw()).optional()}).transform(Cj)),kie=P(()=>l.object({type:l.literal("ws"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),Eie=P(()=>l.object({type:l.literal("sdk"),name:l.string(),timeout:io().optional(),alwaysLoad:l.boolean().optional()})),Lw=P(()=>l.enum(["allow","ask","blocked"])),Tie=P(()=>l.object({type:l.literal("claudeai-proxy"),url:l.string(),id:l.string(),displayName:l.string().optional(),iconUrl:l.string().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),toolPermissions:l.record(l.string(),Lw()).optional(),stateless:l.boolean().optional(),cachedInitResponse:l.record(l.string(),l.unknown()).nullish()})),Gg=P(()=>l.union([_ie(),Sie(),vie(),xie(),wie(),kie(),Eie(),Tie()])),NWe=P(()=>l.object({mcpServers:l.record(l.string(),Gg())}));var Pie=new Set(["claude-community","claude-plugins-community","healthcare"]),Iie=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins"]),Lj=new Set([...Iie,...Pie]);var Aie=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,Rie=/[^\u0020-\u007E]/;function Oie(e){if(Lj.has(e.toLowerCase()))return!1;if(Rie.test(e))return!0;return Aie.test(e)}var Tr=P(()=>l.string().startsWith("./")),oi=P(()=>Tr().endsWith(".json")),Dj=P(()=>l.union([Tr().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),l.string().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),zw=P(()=>Tr().endsWith(".md")),Fw=P(()=>l.union([zw(),Tr()])),jj=P(()=>l.string().min(1,"Marketplace must have a name").refine((e)=>!e.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine((e)=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((e)=>!Oie(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine((e)=>e.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine((e)=>e.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine((e)=>e.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),Hw=P(()=>l.object({name:l.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:l.string().optional().describe("Contact email for support or feedback"),url:l.string().optional().describe("Website, GitHub profile, or organization URL")})),Cie=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:l.string().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version:l.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:l.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:Hw().optional().describe("Information about the plugin creator or maintainer"),homepage:l.string().url().optional().describe("Plugin homepage or documentation URL"),repository:l.string().optional().describe("Source code repository URL"),license:l.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:l.array(l.string()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:l.boolean().optional().describe("Whether the plugin starts enabled when the user has no explicit enabled/disabled setting for it (default: true). Explicit enabledPlugins values always win, and a plugin required by an enabled dependent is enabled regardless of this value."),dependencies:l.array(pse()).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.`)})),ZWe=P(()=>l.object({description:l.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:l.lazy(()=>ni()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),$ie=P(()=>l.object({hooks:l.union([oi().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>ni()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),l.array(l.union([oi().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>ni()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),Mie=P(()=>l.object({source:Fw().optional().describe("Path to command markdown file, relative to plugin root"),content:l.string().optional().describe("Inline markdown content for the command"),description:l.string().optional().describe("Command description override"),argumentHint:l.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:l.string().optional().describe("Default model for this command"),allowedTools:l.array(l.string()).optional().describe("Tools allowed when command runs")}).refine((e)=>e.source&&!e.content||!e.source&&e.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),Die=P(()=>l.object({commands:l.union([Fw().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both."),l.array(Fw().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both.")).describe("List of command file or skill directory paths. When set, the commands/ directory is not auto-loaded."),l.record(l.string(),Mie()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),Nie=P(()=>l.object({agents:l.union([zw().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both."),l.array(zw().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.")])})),Uie=P(()=>l.object({skills:l.union([Tr().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan)."),l.array(Tr().describe("Path to a skill directory, relative to the plugin root.")).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),zj=P(()=>l.object({outputStyles:l.union([Tr().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — list its files here if you want both."),l.array(Tr().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.")])})),Lie=P(()=>l.string().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),jie=16,zie=P(()=>l.object({id:Lie(),remote:l.string().max(256).regex(/^(npm:[@a-z0-9/._-]+(@[a-z0-9._+-]+)?|github:[\w.-]+\/[\w.-]+@[\w./-]+#.+\.js)$/,"must be npm:<pkg>[@ver] or github:<owner>/<repo>@<ref>#<path>.js").optional(),integrity:l.string().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),Fie=P(()=>l.object({syntaxHighlighting:l.object({hljsLanguages:l.array(zie()).max(jie)}).strict()})),Fj=P(()=>l.object({themes:l.union([Tr().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — list its files here if you want both."),l.array(Tr().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.")])})),Hie=P(()=>l.object({})),Nj=P(()=>l.string().min(1)),Bie=P(()=>l.string().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),qie=P(()=>l.object({mcpServers:l.union([oi().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),Dj().describe("Path or URL to MCPB file containing MCP server configuration"),l.record(l.string(),Gg()).describe("MCP server configurations keyed by server name"),l.array(l.union([oi().describe("Path to MCP servers configuration file"),Dj().describe("Path or URL to MCPB file"),l.record(l.string(),Gg()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),Hj=P(()=>l.object({type:l.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:l.string().describe("Human-readable label shown in the config dialog"),description:l.string().describe("Help text shown beneath the field in the config dialog"),required:l.boolean().optional().describe("If true, validation fails when this field is empty"),default:l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]).optional().describe("Default value used when the user provides nothing"),multiple:l.boolean().optional().describe("For string type: allow an array of strings"),sensitive:l.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:l.number().optional().describe("Minimum value (number type only)"),max:l.number().optional().describe("Maximum value (number type only)")}).strict()),Vie=P(()=>l.object({userConfig:l.record(l.string().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) — they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),Hj()).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.")})),Wie=P(()=>l.object({channels:l.array(l.object({server:l.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:l.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:l.record(l.string(),Hj()).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.")})),Uj=P(()=>l.strictObject({command:l.string().min(1).refine((e)=>{if(e.includes(" ")&&!e.startsWith("/"))return!1;return!0},{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:l.array(Nj()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:l.record(Bie(),Nj()).refine((e)=>Object.keys(e).length>0,{message:"extensionToLanguage must have at least one mapping"}).describe("Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping."),transport:l.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:l.record(l.string(),l.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:l.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:l.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:l.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:l.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:l.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:l.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:l.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:l.boolean().optional().describe("Whether to push publishDiagnostics into the agent context after edits. Set to false to keep LSP navigation (goToDefinition, hover, etc.) but suppress automatic diagnostic injection. Defaults to true.")})),Kie=P(()=>l.strictObject({name:l.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:l.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:l.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:l.union([l.literal("always"),l.string().startsWith("on-skill-invoke:").refine((e)=>e.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),Zie=P(()=>l.array(Kie()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),Bj=P(()=>l.object({monitors:l.union([oi().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Zie()]).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.")})),Gie=P(()=>l.object({lspServers:l.union([oi().describe("Path to .lsp.json configuration file relative to plugin root"),l.record(l.string(),Uj()).describe("LSP server configurations keyed by server name"),l.array(l.union([oi().describe("Path to LSP configuration file"),l.record(l.string(),Uj()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),qj=P(()=>l.string().refine((e)=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine((e)=>{let t=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,r=/^[a-z0-9][a-z0-9-._]*$/;return t.test(e)||r.test(e)},"Invalid npm package name format")),Jie=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,Xie=/^[0-9a-f]{64}$/;var Yie=64;var Qie=P(()=>l.object({sha256:l.string().regex(Xie)}));function ese(e){let t=l.record(l.string(),l.unknown()).safeParse(e);if(!t.success)return;let r=Object.create(null),o=0;for(let[n,i]of Object.entries(t.data)){if(o>=Yie)break;let s=Qie().safeParse(i);if(Jie.test(n)&&s.success)r[n]=s.data,o++}return o>0?r:void 0}var tse=P(()=>l.object({binaries:l.unknown().transform(ese).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),rse=P(()=>l.object({settings:l.record(l.string(),l.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),nse=P(()=>l.object({experimental:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,l.object({...Fj().partial().shape,...Fie().partial().shape,...Bj().partial().shape,...zj().partial().shape,evals:l.union([l.string(),l.array(l.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))}));var ose=P(()=>l.object({...Cie().shape,...$ie().partial().shape,...Die().partial().shape,...Nie().partial().shape,...Uie().partial().shape,...zj().partial().shape,...Fj().partial().shape,...Hie().shape,...Wie().partial().shape,...qie().partial().shape,...Gie().partial().shape,...Bj().partial().shape,...rse().partial().shape,...Vie().partial().shape,...tse().partial().shape,...nse().partial().shape})),Nu=P(()=>l.discriminatedUnion("source",[l.object({source:l.literal("url"),url:l.string().url().describe("Direct URL to marketplace.json file"),headers:l.record(l.string(),l.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),l.object({source:l.literal("git"),url:l.string().describe("Full git repository URL"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),l.object({source:l.literal("npm"),package:qj().describe("NPM package containing marketplace.json")}),l.object({source:l.literal("file"),path:l.string().describe("Local file path to marketplace.json")}),l.object({source:l.literal("directory"),path:l.string().describe("Local directory containing .claude-plugin/marketplace.json")}),l.object({source:l.literal("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),l.object({source:l.literal("hostPattern"),hostPattern:l.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against github.com. For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),l.object({source:l.literal("pathPattern"),pathPattern:l.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),l.object({source:l.literal("settings"),name:jj().refine((e)=>!Lj.has(e.toLowerCase()),{message:"Reserved marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation "+"as PluginMarketplaceSchema plus reserved-name rejection — "+"validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:l.array(ise()).describe("Plugin entries declared inline in settings.json"),owner:Hw().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).")])),jw=P(()=>l.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),Vj=P(()=>l.union([l.preprocess((e)=>e==="."?"./":e,Tr()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),l.object({source:l.literal("npm"),package:qj().or(l.string().refine((e)=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(e)||!e.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:l.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:l.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),l.object({source:l.literal("url"),url:l.string().describe("Full git repository URL (https:// or git@)"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:jw().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:jw().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("git-subdir"),url:l.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:l.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:jw().optional().describe("Specific commit SHA to use")}).describe("Plugin located in a subdirectory of a larger repository (monorepo). Only the specified subdirectory is materialized; the rest of the repo is not downloaded."),l.object({source:l.literal("unsupported")}).describe("Placeholder for source types this Claude Code version does not "+"recognize. Never authored by hand — PluginMarketplaceSchema rewrites "+'unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with a clear "update Claude Code" message.')])),ise=P(()=>l.object({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:Vj().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:l.string().optional(),version:l.string().optional(),strict:l.boolean().optional()}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine((e)=>typeof e.source==="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."}));var sse=P(()=>l.object({cli:l.array(l.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:l.array(l.string().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) — exact, case-insensitive match against '+"hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path."),filesRead:l.array(l.string().max(256)).max(10).optional().describe('Glob patterns (e.g. ["**/*.tf"]) — the plugin is relevant when a file Claude has read '+"this session matches any pattern. Matched against read-file paths, forward-slash normalized, case-insensitive."),manifestDeps:l.array(l.object({file:l.string().max(256),pattern:l.string().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: "+"`file` matches the manifest filename (package.json, go.mod, requirements.txt, …); "+"`pattern` matches the dependency declaration inside that file. Evaluated against files read this session."),cwd:l.array(l.string().max(256)).max(10).optional().describe('Glob patterns (e.g. ["Engine/Source/Runtime/Renderer/**"]) — the plugin is relevant when the '+`session's working directory is at or under a directory matching the pattern. Matched against the cwd both relative to the enclosing git repo root and as an absolute path, forward-slash normalized, case-insensitive. A bare directory (no glob characters) means "cwd is at or under this directory". Known at session start, so this signal can surface a suggestion before the first turn.`)})),ase=P(()=>l.object({topic:l.string().max(64).optional().describe('What the user is working with when this plugin is relevant — fills "Working with {topic}?". '+'Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:sse().optional().describe("Matchers that determine when the plugin is relevant.")})),lse=P(()=>ose().partial().extend({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:Vj().describe("Where to fetch the plugin from"),category:l.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:l.array(l.string()).optional().describe("Tags for searchability and discovery"),strict:l.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,ase().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.`)})),cse=P(()=>l.object({name:l.string().min(1).refine((e)=>!e.includes(" "))}));function use(e){let t=lse();return e.flatMap((r,o)=>{let n=t.safeParse(r);if(n.success)return[n.data];let i=cse().safeParse(r).data?.name,s=n.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(i)return Q(`Stubbing unparseable marketplace plugin entry (${i}): ${s}`,{level:"warn"}),[{name:i,source:{source:"unsupported"},strict:!0}];return Q(`Dropping unparseable marketplace plugin entry (index ${o}): ${s}`,{level:"warn"}),[]})}var GWe=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:jj(),version:l.string().optional().describe("Marketplace manifest version"),description:l.string().optional().describe("Human-readable description of this marketplace"),owner:Hw().describe("Marketplace maintainer or curator information"),plugins:l.array(l.unknown()).transform(use).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:l.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:l.object({pluginRoot:l.string().optional().describe("Base path for relative plugin sources"),version:l.string().optional().describe("Marketplace version"),description:l.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:l.array(l.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:l.record(l.string(),l.string().nullable()).optional().catch(void 0).describe("Append-only map of old plugin name → current name (or null when removed). The loader follows this on plugin-not-found and migrates user settings to the new name.")})),Wj=P(()=>l.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),dse=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,pse=P(()=>l.union([l.string().regex(dse,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),l.object({name:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),fse=P(()=>l.object({version:l.string().describe("Currently installed version"),installedAt:l.string().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),installPath:l.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:l.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),mse=P(()=>l.object({version:l.literal(1).describe("Schema version 1"),plugins:l.record(Wj(),fse()).describe("Map of plugin IDs to their installation metadata")})),gse=P(()=>l.enum(["managed","user","project","local"])),hse=P(()=>l.object({scope:gse().describe("Installation scope"),projectPath:l.string().optional().describe("Project path (required for project/local scopes)"),installPath:l.string().describe("Absolute path to the versioned plugin directory"),version:l.string().optional().describe("Currently installed version"),installedAt:l.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to"),auto:l.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),yse=P(()=>l.object({version:l.literal(2).describe("Schema version 2"),plugins:l.record(Wj(),l.array(hse())).describe("Map of plugin IDs to arrays of installation entries")})),JWe=P(()=>l.union([mse(),yse()])),_se=P(()=>l.object({source:Nu().describe("Where to fetch the marketplace from"),installLocation:l.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:l.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),XWe=P(()=>l.record(l.string(),_se()));var bse=["autoMode","deepLink","voice","briefView","screenReader"],Jg={},Xg={autoMode:{buildGate:()=>!1,shape:()=>Jg,permissionsShape:()=>Jg,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:l.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>Jg},briefView:{buildGate:()=>!0,shape:()=>({defaultView:l.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>Jg}};function Bw(){return bse.filter((e)=>Xg[e].buildGate())}function Kj(e){let t={};for(let r of e)t={...t,...Xg[r].shape()};return t}function Zj(e){let t={};for(let r of e)t={...t,...Xg[r].permissionsShape?.()};return t}function Gj(e){let t=[];for(let r of e)t.push(...Xg[r].permissionModes?.()??[]);return t}function qw(e){let t=e.split("__"),[r,o,...n]=t;if(r!=="mcp"||!o)return null;let i=n.length>0?n.join("__"):void 0;return{serverName:o,toolName:i}}var Jj={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool",ReadMcpResourceDir:"ReadMcpResourceDirTool"};function na(e){return Object.hasOwn(Jj,e)?Jj[e]:e}var Xj="workspace",lKe=`mcp__${Xj}__bash`,cKe=`mcp__${Xj}__web_fetch`;function Vw(e){return e.includes("*")}function Sse(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function Yj(e){let t=vse(e,"(");if(t===-1)return{toolName:na(e)};let r=xse(e,")");if(r===-1||r<=t)return{toolName:na(e)};if(r!==e.length-1)return{toolName:na(e)};let o=e.substring(0,t),n=e.substring(t+1,r);if(!o)return{toolName:na(e)};if(n===""||n==="*")return{toolName:na(o)};let i=Sse(n);return{toolName:na(o),ruleContent:i}}function vse(e,t){for(let r=0;r<e.length;r++)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}function xse(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}var Yg={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit","Cd"],bashPrefixTools:["Bash"],customValidation:{WebSearch:(e)=>{if(e.includes("*")||e.includes("?"))return{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]};return{valid:!0}},WebFetch:(e)=>{if(e.includes("://")||e.startsWith("http"))return{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]};if(!e.startsWith("domain:"))return{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]};return{valid:!0}}}};function Qj(e){return Yg.filePatternTools.includes(e)}function ez(e){return Yg.bashPrefixTools.includes(e)}function tz(e){return Object.hasOwn(Yg.customValidation,e)?Yg.customValidation[e]:void 0}function nz(e,t){let r=0,o=t-1;while(o>=0&&e[o]==="\\")r++,o--;return r%2!==0}function Ww(e,t){let r=0;for(let o=0;o<e.length;o++)if(e[o]===t&&!nz(e,o))r++;return r}function wse(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!nz(e,t))return!0}return!1}function rz(e){if(!Vw(e))return null;let t=qw(e);if(t&&!Vw(t.serverName))return null;return{valid:!1,error:`Wildcard tool name "${e}" is not supported in allow rules`,suggestion:"An allow pattern must name the scope it widens — globs are permitted only in the tool position after a literal mcp__<server>__ prefix. Deny and ask rules accept wildcards anywhere",examples:["mcp__puppeteer__*","mcp__github__get_*"]}}function Kw(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let r=Ww(e,"("),o=Ww(e,")");if(r!==o)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(wse(e)){let a=e.substring(0,e.indexOf("("));if(!a)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}}let n=Yj(e),i=qw(n.toolName);if(i){if(n.ruleContent!==void 0||Ww(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${n.toolName}" without parentheses, or use "mcp__${i.serverName}__*" for all tools`,examples:[`mcp__${i.serverName}`,`mcp__${i.serverName}__*`,i.toolName&&i.toolName!=="*"?`mcp__${i.serverName}__${i.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let a=rz(n.toolName);if(a)return a}return{valid:!0}}if(!n.toolName||n.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let a=rz(n.toolName);if(a)return a}if(!n.toolName.includes("_")&&n.toolName[0]!==n.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${gh(String(n.toolName))}"`};let s=tz(n.toolName);if(s&&n.ruleContent!==void 0){let a=s(n.ruleContent);if(!a.valid)return a}if(ez(n.toolName)&&n.ruleContent!==void 0){let a=n.ruleContent;if(a.includes(":*")&&!a.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(a===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(Qj(n.toolName)&&n.ruleContent!==void 0){if(n.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${n.toolName}(*.ts) - matches .ts files`,`${n.toolName}(src/**) - matches all files in src`,`${n.toolName}(**/*.test.ts) - matches test files`]}}return{valid:!0}}var Zw=P(()=>iz()),oz=P(()=>iz("allow"));function iz(e){return l.string().superRefine((t,r)=>{let o=Kw(t,e);if(!o.valid){let n=o.error;if(o.suggestion)n+=`. ${o.suggestion}`;if(o.examples&&o.examples.length>0)n+=`. Examples: ${o.examples.join(", ")}`;r.addIssue({code:l.ZodIssueCode.custom,message:n,params:{received:t}})}})}var kse=P(()=>l.record(l.string(),l.coerce.string()));function uz(e){return l.object({allow:l.array(oz()).optional().describe("List of permission rules for allowed operations"),deny:l.array(Zw()).optional().describe("List of permission rules for denied operations"),ask:l.array(Zw()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:l.preprocess(Mu,l.enum([...$u,...Gj(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:l.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...Zj(e),additionalDirectories:l.array(l.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var CKe=P(()=>uz(Bw())),Ese=P(()=>l.object({source:Nu().describe("Where to fetch the marketplace from"),installLocation:l.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),Qg=P(()=>l.object({serverName:l.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>Ov([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),eh=P(()=>l.object({serverName:l.string().min(1,"Server name must be non-empty").refine((e)=>e.trim().length>0,{message:"Server name must not be whitespace-only"}).refine((e)=>e===e.trim(),{message:"Server name has leading or trailing whitespace and will never match (names are compared verbatim)"}).optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>Ov([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),Tse=P(()=>l.object({path:l.string().describe("Absolute path to the helper executable"),timeoutMs:l.number().int().min(1000).optional(),refreshIntervalMs:l.union([l.literal(0),l.number().int().min(60000)]).optional()})),sz=["skills","agents","hooks","mcp"],az=Object.freeze({type:"invalid-entry-stripped"}),Pse=P(()=>l.union([l.object({type:l.literal("regex").describe('Config variant. This client understands "regex": matches turn output and builds a URL from named capture groups. Entries with other variants are preserved but skipped at runtime.'),pattern:l.string().describe("Regex matched against turn output (tool results and assistant text)"),url:l.string().describe("Link target. {name} placeholders are filled from named regex capture groups, e.g. (?<id>...) -> {id}. Values are URL-encoded; the origin must be literal in the template. The scheme must be https, http, or a recognized editor or workspace deep-link scheme: vscode, vscode-insiders, cursor, windsurf, zed, jetbrains, idea, slack, linear, notion, figma."),label:l.string().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),l.object({type:l.string().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function dz(e){return l.object({$schema:l.string().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:l.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:l.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:l.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:l.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:l.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:Tse().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...ve(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:l.object({issuer:l.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:l.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:l.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:l.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:l.object({enabled:l.boolean().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:l.number().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:l.number().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:l.string().optional().describe("Custom reminder text. Leave unset for a rotating set of friendly nudges.")}).optional().describe("@internal Opt-in break reminder. When enabled, shows a dismissible nudge after sustained continuous use. Never blocks — just a friendly heads-up."),quietHours:l.object({enabled:l.boolean().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:l.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "22:00")').optional().describe('Start of the quiet-hours window, 24-hour local time "HH:MM".'),end:l.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "07:00")').optional().describe('End of the quiet-hours window, 24-hour local time "HH:MM". May be earlier than start for an overnight range.')}).optional().describe("@internal Opt-in quiet hours. When enabled, shows a single soft nudge per session while inside the configured local-time window. Never blocks."),cleanupPeriodDays:l.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:l.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:l.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:l.boolean().optional().describe("When set to true in either admin-only Windows source — the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json — WSL reads managed settings from the full Windows policy chain (HKLM, C:/Program Files/ClaudeCode via DrvFs, HKCU) in addition to /etc/claude-code. Windows sources take priority. The flag is also required in HKCU itself for HKCU policy to apply on WSL (double opt-in: admin enables the chain, user confirms HKCU). On native Windows the flag has no effect."),env:kse().optional().describe("Environment variables to set for Claude Code sessions"),attribution:l.object({commit:l.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:l.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:l.boolean().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:l.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,includeGitInstructions:l.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:uz(e).optional().describe("Tool usage permissions configuration"),model:l.string().optional().describe("Override the default model used by Claude Code"),fallbackModel:l.array(l.string()).optional().describe('Fallback model(s) tried in order when the primary model is overloaded or unavailable. Each element accepts a model name or alias; "default" expands to the default model. CLI --fallback-model takes precedence.'),availableModels:l.array(l.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),enforceAvailableModels:l.boolean().optional().describe("When true and availableModels is a non-empty array, the Default model selection is also constrained: if the default model for the user tier is not in availableModels, Default resolves to the first allowed availableModels entry instead. Has no effect when availableModels is unset or an empty array. Typically set in managed settings by enterprise administrators."),modelOverrides:l.record(l.string(),l.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:l.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:l.array(l.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:l.array(l.string()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:l.boolean().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected. "+"Only gates auto-fetched connectors — a claudeai-proxy server passed explicitly "+"(e.g. via --mcp-config or the SDK mcpServers option) still follows the normal MCP config trust flow. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:l.record(l.string(),l.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),disableBundledSkills:l.boolean().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:l.array(Qg()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:l.array(eh()).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:ni().optional().describe("Custom commands to run before/after tool executions"),worktree:l.object({symlinkDirectories:l.array(l.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:l.array(l.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos — only the listed paths are written to disk."),baseRef:l.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:l.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:l.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:l.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:l.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableWorkflows:l.boolean().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:l.boolean().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableArtifact:l.boolean().optional().describe("Enable or disable the Artifact tool for this user. Unset defaults to enabled once the feature is available."),enableWorkflows:l.boolean().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowKeywordTriggerEnabled:l.boolean().optional().describe('Enable the "ultracode" keyword trigger: including the keyword in a prompt opts that turn into the Workflow tool. Set to false to disable the trigger. Default: true.'),disableSkillShellExecution:l.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:l.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:l.boolean().optional().describe("Whether Claude responds after an input-box ! bash command runs. Set to false to add the command output to context without a response. Default: true."),allowManagedHooksOnly:l.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:l.array(l.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:l.array(l.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:l.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:l.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),allowAllClaudeAiMcps:l.boolean().optional().describe("When true (and set in managed settings), claude.ai cloud MCP connectors load alongside managed-mcp.json instead of being suppressed by its exclusive-control lockdown. Default off preserves the lockdown. Read from managed settings only."),strictPluginOnlyCustomization:l.preprocess((t)=>Array.isArray(t)?t.filter((r)=>sz.includes(r)):t,l.union([l.boolean(),l.array(l.enum(sz))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. '+"Composes with strictKnownMarketplaces for end-to-end admin control — plugins gated by "+"marketplace allowlist, everything else blocked here."),statusLine:l.object({type:l.literal("command"),command:l.string(),padding:l.number().optional(),refreshInterval:l.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:l.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:l.string().optional().describe('URL template for PR links in the footer link badges and inline messages. The detected git PR is rendered as the first footer-link badge. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),footerLinksRegexes:l.array(Pse().catch(az)).transform((t)=>t.filter((r)=>r!==az)).optional().catch(void 0).describe("Extra clickable footer badges that appear when a regex matches turn output (tool results and assistant responses). Read from user, flag, and managed settings only; ignored in project .claude/settings.json and local .claude/settings.local.json. At most 5 badges render; the oldest is displaced by newer matches and /clear removes them. Use to surface IDs printed by project CLIs as session links."),subagentStatusLine:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:l.record(l.string(),l.union([l.array(l.string()),l.boolean(),l.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json — setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:l.record(l.string(),Ese()).check((t)=>{for(let[r,o]of Object.entries(t.value))if(o.source.source==="settings"&&o.source.name!==r)t.issues.push({code:"custom",input:o.source.name,path:[r,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${r}" but source.name "${o.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:l.array(Nu()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. "+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:l.array(Nu()).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."),disableSideloadFlags:l.boolean().optional().describe("When true (and set in managed settings), rejects the --plugin-dir, --plugin-url, --agents, and non-sdk --mcp-config CLI flags at startup. Closes the CLI-flag bypass of strictKnownMarketplaces. Pair with allowedMcpServers for per-server MCP control; this setting does not gate other MCP entry points (SDK setMcpServers, claude mcp add, .mcp.json). Also blocks surfaces that spawn the CLI with these flags internally (see settings documentation). Only honored from managed settings; ignored in user/project/local settings."),pluginSuggestionMarketplaces:l.array(l.string()).optional().describe("Marketplace names whose plugins may surface as contextual install suggestions (relevance-based tips). No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Only honored when set in managed settings (policy scope); the key is ignored in user, project, and local settings. A name only takes effect when the marketplace is registered on the machine AND its registered source is also declared in managed settings, either as the extraKnownMarketplaces entry for that name or as an entry of strictKnownMarketplaces. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source."),forceLoginMethod:l.enum(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:l.string().url().optional().catch(void 0).describe('@internal Cloud gateway URL to pre-fill and auto-connect to during login. Typically set in local managed settings alongside forceLoginMethod: "gateway" so users never type the URL. Hidden from public SDK types until Cloud gateway is documented.'),parentSettingsBehavior:l.enum(["first-wins","merge"]).optional().describe('Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" '+"(default): parent is dropped — admin tiers are the only policy "+`source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:l.union([l.string(),l.array(l.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:l.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:l.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:l.string().optional().describe("Controls the output style for assistant responses"),viewMode:l.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:l.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:l.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:Uw().optional(),feedbackSurveyRate:l.number().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:l.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:l.object({mode:l.enum(["append","replace"]),verbs:l.array(l.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:l.object({excludeDefault:l.boolean().optional(),tips:l.array(l.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:l.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:l.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:l.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:l.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:l.boolean().optional().catch(void 0).describe("Enable ultracode for the session: xhigh effort plus standing dynamic-workflow orchestration. "+"Session-scoped — typically provided via --settings or the apply_flag_settings control request; "+"interactive toggles never persist it. Requires workflows to be enabled and an xhigh-capable model."),autoCompactWindow:l.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:l.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:l.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:l.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:l.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),...{},awaySummaryEnabled:l.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:l.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:l.enum(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers "+"selected so far. Defaults to never — auto-continue only runs "+"when explicitly set to 60s/5m/10m."),agent:l.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:l.array(l.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:l.record(l.string(),l.object({mcpServers:l.record(l.string(),l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(l.undefined())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:l.object({defaultEnvironmentId:l.string().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:l.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:l.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:l.string().optional().describe("Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup with instructions to update. Only enforced from managed (policy) settings."),requiredMaximumVersion:l.string().optional().describe("Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. Only enforced from managed (policy) settings."),plansDirectory:l.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:l.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),...!1,voice:l.object({enabled:l.boolean().optional(),mode:l.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:l.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:l.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:l.array(l.object({marketplace:l.string(),plugin:l.string()})).optional().describe("Managed-org allowlist of channel plugins. When set, "+"replaces the default Anthropic allowlist — admins decide which "+"plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:l.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:l.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),totalTokensReminder:l.enum(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn "+"is on — task-budget semantics). Defaults to off. Env var "+"CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:l.number().int().positive().optional().describe("@internal Starting budget (tokens) for totalTokensReminder 'padded-countdown' mode. Defaults to 15000000. Server-controlled via GrowthBook; env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_BUDGET overrides."),totalTokensReminderAfterUserTurn:l.boolean().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:l.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:l.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:l.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:l.boolean().optional().describe("Request API-side thinking summaries and show them in the conversation and in the transcript view (ctrl+o). Set explicitly to override the default for your install."),skipDangerousModePermissionPrompt:l.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:l.boolean().optional().describe("@internal Whether the user has accepted the multi-agent workflow usage warning. Until set, auto permission mode prompts before running a workflow."),disableAutoMode:l.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:l.array(l.object({id:l.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:l.string().describe("Display name for the SSH connection"),sshHost:l.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:l.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:l.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:l.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:l.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:l.array(l.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:l.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:l.union([l.enum(Pj),l.string().startsWith("custom:").transform((t)=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:l.enum(Ej).optional().catch(void 0).describe("Key binding mode for the prompt input"),vimInsertModeRemaps:l.record(l.string(),l.unknown()).optional().catch(void 0).describe('Vim INSERT-mode key-sequence remaps, e.g. {"jj": "<Esc>"}. Each key is exactly two printable characters typed in sequence; "<Esc>" (return to NORMAL mode) is the only supported target. Applies when editorMode is "vim".'),verbose:l.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:l.enum(kj).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:l.boolean().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:l.boolean().optional().describe("@internal Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:l.boolean().optional().describe("When safety measures flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:l.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:l.boolean().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:l.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:l.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:l.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:l.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:l.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:l.enum(Tj).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:l.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:l.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:l.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:l.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:l.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:l.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...Kj(e)}).passthrough()}var si=P(()=>dz(Bw())),lz=Object.freeze({serverName:"invalid-entry-stripped"});function cz(e,t,r){return l.array(t.catch((o)=>(r({path:`${e}[]`,message:`Invalid entry was ignored: ${o.issues[0]?.message??"failed validation"}`}),lz))).transform((o)=>o.filter((n)=>n!==lz)).optional()}function Gw(e){let t=si(),r={};for(let[s,a]of Object.entries(t.shape))r[s]=a.catch((c)=>{e({path:s,message:`${c.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});r.allowedMcpServers=cz("allowedMcpServers",Qg(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[])),r.deniedMcpServers=cz("deniedMcpServers",eh(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return}),r.allowManagedMcpServersOnly=t.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),r.enforceAvailableModels=t.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),r.availableModels=l.array(l.unknown()).transform((s,a)=>{let c=[];for(let u of s)if(typeof u==="string")c.push(u);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(u)}); the entry was ignored.`});return c}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),r.forceLoginOrgUUID=t.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[]));let o=Object.freeze({mode:"deny"}),n=(s,a)=>l.array(a.catch((c)=>(e({path:`sandbox.credentials.${s}[]`,message:`Invalid entry was ignored: ${c.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),o))).transform((c)=>c.filter((u)=>u!==o)).optional();return r.sandbox=Uw().extend({credentials:l.object({files:n("files",Dw()),envVars:n("envVars",Nw()),allowPlaintextInject:l.boolean().optional().catch((s)=>{e({path:"sandbox.credentials.allowPlaintextInject",message:`${s.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was ignored; plaintext credential injection stays disabled until it is fixed.`});return})}).optional().catch((s)=>{e({path:"sandbox.credentials",message:`${s.issues[0]?.message??"Failed schema validation"}. The credentials block was dropped; no credential protection is applied until it is fixed.`});return})}).optional().catch((s)=>{e({path:"sandbox",message:`${s.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return}),l.object(r).passthrough().transform((s)=>{for(let a of Object.keys(s))if(s[a]===void 0)delete s[a];return s})}var pn="https://code.claude.com/docs/en",Ise=[{matches:(e)=>e.path==="permissions.defaultMode"&&e.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:`${pn}/iam#permission-modes`}},{matches:(e)=>e.path==="apiKeyHelper"&&e.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:(e)=>e.path==="cleanupPeriodDays"&&e.code==="too_small",tip:{suggestion:'cleanupPeriodDays must be at least 1. To keep transcripts for a long time, set a large number (e.g. 3650 for ~10 years). To disable transcript writes entirely, remove this setting and use the --no-session-persistence CLI flag or the SDK persistSession:false option instead. (0 is rejected because it previously silently disabled all transcript writes, which users setting it to mean "never clean up" did not expect.)'}},{matches:(e)=>e.path.startsWith("env.")&&e.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:`${pn}/settings#environment-variables`}},{matches:(e)=>(e.path==="permissions.allow"||e.path==="permissions.deny")&&e.code==="invalid_type"&&e.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:(e)=>e.path.startsWith("hooks.")&&e.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${pn}/hooks`}},{matches:(e)=>/\.hooks\.\d+\.command$/.test(e.path)&&e.code==="invalid_type"&&e.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${pn}/hooks#exec-form-and-shell-form`}},{matches:(e)=>e.path.includes("hooks")&&e.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:(e)=>e.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:`${pn}/settings`}},{matches:(e)=>e.code==="invalid_value"&&e.enumValues!==void 0,tip:{suggestion:void 0}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="object"&&e.received===null&&e.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:(e)=>e.path==="permissions.additionalDirectories"&&e.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:`${pn}/iam#working-directories`}}],Ase={permissions:`${pn}/iam#configuring-permissions`,env:`${pn}/settings#environment-variables`,hooks:`${pn}/hooks`};function pz(e){let t=Ise.find((o)=>o.matches(e));if(!t)return null;let r={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!r.suggestion)r.suggestion=`Valid values: ${e.enumValues.map((o)=>`"${o}"`).join(", ")}`;if(!r.docLink&&e.path)r.docLink=Ase[hh(e.path,".")];return r}var XKe=P(()=>si().strict());function fz(e){return e.code==="invalid_type"}function mz(e){return e.code==="invalid_value"}function Rse(e){return e.code==="unrecognized_keys"}function gz(e){return e.code==="too_small"}function oa(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function hz(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Uu(e,t){return e.issues.map((r)=>{let o=r.path.map(String).join("."),n=r.message,i,s,a,c,u;if(mz(r))s=r.values.map((p)=>String(p)),a=s.join(" | "),c=void 0,u=void 0;else if(fz(r)){a=r.expected;let p=hz(r.message);c=p??oa(r.input),u=p??oa(r.input)}else if(gz(r))a=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,u=c;let d=pz({path:o,code:r.code,expected:a,received:c,enumValues:s,message:r.message,value:c});if(mz(r))i=s?.map((p)=>`"${p}"`).join(", "),n=`Invalid value. Expected one of: ${i}`;else if(fz(r)){let p=hz(r.message)??oa(r.input);if(r.expected==="object"&&p==="null"&&o==="")n="Invalid or malformed JSON";else n=`Expected ${r.expected}, but received ${p}`}else if(Rse(r)){let p=r.keys.join(", ");n=`Unrecognized ${Ik(r.keys.length,"field")}: ${p}`}else if(gz(r))n=`Number must be greater than or equal to ${r.minimum}`,i=String(r.minimum);return{file:t,path:o,message:n,expected:i,invalidValue:u,suggestion:d?.suggestion,docLink:d?.docLink}})}function Ose(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!r.permissions||typeof r.permissions!=="object")return[];let o=r.permissions,n=[];for(let i of["allow","deny","ask"]){let s=o[i];if(!Array.isArray(s))continue;o[i]=s.filter((a)=>{if(typeof a!=="string")return n.push({file:t,path:`permissions.${i}`,message:`Non-string value in ${i} array was removed`,severity:"warning",invalidValue:a}),!1;let c=Kw(a,i);if(!c.valid){let u=`Invalid permission rule "${a}" was skipped: ${c.error}`;if(c.suggestion)u+=`. ${c.suggestion}`;return n.push({file:t,path:`permissions.${i}`,message:u,severity:"warning",invalidValue:a}),!1}return!0})}return n}var Cse=new Set(fi);function $se(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!("hooks"in r))return[];if(r.hooks===null||typeof r.hooks!=="object"||Array.isArray(r.hooks)){let i=oa(r.hooks);return delete r.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${i}. This field was ignored.`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"}]}let o=r.hooks,n=[];for(let i of Object.keys(o)){if(!Cse.has(i)){delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Unknown hook event "${i}" was ignored. Valid events: ${fi.join(", ")}`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(o[i])){let s=oa(o[i]);delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Hook event "${i}" must be an array of matchers; received ${s}. This entry was ignored.`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"})}}if(n.length>0&&Object.keys(o).length===0)delete r.hooks;return n}var Mse=[{key:"allowedMcpServers",schema:Qg},{key:"deniedMcpServers",schema:eh}];function Dse(e,t){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:n,schema:i}of Mse){if(!(n in r))continue;if(!Array.isArray(r[n])){let c=r[n];delete r[n],o.push({file:t,path:n,message:`"${n}" must be an array; received ${oa(c)}. This field was ignored.`,severity:"warning",invalidValue:c});continue}let s=r[n],a=[];for(let c=0;c<s.length;c++){let u=i().safeParse(s[c]);if(u.success)a.push(s[c]);else o.push({file:t,path:`${n}[${c}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:s[c]})}if(a.length<s.length)r[n]=a}return o}function ai(e,t,r){return[...Ose(e,t),...$se(e,t),...r?.skipMcpServerEntryFilter?[]:Dse(e,t)]}function Yw(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),hj.filter((r)=>t.has(r))}function Use(){return ao(ri(),"managed-settings.json")}function _z(e){if(ti()==="wsl"&&e.wslInherits?.()){let t=Jw(ta);if(t.settings)return t;let r=Jw(ri());return{settings:r.settings,errors:[...t.errors,...r.errors]}}return Jw(ri())}function Jw(e){let t=[],r={},o=!1,{settings:n,errors:i}=th(ao(e,"managed-settings.json"),void 0,!0);if(t.push(...i),n&&Object.keys(n).length>0)r=dn(r,n,so),o=!0;let s=ao(e,"managed-settings.d");try{let u=qe().readdirSync(s).filter((d)=>(d.isFile()||d.isSymbolicLink())&&d.name.endsWith(".json")&&!d.name.startsWith(".")).map((d)=>d.name).sort();for(let d of u){let{settings:p,errors:f}=th(ao(s,d),void 0,!0);if(t.push(...f),p&&Object.keys(p).length>0)r=dn(r,p,so),o=!0}}catch(u){let d=Be(u);if(d!=="ENOENT"&&d!=="ENOTDIR")Q(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:a,...c}=r;return{settings:o&&Object.keys(c).length>0?r:null,errors:t}}function Lse(e,t){if(Xr(e))Q(`Broken symlink or missing file encountered for settings.json at path: ${t}`);else Q(`settings file read failed at ${t}: ${e}`,{level:"error"})}function th(e,t,r){let o=oA(e);if(o)return{settings:o.settings?Ln(o.settings):null,errors:o.errors};let n=Fse(e,t,r);return iA(e,n),{settings:n.settings?Ln(n.settings):null,errors:n.errors}}function bz(e){if(!e.mdm)return{settings:null,errors:[]};let t=e.mdm();return{settings:Object.keys(t.settings).length>0?t.settings:null,errors:t.errors}}function rh(e,t){let r=Ln(e),o=ai(r,t,{skipMcpServerEntryFilter:!0}),n=[],i=Gw((s)=>n.push({file:t,path:s.path,message:s.message,severity:"warning"})).safeParse(r);if(!i.success)return{settings:null,errors:[...o,...Uu(i.error,t)]};return{settings:Object.keys(i.data).length>0?i.data:null,errors:[...o,...n]}}function Sz(e){let t=e?.remote?e.remote():gj();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return rh(t,"remote managed settings")}function jse(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return rh(t,"parent managed settings")}function vz(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let r=Ln(t),o=ai(r,"SDK inline settings"),n=si().safeParse(r);if(!n.success)return{settings:null,errors:[...o,...Uu(n.error,"SDK inline settings")]};return{settings:n.data,errors:o}}var zse=2097152;function Fse(e,t,r){try{let o;if(t!==void 0)o=t;else{let{resolvedPath:a}=nm(qe(),e);o=ei(a,zse)}if(o.trim()==="")return{settings:{},errors:[]};let n=Ln(ea(o,!1));if(r){let a=ai(n,e,{skipMcpServerEntryFilter:!0}),c=[],u=Gw((d)=>c.push({file:e,path:d.path,message:d.message,severity:"warning"})).safeParse(n);if(!u.success)return{settings:null,errors:[...a,...Uu(u.error,e)]};return{settings:u.data,errors:[...a,...c]}}let i=ai(n,e),s=si().safeParse(n);if(!s.success){let a=Uu(s.error,e);return{settings:null,errors:[...i,...a]}}return{settings:s.data,errors:i}}catch(o){if(Lse(o,e),Xr(o))return{settings:null,errors:[]};return{settings:null,errors:[{file:e,path:"",message:`Settings file could not be read: ${o instanceof Error?o.message:String(o)}`,severity:"fatal"}]}}}function yz(e,t){switch(e){case"userSettings":return Lu(Xt());case"policySettings":case"projectSettings":case"localSettings":return Lu(t.cwd);case"flagSettings":return t.flagPath?Nse(Lu(t.flagPath)):Lu(t.cwd)}}function Hse(e){if(e.coworkPlugins||ve(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function ju(e,t){switch(e){case"userSettings":return ao(yz(e,t),Hse(t));case"projectSettings":case"localSettings":return ao(yz(e,t),Bse(e));case"policySettings":return Use();case"flagSettings":return t.flagPath}}function Bse(e){switch(e){case"projectSettings":return ao(".claude","settings.json");case"localSettings":return ao(".claude","settings.local.json")}}function xz(e,t){let r=rA(e);if(r!==void 0)return r;let o=Wse(e,t);return nA(e,o),o}function qse(e){return!e||e.parentSettingsBehavior==="merge"}function Vse(e,t){let r={};if(e.allowManagedHooksOnly===!0)r.allowManagedHooksOnly=!0;if(e.allowManagedMcpServersOnly===!0)r.allowManagedMcpServersOnly=!0;if(e.disableClaudeAiConnectors===!0)r.disableClaudeAiConnectors=!0;if(e.allowManagedPermissionRulesOnly===!0)r.allowManagedPermissionRulesOnly=!0;let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)r.strictPluginOnlyCustomization=o;if(e.deniedMcpServers)r.deniedMcpServers=e.deniedMcpServers;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)r.forceLoginOrgUUID=e.forceLoginOrgUUID;if(t.allowedMcpServers===void 0&&e.allowedMcpServers)r.allowedMcpServers=e.allowedMcpServers;if(t.availableModels===void 0&&e.availableModels)r.availableModels=e.availableModels;if(e.enforceAvailableModels===!0)r.enforceAvailableModels=!0;if(e.permissions){let n=Kg(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable")n.disableBypassPermissionsMode="disable";if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:s}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)n.allow=i;if(s)n.additionalDirectories=s}if(Object.keys(n).length>0)r.permissions=n}if(e.sandbox){let{network:n,filesystem:i,credentials:s}=e.sandbox,a={};if(e.sandbox.enabled===!0)a.enabled=!0;if(e.sandbox.failIfUnavailable===!0)a.failIfUnavailable=!0;if(e.sandbox.allowUnsandboxedCommands===!1)a.allowUnsandboxedCommands=!1;if(e.sandbox.autoAllowBashIfSandboxed===!1)a.autoAllowBashIfSandboxed=!1;if(n){let c=Kg(n,["deniedDomains"]);if(n.allowManagedDomainsOnly===!0)c.allowManagedDomainsOnly=!0;if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&n.allowedDomains)c.allowedDomains=n.allowedDomains;if(Object.keys(c).length>0)a.network=c}if(i){let c=Kg(i,["denyRead","denyWrite"]);if(i.allowManagedReadPathsOnly===!0)c.allowManagedReadPathsOnly=!0;if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)c.allowRead=i.allowRead;if(Object.keys(c).length>0)a.filesystem=c}if(s){let c=(s.files??[]).filter((p)=>p.mode==="deny"),u=(s.envVars??[]).filter((p)=>p.mode==="deny"),d={...c.length>0&&{files:c},...u.length>0&&{envVars:u}};if(s.allowPlaintextInject===!1)d.allowPlaintextInject=!1;if(Object.keys(d).length>0)a.credentials=d}if(Object.keys(a).length>0)r.sandbox=a}return r}function wz(e){if(e.helper?.())return"helper";if(Sz(e).settings)return"remote";if(bz(e).settings)return ti()==="macos"?"plist":"hklm";if((e.file?.()??_z(e)).settings)return"file";if(kz(e).parentSlice)return"parent";let t=e.hkcu?.();return t&&Object.keys(t.settings).length>0?"hkcu":null}function kz(e){let t=[],{settings:r,errors:o}=Sz(e);t.push(...o);let{settings:n,errors:i}=bz(e);t.push(...i);let{settings:s,errors:a}=e.file?.()??_z(e);t.push(...a);let{settings:c,errors:u}=jse(e);t.push(...u);let d=[r,n,s].filter((h)=>h!==null),p=d[0]??null,f={allowManagedPermissionRulesOnly:d.some((h)=>h.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:d.find((h)=>h.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:d.find((h)=>h.allowedMcpServers!==void 0)?.allowedMcpServers,availableModels:d[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:d.some((h)=>h.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:d.some((h)=>h.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},m=c&&qse(p)?Vse(c,f):null,g=m&&Object.keys(m).length>0?m:null;return{tiers:d,admin:p,parentSlice:g,errors:t}}function Ez(e){let t=e.helper?.();if(t)return{settings:t,errors:e.helperWarnings?.()??[]};let{tiers:r,admin:o,parentSlice:n,errors:i}=kz(e);if(!o&&!n){let a=e.hkcu?.();if(a&&Object.keys(a.settings).length>0)return{settings:a.settings,errors:[...i,...a.errors]};return{settings:null,errors:[...i,...a?.errors??[]]}}let s=dn({},n??{},o??{},so);if(r.some((a)=>a.forceRemoteSettingsRefresh===!0))s.forceRemoteSettingsRefresh=!0;return{settings:s,errors:i}}function Wse(e,t){if(e==="policySettings")return Ez(t).settings;let r=ju(e,t),{settings:o}=r?th(r,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:n}=vz(t);if(n)return dn(o||{},n,so)}return o}function Kse(e,t){return Sm([...e,...t])}function so(e,t,r){if(Array.isArray(e)&&Array.isArray(t)){if(r==="fallbackModel")return t;return Kse(e,t)}return}var Xw=!1;function Zse(e){if(Xw)return{settings:{},errors:[]};let t=Date.now();Pu("info","settings_load_started"),Xw=!0;try{let r=sA(),o={};if(r)o=dn(o,r,so);let n=[],i=new Set,s=new Set,a=null;for(let c of Yw(e)){if(c==="policySettings"){let{settings:d,errors:p}=Ez(e);if(a=d,d)o=dn(o,d,so);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}continue}let u=ju(c,e);if(u){let d=Lu(u);if(!s.has(d)){s.add(d);let{settings:p,errors:f}=th(u,c==="flagSettings"?e.flagExpectedContent:void 0);for(let m of f){let g=`${m.file}:${m.path}:${m.message}`;if(!i.has(g))i.add(g),n.push(m)}if(p)o=dn(o,p,so)}}if(c==="flagSettings"){let{settings:d,errors:p}=vz(e);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}if(d)o=dn(o,d,so)}}if(a){if(a.availableModels!==void 0)o.availableModels=[...a.availableModels];if(a.enforceAvailableModels!==void 0)o.enforceAvailableModels=a.enforceAvailableModels}return Pu("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:s.size,error_count:n.length}),{settings:o,errors:n}}finally{Xw=!1}}function Gse(e){let t=eA();if(t!==null)return t;let r=Zse(e);return tA(r),r}function Jse(e){let{settings:t}=Gse(e);return t||{}}function Tz(e){Do();let t=[];for(let r of Yw(e)){let o=xz(r,e);if(o&&Object.keys(o).length>0)t.push({source:r,settings:o})}return{effective:Jse(e),sources:t}}function Pz(e,t){let r=Yw(t);for(let o=r.length-1;o>=0;o--){let n=r[o];if(xz(n,t)?.[e]!==void 0)return n}return null}import{execFile as Xse}from"child_process";import{existsSync as Yse}from"fs";var Qse=null;function zu(e,t){return new Promise((r)=>{try{Xse(e,t,{encoding:"utf-8",timeout:Sj,windowsHide:!0},(o,n)=>{r({stdout:n??"",code:o?1:0})})}catch{r({stdout:"",code:1})}})}function Iz(){return(async()=>{if(process.platform==="darwin"){let e=vj(),r=(await Promise.all(e.map(async({path:o,label:n})=>{if(!Yse(o))return{stdout:"",label:n,ok:!1};let{stdout:i,code:s}=await zu(_j,[...bj,o]);return{stdout:i,label:n,ok:s===0&&!!i}}))).find((o)=>o.ok);return{plistStdouts:r?[{stdout:r.stdout,label:r.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[r,o]=await Promise.all([zu(t,["query",Ou,"/v",oo]),zu(t,["query",Cu,"/v",oo])]);return{plistStdouts:null,hklmStdout:r.code===0?r.stdout:null,hkcuStdout:o.code===0?o.stdout:null}}if(Zg()){let[e,t]=await Promise.all([zu(Mw,["query",Ou,"/v",oo]),zu(Mw,["query",Cu,"/v",oo])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function Az(){return Qse}var lo=Object.freeze({settings:{},errors:[]}),$z=null,Mz=null,Dz=!1,nh=null;function eae(){if(nh)return;nh=(async()=>{let e=Date.now(),t=Az()??Iz(),{mdm:r,hkcu:o,wslInherits:n}=tae(await t);$z=r,Mz=o,Dz=n;let i=Date.now()-e;if(Q(`MDM settings load completed in ${i}ms`),Object.keys(r.settings).length>0){Q(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{Pu("info","mdm_settings_loaded",{duration_ms:i,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})()}async function Nz(){if(!nh)eae();await nh}function Uz(){return $z??lo}function Lz(){return Mz??lo}function jz(){return Dz}function Qw(e,t){let r=ea(e,!1);if(!r||typeof r!=="object")return{settings:{},errors:[]};let{settings:o,errors:n}=rh(r,t);return{settings:o??{},errors:n}}function Rz(e,t="Settings"){let r=e.split(/\r?\n/),o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s+${o}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let i of r){let s=i.match(n);if(s&&s[1])return s[1].trimEnd()}return null}function tae(e){let t=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:s,label:a}=e.plistStdouts[0],c=Qw(s,a),{wslInheritsWindowsSettings:u,...d}=c.settings;if(Object.keys(d).length>0)return{mdm:c,hkcu:lo,wslInherits:!1};t.push(...c.errors)}let r=null;if(e.hklmStdout){let s=Rz(e.hklmStdout);if(s)r=Qw(s,`Registry: ${Ou}\\${oo}`)}if(r)t.push(...r.errors);let o=t.length>0?{settings:{},errors:t}:lo,n=Zg(),i=!1;if(n){if(i=r?.settings.wslInheritsWindowsSettings===!0||nae(),!i)return{mdm:o,hkcu:lo,wslInherits:!1}}if(r){let{wslInheritsWindowsSettings:s,...a}=r.settings;if(Object.keys(a).length>0)return{mdm:r,hkcu:lo,wslInherits:i}}if(rae(i))return{mdm:o,hkcu:lo,wslInherits:i};if(e.hkcuStdout){let s=Rz(e.hkcuStdout);if(s){let a=Qw(s,`Registry: ${Cu}\\${oo}`);if(!n||a.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:c,...u}=a.settings;return{mdm:o,hkcu:{settings:u,errors:a.errors},wslInherits:i}}if(a.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:a.errors},wslInherits:i}}}return{mdm:o,hkcu:lo,wslInherits:i}}function rae(e){if(e&&Cz(ta))return!0;return Cz(ri())}function Oz(e){let t=Ln(ea(ei(e),!1));if(!t||typeof t!=="object")return!1;ai(t,e);let{wslInheritsWindowsSettings:r,...o}=t;return Object.keys(o).length>0}function nae(){function e(t){try{let r=ea(ei(t),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(e(ia(ta,"managed-settings.json")))return!0;try{let t=ia(ta,"managed-settings.d");for(let r of qe().readdirSync(t))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&e(ia(t,r.name)))return!0}catch{}return!1}function Cz(e){try{if(Oz(ia(e,"managed-settings.json")))return!0}catch{}try{let t=ia(e,"managed-settings.d"),r=qe().readdirSync(t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(Oz(ia(t,o.name)))return!0}catch{}}}catch{}return!1}var iae={user:"userSettings",project:"projectSettings",local:"localSettings"},zz={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},sae=["user","project","local"],aae=new Set(["bypassPermissions","auto","acceptEdits"]),lae=new Set(["project"]);function cae(e){let t=e.effective.permissions?.defaultMode;if(!t||!aae.has(t))return e.effective;for(let r=e.sources.length-1;r>=0;r--){let o=e.sources[r];if(o.settings.permissions?.defaultMode!==void 0){if(lae.has(o.source)){let{defaultMode:n,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}async function Fz(e={}){await Nz();let t={cwd:oae(e.cwd??qe().cwd()),allowedSources:(e.settingSources??sae).map((r)=>iae[r]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:Uz,hkcu:Lz,wslInherits:jz,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}};try{let{effective:r,sources:o}=Tz(t),n=wz(t)??void 0,i=o.map(({source:a,settings:c})=>({source:zz[a],settings:c,path:a==="policySettings"?void 0:ju(a,t),...a==="policySettings"&&{policyOrigin:n}})),s={};for(let a of Object.keys(r)){let c=Pz(a,t);if(c)s[a]={source:zz[c],path:c==="policySettings"?void 0:ju(c,t),...c==="policySettings"&&{policyOrigin:n}}}return{effective:r,provenance:s,sources:i}}finally{Do()}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function wGe(e){return Fz(e)}async function Sae(e,t){try{await fae(e,t)}catch(r){if(!Xr(r))throw r}}async function vae(e,t){if(!e)return;let r=e;try{let o=Ze(e);if(o?.claudeAiOauth?.refreshToken)delete o.claudeAiOauth.refreshToken,r=me(o)}catch{}await Wz(t,r,{mode:384})}function xae(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=yC(hC);return new Promise((t)=>{uae("security",["find-generic-password","-a",_C(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(r,o)=>t(r?void 0:o.trim()||void 0))})}async function Gz(e,t,r,o,n=60000){if(!Ee(t))return;let i=ar(r),s=await Ar(e.load({projectKey:i,sessionId:t}),n,`SessionStore.load() timed out after ${n}ms for session ${t}`);if(!s||s.length===0)return;let a=Kt(yae(),`claude-resume-${nk()}`);try{let c=Kt(a,"projects",i);await ek(c,{recursive:!0});let u=Kt(c,`${t}.jsonl`);await Rc(u,s);let d=o?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,p=d??Kt(tk(),".claude"),f;try{f=await Vz(Kt(p,".credentials.json"),"utf-8")}catch(m){if(!Xr(m))throw m}if(!d&&!(o??process.env).ANTHROPIC_API_KEY&&!(o??process.env).CLAUDE_CODE_OAUTH_TOKEN)f=await xae()??f;if(await vae(f,Kt(a,".credentials.json")),await Sae(Kt(d??tk(),".claude.json"),Kt(a,".claude.json")),e.listSubkeys)await wae(e,{projectKey:i,sessionId:t},Kt(c,t),n);return a}catch(c){throw await oh(a),c}}async function wae(e,t,r,o){let n=await Ar(e.listSubkeys({projectKey:t.projectKey,sessionId:t.sessionId}),o,`SessionStore.listSubkeys() timed out after ${o}ms for session ${t.sessionId}`);for(let i of n){let s=Fu(r,i+".jsonl");if(!i||Kz(i)||i.split(/[\\/]/).includes("..")||!s.startsWith(r+ok)){Q(`[SessionStore] skipping unsafe subpath from listSubkeys: ${i}`,{level:"warn"});continue}let a=await Ar(e.load({projectKey:t.projectKey,sessionId:t.sessionId,subpath:i}),o,`SessionStore.load() timed out after ${o}ms for session ${t.sessionId} subpath ${i}`);if(!a||a.length===0)continue;let c=[],u=[];for(let d of a)if(rk(d))c.push(d);else u.push(d);if(u.length>0)await ek(Hz(s),{recursive:!0}),await Rc(s,u);if(c.length>0){let d=c.at(-1),p=Fu(r,i+".meta.json");await ek(Hz(p),{recursive:!0});let{type:f,...m}=d;await Wz(p,me(m),{mode:384})}}}function ik(e,t){let{isSingleUserTurn:r,resumeConfigDir:o,deferSpawn:n}=t,{systemPrompt:i,settings:s,managedSettings:a,settingSources:c,sandbox:u,...d}=e??{},p,f,m;if(i===void 0)p="";else if(typeof i==="string")p=i;else if(Array.isArray(i))p=i;else if(i.type==="preset")f=i.append,m=i.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.208";let{abortController:g=pa(),additionalDirectories:h=[],agent:y,agents:S,allowedTools:x=[],betas:w,canUseTool:R,continue:U,cwd:ae,debug:Ge,debugFile:tt,disallowedTools:Zt=[],tools:Ur,env:Gt,executable:li=qu()?"bun":"node",executableArgs:fn=[],extraArgs:ci={},fallbackModel:co,enableFileCheckpointing:W,toolConfig:sa,forkSession:sh,hooks:ui,includeHookEvents:aa,includePartialMessages:la,forwardSubagentText:Hu,onElicitation:di,onUserDialog:ye,supportedDialogKinds:Dt,persistSession:lr,sessionStore:cr,sessionStoreFlush:r1,thinking:ca,effort:n1,maxThinkingTokens:ah,maxTurns:o1,maxBudgetUsd:i1,taskBudget:s1,mcpServers:ak,model:a1,outputFormat:lk,permissionMode:ck="default",allowDangerouslySkipPermissions:l1=!1,permissionPromptToolName:c1,plugins:u1,getOAuthToken:uk,getHostAuthToken:dk,workload:pk,resume:fk,resumeSessionAt:d1,sessionId:p1,skills:mk,stderr:f1,strictMcpConfig:m1}=d;if(cr&&lr===!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(Dt!==void 0&&Dt.length>0&&!ye)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if(cr&&U&&!fk&&!cr.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(cr&&W)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(cr&&d.spawnClaudeCodeProcess)Q("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"});bC(!!R,ck,x);let lh=d.pathToClaudeCodeExecutable;if(!lh){let Nt=bae(import.meta.url),ur=hae(Nt),uo=$A((pi)=>ur.resolve(pi));if(!uo)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.`);lh=uo}let gk=lk?.type==="json_schema"?lk.schema:void 0,ft=Gt?{...Gt}:{...process.env};if(!ft.CLAUDE_CODE_ENTRYPOINT)ft.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!ft.CLAUDE_AGENT_SDK_VERSION)ft.CLAUDE_AGENT_SDK_VERSION="0.3.208";if(W)ft.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(uk)ft.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(dk)ft.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(sa?.askUserQuestion?.previewFormat)ft.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=sa.askUserQuestion.previewFormat;let ch={};if(ih.propagation.inject(ih.context.active(),ch),"traceparent"in ch){for(let Nt of["TRACEPARENT","TRACESTATE"])if(!(Nt in(Gt??{})))delete ft[Nt]}for(let[Nt,ur]of Object.entries(ch)){let uo=Nt.toUpperCase();if(!(uo in(Gt??{})))ft[uo]=ur}let hk={},yk=new Map;if(ak)for(let[Nt,ur]of Object.entries(ak))if(ur.type==="sdk"&&ur.instance)yk.set(Nt,ur.instance);else hk[Nt]=ur;let ua;if(ca)switch(ca.type){case"adaptive":ua={type:"adaptive",display:ca.display};break;case"enabled":ua={type:"enabled",budgetTokens:ca.budgetTokens,display:ca.display};break;case"disabled":ua={type:"disabled"};break}else if(ah!==void 0)ua=ah===0?{type:"disabled"}:{type:"enabled",budgetTokens:ah};if(o){if(ft.CLAUDE_CONFIG_DIR=o,process.platform==="win32")ft.CLAUDE_SECURESTORAGE_CONFIG_DIR=Gt?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??Gt?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let _k=new vS({abortController:g,additionalDirectories:h,agent:y,betas:w,cwd:ae,debug:Ge,debugFile:tt,executable:li,executableArgs:fn,extraArgs:pk?{...ci,workload:pk}:ci,pathToClaudeCodeExecutable:lh,env:ft,forkSession:sh,stderr:f1,thinkingConfig:ua,effort:n1,maxTurns:o1,maxBudgetUsd:i1,taskBudget:s1,model:a1,fallbackModel:co,jsonSchema:gk,permissionMode:ck,allowDangerouslySkipPermissions:l1,permissionPromptToolName:c1,continueConversation:cr?void 0:U,resume:fk,resumeSessionAt:d1,sessionId:p1,settings:typeof s==="object"?me(s):s,managedSettings:a?me(a):void 0,settingSources:c,skills:mk,allowedTools:x,disallowedTools:Zt,tools:Ur,mcpServers:hk,strictMcpConfig:m1,canUseTool:!!R,hooks:!!ui,includeHookEvents:aa,includePartialMessages:la,persistSession:lr,sessionMirror:!!cr,plugins:u1,sandbox:u,spawnClaudeCodeProcess:d.spawnClaudeCodeProcess,deferSpawn:n}),g1={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:d.planModeInstructions,appendSubagentSystemPrompt:d.appendSubagentSystemPrompt,toolAliases:d.toolAliases,excludeDynamicSections:m,agents:S,title:d.title,skills:mk,webSearchIsolationExemptMcpServers:d.webSearchIsolationExemptMcpServers,promptSuggestions:d.promptSuggestions,agentProgressSummaries:d.agentProgressSummaries,forwardSubagentText:Hu,supportedDialogKinds:Dt},uh=new im(_k,r,R,ui,g,yk,gk,g1,di,uk,dk,ye);if(cr){let Nt=()=>Kt(ft.CLAUDE_CONFIG_DIR??Kt(tk(),".claude"),"projects"),ur=r1==="eager",uo=new TS(async(pi,dh)=>{let da=qz(pi,Nt());if(da)await cr.append(da,dh);else Q(`[SessionStore] dropping mirror frame: filePath ${pi} is not under ${Nt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(pi,dh)=>{let da=qz(pi,Nt());if(da)uh.reportMirrorError(da,dh.message)},maxPendingEntries:ur?0:sm,maxPendingBytes:ur?0:am});uh.setTranscriptMirrorBatcher(uo)}return{queryInstance:uh,transport:_k,abortController:g,processEnv:ft}}function sk(e,t,r,o){if(typeof r==="string")t.write(me({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:r}]},parent_tool_use_id:null})+`
|
|
117
|
+
`)){let o=r.match(/^(ID|VERSION_ID)=(.*)$/);if(o&&o[1]&&o[2]){let n=o[2].replace(/^"|"$/g,"");if(o[1]==="ID")e.linuxDistroId=n;else e.linuxDistroVersion=n}}}catch{}return e});var jqe=pe(()=>{if(process.platform!=="darwin")return;let t=jL().match(/^(\d+)\./);if(!t||!t[1])return;return parseInt(t[1],10)-9});var ri=pe(function(){switch(ti()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),qqe=pe(function(){return poe(ri(),"managed-settings.d")});function foe(e,t,r){if(r!==void 0&&!Rr(e[t],r)||r===void 0&&!(t in e))ns(e,t,r)}var Au=foe;function moe(e){return function(t,r,o){var n=-1,i=Object(t),s=o(t),a=s.length;while(a--){var c=s[e?a:++n];if(r(i[c],c,i)===!1)break}return t}}var FL=moe;var goe=FL(),HL=goe;function hoe(e){return _t(e)&&Nn(e)}var BL=hoe;var yoe="[object Object]",_oe=Function.prototype,boe=Object.prototype,qL=_oe.toString,Soe=boe.hasOwnProperty,voe=qL.call(Object);function xoe(e){if(!_t(e)||Lt(e)!=yoe)return!1;var t=cs(e);if(t===null)return!0;var r=Soe.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&qL.call(r)==voe}var VL=xoe;function woe(e,t){if(t==="constructor"&&typeof e[t]==="function")return;if(t=="__proto__")return;return e[t]}var Ru=woe;function koe(e){return jP(e,as(e))}var WL=koe;function Eoe(e,t,r,o,n,i,s){var a=Ru(e,r),c=Ru(t,r),u=s.get(c);if(u){Au(e,r,u);return}var d=i?i(a,c,r+"",e,t,s):void 0,p=d===void 0;if(p){var f=je(c),m=!f&&Mn(c),g=!f&&!m&&is(c);if(d=c,f||m||g)if(je(a))d=a;else if(BL(a))d=oI(a);else if(m)p=!1,d=oS(c,!0);else if(g)p=!1,d=gI(c,!0);else d=[];else if(VL(c)||Yr(c)){if(d=a,Yr(a))d=WL(a);else if(!Je(a)||mi(a))d=_I(c)}else p=!1}if(p)s.set(c,d),n(d,c,o,i,s),s.delete(c);Au(e,r,d)}var KL=Eoe;function ZL(e,t,r,o,n){if(e===t)return;HL(t,function(i,s){if(n||(n=new $n),Je(i))KL(e,t,s,r,ZL,o,n);else{var a=o?o(Ru(e,s),i,s+"",e,t,n):void 0;if(a===void 0)a=i;Au(e,s,a)}},as)}var GL=ZL;function Toe(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var JL=Toe;var XL=Math.max;function Poe(e,t,r){return t=XL(t===void 0?e.length-1:t,0),function(){var o=arguments,n=-1,i=XL(o.length-t,0),s=Array(i);while(++n<i)s[n]=o[t+n];n=-1;var a=Array(t+1);while(++n<t)a[n]=o[n];return a[t]=r(s),JL(e,this,a)}}var qg=Poe;function Ioe(e){return function(){return e}}var YL=Ioe;var Aoe=!rs?ms:function(e,t){return rs(e,"toString",{configurable:!0,enumerable:!1,value:YL(t),writable:!0})},QL=Aoe;var Roe=800,Ooe=16,Coe=Date.now;function $oe(e){var t=0,r=0;return function(){var o=Coe(),n=Ooe-(o-r);if(r=o,n>0){if(++t>=Roe)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var ej=$oe;var Moe=ej(QL),Vg=Moe;function Doe(e,t){return Vg(qg(e,t,ms),e+"")}var tj=Doe;function Noe(e,t,r){if(!Je(r))return!1;var o=typeof t;if(o=="number"?Nn(r)&&Dn(t,r.length):o=="string"&&(t in r))return Rr(r[t],e);return!1}var rj=Noe;function Uoe(e){return tj(function(t,r){var o=-1,n=r.length,i=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;if(i=e.length>3&&typeof i=="function"?(n--,i):void 0,s&&rj(r[0],r[1],s))i=n<3?void 0:i,n=1;t=Object(t);while(++o<n){var a=r[o];if(a)e(t,a,o,i)}return t})}var nj=Uoe;var Loe=nj(function(e,t,r,o){GL(e,t,r,o)}),dn=Loe;function joe(e,t,r,o){if(!Je(e))return e;t=Un(t,e);var n=-1,i=t.length,s=i-1,a=e;while(a!=null&&++n<i){var c=Cr(t[n]),u=r;if(c==="__proto__"||c==="constructor"||c==="prototype")return e;if(n!=s){var d=a[c];if(u=o?o(d,c,a):void 0,u===void 0)u=Je(d)?d:Dn(t[n+1])?[]:{}}Pf(a,c,u),a=a[c]}return e}var oj=joe;function zoe(e,t,r){var o=-1,n=t.length,i={};while(++o<n){var s=t[o],a=fs(e,s);if(r(a,s))oj(i,Un(s,e),a)}return i}var Wg=zoe;function Foe(e,t){return Wg(e,t,function(r,o){return Yf(e,o)})}var ij=Foe;var sj=mt?mt.isConcatSpreadable:void 0;function Hoe(e){return je(e)||Yr(e)||!!(sj&&e&&e[sj])}var aj=Hoe;function lj(e,t,r,o,n){var i=-1,s=e.length;r||(r=aj),n||(n=[]);while(++i<s){var a=e[i];if(t>0&&r(a))if(t>1)lj(a,t-1,r,o,n);else ls(n,a);else if(!o)n[n.length]=a}return n}var cj=lj;function Boe(e){var t=e==null?0:e.length;return t?cj(e,1):[]}var uj=Boe;function qoe(e){return Vg(qg(e,void 0,uj),e+"")}var dj=qoe;var Voe=dj(function(e,t){return e==null?{}:ij(e,t)}),Kg=Voe;import{dirname as Nse,join as ao,resolve as Lu}from"path";var Woe="Expected a function";function Koe(e){if(typeof e!="function")throw TypeError(Woe);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}var pj=Koe;function Zoe(e,t){if(e==null)return{};var r=Xf(lI(e),function(o){return[o]});return t=Qf(t),Wg(e,r,function(o,n){return t(o,n[0])})}var fj=Zoe;function Goe(e,t){return fj(e,pj(Qf(t)))}var mj=Goe;import{join as eie}from"path";var Aw=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","CLOUD_ML_REGION"];var Rw=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_BASE_URL"];var Ow=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_AWS_API_KEY","ANTHROPIC_BEDROCK_MANTLE_API_KEY"],Joe=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],Xoe=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_3P_PROBE_WROTE_SONNET_DEFAULT","CLAUDE_CODE_3P_PROBE_WROTE_OPUS_DEFAULT"];var Yoe=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Qoe=[...Yoe,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var WVe=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...Aw,...Rw,...Ow,...Joe,"CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH","CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS","CLAUDE_CODE_HOST_CREDS_FILE",...Qoe,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT","GCE_METADATA_HOST","GCE_METADATA_IP","METADATA_SERVER_DETECTION","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","AWS_EC2_METADATA_SERVICE_ENDPOINT","AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE","AWS_REGION","AWS_DEFAULT_REGION",...Xoe,"ANTHROPIC_BEDROCK_SERVICE_TIER","CLAUDE_CODE_CERT_STORE","DISABLE_GROWTHBOOK"]);var tie="remote-settings.json",Cw=null,rie;var nie=null,oie=null;function $w(){return}function iie(){return $w()??eie(Xt(),tie)}function sie(){try{let e=ei(iie()),t=Ze(zg(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return t}catch{return null}}var aie=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",...Aw,...Rw,"CLAUDE_CODE_CUSTOM_OAUTH_URL",...Ow,"ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE"].map((e)=>e.toUpperCase()));function lie(e){if(!e?.env)return e;let t=mj(e.env,(r,o)=>aie.has(o.toUpperCase()));return{...e,env:t}}function cie(){if(!$w()&&rie!==!0)return null;if(Cw)return Cw;let e=sie();if(e)return Cw=e,oie??=e,Do(),e;return null}function gj(){let e=cie();if(e===nie||$w())return e;return lie(e)}var hj=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];import{userInfo as uie}from"os";var yj="com.anthropic.claudecode",Ou="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Cu="HKCU\\SOFTWARE\\Policies\\ClaudeCode",oo="Settings",_j="/usr/bin/plutil",bj=["-convert","json","-o","-","--"],Sj=5000,Mw="/mnt/c/Windows/System32/reg.exe",ta="/mnt/c/Program Files/ClaudeCode";function Zg(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=Ut("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function vj(){let e="";try{e=uie().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${yj}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${yj}.plist`,label:"device-level managed preferences"}),t}import{isAbsolute as xj}from"path";var die=P(()=>l.object({allowedDomains:l.array(l.string()).optional(),deniedDomains:l.array(l.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:l.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:l.array(l.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:l.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:l.boolean().optional(),allowMachLookup:l.array(l.string().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:l.number().optional(),socksProxyPort:l.number().optional(),tlsTerminate:l.object({caCertPath:l.string().min(1).optional(),caKeyPath:l.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — project settings "+"(.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),pie=P(()=>l.object({allowWrite:l.array(l.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:l.array(l.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:l.array(l.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:l.array(l.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:l.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),Dw=P(()=>l.object({path:l.string().min(1).describe("Path to a credential file or directory. Same resolution as sandbox.filesystem.* paths: absolute, ~ expanded, or relative to the settings file root (project root for project settings, ~/.claude for user settings)."),mode:l.literal("deny").describe("Access mode for this path. Only `deny` is supported.")})),Nw=P(()=>l.object({name:l.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores").describe("Environment variable name."),mode:l.enum(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the "+"host proxy swaps sentinel→real on egress to `injectHosts`."),injectHosts:l.array(l.string()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")})),fie=P(()=>l.object({files:l.array(Dw()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox."),envVars:l.array(Nw()).optional().describe("Environment variables to protect. `deny` unsets the variable for sandboxed commands; `mask` substitutes a sentinel inside the sandbox and injects the real value at the proxy."),allowPlaintextInject:l.boolean().optional().describe("Allow sentinel→real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored.")}).optional()),Uw=P(()=>l.object({enabled:l.boolean().optional(),failIfUnavailable:l.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:l.boolean().optional(),allowUnsandboxedCommands:l.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:die(),filesystem:pie(),credentials:fie(),ignoreViolations:l.record(l.string(),l.array(l.string())).optional(),enableWeakerNestedSandbox:l.boolean().optional(),enableWeakerNetworkIsolation:l.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. "+"**Reduces security** — opens a potential data exfiltration vector through the trustd service. Default: false"),allowAppleEvents:l.boolean().optional().describe("macOS only: Allow sandboxed commands to send Apple Events (and look up the appleeventsd Mach service). Needed for `open`, `osascript`, and browser-based auth flows that open URLs. "+"**Removes code-execution isolation** — sandboxed commands can launch other applications "+"unsandboxed with no user prompt, and can script running apps (e.g. Terminal) subject to the user's per-app TCC automation consent. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. Default: false"),excludedCommands:l.array(l.string()).optional(),ripgrep:l.object({command:l.string(),args:l.array(l.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:l.preprocess((e)=>typeof e==="string"&&xj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:l.preprocess((e)=>typeof e==="string"&&xj(e)?e:void 0,l.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough());var $u=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],mie=[...$u,"bubble"],wj=mie;function Mu(e){return e==="manual"?"default":e}var kj=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"],Ej=["normal","vim"],Tj=["auto","tmux","iterm2","in-process"],gie=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],Pj=["auto",...gie];var hWe=ti()==="macos"?"⏺":"●";var wWe=P(()=>Sl.preprocess(Mu,Sl.enum(wj))),kWe=P(()=>Sl.preprocess(Mu,Sl.enum($u)));var Ij=["bash","powershell"];var Du=P(()=>l.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));function hie(){let e=l.object({type:l.literal("command").describe("Shell command hook type"),command:l.string().describe("Shell command to execute"),args:l.array(l.string()).optional().describe("Argument list for exec form. When present, `command` is resolved as "+"an executable and spawned directly with these arguments — no shell. "+"Path placeholders like ${CLAUDE_PLUGIN_ROOT} are substituted per-element as plain strings, so paths with quotes, $, or backticks never reach a shell parser. When absent, `command` runs through a shell (bash on POSIX, PowerShell on Windows without Git Bash)."),if:Du(),shell:l.enum(Ij).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:l.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:l.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:l.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:l.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),t=l.object({type:l.literal("prompt").describe("LLM prompt hook type"),prompt:l.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:l.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:l.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=l.object({type:l.literal("mcp_tool").describe("MCP tool hook type"),server:l.string().describe("Name of an already-configured MCP server to invoke"),tool:l.string().describe("Name of the tool on that server to call"),input:l.record(l.string(),l.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),o=l.object({type:l.literal("http").describe("HTTP hook type"),url:l.string().url().describe("URL to POST the hook input JSON to"),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:l.record(l.string(),l.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:l.array(l.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=l.object({type:l.literal("agent").describe("Agentic verifier hook type"),prompt:l.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:Du(),timeout:l.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:l.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:l.string().optional().describe("Custom status message to display in spinner while hook runs"),once:l.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:o,AgentHookSchema:n,McpToolHookSchema:r}}var Aj=P(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:r,HttpHookSchema:o,McpToolHookSchema:n}=hie();return l.discriminatedUnion("type",[e,t,r,o,n])}),Rj=P(()=>l.object({matcher:l.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:l.array(Aj()).describe("List of hooks to execute when the matcher matches")})),ni=P(()=>l.partialRecord(l.enum(fi),l.array(Rj())));var MWe=P(()=>l.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),DWe=P(()=>l.enum(["stdio","sse","sse-ide","http","ws","sdk"])),ra=P(()=>l.literal("comms").optional().catch(void 0)),io=P(()=>l.number().int().positive()),yie=300000,Oj=P(()=>l.number().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function Cj({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,yie)}}}var _ie=P(()=>l.object({type:l.literal("stdio").optional(),command:l.string().min(1,"Command cannot be empty"),args:l.array(l.string()).default([]),env:l.record(l.string(),l.string()).optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),bie=P(()=>l.boolean()),$j=P(()=>l.object({clientId:l.string().optional(),callbackPort:l.number().int().positive().optional(),authServerMetadataUrl:l.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:l.string().min(1).optional(),xaa:bie().optional()})),Mj=P(()=>l.object({name:l.string(),permission_policy:l.enum(["always_allow","always_ask","always_deny"]).optional()})),Sie=P(()=>l.object({type:l.literal("sse"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:$j().optional(),timeout:io().optional(),request_timeout_ms:Oj(),tools:l.array(Mj()).optional(),alwaysLoad:l.boolean().optional(),role:ra(),toolPermissions:l.record(l.string(),Lw()).optional()}).transform(Cj)),vie=P(()=>l.object({type:l.literal("sse-ide"),url:l.string(),ideName:l.string(),ideRunningInWindows:l.boolean().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),xie=P(()=>l.object({type:l.literal("ws-ide"),url:l.string(),ideName:l.string(),authToken:l.string().optional(),ideRunningInWindows:l.boolean().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),wie=P(()=>l.object({type:l.enum(["http","streamable-http"]).transform(()=>"http"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),oauth:$j().optional(),timeout:io().optional(),request_timeout_ms:Oj(),tools:l.array(Mj()).optional(),alwaysLoad:l.boolean().optional(),role:ra(),toolPermissions:l.record(l.string(),Lw()).optional()}).transform(Cj)),kie=P(()=>l.object({type:l.literal("ws"),url:l.string(),headers:l.record(l.string(),l.string()).optional(),headersHelper:l.string().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),role:ra()})),Eie=P(()=>l.object({type:l.literal("sdk"),name:l.string(),timeout:io().optional(),alwaysLoad:l.boolean().optional()})),Lw=P(()=>l.enum(["allow","ask","blocked"])),Tie=P(()=>l.object({type:l.literal("claudeai-proxy"),url:l.string(),id:l.string(),displayName:l.string().optional(),iconUrl:l.string().optional(),timeout:io().optional(),alwaysLoad:l.boolean().optional(),toolPermissions:l.record(l.string(),Lw()).optional(),stateless:l.boolean().optional(),cachedInitResponse:l.record(l.string(),l.unknown()).nullish()})),Gg=P(()=>l.union([_ie(),Sie(),vie(),xie(),wie(),kie(),Eie(),Tie()])),NWe=P(()=>l.object({mcpServers:l.record(l.string(),Gg())}));var Pie=new Set(["claude-community","claude-plugins-community","healthcare"]),Iie=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins"]),Lj=new Set([...Iie,...Pie]);var Aie=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,Rie=/[^\u0020-\u007E]/;function Oie(e){if(Lj.has(e.toLowerCase()))return!1;if(Rie.test(e))return!0;return Aie.test(e)}var Tr=P(()=>l.string().startsWith("./")),oi=P(()=>Tr().endsWith(".json")),Dj=P(()=>l.union([Tr().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),l.string().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),zw=P(()=>Tr().endsWith(".md")),Fw=P(()=>l.union([zw(),Tr()])),jj=P(()=>l.string().min(1,"Marketplace must have a name").refine((e)=>!e.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine((e)=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((e)=>!Oie(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine((e)=>e.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine((e)=>e.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine((e)=>e.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),Hw=P(()=>l.object({name:l.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:l.string().optional().describe("Contact email for support or feedback"),url:l.string().optional().describe("Website, GitHub profile, or organization URL")})),Cie=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:l.string().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version:l.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:l.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:Hw().optional().describe("Information about the plugin creator or maintainer"),homepage:l.string().url().optional().describe("Plugin homepage or documentation URL"),repository:l.string().optional().describe("Source code repository URL"),license:l.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:l.array(l.string()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:l.boolean().optional().describe("Whether the plugin starts enabled when the user has no explicit enabled/disabled setting for it (default: true). Explicit enabledPlugins values always win, and a plugin required by an enabled dependent is enabled regardless of this value."),dependencies:l.array(pse()).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.`)})),ZWe=P(()=>l.object({description:l.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:l.lazy(()=>ni()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),$ie=P(()=>l.object({hooks:l.union([oi().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>ni()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),l.array(l.union([oi().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),l.lazy(()=>ni()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),Mie=P(()=>l.object({source:Fw().optional().describe("Path to command markdown file, relative to plugin root"),content:l.string().optional().describe("Inline markdown content for the command"),description:l.string().optional().describe("Command description override"),argumentHint:l.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:l.string().optional().describe("Default model for this command"),allowedTools:l.array(l.string()).optional().describe("Tools allowed when command runs")}).refine((e)=>e.source&&!e.content||!e.source&&e.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),Die=P(()=>l.object({commands:l.union([Fw().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both."),l.array(Fw().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both.")).describe("List of command file or skill directory paths. When set, the commands/ directory is not auto-loaded."),l.record(l.string(),Mie()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),Nie=P(()=>l.object({agents:l.union([zw().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both."),l.array(zw().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.")])})),Uie=P(()=>l.object({skills:l.union([Tr().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan)."),l.array(Tr().describe("Path to a skill directory, relative to the plugin root.")).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),zj=P(()=>l.object({outputStyles:l.union([Tr().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — list its files here if you want both."),l.array(Tr().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.")])})),Lie=P(()=>l.string().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),jie=16,zie=P(()=>l.object({id:Lie(),remote:l.string().max(256).regex(/^(npm:[@a-z0-9/._-]+(@[a-z0-9._+-]+)?|github:[\w.-]+\/[\w.-]+@[\w./-]+#.+\.js)$/,"must be npm:<pkg>[@ver] or github:<owner>/<repo>@<ref>#<path>.js").optional(),integrity:l.string().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),Fie=P(()=>l.object({syntaxHighlighting:l.object({hljsLanguages:l.array(zie()).max(jie)}).strict()})),Fj=P(()=>l.object({themes:l.union([Tr().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — list its files here if you want both."),l.array(Tr().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.")])})),Hie=P(()=>l.object({})),Nj=P(()=>l.string().min(1)),Bie=P(()=>l.string().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),qie=P(()=>l.object({mcpServers:l.union([oi().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),Dj().describe("Path or URL to MCPB file containing MCP server configuration"),l.record(l.string(),Gg()).describe("MCP server configurations keyed by server name"),l.array(l.union([oi().describe("Path to MCP servers configuration file"),Dj().describe("Path or URL to MCPB file"),l.record(l.string(),Gg()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),Hj=P(()=>l.object({type:l.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:l.string().describe("Human-readable label shown in the config dialog"),description:l.string().describe("Help text shown beneath the field in the config dialog"),required:l.boolean().optional().describe("If true, validation fails when this field is empty"),default:l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]).optional().describe("Default value used when the user provides nothing"),multiple:l.boolean().optional().describe("For string type: allow an array of strings"),sensitive:l.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:l.number().optional().describe("Minimum value (number type only)"),max:l.number().optional().describe("Maximum value (number type only)")}).strict()),Vie=P(()=>l.object({userConfig:l.record(l.string().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) — they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),Hj()).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.")})),Wie=P(()=>l.object({channels:l.array(l.object({server:l.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:l.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:l.record(l.string(),Hj()).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.")})),Uj=P(()=>l.strictObject({command:l.string().min(1).refine((e)=>{if(e.includes(" ")&&!e.startsWith("/"))return!1;return!0},{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:l.array(Nj()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:l.record(Bie(),Nj()).refine((e)=>Object.keys(e).length>0,{message:"extensionToLanguage must have at least one mapping"}).describe("Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping."),transport:l.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:l.record(l.string(),l.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:l.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:l.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:l.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:l.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:l.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:l.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:l.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:l.boolean().optional().describe("Whether to push publishDiagnostics into the agent context after edits. Set to false to keep LSP navigation (goToDefinition, hover, etc.) but suppress automatic diagnostic injection. Defaults to true.")})),Kie=P(()=>l.strictObject({name:l.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:l.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:l.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:l.union([l.literal("always"),l.string().startsWith("on-skill-invoke:").refine((e)=>e.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),Zie=P(()=>l.array(Kie()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),Bj=P(()=>l.object({monitors:l.union([oi().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),Zie()]).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.")})),Gie=P(()=>l.object({lspServers:l.union([oi().describe("Path to .lsp.json configuration file relative to plugin root"),l.record(l.string(),Uj()).describe("LSP server configurations keyed by server name"),l.array(l.union([oi().describe("Path to LSP configuration file"),l.record(l.string(),Uj()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),qj=P(()=>l.string().refine((e)=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine((e)=>{let t=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,r=/^[a-z0-9][a-z0-9-._]*$/;return t.test(e)||r.test(e)},"Invalid npm package name format")),Jie=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,Xie=/^[0-9a-f]{64}$/;var Yie=64;var Qie=P(()=>l.object({sha256:l.string().regex(Xie)}));function ese(e){let t=l.record(l.string(),l.unknown()).safeParse(e);if(!t.success)return;let r=Object.create(null),o=0;for(let[n,i]of Object.entries(t.data)){if(o>=Yie)break;let s=Qie().safeParse(i);if(Jie.test(n)&&s.success)r[n]=s.data,o++}return o>0?r:void 0}var tse=P(()=>l.object({binaries:l.unknown().transform(ese).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),rse=P(()=>l.object({settings:l.record(l.string(),l.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),nse=P(()=>l.object({experimental:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,l.object({...Fj().partial().shape,...Fie().partial().shape,...Bj().partial().shape,...zj().partial().shape,evals:l.union([l.string(),l.array(l.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))}));var ose=P(()=>l.object({...Cie().shape,...$ie().partial().shape,...Die().partial().shape,...Nie().partial().shape,...Uie().partial().shape,...zj().partial().shape,...Fj().partial().shape,...Hie().shape,...Wie().partial().shape,...qie().partial().shape,...Gie().partial().shape,...Bj().partial().shape,...rse().partial().shape,...Vie().partial().shape,...tse().partial().shape,...nse().partial().shape})),Nu=P(()=>l.discriminatedUnion("source",[l.object({source:l.literal("url"),url:l.string().url().describe("Direct URL to marketplace.json file"),headers:l.record(l.string(),l.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),l.object({source:l.literal("git"),url:l.string().describe("Full git repository URL"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:l.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:l.array(l.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:l.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),l.object({source:l.literal("npm"),package:qj().describe("NPM package containing marketplace.json")}),l.object({source:l.literal("file"),path:l.string().describe("Local file path to marketplace.json")}),l.object({source:l.literal("directory"),path:l.string().describe("Local directory containing .claude-plugin/marketplace.json")}),l.object({source:l.literal("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),l.object({source:l.literal("hostPattern"),hostPattern:l.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against github.com. For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),l.object({source:l.literal("pathPattern"),pathPattern:l.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),l.object({source:l.literal("settings"),name:jj().refine((e)=>!Lj.has(e.toLowerCase()),{message:"Reserved marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation "+"as PluginMarketplaceSchema plus reserved-name rejection — "+"validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:l.array(ise()).describe("Plugin entries declared inline in settings.json"),owner:Hw().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).")])),jw=P(()=>l.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),Vj=P(()=>l.union([l.preprocess((e)=>e==="."?"./":e,Tr()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),l.object({source:l.literal("npm"),package:qj().or(l.string().refine((e)=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(e)||!e.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:l.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:l.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),l.object({source:l.literal("url"),url:l.string().describe("Full git repository URL (https:// or git@)"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:jw().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("github"),repo:l.string().describe("GitHub repository in owner/repo format"),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:jw().optional().describe("Specific commit SHA to use")}),l.object({source:l.literal("git-subdir"),url:l.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:l.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:l.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:jw().optional().describe("Specific commit SHA to use")}).describe("Plugin located in a subdirectory of a larger repository (monorepo). Only the specified subdirectory is materialized; the rest of the repo is not downloaded."),l.object({source:l.literal("unsupported")}).describe("Placeholder for source types this Claude Code version does not "+"recognize. Never authored by hand — PluginMarketplaceSchema rewrites "+'unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with a clear "update Claude Code" message.')])),ise=P(()=>l.object({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:Vj().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against."),description:l.string().optional(),version:l.string().optional(),strict:l.boolean().optional()}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine((e)=>typeof e.source==="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."}));var sse=P(()=>l.object({cli:l.array(l.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:l.array(l.string().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) — exact, case-insensitive match against '+"hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path."),filesRead:l.array(l.string().max(256)).max(10).optional().describe('Glob patterns (e.g. ["**/*.tf"]) — the plugin is relevant when a file Claude has read '+"this session matches any pattern. Matched against read-file paths, forward-slash normalized, case-insensitive."),manifestDeps:l.array(l.object({file:l.string().max(256),pattern:l.string().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: "+"`file` matches the manifest filename (package.json, go.mod, requirements.txt, …); "+"`pattern` matches the dependency declaration inside that file. Evaluated against files read this session."),cwd:l.array(l.string().max(256)).max(10).optional().describe('Glob patterns (e.g. ["Engine/Source/Runtime/Renderer/**"]) — the plugin is relevant when the '+`session's working directory is at or under a directory matching the pattern. Matched against the cwd both relative to the enclosing git repo root and as an absolute path, forward-slash normalized, case-insensitive. A bare directory (no glob characters) means "cwd is at or under this directory". Known at session start, so this signal can surface a suggestion before the first turn.`)})),ase=P(()=>l.object({topic:l.string().max(64).optional().describe('What the user is working with when this plugin is relevant — fills "Working with {topic}?". '+'Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:sse().optional().describe("Matchers that determine when the plugin is relevant.")})),lse=P(()=>ose().partial().extend({name:l.string().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:Vj().describe("Where to fetch the plugin from"),category:l.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:l.array(l.string()).optional().describe("Tags for searchability and discovery"),strict:l.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:l.preprocess((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0,ase().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.`)})),cse=P(()=>l.object({name:l.string().min(1).refine((e)=>!e.includes(" "))}));function use(e){let t=lse();return e.flatMap((r,o)=>{let n=t.safeParse(r);if(n.success)return[n.data];let i=cse().safeParse(r).data?.name,s=n.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(i)return Q(`Stubbing unparseable marketplace plugin entry (${i}): ${s}`,{level:"warn"}),[{name:i,source:{source:"unsupported"},strict:!0}];return Q(`Dropping unparseable marketplace plugin entry (index ${o}): ${s}`,{level:"warn"}),[]})}var GWe=P(()=>l.object({$schema:l.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:jj(),version:l.string().optional().describe("Marketplace manifest version"),description:l.string().optional().describe("Human-readable description of this marketplace"),owner:Hw().describe("Marketplace maintainer or curator information"),plugins:l.array(l.unknown()).transform(use).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:l.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:l.object({pluginRoot:l.string().optional().describe("Base path for relative plugin sources"),version:l.string().optional().describe("Marketplace version"),description:l.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:l.array(l.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:l.record(l.string(),l.string().nullable()).optional().catch(void 0).describe("Append-only map of old plugin name → current name (or null when removed). The loader follows this on plugin-not-found and migrates user settings to the new name.")})),Wj=P(()=>l.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),dse=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,pse=P(()=>l.union([l.string().regex(dse,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),l.object({name:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:l.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),fse=P(()=>l.object({version:l.string().describe("Currently installed version"),installedAt:l.string().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),installPath:l.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:l.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),mse=P(()=>l.object({version:l.literal(1).describe("Schema version 1"),plugins:l.record(Wj(),fse()).describe("Map of plugin IDs to their installation metadata")})),gse=P(()=>l.enum(["managed","user","project","local"])),hse=P(()=>l.object({scope:gse().describe("Installation scope"),projectPath:l.string().optional().describe("Project path (required for project/local scopes)"),installPath:l.string().describe("Absolute path to the versioned plugin directory"),version:l.string().optional().describe("Currently installed version"),installedAt:l.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:l.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:l.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:l.string().optional().describe("Tag-derived semver this install resolved to"),auto:l.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),yse=P(()=>l.object({version:l.literal(2).describe("Schema version 2"),plugins:l.record(Wj(),l.array(hse())).describe("Map of plugin IDs to arrays of installation entries")})),JWe=P(()=>l.union([mse(),yse()])),_se=P(()=>l.object({source:Nu().describe("Where to fetch the marketplace from"),installLocation:l.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:l.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),XWe=P(()=>l.record(l.string(),_se()));var bse=["autoMode","deepLink","voice","briefView","screenReader"],Jg={},Xg={autoMode:{buildGate:()=>!1,shape:()=>Jg,permissionsShape:()=>Jg,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:l.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>Jg},briefView:{buildGate:()=>!0,shape:()=>({defaultView:l.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>Jg}};function Bw(){return bse.filter((e)=>Xg[e].buildGate())}function Kj(e){let t={};for(let r of e)t={...t,...Xg[r].shape()};return t}function Zj(e){let t={};for(let r of e)t={...t,...Xg[r].permissionsShape?.()};return t}function Gj(e){let t=[];for(let r of e)t.push(...Xg[r].permissionModes?.()??[]);return t}function qw(e){let t=e.split("__"),[r,o,...n]=t;if(r!=="mcp"||!o)return null;let i=n.length>0?n.join("__"):void 0;return{serverName:o,toolName:i}}var Jj={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool",ReadMcpResourceDir:"ReadMcpResourceDirTool"};function na(e){return Object.hasOwn(Jj,e)?Jj[e]:e}var Xj="workspace",lKe=`mcp__${Xj}__bash`,cKe=`mcp__${Xj}__web_fetch`;function Vw(e){return e.includes("*")}function Sse(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function Yj(e){let t=vse(e,"(");if(t===-1)return{toolName:na(e)};let r=xse(e,")");if(r===-1||r<=t)return{toolName:na(e)};if(r!==e.length-1)return{toolName:na(e)};let o=e.substring(0,t),n=e.substring(t+1,r);if(!o)return{toolName:na(e)};if(n===""||n==="*")return{toolName:na(o)};let i=Sse(n);return{toolName:na(o),ruleContent:i}}function vse(e,t){for(let r=0;r<e.length;r++)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}function xse(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]===t){let o=0,n=r-1;while(n>=0&&e[n]==="\\")o++,n--;if(o%2===0)return r}return-1}var Yg={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit","Cd"],bashPrefixTools:["Bash"],customValidation:{WebSearch:(e)=>{if(e.includes("*")||e.includes("?"))return{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]};return{valid:!0}},WebFetch:(e)=>{if(e.includes("://")||e.startsWith("http"))return{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]};if(!e.startsWith("domain:"))return{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]};return{valid:!0}}}};function Qj(e){return Yg.filePatternTools.includes(e)}function ez(e){return Yg.bashPrefixTools.includes(e)}function tz(e){return Object.hasOwn(Yg.customValidation,e)?Yg.customValidation[e]:void 0}function nz(e,t){let r=0,o=t-1;while(o>=0&&e[o]==="\\")r++,o--;return r%2!==0}function Ww(e,t){let r=0;for(let o=0;o<e.length;o++)if(e[o]===t&&!nz(e,o))r++;return r}function wse(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"){if(!nz(e,t))return!0}return!1}function rz(e){if(!Vw(e))return null;let t=qw(e);if(t&&!Vw(t.serverName))return null;return{valid:!1,error:`Wildcard tool name "${e}" is not supported in allow rules`,suggestion:"An allow pattern must name the scope it widens — globs are permitted only in the tool position after a literal mcp__<server>__ prefix. Deny and ask rules accept wildcards anywhere",examples:["mcp__puppeteer__*","mcp__github__get_*"]}}function Kw(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let r=Ww(e,"("),o=Ww(e,")");if(r!==o)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(wse(e)){let a=e.substring(0,e.indexOf("("));if(!a)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}}let n=Yj(e),i=qw(n.toolName);if(i){if(n.ruleContent!==void 0||Ww(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${n.toolName}" without parentheses, or use "mcp__${i.serverName}__*" for all tools`,examples:[`mcp__${i.serverName}`,`mcp__${i.serverName}__*`,i.toolName&&i.toolName!=="*"?`mcp__${i.serverName}__${i.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let a=rz(n.toolName);if(a)return a}return{valid:!0}}if(!n.toolName||n.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let a=rz(n.toolName);if(a)return a}if(!n.toolName.includes("_")&&n.toolName[0]!==n.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${gh(String(n.toolName))}"`};let s=tz(n.toolName);if(s&&n.ruleContent!==void 0){let a=s(n.ruleContent);if(!a.valid)return a}if(ez(n.toolName)&&n.ruleContent!==void 0){let a=n.ruleContent;if(a.includes(":*")&&!a.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(a===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}if(Qj(n.toolName)&&n.ruleContent!==void 0){if(n.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${n.toolName}(*.ts) - matches .ts files`,`${n.toolName}(src/**) - matches all files in src`,`${n.toolName}(**/*.test.ts) - matches test files`]}}return{valid:!0}}var Zw=P(()=>iz()),oz=P(()=>iz("allow"));function iz(e){return l.string().superRefine((t,r)=>{let o=Kw(t,e);if(!o.valid){let n=o.error;if(o.suggestion)n+=`. ${o.suggestion}`;if(o.examples&&o.examples.length>0)n+=`. Examples: ${o.examples.join(", ")}`;r.addIssue({code:l.ZodIssueCode.custom,message:n,params:{received:t}})}})}var kse=P(()=>l.record(l.string(),l.coerce.string()));function uz(e){return l.object({allow:l.array(oz()).optional().describe("List of permission rules for allowed operations"),deny:l.array(Zw()).optional().describe("List of permission rules for denied operations"),ask:l.array(Zw()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:l.preprocess(Mu,l.enum([...$u,...Gj(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:l.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...Zj(e),additionalDirectories:l.array(l.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var CKe=P(()=>uz(Bw())),Ese=P(()=>l.object({source:Nu().describe("Where to fetch the marketplace from"),installLocation:l.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:l.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),Qg=P(()=>l.object({serverName:l.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>Ov([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),eh=P(()=>l.object({serverName:l.string().min(1,"Server name must be non-empty").refine((e)=>e.trim().length>0,{message:"Server name must not be whitespace-only"}).refine((e)=>e===e.trim(),{message:"Server name has leading or trailing whitespace and will never match (names are compared verbatim)"}).optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:l.array(l.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:l.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>Ov([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),Tse=P(()=>l.object({path:l.string().describe("Absolute path to the helper executable"),timeoutMs:l.number().int().min(1000).optional(),refreshIntervalMs:l.union([l.literal(0),l.number().int().min(60000)]).optional()})),sz=["skills","agents","hooks","mcp"],az=Object.freeze({type:"invalid-entry-stripped"}),Pse=P(()=>l.union([l.object({type:l.literal("regex").describe('Config variant. This client understands "regex": matches turn output and builds a URL from named capture groups. Entries with other variants are preserved but skipped at runtime.'),pattern:l.string().describe("Regex matched against turn output (tool results and assistant text)"),url:l.string().describe("Link target. {name} placeholders are filled from named regex capture groups, e.g. (?<id>...) -> {id}. Values are URL-encoded; the origin must be literal in the template. The scheme must be https, http, or a recognized editor or workspace deep-link scheme: vscode, vscode-insiders, cursor, windsurf, zed, jetbrains, idea, slack, linear, notion, figma."),label:l.string().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),l.object({type:l.string().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));function dz(e){return l.object({$schema:l.string().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:l.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:l.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:l.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:l.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:l.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:Tse().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...ve(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:l.object({issuer:l.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:l.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:l.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:l.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:l.object({enabled:l.boolean().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:l.number().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:l.number().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:l.string().optional().describe("Custom reminder text. Leave unset for a rotating set of friendly nudges.")}).optional().describe("@internal Opt-in break reminder. When enabled, shows a dismissible nudge after sustained continuous use. Never blocks — just a friendly heads-up."),quietHours:l.object({enabled:l.boolean().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:l.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "22:00")').optional().describe('Start of the quiet-hours window, 24-hour local time "HH:MM".'),end:l.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "07:00")').optional().describe('End of the quiet-hours window, 24-hour local time "HH:MM". May be earlier than start for an overnight range.')}).optional().describe("@internal Opt-in quiet hours. When enabled, shows a single soft nudge per session while inside the configured local-time window. Never blocks."),cleanupPeriodDays:l.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:l.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:l.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:l.boolean().optional().describe("When set to true in either admin-only Windows source — the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json — WSL reads managed settings from the full Windows policy chain (HKLM, C:/Program Files/ClaudeCode via DrvFs, HKCU) in addition to /etc/claude-code. Windows sources take priority. The flag is also required in HKCU itself for HKCU policy to apply on WSL (double opt-in: admin enables the chain, user confirms HKCU). On native Windows the flag has no effect."),env:kse().optional().describe("Environment variables to set for Claude Code sessions"),attribution:l.object({commit:l.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:l.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:l.boolean().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:l.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,includeGitInstructions:l.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:uz(e).optional().describe("Tool usage permissions configuration"),model:l.string().optional().describe("Override the default model used by Claude Code"),fallbackModel:l.array(l.string()).optional().describe('Fallback model(s) tried in order when the primary model is overloaded or unavailable. Each element accepts a model name or alias; "default" expands to the default model. CLI --fallback-model takes precedence.'),availableModels:l.array(l.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),enforceAvailableModels:l.boolean().optional().describe("When true and availableModels is a non-empty array, the Default model selection is also constrained: if the default model for the user tier is not in availableModels, Default resolves to the first allowed availableModels entry instead. Has no effect when availableModels is unset or an empty array. Typically set in managed settings by enterprise administrators."),modelOverrides:l.record(l.string(),l.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:l.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:l.array(l.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:l.array(l.string()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:l.boolean().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected. "+"Only gates auto-fetched connectors — a claudeai-proxy server passed explicitly "+"(e.g. via --mcp-config or the SDK mcpServers option) still follows the normal MCP config trust flow. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:l.record(l.string(),l.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),disableBundledSkills:l.boolean().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:l.array(Qg()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:l.array(eh()).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:ni().optional().describe("Custom commands to run before/after tool executions"),worktree:l.object({symlinkDirectories:l.array(l.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:l.array(l.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos — only the listed paths are written to disk."),baseRef:l.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:l.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:l.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:l.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:l.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableWorkflows:l.boolean().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:l.boolean().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableArtifact:l.boolean().optional().describe("Enable or disable the Artifact tool for this user. Unset defaults to enabled once the feature is available."),enableWorkflows:l.boolean().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowKeywordTriggerEnabled:l.boolean().optional().describe('Enable the "ultracode" keyword trigger: including the keyword in a prompt opts that turn into the Workflow tool. Set to false to disable the trigger. Default: true.'),disableSkillShellExecution:l.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:l.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:l.boolean().optional().describe("Whether Claude responds after an input-box ! bash command runs. Set to false to add the command output to context without a response. Default: true."),allowManagedHooksOnly:l.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:l.array(l.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:l.array(l.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:l.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:l.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),allowAllClaudeAiMcps:l.boolean().optional().describe("When true (and set in managed settings), claude.ai cloud MCP connectors load alongside managed-mcp.json instead of being suppressed by its exclusive-control lockdown. Default off preserves the lockdown. Read from managed settings only."),strictPluginOnlyCustomization:l.preprocess((t)=>Array.isArray(t)?t.filter((r)=>sz.includes(r)):t,l.union([l.boolean(),l.array(l.enum(sz))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. '+"Composes with strictKnownMarketplaces for end-to-end admin control — plugins gated by "+"marketplace allowlist, everything else blocked here."),statusLine:l.object({type:l.literal("command"),command:l.string(),padding:l.number().optional(),refreshInterval:l.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:l.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:l.string().optional().describe('URL template for PR links in the footer link badges and inline messages. The detected git PR is rendered as the first footer-link badge. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),footerLinksRegexes:l.array(Pse().catch(az)).transform((t)=>t.filter((r)=>r!==az)).optional().catch(void 0).describe("Extra clickable footer badges that appear when a regex matches turn output (tool results and assistant responses). Read from user, flag, and managed settings only; ignored in project .claude/settings.json and local .claude/settings.local.json. At most 5 badges render; the oldest is displaced by newer matches and /clear removes them. Use to surface IDs printed by project CLIs as session links."),subagentStatusLine:l.object({type:l.literal("command"),command:l.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:l.record(l.string(),l.union([l.array(l.string()),l.boolean(),l.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json — setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:l.record(l.string(),Ese()).check((t)=>{for(let[r,o]of Object.entries(t.value))if(o.source.source==="settings"&&o.source.name!==r)t.issues.push({code:"custom",input:o.source.name,path:[r,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${r}" but source.name "${o.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:l.array(Nu()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. "+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:l.array(Nu()).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."),disableSideloadFlags:l.boolean().optional().describe("When true (and set in managed settings), rejects the --plugin-dir, --plugin-url, --agents, and non-sdk --mcp-config CLI flags at startup. Closes the CLI-flag bypass of strictKnownMarketplaces. Pair with allowedMcpServers for per-server MCP control; this setting does not gate other MCP entry points (SDK setMcpServers, claude mcp add, .mcp.json). Also blocks surfaces that spawn the CLI with these flags internally (see settings documentation). Only honored from managed settings; ignored in user/project/local settings."),pluginSuggestionMarketplaces:l.array(l.string()).optional().describe("Marketplace names whose plugins may surface as contextual install suggestions (relevance-based tips). No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Only honored when set in managed settings (policy scope); the key is ignored in user, project, and local settings. A name only takes effect when the marketplace is registered on the machine AND its registered source is also declared in managed settings, either as the extraKnownMarketplaces entry for that name or as an entry of strictKnownMarketplaces. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source."),forceLoginMethod:l.enum(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:l.string().url().optional().catch(void 0).describe('@internal Cloud gateway URL to pre-fill and auto-connect to during login. Typically set in local managed settings alongside forceLoginMethod: "gateway" so users never type the URL. Hidden from public SDK types until Cloud gateway is documented.'),parentSettingsBehavior:l.enum(["first-wins","merge"]).optional().describe('Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" '+"(default): parent is dropped — admin tiers are the only policy "+`source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:l.union([l.string(),l.array(l.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:l.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:l.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:l.string().optional().describe("Controls the output style for assistant responses"),viewMode:l.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:l.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:l.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:Uw().optional(),feedbackSurveyRate:l.number().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:l.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:l.object({mode:l.enum(["append","replace"]),verbs:l.array(l.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:l.object({excludeDefault:l.boolean().optional(),tips:l.array(l.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:l.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:l.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:l.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:l.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:l.boolean().optional().catch(void 0).describe("Enable ultracode for the session: xhigh effort plus standing dynamic-workflow orchestration. "+"Session-scoped — typically provided via --settings or the apply_flag_settings control request; "+"interactive toggles never persist it. Requires workflows to be enabled and an xhigh-capable model."),autoCompactWindow:l.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:l.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:l.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:l.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:l.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),...{},awaySummaryEnabled:l.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:l.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:l.enum(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers "+"selected so far. Defaults to never — auto-continue only runs "+"when explicitly set to 60s/5m/10m."),agent:l.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:l.array(l.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:l.record(l.string(),l.object({mcpServers:l.record(l.string(),l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(l.undefined())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:l.object({defaultEnvironmentId:l.string().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:l.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:l.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:l.string().optional().describe("Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup with instructions to update. Only enforced from managed (policy) settings."),requiredMaximumVersion:l.string().optional().describe("Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. Only enforced from managed (policy) settings."),plansDirectory:l.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:l.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),...!1,voice:l.object({enabled:l.boolean().optional(),mode:l.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:l.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:l.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:l.array(l.object({marketplace:l.string(),plugin:l.string()})).optional().describe("Managed-org allowlist of channel plugins. When set, "+"replaces the default Anthropic allowlist — admins decide which "+"plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:l.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:l.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),totalTokensReminder:l.enum(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn "+"is on — task-budget semantics). Defaults to off. Env var "+"CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:l.number().int().positive().optional().describe("@internal Starting budget (tokens) for totalTokensReminder 'padded-countdown' mode. Defaults to 15000000. Server-controlled via GrowthBook; env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_BUDGET overrides."),totalTokensReminderAfterUserTurn:l.boolean().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:l.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:l.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:l.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:l.boolean().optional().describe("Request API-side thinking summaries and show them in the conversation and in the transcript view (ctrl+o). Set explicitly to override the default for your install."),skipDangerousModePermissionPrompt:l.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:l.boolean().optional().describe("@internal Whether the user has accepted the multi-agent workflow usage warning. Until set, auto permission mode prompts before running a workflow."),disableAutoMode:l.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:l.array(l.object({id:l.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:l.string().describe("Display name for the SSH connection"),sshHost:l.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:l.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:l.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:l.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:l.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:l.array(l.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:l.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:l.union([l.enum(Pj),l.string().startsWith("custom:").transform((t)=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:l.enum(Ej).optional().catch(void 0).describe("Key binding mode for the prompt input"),vimInsertModeRemaps:l.record(l.string(),l.unknown()).optional().catch(void 0).describe('Vim INSERT-mode key-sequence remaps, e.g. {"jj": "<Esc>"}. Each key is exactly two printable characters typed in sequence; "<Esc>" (return to NORMAL mode) is the only supported target. Applies when editorMode is "vim".'),verbose:l.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:l.enum(kj).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:l.boolean().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:l.boolean().optional().describe("@internal Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:l.boolean().optional().describe("When safety measures flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:l.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:l.boolean().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:l.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:l.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:l.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:l.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:l.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:l.enum(Tj).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:l.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:l.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:l.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:l.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:l.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:l.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...Kj(e)}).passthrough()}var si=P(()=>dz(Bw())),lz=Object.freeze({serverName:"invalid-entry-stripped"});function cz(e,t,r){return l.array(t.catch((o)=>(r({path:`${e}[]`,message:`Invalid entry was ignored: ${o.issues[0]?.message??"failed validation"}`}),lz))).transform((o)=>o.filter((n)=>n!==lz)).optional()}function Gw(e){let t=si(),r={};for(let[s,a]of Object.entries(t.shape))r[s]=a.catch((c)=>{e({path:s,message:`${c.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});r.allowedMcpServers=cz("allowedMcpServers",Qg(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[])),r.deniedMcpServers=cz("deniedMcpServers",eh(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return}),r.allowManagedMcpServersOnly=t.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),r.enforceAvailableModels=t.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),r.availableModels=l.array(l.unknown()).transform((s,a)=>{let c=[];for(let u of s)if(typeof u==="string")c.push(u);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(u)}); the entry was ignored.`});return c}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),r.forceLoginOrgUUID=t.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[]));let o=Object.freeze({mode:"deny"}),n=(s,a)=>l.array(a.catch((c)=>(e({path:`sandbox.credentials.${s}[]`,message:`Invalid entry was ignored: ${c.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),o))).transform((c)=>c.filter((u)=>u!==o)).optional();return r.sandbox=Uw().extend({credentials:l.object({files:n("files",Dw()),envVars:n("envVars",Nw()),allowPlaintextInject:l.boolean().optional().catch((s)=>{e({path:"sandbox.credentials.allowPlaintextInject",message:`${s.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was ignored; plaintext credential injection stays disabled until it is fixed.`});return})}).optional().catch((s)=>{e({path:"sandbox.credentials",message:`${s.issues[0]?.message??"Failed schema validation"}. The credentials block was dropped; no credential protection is applied until it is fixed.`});return})}).optional().catch((s)=>{e({path:"sandbox",message:`${s.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return}),l.object(r).passthrough().transform((s)=>{for(let a of Object.keys(s))if(s[a]===void 0)delete s[a];return s})}var pn="https://code.claude.com/docs/en",Ise=[{matches:(e)=>e.path==="permissions.defaultMode"&&e.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:`${pn}/iam#permission-modes`}},{matches:(e)=>e.path==="apiKeyHelper"&&e.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:(e)=>e.path==="cleanupPeriodDays"&&e.code==="too_small",tip:{suggestion:'cleanupPeriodDays must be at least 1. To keep transcripts for a long time, set a large number (e.g. 3650 for ~10 years). To disable transcript writes entirely, remove this setting and use the --no-session-persistence CLI flag or the SDK persistSession:false option instead. (0 is rejected because it previously silently disabled all transcript writes, which users setting it to mean "never clean up" did not expect.)'}},{matches:(e)=>e.path.startsWith("env.")&&e.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:`${pn}/settings#environment-variables`}},{matches:(e)=>(e.path==="permissions.allow"||e.path==="permissions.deny")&&e.code==="invalid_type"&&e.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:(e)=>e.path.startsWith("hooks.")&&e.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${pn}/hooks`}},{matches:(e)=>/\.hooks\.\d+\.command$/.test(e.path)&&e.code==="invalid_type"&&e.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${pn}/hooks#exec-form-and-shell-form`}},{matches:(e)=>e.path.includes("hooks")&&e.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:(e)=>e.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:`${pn}/settings`}},{matches:(e)=>e.code==="invalid_value"&&e.enumValues!==void 0,tip:{suggestion:void 0}},{matches:(e)=>e.code==="invalid_type"&&e.expected==="object"&&e.received===null&&e.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:(e)=>e.path==="permissions.additionalDirectories"&&e.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:`${pn}/iam#working-directories`}}],Ase={permissions:`${pn}/iam#configuring-permissions`,env:`${pn}/settings#environment-variables`,hooks:`${pn}/hooks`};function pz(e){let t=Ise.find((o)=>o.matches(e));if(!t)return null;let r={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!r.suggestion)r.suggestion=`Valid values: ${e.enumValues.map((o)=>`"${o}"`).join(", ")}`;if(!r.docLink&&e.path)r.docLink=Ase[hh(e.path,".")];return r}var XKe=P(()=>si().strict());function fz(e){return e.code==="invalid_type"}function mz(e){return e.code==="invalid_value"}function Rse(e){return e.code==="unrecognized_keys"}function gz(e){return e.code==="too_small"}function oa(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function hz(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Uu(e,t){return e.issues.map((r)=>{let o=r.path.map(String).join("."),n=r.message,i,s,a,c,u;if(mz(r))s=r.values.map((p)=>String(p)),a=s.join(" | "),c=void 0,u=void 0;else if(fz(r)){a=r.expected;let p=hz(r.message);c=p??oa(r.input),u=p??oa(r.input)}else if(gz(r))a=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,u=c;let d=pz({path:o,code:r.code,expected:a,received:c,enumValues:s,message:r.message,value:c});if(mz(r))i=s?.map((p)=>`"${p}"`).join(", "),n=`Invalid value. Expected one of: ${i}`;else if(fz(r)){let p=hz(r.message)??oa(r.input);if(r.expected==="object"&&p==="null"&&o==="")n="Invalid or malformed JSON";else n=`Expected ${r.expected}, but received ${p}`}else if(Rse(r)){let p=r.keys.join(", ");n=`Unrecognized ${Ik(r.keys.length,"field")}: ${p}`}else if(gz(r))n=`Number must be greater than or equal to ${r.minimum}`,i=String(r.minimum);return{file:t,path:o,message:n,expected:i,invalidValue:u,suggestion:d?.suggestion,docLink:d?.docLink}})}function Ose(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!r.permissions||typeof r.permissions!=="object")return[];let o=r.permissions,n=[];for(let i of["allow","deny","ask"]){let s=o[i];if(!Array.isArray(s))continue;o[i]=s.filter((a)=>{if(typeof a!=="string")return n.push({file:t,path:`permissions.${i}`,message:`Non-string value in ${i} array was removed`,severity:"warning",invalidValue:a}),!1;let c=Kw(a,i);if(!c.valid){let u=`Invalid permission rule "${a}" was skipped: ${c.error}`;if(c.suggestion)u+=`. ${c.suggestion}`;return n.push({file:t,path:`permissions.${i}`,message:u,severity:"warning",invalidValue:a}),!1}return!0})}return n}var Cse=new Set(fi);function $se(e,t){if(!e||typeof e!=="object")return[];let r=e;if(!("hooks"in r))return[];if(r.hooks===null||typeof r.hooks!=="object"||Array.isArray(r.hooks)){let i=oa(r.hooks);return delete r.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${i}. This field was ignored.`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"}]}let o=r.hooks,n=[];for(let i of Object.keys(o)){if(!Cse.has(i)){delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Unknown hook event "${i}" was ignored. Valid events: ${fi.join(", ")}`,severity:"warning",invalidValue:i,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(o[i])){let s=oa(o[i]);delete o[i],n.push({file:t,path:`hooks.${i}`,message:`Hook event "${i}" must be an array of matchers; received ${s}. This entry was ignored.`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks"})}}if(n.length>0&&Object.keys(o).length===0)delete r.hooks;return n}var Mse=[{key:"allowedMcpServers",schema:Qg},{key:"deniedMcpServers",schema:eh}];function Dse(e,t){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:n,schema:i}of Mse){if(!(n in r))continue;if(!Array.isArray(r[n])){let c=r[n];delete r[n],o.push({file:t,path:n,message:`"${n}" must be an array; received ${oa(c)}. This field was ignored.`,severity:"warning",invalidValue:c});continue}let s=r[n],a=[];for(let c=0;c<s.length;c++){let u=i().safeParse(s[c]);if(u.success)a.push(s[c]);else o.push({file:t,path:`${n}[${c}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:s[c]})}if(a.length<s.length)r[n]=a}return o}function ai(e,t,r){return[...Ose(e,t),...$se(e,t),...r?.skipMcpServerEntryFilter?[]:Dse(e,t)]}function Yw(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),hj.filter((r)=>t.has(r))}function Use(){return ao(ri(),"managed-settings.json")}function _z(e){if(ti()==="wsl"&&e.wslInherits?.()){let t=Jw(ta);if(t.settings)return t;let r=Jw(ri());return{settings:r.settings,errors:[...t.errors,...r.errors]}}return Jw(ri())}function Jw(e){let t=[],r={},o=!1,{settings:n,errors:i}=th(ao(e,"managed-settings.json"),void 0,!0);if(t.push(...i),n&&Object.keys(n).length>0)r=dn(r,n,so),o=!0;let s=ao(e,"managed-settings.d");try{let u=qe().readdirSync(s).filter((d)=>(d.isFile()||d.isSymbolicLink())&&d.name.endsWith(".json")&&!d.name.startsWith(".")).map((d)=>d.name).sort();for(let d of u){let{settings:p,errors:f}=th(ao(s,d),void 0,!0);if(t.push(...f),p&&Object.keys(p).length>0)r=dn(r,p,so),o=!0}}catch(u){let d=Be(u);if(d!=="ENOENT"&&d!=="ENOTDIR")Q(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:a,...c}=r;return{settings:o&&Object.keys(c).length>0?r:null,errors:t}}function Lse(e,t){if(Xr(e))Q(`Broken symlink or missing file encountered for settings.json at path: ${t}`);else Q(`settings file read failed at ${t}: ${e}`,{level:"error"})}function th(e,t,r){let o=oA(e);if(o)return{settings:o.settings?Ln(o.settings):null,errors:o.errors};let n=Fse(e,t,r);return iA(e,n),{settings:n.settings?Ln(n.settings):null,errors:n.errors}}function bz(e){if(!e.mdm)return{settings:null,errors:[]};let t=e.mdm();return{settings:Object.keys(t.settings).length>0?t.settings:null,errors:t.errors}}function rh(e,t){let r=Ln(e),o=ai(r,t,{skipMcpServerEntryFilter:!0}),n=[],i=Gw((s)=>n.push({file:t,path:s.path,message:s.message,severity:"warning"})).safeParse(r);if(!i.success)return{settings:null,errors:[...o,...Uu(i.error,t)]};return{settings:Object.keys(i.data).length>0?i.data:null,errors:[...o,...n]}}function Sz(e){let t=e?.remote?e.remote():gj();if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return rh(t,"remote managed settings")}function jse(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};return rh(t,"parent managed settings")}function vz(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let r=Ln(t),o=ai(r,"SDK inline settings"),n=si().safeParse(r);if(!n.success)return{settings:null,errors:[...o,...Uu(n.error,"SDK inline settings")]};return{settings:n.data,errors:o}}var zse=2097152;function Fse(e,t,r){try{let o;if(t!==void 0)o=t;else{let{resolvedPath:a}=nm(qe(),e);o=ei(a,zse)}if(o.trim()==="")return{settings:{},errors:[]};let n=Ln(ea(o,!1));if(r){let a=ai(n,e,{skipMcpServerEntryFilter:!0}),c=[],u=Gw((d)=>c.push({file:e,path:d.path,message:d.message,severity:"warning"})).safeParse(n);if(!u.success)return{settings:null,errors:[...a,...Uu(u.error,e)]};return{settings:u.data,errors:[...a,...c]}}let i=ai(n,e),s=si().safeParse(n);if(!s.success){let a=Uu(s.error,e);return{settings:null,errors:[...i,...a]}}return{settings:s.data,errors:i}}catch(o){if(Lse(o,e),Xr(o))return{settings:null,errors:[]};return{settings:null,errors:[{file:e,path:"",message:`Settings file could not be read: ${o instanceof Error?o.message:String(o)}`,severity:"fatal"}]}}}function yz(e,t){switch(e){case"userSettings":return Lu(Xt());case"policySettings":case"projectSettings":case"localSettings":return Lu(t.cwd);case"flagSettings":return t.flagPath?Nse(Lu(t.flagPath)):Lu(t.cwd)}}function Hse(e){if(e.coworkPlugins||ve(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function ju(e,t){switch(e){case"userSettings":return ao(yz(e,t),Hse(t));case"projectSettings":case"localSettings":return ao(yz(e,t),Bse(e));case"policySettings":return Use();case"flagSettings":return t.flagPath}}function Bse(e){switch(e){case"projectSettings":return ao(".claude","settings.json");case"localSettings":return ao(".claude","settings.local.json")}}function xz(e,t){let r=rA(e);if(r!==void 0)return r;let o=Wse(e,t);return nA(e,o),o}function qse(e){return!e||e.parentSettingsBehavior==="merge"}function Vse(e,t){let r={};if(e.allowManagedHooksOnly===!0)r.allowManagedHooksOnly=!0;if(e.allowManagedMcpServersOnly===!0)r.allowManagedMcpServersOnly=!0;if(e.disableClaudeAiConnectors===!0)r.disableClaudeAiConnectors=!0;if(e.allowManagedPermissionRulesOnly===!0)r.allowManagedPermissionRulesOnly=!0;let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)r.strictPluginOnlyCustomization=o;if(e.deniedMcpServers)r.deniedMcpServers=e.deniedMcpServers;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)r.forceLoginOrgUUID=e.forceLoginOrgUUID;if(t.allowedMcpServers===void 0&&e.allowedMcpServers)r.allowedMcpServers=e.allowedMcpServers;if(t.availableModels===void 0&&e.availableModels)r.availableModels=e.availableModels;if(e.enforceAvailableModels===!0)r.enforceAvailableModels=!0;if(e.permissions){let n=Kg(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable")n.disableBypassPermissionsMode="disable";if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:s}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)n.allow=i;if(s)n.additionalDirectories=s}if(Object.keys(n).length>0)r.permissions=n}if(e.sandbox){let{network:n,filesystem:i,credentials:s}=e.sandbox,a={};if(e.sandbox.enabled===!0)a.enabled=!0;if(e.sandbox.failIfUnavailable===!0)a.failIfUnavailable=!0;if(e.sandbox.allowUnsandboxedCommands===!1)a.allowUnsandboxedCommands=!1;if(e.sandbox.autoAllowBashIfSandboxed===!1)a.autoAllowBashIfSandboxed=!1;if(n){let c=Kg(n,["deniedDomains"]);if(n.allowManagedDomainsOnly===!0)c.allowManagedDomainsOnly=!0;if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&n.allowedDomains)c.allowedDomains=n.allowedDomains;if(Object.keys(c).length>0)a.network=c}if(i){let c=Kg(i,["denyRead","denyWrite"]);if(i.allowManagedReadPathsOnly===!0)c.allowManagedReadPathsOnly=!0;if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)c.allowRead=i.allowRead;if(Object.keys(c).length>0)a.filesystem=c}if(s){let c=(s.files??[]).filter((p)=>p.mode==="deny"),u=(s.envVars??[]).filter((p)=>p.mode==="deny"),d={...c.length>0&&{files:c},...u.length>0&&{envVars:u}};if(s.allowPlaintextInject===!1)d.allowPlaintextInject=!1;if(Object.keys(d).length>0)a.credentials=d}if(Object.keys(a).length>0)r.sandbox=a}return r}function wz(e){if(e.helper?.())return"helper";if(Sz(e).settings)return"remote";if(bz(e).settings)return ti()==="macos"?"plist":"hklm";if((e.file?.()??_z(e)).settings)return"file";if(kz(e).parentSlice)return"parent";let t=e.hkcu?.();return t&&Object.keys(t.settings).length>0?"hkcu":null}function kz(e){let t=[],{settings:r,errors:o}=Sz(e);t.push(...o);let{settings:n,errors:i}=bz(e);t.push(...i);let{settings:s,errors:a}=e.file?.()??_z(e);t.push(...a);let{settings:c,errors:u}=jse(e);t.push(...u);let d=[r,n,s].filter((h)=>h!==null),p=d[0]??null,f={allowManagedPermissionRulesOnly:d.some((h)=>h.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:d.find((h)=>h.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:d.find((h)=>h.allowedMcpServers!==void 0)?.allowedMcpServers,availableModels:d[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:d.some((h)=>h.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:d.some((h)=>h.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},m=c&&qse(p)?Vse(c,f):null,g=m&&Object.keys(m).length>0?m:null;return{tiers:d,admin:p,parentSlice:g,errors:t}}function Ez(e){let t=e.helper?.();if(t)return{settings:t,errors:e.helperWarnings?.()??[]};let{tiers:r,admin:o,parentSlice:n,errors:i}=kz(e);if(!o&&!n){let a=e.hkcu?.();if(a&&Object.keys(a.settings).length>0)return{settings:a.settings,errors:[...i,...a.errors]};return{settings:null,errors:[...i,...a?.errors??[]]}}let s=dn({},n??{},o??{},so);if(r.some((a)=>a.forceRemoteSettingsRefresh===!0))s.forceRemoteSettingsRefresh=!0;return{settings:s,errors:i}}function Wse(e,t){if(e==="policySettings")return Ez(t).settings;let r=ju(e,t),{settings:o}=r?th(r,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:n}=vz(t);if(n)return dn(o||{},n,so)}return o}function Kse(e,t){return Sm([...e,...t])}function so(e,t,r){if(Array.isArray(e)&&Array.isArray(t)){if(r==="fallbackModel")return t;return Kse(e,t)}return}var Xw=!1;function Zse(e){if(Xw)return{settings:{},errors:[]};let t=Date.now();Pu("info","settings_load_started"),Xw=!0;try{let r=sA(),o={};if(r)o=dn(o,r,so);let n=[],i=new Set,s=new Set,a=null;for(let c of Yw(e)){if(c==="policySettings"){let{settings:d,errors:p}=Ez(e);if(a=d,d)o=dn(o,d,so);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}continue}let u=ju(c,e);if(u){let d=Lu(u);if(!s.has(d)){s.add(d);let{settings:p,errors:f}=th(u,c==="flagSettings"?e.flagExpectedContent:void 0);for(let m of f){let g=`${m.file}:${m.path}:${m.message}`;if(!i.has(g))i.add(g),n.push(m)}if(p)o=dn(o,p,so)}}if(c==="flagSettings"){let{settings:d,errors:p}=vz(e);for(let f of p){let m=`${f.file}:${f.path}:${f.message}`;if(!i.has(m))i.add(m),n.push(f)}if(d)o=dn(o,d,so)}}if(a){if(a.availableModels!==void 0)o.availableModels=[...a.availableModels];if(a.enforceAvailableModels!==void 0)o.enforceAvailableModels=a.enforceAvailableModels}return Pu("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:s.size,error_count:n.length}),{settings:o,errors:n}}finally{Xw=!1}}function Gse(e){let t=eA();if(t!==null)return t;let r=Zse(e);return tA(r),r}function Jse(e){let{settings:t}=Gse(e);return t||{}}function Tz(e){Do();let t=[];for(let r of Yw(e)){let o=xz(r,e);if(o&&Object.keys(o).length>0)t.push({source:r,settings:o})}return{effective:Jse(e),sources:t}}function Pz(e,t){let r=Yw(t);for(let o=r.length-1;o>=0;o--){let n=r[o];if(xz(n,t)?.[e]!==void 0)return n}return null}import{execFile as Xse}from"child_process";import{existsSync as Yse}from"fs";var Qse=null;function zu(e,t){return new Promise((r)=>{try{Xse(e,t,{encoding:"utf-8",timeout:Sj,windowsHide:!0},(o,n)=>{r({stdout:n??"",code:o?1:0})})}catch{r({stdout:"",code:1})}})}function Iz(){return(async()=>{if(process.platform==="darwin"){let e=vj(),r=(await Promise.all(e.map(async({path:o,label:n})=>{if(!Yse(o))return{stdout:"",label:n,ok:!1};let{stdout:i,code:s}=await zu(_j,[...bj,o]);return{stdout:i,label:n,ok:s===0&&!!i}}))).find((o)=>o.ok);return{plistStdouts:r?[{stdout:r.stdout,label:r.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[r,o]=await Promise.all([zu(t,["query",Ou,"/v",oo]),zu(t,["query",Cu,"/v",oo])]);return{plistStdouts:null,hklmStdout:r.code===0?r.stdout:null,hkcuStdout:o.code===0?o.stdout:null}}if(Zg()){let[e,t]=await Promise.all([zu(Mw,["query",Ou,"/v",oo]),zu(Mw,["query",Cu,"/v",oo])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function Az(){return Qse}var lo=Object.freeze({settings:{},errors:[]}),$z=null,Mz=null,Dz=!1,nh=null;function eae(){if(nh)return;nh=(async()=>{let e=Date.now(),t=Az()??Iz(),{mdm:r,hkcu:o,wslInherits:n}=tae(await t);$z=r,Mz=o,Dz=n;let i=Date.now()-e;if(Q(`MDM settings load completed in ${i}ms`),Object.keys(r.settings).length>0){Q(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{Pu("info","mdm_settings_loaded",{duration_ms:i,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})()}async function Nz(){if(!nh)eae();await nh}function Uz(){return $z??lo}function Lz(){return Mz??lo}function jz(){return Dz}function Qw(e,t){let r=ea(e,!1);if(!r||typeof r!=="object")return{settings:{},errors:[]};let{settings:o,errors:n}=rh(r,t);return{settings:o??{},errors:n}}function Rz(e,t="Settings"){let r=e.split(/\r?\n/),o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s+${o}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let i of r){let s=i.match(n);if(s&&s[1])return s[1].trimEnd()}return null}function tae(e){let t=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:s,label:a}=e.plistStdouts[0],c=Qw(s,a),{wslInheritsWindowsSettings:u,...d}=c.settings;if(Object.keys(d).length>0)return{mdm:c,hkcu:lo,wslInherits:!1};t.push(...c.errors)}let r=null;if(e.hklmStdout){let s=Rz(e.hklmStdout);if(s)r=Qw(s,`Registry: ${Ou}\\${oo}`)}if(r)t.push(...r.errors);let o=t.length>0?{settings:{},errors:t}:lo,n=Zg(),i=!1;if(n){if(i=r?.settings.wslInheritsWindowsSettings===!0||nae(),!i)return{mdm:o,hkcu:lo,wslInherits:!1}}if(r){let{wslInheritsWindowsSettings:s,...a}=r.settings;if(Object.keys(a).length>0)return{mdm:r,hkcu:lo,wslInherits:i}}if(rae(i))return{mdm:o,hkcu:lo,wslInherits:i};if(e.hkcuStdout){let s=Rz(e.hkcuStdout);if(s){let a=Qw(s,`Registry: ${Cu}\\${oo}`);if(!n||a.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:c,...u}=a.settings;return{mdm:o,hkcu:{settings:u,errors:a.errors},wslInherits:i}}if(a.errors.length>0)return{mdm:o,hkcu:{settings:{},errors:a.errors},wslInherits:i}}}return{mdm:o,hkcu:lo,wslInherits:i}}function rae(e){if(e&&Cz(ta))return!0;return Cz(ri())}function Oz(e){let t=Ln(ea(ei(e),!1));if(!t||typeof t!=="object")return!1;ai(t,e);let{wslInheritsWindowsSettings:r,...o}=t;return Object.keys(o).length>0}function nae(){function e(t){try{let r=ea(ei(t),!1);return!!r&&typeof r==="object"&&"wslInheritsWindowsSettings"in r&&r.wslInheritsWindowsSettings===!0}catch{return!1}}if(e(ia(ta,"managed-settings.json")))return!0;try{let t=ia(ta,"managed-settings.d");for(let r of qe().readdirSync(t))if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith(".")&&e(ia(t,r.name)))return!0}catch{}return!1}function Cz(e){try{if(Oz(ia(e,"managed-settings.json")))return!0}catch{}try{let t=ia(e,"managed-settings.d"),r=qe().readdirSync(t);for(let o of r){if(!(o.isFile()||o.isSymbolicLink())||!o.name.endsWith(".json")||o.name.startsWith("."))continue;try{if(Oz(ia(t,o.name)))return!0}catch{}}}catch{}return!1}var iae={user:"userSettings",project:"projectSettings",local:"localSettings"},zz={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},sae=["user","project","local"],aae=new Set(["bypassPermissions","auto","acceptEdits"]),lae=new Set(["project"]);function cae(e){let t=e.effective.permissions?.defaultMode;if(!t||!aae.has(t))return e.effective;for(let r=e.sources.length-1;r>=0;r--){let o=e.sources[r];if(o.settings.permissions?.defaultMode!==void 0){if(lae.has(o.source)){let{defaultMode:n,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}async function Fz(e={}){await Nz();let t={cwd:oae(e.cwd??qe().cwd()),allowedSources:(e.settingSources??sae).map((r)=>iae[r]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:Uz,hkcu:Lz,wslInherits:jz,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}};try{let{effective:r,sources:o}=Tz(t),n=wz(t)??void 0,i=o.map(({source:a,settings:c})=>({source:zz[a],settings:c,path:a==="policySettings"?void 0:ju(a,t),...a==="policySettings"&&{policyOrigin:n}})),s={};for(let a of Object.keys(r)){let c=Pz(a,t);if(c)s[a]={source:zz[c],path:c==="policySettings"?void 0:ju(c,t),...c==="policySettings"&&{policyOrigin:n}}}return{effective:r,provenance:s,sources:i}}finally{Do()}}process.env.NoDefaultCurrentDirectoryInExePath="1";async function wGe(e){return Fz(e)}async function Sae(e,t){try{await fae(e,t)}catch(r){if(!Xr(r))throw r}}async function vae(e,t){if(!e)return;let r=e;try{let o=Ze(e);if(o?.claudeAiOauth?.refreshToken)delete o.claudeAiOauth.refreshToken,r=me(o)}catch{}await Wz(t,r,{mode:384})}function xae(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=yC(hC);return new Promise((t)=>{uae("security",["find-generic-password","-a",_C(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(r,o)=>t(r?void 0:o.trim()||void 0))})}async function Gz(e,t,r,o,n=60000){if(!Ee(t))return;let i=ar(r),s=await Ar(e.load({projectKey:i,sessionId:t}),n,`SessionStore.load() timed out after ${n}ms for session ${t}`);if(!s||s.length===0)return;let a=Kt(yae(),`claude-resume-${nk()}`);try{let c=Kt(a,"projects",i);await ek(c,{recursive:!0});let u=Kt(c,`${t}.jsonl`);await Rc(u,s);let d=o?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,p=d??Kt(tk(),".claude"),f;try{f=await Vz(Kt(p,".credentials.json"),"utf-8")}catch(m){if(!Xr(m))throw m}if(!d&&!(o??process.env).ANTHROPIC_API_KEY&&!(o??process.env).CLAUDE_CODE_OAUTH_TOKEN)f=await xae()??f;if(await vae(f,Kt(a,".credentials.json")),await Sae(Kt(d??tk(),".claude.json"),Kt(a,".claude.json")),e.listSubkeys)await wae(e,{projectKey:i,sessionId:t},Kt(c,t),n);return a}catch(c){throw await oh(a),c}}async function wae(e,t,r,o){let n=await Ar(e.listSubkeys({projectKey:t.projectKey,sessionId:t.sessionId}),o,`SessionStore.listSubkeys() timed out after ${o}ms for session ${t.sessionId}`);for(let i of n){let s=Fu(r,i+".jsonl");if(!i||Kz(i)||i.split(/[\\/]/).includes("..")||!s.startsWith(r+ok)){Q(`[SessionStore] skipping unsafe subpath from listSubkeys: ${i}`,{level:"warn"});continue}let a=await Ar(e.load({projectKey:t.projectKey,sessionId:t.sessionId,subpath:i}),o,`SessionStore.load() timed out after ${o}ms for session ${t.sessionId} subpath ${i}`);if(!a||a.length===0)continue;let c=[],u=[];for(let d of a)if(rk(d))c.push(d);else u.push(d);if(u.length>0)await ek(Hz(s),{recursive:!0}),await Rc(s,u);if(c.length>0){let d=c.at(-1),p=Fu(r,i+".meta.json");await ek(Hz(p),{recursive:!0});let{type:f,...m}=d;await Wz(p,me(m),{mode:384})}}}function ik(e,t){let{isSingleUserTurn:r,resumeConfigDir:o,deferSpawn:n}=t,{systemPrompt:i,settings:s,managedSettings:a,settingSources:c,sandbox:u,...d}=e??{},p,f,m;if(i===void 0)p="";else if(typeof i==="string")p=i;else if(Array.isArray(i))p=i;else if(i.type==="preset")f=i.append,m=i.excludeDynamicSections;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.209";let{abortController:g=pa(),additionalDirectories:h=[],agent:y,agents:S,allowedTools:x=[],betas:w,canUseTool:R,continue:U,cwd:ae,debug:Ge,debugFile:tt,disallowedTools:Zt=[],tools:Ur,env:Gt,executable:li=qu()?"bun":"node",executableArgs:fn=[],extraArgs:ci={},fallbackModel:co,enableFileCheckpointing:W,toolConfig:sa,forkSession:sh,hooks:ui,includeHookEvents:aa,includePartialMessages:la,forwardSubagentText:Hu,onElicitation:di,onUserDialog:ye,supportedDialogKinds:Dt,persistSession:lr,sessionStore:cr,sessionStoreFlush:r1,thinking:ca,effort:n1,maxThinkingTokens:ah,maxTurns:o1,maxBudgetUsd:i1,taskBudget:s1,mcpServers:ak,model:a1,outputFormat:lk,permissionMode:ck="default",allowDangerouslySkipPermissions:l1=!1,permissionPromptToolName:c1,plugins:u1,getOAuthToken:uk,getHostAuthToken:dk,workload:pk,resume:fk,resumeSessionAt:d1,sessionId:p1,skills:mk,stderr:f1,strictMcpConfig:m1}=d;if(cr&&lr===!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(Dt!==void 0&&Dt.length>0&&!ye)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if(cr&&U&&!fk&&!cr.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(cr&&W)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(cr&&d.spawnClaudeCodeProcess)Q("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"});bC(!!R,ck,x);let lh=d.pathToClaudeCodeExecutable;if(!lh){let Nt=bae(import.meta.url),ur=hae(Nt),uo=$A((pi)=>ur.resolve(pi));if(!uo)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.`);lh=uo}let gk=lk?.type==="json_schema"?lk.schema:void 0,ft=Gt?{...Gt}:{...process.env};if(!ft.CLAUDE_CODE_ENTRYPOINT)ft.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!ft.CLAUDE_AGENT_SDK_VERSION)ft.CLAUDE_AGENT_SDK_VERSION="0.3.209";if(W)ft.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(uk)ft.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(dk)ft.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(sa?.askUserQuestion?.previewFormat)ft.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=sa.askUserQuestion.previewFormat;let ch={};if(ih.propagation.inject(ih.context.active(),ch),"traceparent"in ch){for(let Nt of["TRACEPARENT","TRACESTATE"])if(!(Nt in(Gt??{})))delete ft[Nt]}for(let[Nt,ur]of Object.entries(ch)){let uo=Nt.toUpperCase();if(!(uo in(Gt??{})))ft[uo]=ur}let hk={},yk=new Map;if(ak)for(let[Nt,ur]of Object.entries(ak))if(ur.type==="sdk"&&ur.instance)yk.set(Nt,ur.instance);else hk[Nt]=ur;let ua;if(ca)switch(ca.type){case"adaptive":ua={type:"adaptive",display:ca.display};break;case"enabled":ua={type:"enabled",budgetTokens:ca.budgetTokens,display:ca.display};break;case"disabled":ua={type:"disabled"};break}else if(ah!==void 0)ua=ah===0?{type:"disabled"}:{type:"enabled",budgetTokens:ah};if(o){if(ft.CLAUDE_CONFIG_DIR=o,process.platform==="win32")ft.CLAUDE_SECURESTORAGE_CONFIG_DIR=Gt?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??Gt?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let _k=new vS({abortController:g,additionalDirectories:h,agent:y,betas:w,cwd:ae,debug:Ge,debugFile:tt,executable:li,executableArgs:fn,extraArgs:pk?{...ci,workload:pk}:ci,pathToClaudeCodeExecutable:lh,env:ft,forkSession:sh,stderr:f1,thinkingConfig:ua,effort:n1,maxTurns:o1,maxBudgetUsd:i1,taskBudget:s1,model:a1,fallbackModel:co,jsonSchema:gk,permissionMode:ck,allowDangerouslySkipPermissions:l1,permissionPromptToolName:c1,continueConversation:cr?void 0:U,resume:fk,resumeSessionAt:d1,sessionId:p1,settings:typeof s==="object"?me(s):s,managedSettings:a?me(a):void 0,settingSources:c,skills:mk,allowedTools:x,disallowedTools:Zt,tools:Ur,mcpServers:hk,strictMcpConfig:m1,canUseTool:!!R,hooks:!!ui,includeHookEvents:aa,includePartialMessages:la,persistSession:lr,sessionMirror:!!cr,plugins:u1,sandbox:u,spawnClaudeCodeProcess:d.spawnClaudeCodeProcess,deferSpawn:n}),g1={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:d.planModeInstructions,appendSubagentSystemPrompt:d.appendSubagentSystemPrompt,toolAliases:d.toolAliases,excludeDynamicSections:m,agents:S,title:d.title,skills:mk,webSearchIsolationExemptMcpServers:d.webSearchIsolationExemptMcpServers,promptSuggestions:d.promptSuggestions,agentProgressSummaries:d.agentProgressSummaries,forwardSubagentText:Hu,supportedDialogKinds:Dt},uh=new im(_k,r,R,ui,g,yk,gk,g1,di,uk,dk,ye);if(cr){let Nt=()=>Kt(ft.CLAUDE_CONFIG_DIR??Kt(tk(),".claude"),"projects"),ur=r1==="eager",uo=new TS(async(pi,dh)=>{let da=qz(pi,Nt());if(da)await cr.append(da,dh);else Q(`[SessionStore] dropping mirror frame: filePath ${pi} is not under ${Nt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(pi,dh)=>{let da=qz(pi,Nt());if(da)uh.reportMirrorError(da,dh.message)},maxPendingEntries:ur?0:sm,maxPendingBytes:ur?0:am});uh.setTranscriptMirrorBatcher(uo)}return{queryInstance:uh,transport:_k,abortController:g,processEnv:ft}}function sk(e,t,r,o){if(typeof r==="string")t.write(me({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:r}]},parent_tool_use_id:null})+`
|
|
118
118
|
`);else e.streamInput(r).catch((n)=>o.abort(n))}var kae=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function oh(e){for(let t=0;;t++)try{return await gae(e,{recursive:!0,force:!0})}catch(r){if(t>=4||!kae.has(Be(r)??""))return;await mn((t+1)*100)}}function Eae(e,t){e.waitForExit().catch(()=>{}).finally(()=>oh(t))}function kGe({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return Tae(e,t);let{queryInstance:r,transport:o,abortController:n}=ik(t,{isSingleUserTurn:typeof e==="string"});return sk(r,o,e,n),r}function Tae(e,t){let{queryInstance:r,transport:o,abortController:n,processEnv:i}=ik({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),s=Fu(t.cwd??"."),a=t.sessionStore,c=t.loadTimeoutMs??60000,u=t.resume;return(async()=>{if(!u)u=(await Ar(a.listSessions(ar(s)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((f,m)=>m.mtime-f.mtime)[0]?.sessionId;if(!u)return;return Gz(a,u,s,t.env,t.loadTimeoutMs)})().then((p)=>{if(p){o.updateResume(u);let f={CLAUDE_CONFIG_DIR:p};if(process.platform==="win32"){let m=t.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??t.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";f.CLAUDE_SECURESTORAGE_CONFIG_DIR=m,i.CLAUDE_SECURESTORAGE_CONFIG_DIR=m}o.updateEnv(f),i.CLAUDE_CONFIG_DIR=p,r.addCleanupCallback(()=>Eae(o,p))}if(!r.isClosed())o.spawn()}).catch((p)=>{let f=Or(p);o.spawnAbort(f),r.setError(f)}),sk(r,o,e,n),r}async function EGe({options:e,initializeTimeoutMs:t=60000}={}){let r,o=e?.resume;if((o||e?.continue)&&e?.sessionStore){let a=Fu(e.cwd??".");if(!o){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let c=e.loadTimeoutMs??60000;o=(await Ar(e.sessionStore.listSessions(ar(a)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((d,p)=>p.mtime-d.mtime)[0]?.sessionId}if(o)r=await Gz(e.sessionStore,o,a,e.env,e.loadTimeoutMs)}let n,i,s;try{let f=function(){if(p)return;p=!0,d.close()},a=ik(r&&o&&o!==e?.resume?{...e,resume:o}:e,{isSingleUserTurn:!1,resumeConfigDir:r});n=a.queryInstance;let{transport:c,abortController:u}=a;i=c;let d=a.queryInstance;if(r){let m=r;d.addCleanupCallback(()=>{s=c.waitForExit().catch(()=>{}).then(()=>oh(m))})}await Ar(d.initializationResult(),t,`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`);let p=!1;return{query(m){if(p)throw Error("WarmQuery.query() can only be called once");p=!0;try{sk(d,c,m,u)}catch(g){throw d.close(),g}if(typeof m==="string")d.setIsSingleUserTurn(!0);return d},close:f,async[Symbol.asyncDispose](){p=!0,d.close(),await s}}}catch(a){if(n?.close(),r&&!s){let c=i;s=(c?c.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>oh(r))}throw await s,a}}async function TGe(e,t){if(t?.sessionStore)return Oae(t.sessionStore,e,t);return K0(e,t)}async function PGe(e){if(e?.sessionStore)return Iae(e.sessionStore,e);return G0(e)}async function IGe(e,t){if(t?.sessionStore)return Cae(t.sessionStore,e,t);return J0(e,t)}async function AGe(e,t,r){if(r?.sessionStore)return $ae(r.sessionStore,e,t,r.dir);return eC(e,t,r)}async function RGe(e,t,r){if(r?.sessionStore)return Mae(r.sessionStore,e,t,r.dir);return tC(e,t,r)}async function OGe(e,t){if(!Ee(e))throw new ht(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let r=ar(t.dir);await t.sessionStore.delete({projectKey:r,sessionId:e});return}return rC(e,t)}async function CGe(e,t){if(t?.sessionStore)return Dae(t.sessionStore,e,t);return iC(e,t)}async function $Ge(e,t,r){if(!Ee(e))throw new ht(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=await Fn(e,r?.dir);if(!o)throw Error(`Session ${e} not found`);let n=ar(r?.dir),i=r?.batchSize&&r.batchSize>0?r.batchSize:sm;if(await Bz(o.filePath,{projectKey:n,sessionId:e},t,i),r?.includeSubagents===!1)return;let s=o.filePath.replace(/\.jsonl$/,""),a=Kt(s,"subagents");for(let c of await Pae(a)){let u=Zz(s,c).split(ok);u[u.length-1]=u.at(-1).replace(/\.jsonl$/,"");let d={projectKey:n,sessionId:e,subpath:u.join("/")};await Bz(c,d,t,i);let p=c.replace(/\.jsonl$/,".meta.json"),f;try{f=Ze(await Vz(p,"utf8"))}catch(m){if(!Xr(m))Q(`importSessionToStore: skipping unreadable sidecar ${p}: ${m}`)}if(f!==void 0)await t.append(d,[{type:"agent_metadata",...f}])}}async function Bz(e,t,r,o){let n=_ae({input:dae(e,{encoding:"utf8"}),crlfDelay:1/0}),i=[],s=0;for await(let a of n){if(!a)continue;try{i.push(Ze(a))}catch(c){Q(`importSessionToStore: skipping unparseable line in ${e}: ${c}`);continue}if(s+=a.length,i.length>=o||s>=am)await r.append(t,i),i=[],s=0}if(i.length>0)await r.append(t,i)}async function Pae(e){let t=[];async function r(o){let n;try{n=await mae(o,{withFileTypes:!0})}catch{return}for(let i of n){let s=Kt(o,i.name);if(i.isDirectory())await r(s);else if(i.isFile()&&i.name.endsWith(".jsonl"))t.push(s)}}return await r(e),t}async function MGe(e,t){if(t?.sessionStore)return Nae(t.sessionStore,e,t.dir);return dC(e,t)}async function DGe(e,t,r){if(r?.sessionStore)return Uae(r.sessionStore,e,t,r);return pC(e,t,r)}function Jz(e){let t=Fu(e??"."),r;try{r=pae(t)}catch{r=t}return Ir(r)}function ar(e){return Ho(Jz(e))}function Xz(e){return e.map((t)=>me(t)).join(`
|
|
119
119
|
`)+`
|
|
120
120
|
`}function Yz(e,t,r){if(t!==void 0&&t>0)return e.slice(r,r+t);if(r>0)return e.slice(r);return e}function rk(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}async function Iae(e,t){let r=Jz(t.dir),o=Ho(r),n=t.offset??0,i=t.limit;if(e.listSessionSummaries)return Aae(e,o,r,t.dir,i,n);if(!e.listSessions)throw Error("sessionStore.listSessions is not implemented -- cannot list sessions. Provide a store with a listSessions() method.");let a=(await e.listSessions(o)).slice().sort((u,d)=>d.mtime-u.mtime),c=Yz(a,i,n);return Qz(e,c,t.dir,r)}async function Aae(e,t,r,o,n,i){let s=await e.listSessionSummaries(t),a=e.listSessions?new Map((await e.listSessions(t)).map((p)=>[p.sessionId,p])):void 0,c=[];for(let p of s){let f=a?.get(p.sessionId);if(a&&!f)continue;let m=f!==void 0&&p.mtime<f.mtime;c.push({sessionId:p.sessionId,mtime:m?f.mtime:p.mtime,info:m?void 0:Ok(p,r)})}if(a){let p=new Set(s.map((f)=>f.sessionId));for(let[f,m]of a)if(!p.has(f))c.push({sessionId:f,mtime:m.mtime})}else Q("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");c.sort((p,f)=>f.mtime-p.mtime);let u=Yz(c,n,i),d=u.filter((p)=>p.info===void 0);if(d.length>0){let p=await Qz(e,d,o,r),f=new Map(p.map((m)=>[m.sessionId,m]));for(let m of u)if(m.info===void 0)m.info=f.get(m.sessionId)??null}return u.flatMap((p)=>p.info?[p.info]:[])}async function Qz(e,t,r,o){return(await Promise.allSettled(t.map(async(i)=>{let s=await t1(e,i.sessionId,r);if(!s)return null;let a=ks(i.sessionId,e1(s,i.mtime),o);return a?{...a,lastModified:i.mtime}:null}))).flatMap((i,s)=>{let a=t[s];if(i.status==="fulfilled")return i.value?[i.value]:[];return[{sessionId:a.sessionId,summary:"",lastModified:a.mtime}]})}function e1(e,t){let r=Buffer.from(e,"utf-8"),o=r.length,n=r.subarray(0,mr).toString("utf-8"),i=o>mr?r.subarray(o-mr).toString("utf-8"):n;return{mtime:t,size:o,head:n,tail:i}}function Rae(e){let t=e.trimEnd(),r=t.slice(t.lastIndexOf(`
|