@anthropic-ai/claude-agent-sdk 0.3.321 → 0.3.322
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 +3 -3
- package/browser-sdk.js +2 -2
- package/{core-hz6x1gbv.mjs → core-8zdh6hy9.mjs} +3 -3
- package/{core-4jkx88px.mjs → core-b5da77cd.mjs} +1 -1
- package/{core-9cm2w1sd.mjs → core-f2yzhw4m.mjs} +2 -2
- package/{core-ke81nxtn.mjs → core-j29a9c1a.mjs} +2 -2
- package/core.mjs +5 -5
- package/manifest.json +19 -19
- package/manifest.zst.json +25 -25
- package/package.json +14 -14
- package/sdk.d.ts +1 -1
- package/sdk.mjs +5 -5
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.322
|
|
5
5
|
|
|
6
6
|
// Want to see the unminified source? We're hiring!
|
|
7
7
|
// https://job-boards.greenhouse.io/anthropic/jobs/4816199008
|
|
@@ -123,7 +123,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
123
123
|
`),e.initPromise=Pl().mkdir(t).catch(()=>{}),e.initPromise}function eje(e){return e.logStem===null?null:{namespace:"log",sessionId:e.logStem,channel:"debug"}}function RW(){let e=CW();return AW(e),e.debugFilePath??null}function on(e,t){let n=CW();if(n.debugFilePath===null)return;let o=`${new Date().toISOString()} ${e}
|
|
124
124
|
`;AW(n).then(()=>{if(t!==void 0){let s=eje(n);if(s!==null)t.append(s,[{data:o}]).catch(()=>{});return}if(n.debugFilePath)Pl().append(n.debugFilePath,o).catch(()=>{})})}class Pp{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}get ended(){return this.isDone}[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})}get readerIsWaiting(){return this.readResolve!==void 0&&!this.isDone}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)}dropNewestQueued(e){let t=this.queue.findLastIndex(e);if(t!==-1)this.queue.splice(t,1)}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 OW=15000,tje=P(()=>O({session_id:h(),ws_url:h(),work_dir:h().optional(),session_key:h().optional()}));class Kr extends Error{code;constructor(e,t){super(e);this.name="DirectConnectError",this.code=t}}class wW{options;ws;sessionId;workDir;abortController;readyState=!1;closed=!1;exitError;messages=new Pp;readyPromise;readyResolve;readyReject;abortHandler;partialChunks=[];telemetryEmitted=!1;constructor(e){this.options=e;this.abortController=e.abortController??new AbortController,this.readyPromise=new Promise((t,n)=>{this.readyResolve=t,this.readyReject=n}),this.readyPromise.catch(()=>{}),this.initialize()}get ready(){return this.readyPromise}getSessionId(){return this.sessionId}getWorkDir(){return this.workDir}async initialize(){if(this.abortController.signal.aborted){this.failInit(new tr("Connection aborted"));return}this.abortHandler=()=>{this.close(),this.exitError=new tr("Connection aborted by user")},this.abortController.signal.addEventListener("abort",this.abortHandler);let e;try{let o=await rje(this.options);this.sessionId=o.sessionId,this.workDir=o.workDir,e=o.wsUrl}catch(o){let s=Yn(o);if(!(s instanceof tr)){let i=s instanceof Kr&&s.code?s.code:"session_create_failed";this.emitTelemetry("bad",i)}this.failInit(s);return}if(this.closed){if(this.options.deleteSessionOnClose&&this.sessionId)TW(this.options.serverUrl,this.sessionId,this.options.authToken);return}let t={};if(this.options.authToken)t.authorization=`Bearer ${this.options.authToken}`;let n=new WebSocket(e,{headers:t});this.ws=n;let r=setTimeout((o,s)=>{if(!o.readyState){s.close();let i=new Kr(`WebSocket connection timeout after ${OW}ms`);o.exitError=i,o.readyReject?.(i),o.emitTelemetry("bad","connect_timeout")}},OW,this,n);n.addEventListener("open",()=>{clearTimeout(r),this.readyState=!0,on(`[DirectConnectTransport] Connected to ${this.options.serverUrl}, session=${this.sessionId}`),this.readyResolve?.(),this.emitTelemetry("ok")}),n.addEventListener("message",(o)=>{let s=typeof o.data==="string"?o.data:"";if(s.indexOf(`
|
|
125
125
|
`)===-1){if(s)this.partialChunks.push(s);return}let i=this.partialChunks.join("")+s;this.partialChunks.length=0;let a=i.split(`
|
|
126
|
-
`),l=a.pop()??"";if(l)this.partialChunks.push(l);for(let c of a){if(!c)continue;let d;try{d=je(c)}catch(p){on(`DirectConnect: dropped malformed JSON line (${c.length} bytes): ${p}`);continue}this.messages.enqueue(d)}}),n.addEventListener("error",()=>{clearTimeout(r);let o=new Kr("WebSocket connection error");if(this.exitError=o,this.readyReject?.(o),this.messages.done(),!this.readyState)this.emitTelemetry("bad","ws_error")}),n.addEventListener("close",(o)=>{let s=this.readyState;this.readyState=!1,this.closed=!0;let i=o.code!==1000&&o.code!==1001;if(i&&!this.exitError)this.exitError=new Kr(`WebSocket closed abnormally: ${o.code} ${o.reason}`);if(this.messages.done(),s&&i&&!this.abortController.signal.aborted)this.emitTelemetry("sad","ws_closed_abnormally")})}emitTelemetry(e,t){if(this.telemetryEmitted)return;if(this.telemetryEmitted=!0,e==="ok")kp("transport_direct_connect");else if(e==="bad")Dw("transport_direct_connect",t??"unknown");else pc("transport_direct_connect",t??"unknown")}failInit(e){this.exitError=e,this.closed=!0,this.readyReject?.(e),this.messages.done()}async write(e){if(this.abortController.signal.aborted)throw new tr("Operation aborted");if(!this.readyState)await this.readyPromise;if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Kr("Transport is not ready for writing");this.ws.send(e)}isReady(){return this.readyState&&this.ws?.readyState===WebSocket.OPEN}endInput(){}[Symbol.dispose](){this.close()}close(){if(this.closed)return;if(this.closed=!0,this.readyState=!1,this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;if(!this.abortController.signal.aborted)this.abortController.abort();if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.close(1000,"Normal closure");if(this.messages.done(),this.options.deleteSessionOnClose&&this.sessionId)TW(this.options.serverUrl,this.sessionId,this.options.authToken)}async*readMessages(){if(yield*this.messages,this.exitError)throw this.exitError}}function nje(e){if(e.startsWith("cc://")){let r=e.slice(5),o=new URL(`http://${r}`),s=o.pathname.slice(1)||void 0;return{serverUrl:`http://${o.host}`,authToken:s}}if(e.startsWith("cc+unix://"))throw new Kr("Unix socket connect (cc+unix://) is not supported by the SDK transport");let t=/^https?:\/\//i.test(e)?e:`http://${e}`,n=new URL(t);return{serverUrl:`${n.protocol}//${n.host}`,authToken:void 0}}async function rje(e){let t={"content-type":"application/json"};if(e.authToken)t.authorization=`Bearer ${e.authToken}`;let n={};if(e.cwd)n.cwd=e.cwd;if(e.sessionKey)n.session_key=e.sessionKey;if(e.permissionMode)n.permission_mode=e.permissionMode;let r;try{r=await fetch(`${e.serverUrl}/sessions`,{method:"POST",headers:t,body:ce(n)})}catch(s){throw new Kr(`Failed to connect to server at ${e.serverUrl}: ${s instanceof Error?s.message:String(s)}`,"session_create_failed")}if(!r.ok){let s=await r.text().catch(()=>"");throw new Kr(`Failed to create session: ${r.status} ${r.statusText}${s?` — ${s}`:""}`,"session_create_failed")}let o=tje().safeParse(await r.json());if(!o.success)throw new Kr(`Invalid session response: ${o.error.message}`,"session_create_invalid_response");return{sessionId:o.data.session_id,wsUrl:o.data.ws_url,workDir:o.data.work_dir}}async function TW(e,t,n){let r={};if(n)r.authorization=`Bearer ${n}`;try{await fetch(`${e}/sessions/${t}`,{method:"DELETE",headers:r})}catch{}}import{resolve as gXe}from"path";function oje(){this.__data__=[],this.size=0}var vW=oje;function sje(e,t){return e===t||e!==e&&t!==t}var bo=sje;function ije(e,t){var n=e.length;while(n--)if(bo(e[n][0],t))return n;return-1}var fi=ije;var aje=Array.prototype,lje=aje.splice;function cje(e){var t=this.__data__,n=fi(t,e);if(n<0)return!1;var r=t.length-1;if(n==r)t.pop();else lje.call(t,n,1);return--this.size,!0}var xW=cje;function uje(e){var t=this.__data__,n=fi(t,e);return n<0?void 0:t[n][1]}var kW=uje;function dje(e){return fi(this.__data__,e)>-1}var PW=dje;function pje(e,t){var n=this.__data__,r=fi(n,e);if(r<0)++this.size,n.push([e,t]);else n[r][1]=t;return this}var IW=pje;function fc(e){var t=-1,n=e==null?0:e.length;this.clear();while(++t<n){var r=e[t];this.set(r[0],r[1])}}fc.prototype.clear=vW;fc.prototype.delete=xW;fc.prototype.get=kW;fc.prototype.has=PW;fc.prototype.set=IW;var mi=fc;function fje(){this.__data__=new mi,this.size=0}var DW=fje;function mje(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var LW=mje;function gje(e){return this.__data__.get(e)}var MW=gje;function hje(e){return this.__data__.has(e)}var NW=hje;function _je(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Lt=_je;var yje="[object AsyncFunction]",Sje="[object Function]",Eje="[object GeneratorFunction]",bje="[object Proxy]";function Cje(e){if(!Lt(e))return!1;var t=nr(e);return t==Sje||t==Eje||t==yje||t==bje}var mc=Cje;var Aje=Bt["__core-js_shared__"],p_=Aje;var UW=function(){var e=/[^.]+$/.exec(p_&&p_.keys&&p_.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Rje(e){return!!UW&&UW in e}var FW=Rje;var Oje=Function.prototype,Tje=Oje.toString;function wje(e){if(e!=null){try{return Tje.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var os=wje;var vje=/[\\^$.*+?()[\]{}|]/g,xje=/^\[object .+?Constructor\]$/,kje=Function.prototype,Pje=Object.prototype,Ije=kje.toString,Dje=Pje.hasOwnProperty,Lje=RegExp("^"+Ije.call(Dje).replace(vje,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mje(e){if(!Lt(e)||FW(e))return!1;var t=mc(e)?Lje:xje;return t.test(os(e))}var HW=Mje;function Nje(e,t){return e==null?void 0:e[t]}var $W=Nje;function Uje(e,t){var n=$W(e,t);return HW(n)?n:void 0}var Vn=Uje;var Fje=Vn(Bt,"Map"),gi=Fje;var Hje=Vn(Object,"create"),ss=Hje;function $je(){this.__data__=ss?ss(null):{},this.size=0}var zW=$je;function zje(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var BW=zje;var Bje="__lodash_hash_undefined__",jje=Object.prototype,Kje=jje.hasOwnProperty;function Gje(e){var t=this.__data__;if(ss){var n=t[e];return n===Bje?void 0:n}return Kje.call(t,e)?t[e]:void 0}var jW=Gje;var Wje=Object.prototype,Vje=Wje.hasOwnProperty;function qje(e){var t=this.__data__;return ss?t[e]!==void 0:Vje.call(t,e)}var KW=qje;var Yje="__lodash_hash_undefined__";function Zje(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=ss&&t===void 0?Yje:t,this}var GW=Zje;function gc(e){var t=-1,n=e==null?0:e.length;this.clear();while(++t<n){var r=e[t];this.set(r[0],r[1])}}gc.prototype.clear=zW;gc.prototype.delete=BW;gc.prototype.get=jW;gc.prototype.has=KW;gc.prototype.set=GW;var Lw=gc;function Jje(){this.size=0,this.__data__={hash:new Lw,map:new(gi||mi),string:new Lw}}var WW=Jje;function Xje(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var VW=Xje;function Qje(e,t){var n=e.__data__;return VW(t)?n[typeof t=="string"?"string":"hash"]:n.map}var hi=Qje;function eKe(e){var t=hi(this,e).delete(e);return this.size-=t?1:0,t}var qW=eKe;function tKe(e){return hi(this,e).get(e)}var YW=tKe;function nKe(e){return hi(this,e).has(e)}var ZW=nKe;function rKe(e,t){var n=hi(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var JW=rKe;function hc(e){var t=-1,n=e==null?0:e.length;this.clear();while(++t<n){var r=e[t];this.set(r[0],r[1])}}hc.prototype.clear=WW;hc.prototype.delete=qW;hc.prototype.get=YW;hc.prototype.has=ZW;hc.prototype.set=JW;var _a=hc;var oKe=200;function sKe(e,t){var n=this.__data__;if(n instanceof mi){var r=n.__data__;if(!gi||r.length<oKe-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new _a(r)}return n.set(e,t),this.size=n.size,this}var XW=sKe;function _c(e){var t=this.__data__=new mi(e);this.size=t.size}_c.prototype.clear=DW;_c.prototype.delete=LW;_c.prototype.get=MW;_c.prototype.has=NW;_c.prototype.set=XW;var Co=_c;var iKe="__lodash_hash_undefined__";function aKe(e){return this.__data__.set(e,iKe),this}var QW=aKe;function lKe(e){return this.__data__.has(e)}var eV=lKe;function f_(e){var t=-1,n=e==null?0:e.length;this.__data__=new _a;while(++t<n)this.add(e[t])}f_.prototype.add=f_.prototype.push=QW;f_.prototype.has=eV;var m_=f_;function cKe(e,t){var n=-1,r=e==null?0:e.length;while(++n<r)if(t(e[n],n,e))return!0;return!1}var tV=cKe;function uKe(e,t){return e.has(t)}var g_=uKe;var dKe=1,pKe=2;function fKe(e,t,n,r,o,s){var i=n&dKe,a=e.length,l=t.length;if(a!=l&&!(i&&l>a))return!1;var c=s.get(e),d=s.get(t);if(c&&d)return c==t&&d==e;var p=-1,f=!0,m=n&pKe?new m_:void 0;s.set(e,t),s.set(t,e);while(++p<a){var g=e[p],_=t[p];if(r)var y=i?r(_,g,p,t,e,s):r(g,_,p,e,t,s);if(y!==void 0){if(y)continue;f=!1;break}if(m){if(!tV(t,function(S,E){if(!g_(m,E)&&(g===S||o(g,S,n,r,s)))return m.push(E)})){f=!1;break}}else if(!(g===_||o(g,_,n,r,s))){f=!1;break}}return s.delete(e),s.delete(t),f}var h_=fKe;var mKe=Bt.Uint8Array,yc=mKe;function gKe(e){var t=-1,n=Array(e.size);return e.forEach(function(r,o){n[++t]=[o,r]}),n}var nV=gKe;function hKe(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var Sc=hKe;var _Ke=1,yKe=2,SKe="[object Boolean]",EKe="[object Date]",bKe="[object Error]",CKe="[object Map]",AKe="[object Number]",RKe="[object RegExp]",OKe="[object Set]",TKe="[object String]",wKe="[object Symbol]",vKe="[object ArrayBuffer]",xKe="[object DataView]",rV=nn?nn.prototype:void 0,Mw=rV?rV.valueOf:void 0;function kKe(e,t,n,r,o,s,i){switch(n){case xKe:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case vKe:if(e.byteLength!=t.byteLength||!s(new yc(e),new yc(t)))return!1;return!0;case SKe:case EKe:case AKe:return bo(+e,+t);case bKe:return e.name==t.name&&e.message==t.message;case RKe:case TKe:return e==t+"";case CKe:var a=nV;case OKe:var l=r&_Ke;if(a||(a=Sc),e.size!=t.size&&!l)return!1;var c=i.get(e);if(c)return c==t;r|=yKe,i.set(e,t);var d=h_(a(e),a(t),r,o,s,i);return i.delete(e),d;case wKe:if(Mw)return Mw.call(e)==Mw.call(t)}return!1}var oV=kKe;function PKe(e,t){var n=-1,r=t.length,o=e.length;while(++n<r)e[o+n]=t[n];return e}var Ec=PKe;function IKe(e,t,n){var r=t(e);return lt(e)?r:Ec(r,n(e))}var __=IKe;function DKe(e,t){var n=-1,r=e==null?0:e.length,o=0,s=[];while(++n<r){var i=e[n];if(t(i,n,e))s[o++]=i}return s}var sV=DKe;function LKe(){return[]}var y_=LKe;var MKe=Object.prototype,NKe=MKe.propertyIsEnumerable,iV=Object.getOwnPropertySymbols,UKe=!iV?y_:function(e){if(e==null)return[];return e=Object(e),sV(iV(e),function(t){return NKe.call(e,t)})},bc=UKe;function FKe(e,t){var n=-1,r=Array(e);while(++n<e)r[n]=t(n);return r}var aV=FKe;var HKe="[object Arguments]";function $Ke(e){return Yt(e)&&nr(e)==HKe}var Nw=$Ke;var lV=Object.prototype,{hasOwnProperty:zKe,propertyIsEnumerable:BKe}=lV,jKe=Nw(function(){return arguments}())?Nw:function(e){return Yt(e)&&zKe.call(e,"callee")&&!BKe.call(e,"callee")},is=jKe;function KKe(){return!1}var cV=KKe;var pV=typeof E_=="object"&&E_&&!E_.nodeType&&E_,uV=pV&&typeof S_=="object"&&S_&&!S_.nodeType&&S_,GKe=uV&&uV.exports===pV,dV=GKe?Bt.Buffer:void 0,WKe=dV?dV.isBuffer:void 0,VKe=WKe||cV,Ao=VKe;var qKe=9007199254740991,YKe=/^(?:0|[1-9]\d*)$/;function ZKe(e,t){var n=typeof e;return t=t==null?qKe:t,!!t&&(n=="number"||n!="symbol"&&YKe.test(e))&&(e>-1&&e%1==0&&e<t)}var _i=ZKe;var JKe=9007199254740991;function XKe(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=JKe}var Cc=XKe;var QKe="[object Arguments]",e1e="[object Array]",t1e="[object Boolean]",n1e="[object Date]",r1e="[object Error]",o1e="[object Function]",s1e="[object Map]",i1e="[object Number]",a1e="[object Object]",l1e="[object RegExp]",c1e="[object Set]",u1e="[object String]",d1e="[object WeakMap]",p1e="[object ArrayBuffer]",f1e="[object DataView]",m1e="[object Float32Array]",g1e="[object Float64Array]",h1e="[object Int8Array]",_1e="[object Int16Array]",y1e="[object Int32Array]",S1e="[object Uint8Array]",E1e="[object Uint8ClampedArray]",b1e="[object Uint16Array]",C1e="[object Uint32Array]",dt={};dt[m1e]=dt[g1e]=dt[h1e]=dt[_1e]=dt[y1e]=dt[S1e]=dt[E1e]=dt[b1e]=dt[C1e]=!0;dt[QKe]=dt[e1e]=dt[p1e]=dt[t1e]=dt[f1e]=dt[n1e]=dt[r1e]=dt[o1e]=dt[s1e]=dt[i1e]=dt[a1e]=dt[l1e]=dt[c1e]=dt[u1e]=dt[d1e]=!1;function A1e(e){return Yt(e)&&Cc(e.length)&&!!dt[nr(e)]}var fV=A1e;function R1e(e){return function(t){return e(t)}}var Ac=R1e;var mV=typeof C_=="object"&&C_&&!C_.nodeType&&C_,Ip=mV&&typeof b_=="object"&&b_&&!b_.nodeType&&b_,O1e=Ip&&Ip.exports===mV,Uw=O1e&&d_.process,T1e=function(){try{var e=Ip&&Ip.require&&Ip.require("util").types;if(e)return e;return Uw&&Uw.binding&&Uw.binding("util")}catch(t){}}(),Ro=T1e;var gV=Ro&&Ro.isTypedArray,w1e=gV?Ac(gV):fV,Rc=w1e;var v1e=Object.prototype,x1e=v1e.hasOwnProperty;function k1e(e,t){var n=lt(e),r=!n&&is(e),o=!n&&!r&&Ao(e),s=!n&&!r&&!o&&Rc(e),i=n||r||o||s,a=i?aV(e.length,String):[],l=a.length;for(var c in e)if((t||x1e.call(e,c))&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||_i(c,l))))a.push(c);return a}var A_=k1e;var P1e=Object.prototype;function I1e(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||P1e;return e===n}var Oc=I1e;function D1e(e,t){return function(n){return e(t(n))}}var R_=D1e;var L1e=R_(Object.keys,Object),hV=L1e;var M1e=Object.prototype,N1e=M1e.hasOwnProperty;function U1e(e){if(!Oc(e))return hV(e);var t=[];for(var n in Object(e))if(N1e.call(e,n)&&n!="constructor")t.push(n);return t}var _V=U1e;function F1e(e){return e!=null&&Cc(e.length)&&!mc(e)}var Oo=F1e;function H1e(e){return Oo(e)?A_(e):_V(e)}var To=H1e;function $1e(e){return __(e,To,bc)}var Dp=$1e;var z1e=1,B1e=Object.prototype,j1e=B1e.hasOwnProperty;function K1e(e,t,n,r,o,s){var i=n&z1e,a=Dp(e),l=a.length,c=Dp(t),d=c.length;if(l!=d&&!i)return!1;var p=l;while(p--){var f=a[p];if(!(i?f in t:j1e.call(t,f)))return!1}var m=s.get(e),g=s.get(t);if(m&&g)return m==t&&g==e;var _=!0;s.set(e,t),s.set(t,e);var y=i;while(++p<l){f=a[p];var S=e[f],E=t[f];if(r)var b=i?r(E,S,f,t,e,s):r(S,E,f,e,t,s);if(!(b===void 0?S===E||o(S,E,n,r,s):b)){_=!1;break}y||(y=f=="constructor")}if(_&&!y){var C=e.constructor,A=t.constructor;if(C!=A&&(("constructor"in e)&&("constructor"in t))&&!(typeof C=="function"&&C instanceof C&&typeof A=="function"&&A instanceof A))_=!1}return s.delete(e),s.delete(t),_}var yV=K1e;var G1e=Vn(Bt,"DataView"),O_=G1e;var W1e=Vn(Bt,"Promise"),T_=W1e;var V1e=Vn(Bt,"Set"),yi=V1e;var q1e=Vn(Bt,"WeakMap"),w_=q1e;var SV="[object Map]",Y1e="[object Object]",EV="[object Promise]",bV="[object Set]",CV="[object WeakMap]",AV="[object DataView]",Z1e=os(O_),J1e=os(gi),X1e=os(T_),Q1e=os(yi),eGe=os(w_),ya=nr;if(O_&&ya(new O_(new ArrayBuffer(1)))!=AV||gi&&ya(new gi)!=SV||T_&&ya(T_.resolve())!=EV||yi&&ya(new yi)!=bV||w_&&ya(new w_)!=CV)ya=function(e){var t=nr(e),n=t==Y1e?e.constructor:void 0,r=n?os(n):"";if(r)switch(r){case Z1e:return AV;case J1e:return SV;case X1e:return EV;case Q1e:return bV;case eGe:return CV}return t};var as=ya;var tGe=1,RV="[object Arguments]",OV="[object Array]",v_="[object Object]",nGe=Object.prototype,TV=nGe.hasOwnProperty;function rGe(e,t,n,r,o,s){var i=lt(e),a=lt(t),l=i?OV:as(e),c=a?OV:as(t);l=l==RV?v_:l,c=c==RV?v_:c;var d=l==v_,p=c==v_,f=l==c;if(f&&Ao(e)){if(!Ao(t))return!1;i=!0,d=!1}if(f&&!d)return s||(s=new Co),i||Rc(e)?h_(e,t,n,r,o,s):oV(e,t,l,n,r,o,s);if(!(n&tGe)){var m=d&&TV.call(e,"__wrapped__"),g=p&&TV.call(t,"__wrapped__");if(m||g){var _=m?e.value():e,y=g?t.value():t;return s||(s=new Co),o(_,y,n,r,s)}}if(!f)return!1;return s||(s=new Co),yV(e,t,n,r,o,s)}var wV=rGe;function vV(e,t,n,r,o){if(e===t)return!0;if(e==null||t==null||!Yt(e)&&!Yt(t))return e!==e&&t!==t;return wV(e,t,n,r,vV,o)}var Tc=vV;var oGe=1,sGe=2;function iGe(e,t,n,r){var o=n.length,s=o,i=!r;if(e==null)return!s;e=Object(e);while(o--){var a=n[o];if(i&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}while(++o<s){a=n[o];var l=a[0],c=e[l],d=a[1];if(i&&a[2]){if(c===void 0&&!(l in e))return!1}else{var p=new Co;if(r)var f=r(c,d,l,e,t,p);if(!(f===void 0?Tc(d,c,oGe|sGe,r,p):f))return!1}}return!0}var xV=iGe;function aGe(e){return e===e&&!Lt(e)}var x_=aGe;function lGe(e){var t=To(e),n=t.length;while(n--){var r=t[n],o=e[r];t[n]=[r,o,x_(o)]}return t}var kV=lGe;function cGe(e,t){return function(n){if(n==null)return!1;return n[e]===t&&(t!==void 0||(e in Object(n)))}}var k_=cGe;function uGe(e){var t=kV(e);if(t.length==1&&t[0][2])return k_(t[0][0],t[0][1]);return function(n){return n===e||xV(n,e,t)}}var PV=uGe;var dGe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,pGe=/^\w*$/;function fGe(e,t){if(lt(e))return!1;var n=typeof e;if(n=="number"||n=="symbol"||n=="boolean"||e==null||dc(e))return!0;return pGe.test(e)||!dGe.test(e)||t!=null&&e in Object(t)}var wc=fGe;var mGe="Expected a function";function Fw(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw TypeError(mGe);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],s=n.cache;if(s.has(o))return s.get(o);var i=e.apply(this,r);return n.cache=s.set(o,i)||s,i};return n.cache=new(Fw.Cache||_a),n}Fw.Cache=_a;var IV=Fw;var gGe=500;function hGe(e){var t=IV(e,function(r){if(n.size===gGe)n.clear();return r}),n=t.cache;return t}var DV=hGe;var _Ge=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,yGe=/\\(\\)?/g,SGe=DV(function(e){var t=[];if(e.charCodeAt(0)===46)t.push("");return e.replace(_Ge,function(n,r,o,s){t.push(o?s.replace(yGe,"$1"):r||n)}),t}),LV=SGe;function EGe(e,t){if(lt(e))return e;return wc(e,t)?[e]:LV(yW(e))}var Cr=EGe;var bGe=1/0;function CGe(e){if(typeof e=="string"||dc(e))return e;var t=e+"";return t=="0"&&1/e==-bGe?"-0":t}var rr=CGe;function AGe(e,t){t=Cr(t,e);var n=0,r=t.length;while(e!=null&&n<r)e=e[rr(t[n++])];return n&&n==r?e:void 0}var Si=AGe;function RGe(e,t,n){var r=e==null?void 0:Si(e,t);return r===void 0?n:r}var MV=RGe;function OGe(e,t){return e!=null&&t in Object(e)}var NV=OGe;function TGe(e,t,n){t=Cr(t,e);var r=-1,o=t.length,s=!1;while(++r<o){var i=rr(t[r]);if(!(s=e!=null&&n(e,i)))break;e=e[i]}if(s||++r!=o)return s;return o=e==null?0:e.length,!!o&&Cc(o)&&_i(i,o)&&(lt(e)||is(e))}var UV=TGe;function wGe(e,t){return e!=null&&UV(e,t,NV)}var P_=wGe;var vGe=1,xGe=2;function kGe(e,t){if(wc(e)&&x_(t))return k_(rr(e),t);return function(n){var r=MV(n,e);return r===void 0&&r===t?P_(n,e):Tc(t,r,vGe|xGe)}}var FV=kGe;function PGe(e){return e}var vc=PGe;function IGe(e){return function(t){return t==null?void 0:t[e]}}var HV=IGe;function DGe(e){return function(t){return Si(t,e)}}var $V=DGe;function LGe(e){return wc(e)?HV(rr(e)):$V(e)}var zV=LGe;function MGe(e){if(typeof e=="function")return e;if(e==null)return vc;if(typeof e=="object")return lt(e)?FV(e[0],e[1]):PV(e);return zV(e)}var wo=MGe;var NGe=function(){try{var e=Vn(Object,"defineProperty");return e({},"",{}),e}catch(t){}}(),xc=NGe;function UGe(e,t,n){if(t=="__proto__"&&xc)xc(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0});else e[t]=n}var Ei=UGe;var FGe=Object.prototype,HGe=FGe.hasOwnProperty;function $Ge(e,t,n){var r=e[t];if(!(HGe.call(e,t)&&bo(r,n))||n===void 0&&!(t in e))Ei(e,t,n)}var kc=$Ge;function zGe(e,t,n,r){if(!Lt(e))return e;t=Cr(t,e);var o=-1,s=t.length,i=s-1,a=e;while(a!=null&&++o<s){var l=rr(t[o]),c=n;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=i){var d=a[l];if(c=r?r(d,l,a):void 0,c===void 0)c=Lt(d)?d:_i(t[o+1])?[]:{}}kc(a,l,c),a=a[l]}return e}var BV=zGe;function BGe(e,t,n){var r=-1,o=t.length,s={};while(++r<o){var i=t[r],a=Si(e,i);if(n(a,i))BV(s,Cr(i,e),a)}return s}var I_=BGe;var jGe=R_(Object.getPrototypeOf,Object),Pc=jGe;var KGe=Object.getOwnPropertySymbols,GGe=!KGe?y_:function(e){var t=[];while(e)Ec(t,bc(e)),e=Pc(e);return t},D_=GGe;function WGe(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var jV=WGe;var VGe=Object.prototype,qGe=VGe.hasOwnProperty;function YGe(e){if(!Lt(e))return jV(e);var t=Oc(e),n=[];for(var r in e)if(!(r=="constructor"&&(t||!qGe.call(e,r))))n.push(r);return n}var KV=YGe;function ZGe(e){return Oo(e)?A_(e,!0):KV(e)}var vo=ZGe;function JGe(e){return __(e,vo,D_)}var Ic=JGe;function XGe(e,t){if(e==null)return{};var n=uc(Ic(e),function(r){return[r]});return t=wo(t),I_(e,n,function(r,o){return t(r,o[0])})}var Dc=XGe;import{lstat as eXe}from"fs/promises";import{dirname as tXe,join as Ma}from"path";import{dirname as tWe}from"path";import{AsyncLocalStorage as QGe}from"async_hooks";var eWe=new QGe;function GV(){return eWe.getStore()!==void 0}var uxt=new Te(()=>new Set);function WV(){}class qV{pendingWrite=Promise.resolve();cleanupRegistered=!1;notStarted=[];appendOldest=this.appendOldestNotStarted.bind(this);append(e,t){let n=this.notStarted.at(-1);if(n?.logFile===e){n.lines+=t;return}if(this.notStarted.push({logFile:e,lines:t}),this.pendingWrite=this.pendingWrite.then(this.appendOldest).catch(WV),!this.cleanupRegistered)this.cleanupRegistered=!0,rm(()=>this.flush())}async appendOldestNotStarted(){let e=this.notStarted.shift();if(e===void 0)return;let t=Oe();try{await t.appendFile(e.logFile,e.lines)}catch{await t.mkdir(tWe(e.logFile)).catch(WV),await t.appendFile(e.logFile,e.lines)}}flush(){return this.pendingWrite}}var nWe=new Te(()=>new qV);function rWe(){return Qr(nWe)}function Lp(e,t,n,r="queued"){let o=sWe();if(!o)return;let s;try{s=VV(e,t,oWe(n))}catch{s=VV(e,t,{diagnostics_payload_failed:!0})}if(r==="now")try{Oe().appendFileSync(o,s)}catch{}else rWe().append(o,s)}function oWe(e){try{return(typeof e==="function"?e():e)??{}}catch{return{diagnostics_payload_failed:!0}}}function VV(e,t,n){let r={timestamp:new Date().toISOString(),level:e,event:t,data:n,cc_version:typeof{VERSION:"0.3.321"}<"u"?"0.3.321":"unknown"};return ce(r)+`
|
|
126
|
+
`),l=a.pop()??"";if(l)this.partialChunks.push(l);for(let c of a){if(!c)continue;let d;try{d=je(c)}catch(p){on(`DirectConnect: dropped malformed JSON line (${c.length} bytes): ${p}`);continue}this.messages.enqueue(d)}}),n.addEventListener("error",()=>{clearTimeout(r);let o=new Kr("WebSocket connection error");if(this.exitError=o,this.readyReject?.(o),this.messages.done(),!this.readyState)this.emitTelemetry("bad","ws_error")}),n.addEventListener("close",(o)=>{let s=this.readyState;this.readyState=!1,this.closed=!0;let i=o.code!==1000&&o.code!==1001;if(i&&!this.exitError)this.exitError=new Kr(`WebSocket closed abnormally: ${o.code} ${o.reason}`);if(this.messages.done(),s&&i&&!this.abortController.signal.aborted)this.emitTelemetry("sad","ws_closed_abnormally")})}emitTelemetry(e,t){if(this.telemetryEmitted)return;if(this.telemetryEmitted=!0,e==="ok")kp("transport_direct_connect");else if(e==="bad")Dw("transport_direct_connect",t??"unknown");else pc("transport_direct_connect",t??"unknown")}failInit(e){this.exitError=e,this.closed=!0,this.readyReject?.(e),this.messages.done()}async write(e){if(this.abortController.signal.aborted)throw new tr("Operation aborted");if(!this.readyState)await this.readyPromise;if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Kr("Transport is not ready for writing");this.ws.send(e)}isReady(){return this.readyState&&this.ws?.readyState===WebSocket.OPEN}endInput(){}[Symbol.dispose](){this.close()}close(){if(this.closed)return;if(this.closed=!0,this.readyState=!1,this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;if(!this.abortController.signal.aborted)this.abortController.abort();if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.close(1000,"Normal closure");if(this.messages.done(),this.options.deleteSessionOnClose&&this.sessionId)TW(this.options.serverUrl,this.sessionId,this.options.authToken)}async*readMessages(){if(yield*this.messages,this.exitError)throw this.exitError}}function nje(e){if(e.startsWith("cc://")){let r=e.slice(5),o=new URL(`http://${r}`),s=o.pathname.slice(1)||void 0;return{serverUrl:`http://${o.host}`,authToken:s}}if(e.startsWith("cc+unix://"))throw new Kr("Unix socket connect (cc+unix://) is not supported by the SDK transport");let t=/^https?:\/\//i.test(e)?e:`http://${e}`,n=new URL(t);return{serverUrl:`${n.protocol}//${n.host}`,authToken:void 0}}async function rje(e){let t={"content-type":"application/json"};if(e.authToken)t.authorization=`Bearer ${e.authToken}`;let n={};if(e.cwd)n.cwd=e.cwd;if(e.sessionKey)n.session_key=e.sessionKey;if(e.permissionMode)n.permission_mode=e.permissionMode;let r;try{r=await fetch(`${e.serverUrl}/sessions`,{method:"POST",headers:t,body:ce(n)})}catch(s){throw new Kr(`Failed to connect to server at ${e.serverUrl}: ${s instanceof Error?s.message:String(s)}`,"session_create_failed")}if(!r.ok){let s=await r.text().catch(()=>"");throw new Kr(`Failed to create session: ${r.status} ${r.statusText}${s?` — ${s}`:""}`,"session_create_failed")}let o=tje().safeParse(await r.json());if(!o.success)throw new Kr(`Invalid session response: ${o.error.message}`,"session_create_invalid_response");return{sessionId:o.data.session_id,wsUrl:o.data.ws_url,workDir:o.data.work_dir}}async function TW(e,t,n){let r={};if(n)r.authorization=`Bearer ${n}`;try{await fetch(`${e}/sessions/${t}`,{method:"DELETE",headers:r})}catch{}}import{resolve as gXe}from"path";function oje(){this.__data__=[],this.size=0}var vW=oje;function sje(e,t){return e===t||e!==e&&t!==t}var bo=sje;function ije(e,t){var n=e.length;while(n--)if(bo(e[n][0],t))return n;return-1}var fi=ije;var aje=Array.prototype,lje=aje.splice;function cje(e){var t=this.__data__,n=fi(t,e);if(n<0)return!1;var r=t.length-1;if(n==r)t.pop();else lje.call(t,n,1);return--this.size,!0}var xW=cje;function uje(e){var t=this.__data__,n=fi(t,e);return n<0?void 0:t[n][1]}var kW=uje;function dje(e){return fi(this.__data__,e)>-1}var PW=dje;function pje(e,t){var n=this.__data__,r=fi(n,e);if(r<0)++this.size,n.push([e,t]);else n[r][1]=t;return this}var IW=pje;function fc(e){var t=-1,n=e==null?0:e.length;this.clear();while(++t<n){var r=e[t];this.set(r[0],r[1])}}fc.prototype.clear=vW;fc.prototype.delete=xW;fc.prototype.get=kW;fc.prototype.has=PW;fc.prototype.set=IW;var mi=fc;function fje(){this.__data__=new mi,this.size=0}var DW=fje;function mje(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var LW=mje;function gje(e){return this.__data__.get(e)}var MW=gje;function hje(e){return this.__data__.has(e)}var NW=hje;function _je(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Lt=_je;var yje="[object AsyncFunction]",Sje="[object Function]",Eje="[object GeneratorFunction]",bje="[object Proxy]";function Cje(e){if(!Lt(e))return!1;var t=nr(e);return t==Sje||t==Eje||t==yje||t==bje}var mc=Cje;var Aje=Bt["__core-js_shared__"],p_=Aje;var UW=function(){var e=/[^.]+$/.exec(p_&&p_.keys&&p_.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Rje(e){return!!UW&&UW in e}var FW=Rje;var Oje=Function.prototype,Tje=Oje.toString;function wje(e){if(e!=null){try{return Tje.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var os=wje;var vje=/[\\^$.*+?()[\]{}|]/g,xje=/^\[object .+?Constructor\]$/,kje=Function.prototype,Pje=Object.prototype,Ije=kje.toString,Dje=Pje.hasOwnProperty,Lje=RegExp("^"+Ije.call(Dje).replace(vje,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mje(e){if(!Lt(e)||FW(e))return!1;var t=mc(e)?Lje:xje;return t.test(os(e))}var HW=Mje;function Nje(e,t){return e==null?void 0:e[t]}var $W=Nje;function Uje(e,t){var n=$W(e,t);return HW(n)?n:void 0}var Vn=Uje;var Fje=Vn(Bt,"Map"),gi=Fje;var Hje=Vn(Object,"create"),ss=Hje;function $je(){this.__data__=ss?ss(null):{},this.size=0}var zW=$je;function zje(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var BW=zje;var Bje="__lodash_hash_undefined__",jje=Object.prototype,Kje=jje.hasOwnProperty;function Gje(e){var t=this.__data__;if(ss){var n=t[e];return n===Bje?void 0:n}return Kje.call(t,e)?t[e]:void 0}var jW=Gje;var Wje=Object.prototype,Vje=Wje.hasOwnProperty;function qje(e){var t=this.__data__;return ss?t[e]!==void 0:Vje.call(t,e)}var KW=qje;var Yje="__lodash_hash_undefined__";function Zje(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=ss&&t===void 0?Yje:t,this}var GW=Zje;function gc(e){var t=-1,n=e==null?0:e.length;this.clear();while(++t<n){var r=e[t];this.set(r[0],r[1])}}gc.prototype.clear=zW;gc.prototype.delete=BW;gc.prototype.get=jW;gc.prototype.has=KW;gc.prototype.set=GW;var Lw=gc;function Jje(){this.size=0,this.__data__={hash:new Lw,map:new(gi||mi),string:new Lw}}var WW=Jje;function Xje(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var VW=Xje;function Qje(e,t){var n=e.__data__;return VW(t)?n[typeof t=="string"?"string":"hash"]:n.map}var hi=Qje;function eKe(e){var t=hi(this,e).delete(e);return this.size-=t?1:0,t}var qW=eKe;function tKe(e){return hi(this,e).get(e)}var YW=tKe;function nKe(e){return hi(this,e).has(e)}var ZW=nKe;function rKe(e,t){var n=hi(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var JW=rKe;function hc(e){var t=-1,n=e==null?0:e.length;this.clear();while(++t<n){var r=e[t];this.set(r[0],r[1])}}hc.prototype.clear=WW;hc.prototype.delete=qW;hc.prototype.get=YW;hc.prototype.has=ZW;hc.prototype.set=JW;var _a=hc;var oKe=200;function sKe(e,t){var n=this.__data__;if(n instanceof mi){var r=n.__data__;if(!gi||r.length<oKe-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new _a(r)}return n.set(e,t),this.size=n.size,this}var XW=sKe;function _c(e){var t=this.__data__=new mi(e);this.size=t.size}_c.prototype.clear=DW;_c.prototype.delete=LW;_c.prototype.get=MW;_c.prototype.has=NW;_c.prototype.set=XW;var Co=_c;var iKe="__lodash_hash_undefined__";function aKe(e){return this.__data__.set(e,iKe),this}var QW=aKe;function lKe(e){return this.__data__.has(e)}var eV=lKe;function f_(e){var t=-1,n=e==null?0:e.length;this.__data__=new _a;while(++t<n)this.add(e[t])}f_.prototype.add=f_.prototype.push=QW;f_.prototype.has=eV;var m_=f_;function cKe(e,t){var n=-1,r=e==null?0:e.length;while(++n<r)if(t(e[n],n,e))return!0;return!1}var tV=cKe;function uKe(e,t){return e.has(t)}var g_=uKe;var dKe=1,pKe=2;function fKe(e,t,n,r,o,s){var i=n&dKe,a=e.length,l=t.length;if(a!=l&&!(i&&l>a))return!1;var c=s.get(e),d=s.get(t);if(c&&d)return c==t&&d==e;var p=-1,f=!0,m=n&pKe?new m_:void 0;s.set(e,t),s.set(t,e);while(++p<a){var g=e[p],_=t[p];if(r)var y=i?r(_,g,p,t,e,s):r(g,_,p,e,t,s);if(y!==void 0){if(y)continue;f=!1;break}if(m){if(!tV(t,function(S,E){if(!g_(m,E)&&(g===S||o(g,S,n,r,s)))return m.push(E)})){f=!1;break}}else if(!(g===_||o(g,_,n,r,s))){f=!1;break}}return s.delete(e),s.delete(t),f}var h_=fKe;var mKe=Bt.Uint8Array,yc=mKe;function gKe(e){var t=-1,n=Array(e.size);return e.forEach(function(r,o){n[++t]=[o,r]}),n}var nV=gKe;function hKe(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var Sc=hKe;var _Ke=1,yKe=2,SKe="[object Boolean]",EKe="[object Date]",bKe="[object Error]",CKe="[object Map]",AKe="[object Number]",RKe="[object RegExp]",OKe="[object Set]",TKe="[object String]",wKe="[object Symbol]",vKe="[object ArrayBuffer]",xKe="[object DataView]",rV=nn?nn.prototype:void 0,Mw=rV?rV.valueOf:void 0;function kKe(e,t,n,r,o,s,i){switch(n){case xKe:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case vKe:if(e.byteLength!=t.byteLength||!s(new yc(e),new yc(t)))return!1;return!0;case SKe:case EKe:case AKe:return bo(+e,+t);case bKe:return e.name==t.name&&e.message==t.message;case RKe:case TKe:return e==t+"";case CKe:var a=nV;case OKe:var l=r&_Ke;if(a||(a=Sc),e.size!=t.size&&!l)return!1;var c=i.get(e);if(c)return c==t;r|=yKe,i.set(e,t);var d=h_(a(e),a(t),r,o,s,i);return i.delete(e),d;case wKe:if(Mw)return Mw.call(e)==Mw.call(t)}return!1}var oV=kKe;function PKe(e,t){var n=-1,r=t.length,o=e.length;while(++n<r)e[o+n]=t[n];return e}var Ec=PKe;function IKe(e,t,n){var r=t(e);return lt(e)?r:Ec(r,n(e))}var __=IKe;function DKe(e,t){var n=-1,r=e==null?0:e.length,o=0,s=[];while(++n<r){var i=e[n];if(t(i,n,e))s[o++]=i}return s}var sV=DKe;function LKe(){return[]}var y_=LKe;var MKe=Object.prototype,NKe=MKe.propertyIsEnumerable,iV=Object.getOwnPropertySymbols,UKe=!iV?y_:function(e){if(e==null)return[];return e=Object(e),sV(iV(e),function(t){return NKe.call(e,t)})},bc=UKe;function FKe(e,t){var n=-1,r=Array(e);while(++n<e)r[n]=t(n);return r}var aV=FKe;var HKe="[object Arguments]";function $Ke(e){return Yt(e)&&nr(e)==HKe}var Nw=$Ke;var lV=Object.prototype,{hasOwnProperty:zKe,propertyIsEnumerable:BKe}=lV,jKe=Nw(function(){return arguments}())?Nw:function(e){return Yt(e)&&zKe.call(e,"callee")&&!BKe.call(e,"callee")},is=jKe;function KKe(){return!1}var cV=KKe;var pV=typeof E_=="object"&&E_&&!E_.nodeType&&E_,uV=pV&&typeof S_=="object"&&S_&&!S_.nodeType&&S_,GKe=uV&&uV.exports===pV,dV=GKe?Bt.Buffer:void 0,WKe=dV?dV.isBuffer:void 0,VKe=WKe||cV,Ao=VKe;var qKe=9007199254740991,YKe=/^(?:0|[1-9]\d*)$/;function ZKe(e,t){var n=typeof e;return t=t==null?qKe:t,!!t&&(n=="number"||n!="symbol"&&YKe.test(e))&&(e>-1&&e%1==0&&e<t)}var _i=ZKe;var JKe=9007199254740991;function XKe(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=JKe}var Cc=XKe;var QKe="[object Arguments]",e1e="[object Array]",t1e="[object Boolean]",n1e="[object Date]",r1e="[object Error]",o1e="[object Function]",s1e="[object Map]",i1e="[object Number]",a1e="[object Object]",l1e="[object RegExp]",c1e="[object Set]",u1e="[object String]",d1e="[object WeakMap]",p1e="[object ArrayBuffer]",f1e="[object DataView]",m1e="[object Float32Array]",g1e="[object Float64Array]",h1e="[object Int8Array]",_1e="[object Int16Array]",y1e="[object Int32Array]",S1e="[object Uint8Array]",E1e="[object Uint8ClampedArray]",b1e="[object Uint16Array]",C1e="[object Uint32Array]",dt={};dt[m1e]=dt[g1e]=dt[h1e]=dt[_1e]=dt[y1e]=dt[S1e]=dt[E1e]=dt[b1e]=dt[C1e]=!0;dt[QKe]=dt[e1e]=dt[p1e]=dt[t1e]=dt[f1e]=dt[n1e]=dt[r1e]=dt[o1e]=dt[s1e]=dt[i1e]=dt[a1e]=dt[l1e]=dt[c1e]=dt[u1e]=dt[d1e]=!1;function A1e(e){return Yt(e)&&Cc(e.length)&&!!dt[nr(e)]}var fV=A1e;function R1e(e){return function(t){return e(t)}}var Ac=R1e;var mV=typeof C_=="object"&&C_&&!C_.nodeType&&C_,Ip=mV&&typeof b_=="object"&&b_&&!b_.nodeType&&b_,O1e=Ip&&Ip.exports===mV,Uw=O1e&&d_.process,T1e=function(){try{var e=Ip&&Ip.require&&Ip.require("util").types;if(e)return e;return Uw&&Uw.binding&&Uw.binding("util")}catch(t){}}(),Ro=T1e;var gV=Ro&&Ro.isTypedArray,w1e=gV?Ac(gV):fV,Rc=w1e;var v1e=Object.prototype,x1e=v1e.hasOwnProperty;function k1e(e,t){var n=lt(e),r=!n&&is(e),o=!n&&!r&&Ao(e),s=!n&&!r&&!o&&Rc(e),i=n||r||o||s,a=i?aV(e.length,String):[],l=a.length;for(var c in e)if((t||x1e.call(e,c))&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||_i(c,l))))a.push(c);return a}var A_=k1e;var P1e=Object.prototype;function I1e(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||P1e;return e===n}var Oc=I1e;function D1e(e,t){return function(n){return e(t(n))}}var R_=D1e;var L1e=R_(Object.keys,Object),hV=L1e;var M1e=Object.prototype,N1e=M1e.hasOwnProperty;function U1e(e){if(!Oc(e))return hV(e);var t=[];for(var n in Object(e))if(N1e.call(e,n)&&n!="constructor")t.push(n);return t}var _V=U1e;function F1e(e){return e!=null&&Cc(e.length)&&!mc(e)}var Oo=F1e;function H1e(e){return Oo(e)?A_(e):_V(e)}var To=H1e;function $1e(e){return __(e,To,bc)}var Dp=$1e;var z1e=1,B1e=Object.prototype,j1e=B1e.hasOwnProperty;function K1e(e,t,n,r,o,s){var i=n&z1e,a=Dp(e),l=a.length,c=Dp(t),d=c.length;if(l!=d&&!i)return!1;var p=l;while(p--){var f=a[p];if(!(i?f in t:j1e.call(t,f)))return!1}var m=s.get(e),g=s.get(t);if(m&&g)return m==t&&g==e;var _=!0;s.set(e,t),s.set(t,e);var y=i;while(++p<l){f=a[p];var S=e[f],E=t[f];if(r)var b=i?r(E,S,f,t,e,s):r(S,E,f,e,t,s);if(!(b===void 0?S===E||o(S,E,n,r,s):b)){_=!1;break}y||(y=f=="constructor")}if(_&&!y){var C=e.constructor,A=t.constructor;if(C!=A&&(("constructor"in e)&&("constructor"in t))&&!(typeof C=="function"&&C instanceof C&&typeof A=="function"&&A instanceof A))_=!1}return s.delete(e),s.delete(t),_}var yV=K1e;var G1e=Vn(Bt,"DataView"),O_=G1e;var W1e=Vn(Bt,"Promise"),T_=W1e;var V1e=Vn(Bt,"Set"),yi=V1e;var q1e=Vn(Bt,"WeakMap"),w_=q1e;var SV="[object Map]",Y1e="[object Object]",EV="[object Promise]",bV="[object Set]",CV="[object WeakMap]",AV="[object DataView]",Z1e=os(O_),J1e=os(gi),X1e=os(T_),Q1e=os(yi),eGe=os(w_),ya=nr;if(O_&&ya(new O_(new ArrayBuffer(1)))!=AV||gi&&ya(new gi)!=SV||T_&&ya(T_.resolve())!=EV||yi&&ya(new yi)!=bV||w_&&ya(new w_)!=CV)ya=function(e){var t=nr(e),n=t==Y1e?e.constructor:void 0,r=n?os(n):"";if(r)switch(r){case Z1e:return AV;case J1e:return SV;case X1e:return EV;case Q1e:return bV;case eGe:return CV}return t};var as=ya;var tGe=1,RV="[object Arguments]",OV="[object Array]",v_="[object Object]",nGe=Object.prototype,TV=nGe.hasOwnProperty;function rGe(e,t,n,r,o,s){var i=lt(e),a=lt(t),l=i?OV:as(e),c=a?OV:as(t);l=l==RV?v_:l,c=c==RV?v_:c;var d=l==v_,p=c==v_,f=l==c;if(f&&Ao(e)){if(!Ao(t))return!1;i=!0,d=!1}if(f&&!d)return s||(s=new Co),i||Rc(e)?h_(e,t,n,r,o,s):oV(e,t,l,n,r,o,s);if(!(n&tGe)){var m=d&&TV.call(e,"__wrapped__"),g=p&&TV.call(t,"__wrapped__");if(m||g){var _=m?e.value():e,y=g?t.value():t;return s||(s=new Co),o(_,y,n,r,s)}}if(!f)return!1;return s||(s=new Co),yV(e,t,n,r,o,s)}var wV=rGe;function vV(e,t,n,r,o){if(e===t)return!0;if(e==null||t==null||!Yt(e)&&!Yt(t))return e!==e&&t!==t;return wV(e,t,n,r,vV,o)}var Tc=vV;var oGe=1,sGe=2;function iGe(e,t,n,r){var o=n.length,s=o,i=!r;if(e==null)return!s;e=Object(e);while(o--){var a=n[o];if(i&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}while(++o<s){a=n[o];var l=a[0],c=e[l],d=a[1];if(i&&a[2]){if(c===void 0&&!(l in e))return!1}else{var p=new Co;if(r)var f=r(c,d,l,e,t,p);if(!(f===void 0?Tc(d,c,oGe|sGe,r,p):f))return!1}}return!0}var xV=iGe;function aGe(e){return e===e&&!Lt(e)}var x_=aGe;function lGe(e){var t=To(e),n=t.length;while(n--){var r=t[n],o=e[r];t[n]=[r,o,x_(o)]}return t}var kV=lGe;function cGe(e,t){return function(n){if(n==null)return!1;return n[e]===t&&(t!==void 0||(e in Object(n)))}}var k_=cGe;function uGe(e){var t=kV(e);if(t.length==1&&t[0][2])return k_(t[0][0],t[0][1]);return function(n){return n===e||xV(n,e,t)}}var PV=uGe;var dGe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,pGe=/^\w*$/;function fGe(e,t){if(lt(e))return!1;var n=typeof e;if(n=="number"||n=="symbol"||n=="boolean"||e==null||dc(e))return!0;return pGe.test(e)||!dGe.test(e)||t!=null&&e in Object(t)}var wc=fGe;var mGe="Expected a function";function Fw(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw TypeError(mGe);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],s=n.cache;if(s.has(o))return s.get(o);var i=e.apply(this,r);return n.cache=s.set(o,i)||s,i};return n.cache=new(Fw.Cache||_a),n}Fw.Cache=_a;var IV=Fw;var gGe=500;function hGe(e){var t=IV(e,function(r){if(n.size===gGe)n.clear();return r}),n=t.cache;return t}var DV=hGe;var _Ge=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,yGe=/\\(\\)?/g,SGe=DV(function(e){var t=[];if(e.charCodeAt(0)===46)t.push("");return e.replace(_Ge,function(n,r,o,s){t.push(o?s.replace(yGe,"$1"):r||n)}),t}),LV=SGe;function EGe(e,t){if(lt(e))return e;return wc(e,t)?[e]:LV(yW(e))}var Cr=EGe;var bGe=1/0;function CGe(e){if(typeof e=="string"||dc(e))return e;var t=e+"";return t=="0"&&1/e==-bGe?"-0":t}var rr=CGe;function AGe(e,t){t=Cr(t,e);var n=0,r=t.length;while(e!=null&&n<r)e=e[rr(t[n++])];return n&&n==r?e:void 0}var Si=AGe;function RGe(e,t,n){var r=e==null?void 0:Si(e,t);return r===void 0?n:r}var MV=RGe;function OGe(e,t){return e!=null&&t in Object(e)}var NV=OGe;function TGe(e,t,n){t=Cr(t,e);var r=-1,o=t.length,s=!1;while(++r<o){var i=rr(t[r]);if(!(s=e!=null&&n(e,i)))break;e=e[i]}if(s||++r!=o)return s;return o=e==null?0:e.length,!!o&&Cc(o)&&_i(i,o)&&(lt(e)||is(e))}var UV=TGe;function wGe(e,t){return e!=null&&UV(e,t,NV)}var P_=wGe;var vGe=1,xGe=2;function kGe(e,t){if(wc(e)&&x_(t))return k_(rr(e),t);return function(n){var r=MV(n,e);return r===void 0&&r===t?P_(n,e):Tc(t,r,vGe|xGe)}}var FV=kGe;function PGe(e){return e}var vc=PGe;function IGe(e){return function(t){return t==null?void 0:t[e]}}var HV=IGe;function DGe(e){return function(t){return Si(t,e)}}var $V=DGe;function LGe(e){return wc(e)?HV(rr(e)):$V(e)}var zV=LGe;function MGe(e){if(typeof e=="function")return e;if(e==null)return vc;if(typeof e=="object")return lt(e)?FV(e[0],e[1]):PV(e);return zV(e)}var wo=MGe;var NGe=function(){try{var e=Vn(Object,"defineProperty");return e({},"",{}),e}catch(t){}}(),xc=NGe;function UGe(e,t,n){if(t=="__proto__"&&xc)xc(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0});else e[t]=n}var Ei=UGe;var FGe=Object.prototype,HGe=FGe.hasOwnProperty;function $Ge(e,t,n){var r=e[t];if(!(HGe.call(e,t)&&bo(r,n))||n===void 0&&!(t in e))Ei(e,t,n)}var kc=$Ge;function zGe(e,t,n,r){if(!Lt(e))return e;t=Cr(t,e);var o=-1,s=t.length,i=s-1,a=e;while(a!=null&&++o<s){var l=rr(t[o]),c=n;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=i){var d=a[l];if(c=r?r(d,l,a):void 0,c===void 0)c=Lt(d)?d:_i(t[o+1])?[]:{}}kc(a,l,c),a=a[l]}return e}var BV=zGe;function BGe(e,t,n){var r=-1,o=t.length,s={};while(++r<o){var i=t[r],a=Si(e,i);if(n(a,i))BV(s,Cr(i,e),a)}return s}var I_=BGe;var jGe=R_(Object.getPrototypeOf,Object),Pc=jGe;var KGe=Object.getOwnPropertySymbols,GGe=!KGe?y_:function(e){var t=[];while(e)Ec(t,bc(e)),e=Pc(e);return t},D_=GGe;function WGe(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var jV=WGe;var VGe=Object.prototype,qGe=VGe.hasOwnProperty;function YGe(e){if(!Lt(e))return jV(e);var t=Oc(e),n=[];for(var r in e)if(!(r=="constructor"&&(t||!qGe.call(e,r))))n.push(r);return n}var KV=YGe;function ZGe(e){return Oo(e)?A_(e,!0):KV(e)}var vo=ZGe;function JGe(e){return __(e,vo,D_)}var Ic=JGe;function XGe(e,t){if(e==null)return{};var n=uc(Ic(e),function(r){return[r]});return t=wo(t),I_(e,n,function(r,o){return t(r,o[0])})}var Dc=XGe;import{lstat as eXe}from"fs/promises";import{dirname as tXe,join as Ma}from"path";import{dirname as tWe}from"path";import{AsyncLocalStorage as QGe}from"async_hooks";var eWe=new QGe;function GV(){return eWe.getStore()!==void 0}var uxt=new Te(()=>new Set);function WV(){}class qV{pendingWrite=Promise.resolve();cleanupRegistered=!1;notStarted=[];appendOldest=this.appendOldestNotStarted.bind(this);append(e,t){let n=this.notStarted.at(-1);if(n?.logFile===e){n.lines+=t;return}if(this.notStarted.push({logFile:e,lines:t}),this.pendingWrite=this.pendingWrite.then(this.appendOldest).catch(WV),!this.cleanupRegistered)this.cleanupRegistered=!0,rm(()=>this.flush())}async appendOldestNotStarted(){let e=this.notStarted.shift();if(e===void 0)return;let t=Oe();try{await t.appendFile(e.logFile,e.lines)}catch{await t.mkdir(tWe(e.logFile)).catch(WV),await t.appendFile(e.logFile,e.lines)}}flush(){return this.pendingWrite}}var nWe=new Te(()=>new qV);function rWe(){return Qr(nWe)}function Lp(e,t,n,r="queued"){let o=sWe();if(!o)return;let s;try{s=VV(e,t,oWe(n))}catch{s=VV(e,t,{diagnostics_payload_failed:!0})}if(r==="now")try{Oe().appendFileSync(o,s)}catch{}else rWe().append(o,s)}function oWe(e){try{return(typeof e==="function"?e():e)??{}}catch{return{diagnostics_payload_failed:!0}}}function VV(e,t,n){let r={timestamp:new Date().toISOString(),level:e,event:t,data:n,cc_version:typeof{VERSION:"0.3.322"}<"u"?"0.3.322":"unknown"};return ce(r)+`
|
|
127
127
|
`}function sWe(){return iWe()?void 0:Dt.CLAUDE_CODE_DIAGNOSTICS_FILE}function iWe(){return GV()?tt():eb()}import{isUtf8 as aWe}from"buffer";import{open as lWe}from"fs/promises";function YV(e,t){if(!hL())return;let{resolvedPath:n,isSymlink:r}=tl(e,t);if(r)G(`Reading through symlink: ${t} -> ${n}`)}function cWe(e,t,n){let r=e.statSync(t);return L_(r,t,n),r}function L_(e,t,n){if(e.isDirectory())throw Object.assign(Error("EISDIR: illegal operation on a directory, read"),{code:"EISDIR",errno:-21,syscall:"read",path:t});if(!e.isFile())throw Object.assign(Error("Not a regular file (device, FIFO, or socket)"),{code:"ERR_NOT_REGULAR_FILE",path:t});if(n!==void 0&&e.size>n)throw Object.assign(Error("File exceeds maxBytes limit"),{code:"ERR_FILE_TOO_LARGE",path:t,size:e.size,maxBytes:n})}function Hw(e,t,n){if(n===void 0)return;if(e>n)throw Object.assign(Error("File exceeds maxBytes limit"),{code:"ERR_FILE_TOO_LARGE",path:t,size:e,maxBytes:n})}function ZV(e){return e!=null&&typeof e==="object"&&"code"in e&&e.code==="ERR_FILE_TOO_LARGE"}function JV(e){if(e.byteLength===0)return"utf8";if(e.byteLength>=2){if(e[0]===255&&e[1]===254)return"utf16le"}if(e.byteLength>=3&&e[0]===239&&e[1]===187&&e[2]===191)return"utf8";return"utf8"}var XV=4096,uWe=8000;function dWe(e){return e.subarray(0,uWe).includes(0)}function pWe(e){let t=JV(e.subarray(0,XV));if(t!=="utf8")return{encoding:t};if(e.byteLength>=2&&e[0]===254&&e[1]===255)return{encoding:t,notText:"utf16be"};if(dWe(e))return{encoding:t,notText:"nul"};return aWe(e)?{encoding:t}:{encoding:t,notText:"not_utf8"}}function fWe(e){let{buffer:t,bytesRead:n}=Oe().readSync(e,{length:XV});return JV(t.subarray(0,n))}function QV(e){let t=0,n=0;for(let r=0;r<e.length;r++)if(e[r]===`
|
|
128
128
|
`)if(r>0&&e[r-1]==="\r")t++;else n++;return t>n?"CRLF":"LF"}function mWe(e,t,n){let r=Oe();YV(r,e);let o=cWe(r,e,t);n?.(o);let s=fWe(e),i;if(t===void 0)i=r.readFileSync(e,{encoding:s});else{let{buffer:l,bytesRead:c}=r.readSync(e,{length:t+1});Hw(c,e,t),i=l.subarray(0,c).toString(s)}let a=QV(i.slice(0,4096));return{content:i.replaceAll(`\r
|
|
129
129
|
`,`
|
|
@@ -147,18 +147,18 @@ e+zhUoJOBhE9hXPs+SkCIQCHdbMcFo/ZQEq/rVnaS8qv/BZvRfYoEm318TY0WBU4
|
|
|
147
147
|
XA==
|
|
148
148
|
-----END CERTIFICATE-----`,marker:"urn:anthropic:claude-code:signed-cache:production"}],end:"-----SIGNED-CACHE-ROOTS-END-----"},SY=pYe.roots;var EY={marker:"urn:anthropic:claude-code:signed-cache:production",issuingCommonName:"Claude Code Signed Cache Issuing CA"},$c=void 0,bY=Object.freeze(SY.map((e)=>Object.freeze({...e,issuingCommonName:$c!==void 0&&e.marker===$c.marker?$c.issuingCommonName:EY.issuingCommonName})));function fYe(){if($c!==void 0&&RL()&&bY.some((e)=>e.marker===$c.marker))return $c.marker;return EY.marker}function mYe(e,t){return Object.freeze(e.filter((n)=>n.marker===t))}function CY(){return mYe(bY,fYe())}var Ca=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_VERTEX"];var gYe=Le(new Map,(e)=>e.clear());var sy=Le({isOpen:!1},(e)=>{e.isOpen=!1});function hYe(e){return process.env[e]}function AY(e,t){if(t===void 0){delete process.env[e];return}process.env[e]=t}function _Ye(e){return hYe(e.name)===e.theirs}function yYe(){let e=[...gYe.values()];return sy.isOpen?e:e.filter(_Ye)}function RY(e,t){if(sy.isOpen)return e();let n=yYe();if(n.length===0)return e();let r=n.filter((o)=>o.writer===void 0||t===void 0||!t(o.writer));for(let o=r.length-1;o>=0;o--)AY(r[o].name,r[o].before);sy.isOpen=!0;try{return e()}finally{for(let o of r)AY(o.name,o.theirs);sy.isOpen=!1}}var Vp="$defaults";var SYe=["user_allow_rules_to_replace","user_soft_deny_rules_to_replace","user_hard_deny_rules_to_replace","user_environment_to_replace"];var EYe=["account_standing_rule_changes","auto_mode_bypass","blind_apply","browser_file_upload_exfil","browser_input_exfil","browser_js_exfil","browser_navigate_exfil","browser_shortcut_execution","chatops_trigger_comments","ci_bypass","cloud_storage_mass_delete","cluster_wide_workload_creation","code_from_external","code_that_leaks_when_run","command_network_lists","containment_escape","create_public_surface","create_rce_surface","create_unsafe_agents","credential_exploration","credential_leakage","credential_materialization","data_exfiltration","dns_domain_cert_changes","excess_sensitive_detail","exfil_scouting","expose_local_services","external_ingress_tunnel","external_system_writes","feature_flag_writes","git_destructive","instruction_poisoning","interfere_with_workloads","irreversible_deletion_general","irreversible_local_destruction","live_shared_artifact_sensitive_delta","logging_audit_tampering","merge_without_review","modify_shared_resources","node_lifecycle_operations","out_of_place_publication","package_registry_bypass","permission_grant","pii_data_handling","production_deploy","production_reads","protected_scope_iac_apply","public_data_sharing_upload","real_world_transactions","remote_repoint","remote_shell_writes","safety_bypass_flag","sandbox_network_callback","secret_store_writes","security_test_removal","security_weaken","self_approval","self_modification","sensitive_remote_exec","sensitive_source_provenance","session_transcript_tampering","shared_cluster_mutation","shared_scratch_sweep","third_party_attack","tls_auth_weaken","tmux_self_drive","traffic_redirection","unauthorized_persistence","unrequested_artifact_publish","unrequested_commit_in_a_connected_app","untrusted_code_integration","unverifiable_deletion_scope","unverifiable_deletion_target"],bYe=["cowork_delete_grant","cowork_folder_access","cowork_run_routine_now","cowork_scheduled_task_delete","cowork_scheduled_task_write","cowork_skill_persistence"],CYe=["access_added_as_a_means","bot_check_circumvention","consent_given_for_the_user","identity_not_given","notes_for_later_sessions","save_over_an_occupied_name","stated_interface_sidestepped","walled_content_from_a_copy","website_access_circumvention"];var AYe=[],OY=new Set([...EYe,...AYe]),qNt=new Set([...OY,...CYe]),YNt=new Set([...OY,...bYe]);function iy(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==9||n>=127&&n<=159||n===8232||n===8233)return!0}return!1}var RYe=/[\p{Cf}\p{Default_Ignorable_Code_Point}\u2028\u2029\u2800\uFFF9-\uFFFB\u{1D173}-\u{1D17A}]/u;function ay(e){return RYe.test(e)}function TY(e){if(e.includes("<settings_")||SYe.some((t)=>e.includes(`<${t}`)||e.includes(`</${t}`)))return"template_token";if(e.includes("<cc_automode")||e.includes("</cc_automode"))return"region_tag";return null}function wY(e){return e.trim().length>0&&!iy(e)&&!ay(e)&&TY(e)===null}import{posix as $Z,win32 as zZ}from"path";import{isAbsolute as vY}from"path";var rv="When managed settings or a --settings file set allowUnsandboxedCommands: false, or managed settings set network.allowManagedDomainsOnly: true",OYe="When managed settings or a --settings file set allowUnsandboxedCommands: false, network.deniedDomains "+"or a WebFetch(domain:…) deny rule, when managed settings set network.allowManagedDomainsOnly: true, "+"or when managed, --settings or user settings set network.strictAllowlist: true",TYe="When managed settings or a --settings file set allowUnsandboxedCommands: false, filesystem.denyRead, "+"a Read(…) deny rule or a credentials.files entry (deny or mask), or managed settings set network.allowManagedDomainsOnly: true",wYe="When managed settings or a --settings file set filesystem.denyRead, a Read(…) deny rule "+"or a credentials.files entry (deny or mask)",us="project settings (.claude/settings.json and .claude/settings.local.json)",zc=`${rv}, values from ${us} are ignored.`,ly=`${rv}, true from ${us} is ignored (false there still applies).`,xY=`${rv}, and managed, --settings or user settings set true, false from ${us} is ignored (true there still applies).`,kY=`${OYe}, values from ${us} are ignored. With network.allowManagedDomainsOnly, only managed settings may set it.`,vYe=`${TYe}, a value from ${us} that would re-open a path managed, --settings or user settings deny reading is ignored, as is one spelled as a glob or a network path (UNC or automount); one carving out of the project's own denyRead still applies. A value inside a directory sandboxed commands can write is re-checked before every command and dropped once it has been re-pointed into a denied path.`,xYe=`${zc} ${wYe}, a value from ${us} under or equal to a denied path, or spelled as a glob or a network path (UNC or automount), is ignored. A value inside a directory sandboxed commands can already write is re-checked before every command and dropped once it has been re-pointed into a denied read path.`,kYe=P(()=>O({allowedDomains:k(h()).optional().describe("Domains sandboxed commands may reach without a prompt (wildcards such as *.example.com supported). "+"Merged with WebFetch(domain:…) allow rules and across settings sources. "+zc+" With network.allowManagedDomainsOnly, only managed settings supply it."),deniedDomains:k(h()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),strictAllowlist:v().optional().describe("When true, the sandbox runtime deterministically denies hosts not in allowedDomains instead of prompting. "+"Enforced for sandboxed commands only — in-process tools such as WebFetch are not gated by this setting. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+`${us} are ignored, and while it is on their allowedDomains `+"and WebFetch(domain:…) allow rules are left out of the allowlist."),allowManagedDomainsOnly:v().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:k(h()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path). Merged across settings sources. "+zc),allowAllUnixSockets:v().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms). "+ly),allowLocalBinding:v().optional().describe("macOS only: If true, sandboxed commands can bind to localhost ports. "+ly),allowMachLookup:k(h().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. Each entry lets sandboxed commands reach services outside the sandbox, and the sandbox does not confine what those services do for them. Merged across settings sources. '+zc),httpProxyPort:Y().optional().describe("Local TCP port of your own HTTP proxy for sandboxed traffic, used instead of the proxy Claude Code runs. "+kY),socksProxyPort:Y().optional().describe("Local TCP port of your own SOCKS5 proxy for sandboxed traffic, used instead of the proxy Claude Code runs. "+kY),tlsTerminate:O({caCertPath:h().min(1).optional(),caKeyPath:h().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session. On native Windows an ephemeral CA cannot pass the sandbox trust check, so omitting the paths uses a persistent CA managed by the sandbox runtime (set up and trusted via /sandbox install); configured paths are passed to the sandbox runtime verbatim, which rejects a bad or incomplete pair at sandbox initialization. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — project settings "+"(.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),PYe=P(()=>O({allowWrite:k(h()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules. "+xYe),denyWrite:k(h()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:k(h()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:k(h()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths. "+vYe),allowManagedReadPathsOnly:v().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used."),disabled:v().optional().describe("macOS and Linux/WSL only: skip filesystem isolation entirely while keeping network and seccomp isolation. Ignored on native Windows, where the sandboxed process runs as a separate user with no inherent rights, so skipping the filesystem rules would "+"withhold every access grant rather than loosen them — filesystem isolation stays on there. "+"Sandboxed commands get unrestricted read/write access to the host filesystem; network egress is still confined to network.allowedDomains. Intended for deployments whose goal is egress control rather than filesystem containment. Does not change Bash prompting: sandbox.autoAllowBashIfSandboxed is independent and still defaults to true, so set it to false to keep prompting for sandboxed commands. Drops the read protection from filesystem.denyRead and credentials.files deny entries for sandboxed commands, since both are enforced by the filesystem layer this turns off; credentials.files mask entries (sentinel binds) and credentials.envVars deny/mask are unaffected. "+"Only honored from user, managed/policy, or CLI (`--settings`) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored. If managed settings configure sandbox.filesystem at all, or list any sandbox.credentials.files deny entry, only managed settings can set this: an admin who deployed filesystem restrictions must not have them switched off by a user-writable file. (sandbox.credentials.envVars and credentials.files mask entries "+"do not pin it — env scrubbing and sentinel binds are independent of the filesystem "+"layer and survive this setting.) When unset, filesystem isolation stays on.")}).optional());function PY(e,t,n){if(e.length===0||e.some((r)=>r.length===0))n.addIssue({code:fr.custom,path:["maskClaims"],message:"maskClaims must name at least one non-empty claim — omit maskClaims for whole-token masking."});if(t===void 0)n.addIssue({code:fr.custom,path:["maskClaims"],message:"maskClaims requires decode — without a decode format there is no token to read claims from. Set decode, or omit maskClaims."})}function IY(e,t){let n;try{n=new RegExp(e)}catch(o){t.addIssue({code:fr.custom,path:["extract"],message:`extract is not a valid regular expression: ${ft(o)}`});return}if(new RegExp(n.source+"|").exec("").length-1<1)t.addIssue({code:fr.custom,path:["extract"],message:"extract must contain at least one capturing group — "+'group 1 is the credential value to mask (e.g. "token:\\s*(\\S+)").'})}function DY(e){if(typeof e!=="object"||e===null)return e;let t=e;if(t.mode!=="deny")return e;let n={...t};if("extract"in n&&typeof n.extract!=="string")delete n.extract;if("onExtractNoMatch"in n&&n.onExtractNoMatch!=="warn"&&n.onExtractNoMatch!=="deny"&&n.onExtractNoMatch!=="error")delete n.onExtractNoMatch;if("decode"in n&&n.decode!=="jwt")delete n.decode;if("maskClaims"in n&&!(Array.isArray(n.maskClaims)&&n.maskClaims.every((r)=>typeof r==="string")))delete n.maskClaims;if("maskDuplicates"in n&&typeof n.maskDuplicates!=="boolean")delete n.maskDuplicates;if("injectHosts"in n&&!(Array.isArray(n.injectHosts)&&n.injectHosts.every((r)=>typeof r==="string")))delete n.injectHosts;return n}var cy=P(()=>Me(DY,O({path:h().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:K(["deny","mask"]).describe("Access mode for this path. `deny` blocks reads inside the sandbox; `mask` shows sandboxed commands a sentinel-substituted copy (whole-file, or only the spans captured by `extract`) and the "+"host proxy swaps sentinel→real on egress to `injectHosts`. "+"On macOS and Windows `mask` currently degrades to `deny`."),extract:h().optional().describe("Optional regex for structured masking when mode is `mask`. Applied globally to the file; capture group 1 of each match is a credential value, and only those captured spans are replaced "+"with sentinels — the rest of the file is preserved so a tool "+"that parses it (.netrc, JSON, YAML) still succeeds. Without `extract`, the entire file content is replaced with one sentinel (whole-file masking, suited to single-secret files). If the regex matches nothing, behavior is governed by `onExtractNoMatch` (default `warn`). Accepted but ignored for `deny`."),onExtractNoMatch:K(["warn","deny","error"]).optional().describe("What to do when `extract` matches nothing in the file — or, "+"with `decode`, when no candidate survives verification. `warn` (default) emits a stderr warning and leaves the file readable as-is inside the sandbox (fail-open, for credentials that may be legitimately absent); `deny` degrades the entry to "+"mode `deny` so the file is unreadable (fail-closed) — under "+"`sandbox.filesystem.disabled` it is treated as `error`, since read-denies are dropped in that mode; `error` aborts at sandbox setup so nothing runs until the config is fixed. Only meaningful when mode is `mask` and `extract` or `decode` is set; accepted but ignored otherwise."),decode:K(["jwt"]).optional().describe("Optional encoded-credential format for `mask` mode. `jwt`: candidates are located with a built-in JWT regex (or the explicit `extract` pattern, if set), verified to actually be JWTs before masking, and replaced with a structurally valid fake JWT so client-side token parsing inside the sandbox keeps working. If no candidate verifies, behavior is governed by `onExtractNoMatch` (default `warn`). Accepted but ignored for `deny`."),maskClaims:k(h()).optional().describe("Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel and the token is rebuilt around the modified payload; all other claims are preserved so a tool that decodes the token and reads a non-secret claim keeps working. Requires `decode`. If no named claim matches in any verified token, behavior is governed by `onExtractNoMatch` (default `warn`). Only meaningful when mode is `mask`; accepted but ignored for `deny`."),maskDuplicates:v().optional().describe("If true, verbatim occurrences of each captured credential value outside the regex-matched spans are also replaced with the "+"corresponding sentinel — for a secret repeated where the regex "+"does not reach (e.g. pasted into a comment). Matches raw substrings, so short or common values may corrupt unrelated content; intended for long, high-entropy secrets. Defaults to false. Only meaningful when mode is `mask` and `extract` or `decode` is set; accepted but ignored otherwise."),injectHosts:k(h()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")}).superRefine((e,t)=>{if(e.mode==="mask"&&e.path.endsWith("/"))t.addIssue({code:fr.custom,path:["path"],message:'Credential mode "mask" applies to a single file, not a directory. List the specific credential file(s), or use "deny" for the directory.'});if(e.mode==="mask"&&e.extract!==void 0)IY(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)PY(e.maskClaims,e.decode,t)}))),Bc=()=>h().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"),uy=P(()=>Me(DY,O({name:Bc().describe("Environment variable name."),mode:K(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the "+"host proxy swaps sentinel→real on egress to `injectHosts`."),extract:h().optional().describe("Optional regex for structured masking when mode is `mask`. Applied globally to the value; capture group 1 of each match is a credential value, and only those captured spans are "+"replaced with sentinels — the rest of the value is preserved "+"so a tool that parses it (a `DATABASE_URL` connection string, a composite `KEY:SECRET` pair) still succeeds inside the sandbox. Without `extract`, the entire value is replaced with one sentinel (whole-value masking, suited to bare tokens). If the regex matches nothing, behavior is governed by `onExtractNoMatch` (default `warn`). Cannot be combined with `decode` (the decode path never consults it). Accepted but ignored for `deny`."),onExtractNoMatch:K(["warn","deny","error"]).optional().describe("What to do when `extract` matches nothing in the value. `warn` (default) emits a stderr warning and lets the variable pass through unmasked (fail-open, for credentials that may be legitimately absent); `deny` unsets the variable inside the sandbox (fail-closed); `error` aborts at sandbox setup so nothing runs until the config is fixed. Only meaningful when mode is `mask` and `extract` is set without `decode`. On a mask entry with `decode`, the runtime takes the decode path and never consults this field, so a fail-closed setting "+"cannot be honored — `deny` and `error` are rejected there; "+"only `warn` is accepted. In all other shapes the field is accepted but ignored."),decode:K(["jwt"]).optional().describe("Optional encoded-credential format for `mask` mode. `jwt`: the variable's whole value is verified to actually be a JWT and replaced with a structurally valid fake JWT so client-side token parsing inside the sandbox keeps working; the proxy swaps the whole fake token on egress. If the value does not verify, the variable is left unmasked with a stderr warning "+"(fail-open). Cannot be combined with `extract` — the decode "+"path never consults it. Accepted but ignored for `deny`."),maskClaims:k(h()).optional().describe("Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel and the token is rebuilt around the modified payload; all other claims are preserved so claim-reading clients keep working. Requires `decode`. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is `mask`; accepted but ignored for `deny`."),injectHosts:k(h()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to "+"`network.allowedDomains` — the credential is injected at "+"every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")}).superRefine((e,t)=>{if(e.mode==="mask"&&e.extract!==void 0)IY(e.extract,t);if(e.mode==="mask"&&e.maskClaims!==void 0)PY(e.maskClaims,e.decode,t);if(e.mode==="mask"&&e.decode!==void 0&&e.extract!==void 0)t.addIssue({code:fr.custom,path:["extract"],message:"extract cannot be combined with decode on an env entry — the runtime takes the decode path (whole-value JWT verification) and never consults extract, silently disabling the structured masking. Remove one of the two."});if(e.mode==="mask"&&e.decode!==void 0&&(e.onExtractNoMatch==="deny"||e.onExtractNoMatch==="error"))t.addIssue({code:fr.custom,path:["onExtractNoMatch"],message:"onExtractNoMatch cannot be honored on an env entry with decode — the runtime takes the decode path (which is unconditionally fail-open on verify failure) and never consults extract or onExtractNoMatch. Remove onExtractNoMatch, or drop decode to use extract-based masking (whose no-match handling does honor it)."})}))),Oi=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"];var ov="_INVALID_PAIR_",dy="_PARENT_PAIR_SUPPRESSOR_";var py=P(()=>O({accessKeyIdVar:Bc().describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:Bc().describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:Bc().optional().describe("Optional name of the masked env var holding the AWS session token (temporary credentials). When set, the proxy sends the real token as x-amz-security-token on re-signed requests and adds it to the signed header set if the client did not.")}).superRefine((e,t)=>{let n=new Map;for(let[r,o]of[["accessKeyIdVar",e.accessKeyIdVar],["secretAccessKeyVar",e.secretAccessKeyVar],["sessionTokenVar",e.sessionTokenVar]]){if(o===void 0)continue;let s=n.get(o);if(s!==void 0)t.addIssue({code:fr.custom,path:[r],message:`${r} names the same env var ('${o}') as ${s} — each pair member must be a distinct variable.`});else n.set(o,r)}})),IYe=P(()=>{let e=K(["deny","passthrough"]);return O({streaming:e.optional().describe("Policy for aws-chunked streaming uploads (x-amz-content-sha256: STREAMING-*): per-chunk signatures chain off the seed signature, so re-signing would require rewriting the body. `deny` (default) fails closed with a 403; `passthrough` forwards the request unre-signed (the upstream will reject its signature)."),presigned:e.optional().describe("Policy for presigned URLs (X-Amz-Algorithm/X-Amz-Signature in the query, no Authorization header): the signature lives in the URL itself. `deny` (default) or `passthrough`."),sigv4a:e.optional().describe("Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. `deny` (default) or `passthrough`.")})}),DYe=P(()=>O({files:k(cy()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox; `mask` substitutes a sentinel inside the sandbox (whole-file, or per-`extract` capture) and injects the real value at the proxy. On macOS and Windows `mask` degrades to `deny`."),envVars:k(uy()).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:v().optional().describe("Allow sentinel→real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored."),awsPairs:k(py()).optional().describe("Explicit groupings of masked env vars into AWS credential pairs for SigV4 re-signing, for non-standard variable names. The conventional AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN trio is paired automatically when masked. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored. A member is only usable when its env var is forwarded as a whole-value `mask` entry (an entry carrying `extract` or `decode` does not "+"qualify — re-signing needs the whole real value). A pair "+"whose key id or secret member is unusable never re-signs: it is dropped, unless it names a conventional AWS variable, in which case it is forwarded as an inert suppressor so implicit auto-pairing stays overridden. A pair whose ONLY unusable member is the session token still re-signs, without an x-amz-security-token (temporary-credential requests fail upstream until the entry is fixed)."),sigv4:IYe().optional().describe("Policies for AWS SigV4 request shapes the proxy cannot re-sign (streaming, presigned, sigv4a) when they reference a masked credential pair: `deny` (default) or `passthrough`. Only honored from user, managed/policy, or CLI (`--settings`) "+"settings — project settings (.claude/settings.json and "+".claude/settings.local.json) are ignored.")}).superRefine((e,t)=>{let n=new Set;for(let[r,o]of(e?.awsPairs??[]).entries()){let s=[["accessKeyIdVar",o.accessKeyIdVar],["secretAccessKeyVar",o.secretAccessKeyVar],["sessionTokenVar",o.sessionTokenVar]],i=new Set;for(let[a,l]of s){if(l===void 0)continue;if(n.has(l))t.addIssue({code:fr.custom,path:["awsPairs",r,a],message:`"${l}" appears in more than one awsPairs slot (within or across pairs) — each variable can fill exactly one slot.`});i.add(l)}for(let a of i)n.add(a)}}).optional()),sv=P(()=>O({enabled:v().optional().describe("Run Bash commands inside the sandbox. Default: false. "+xY),failIfUnavailable:v().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. "+xY),autoAllowBashIfSandboxed:v().optional(),allowUnsandboxedCommands:v().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. A false in managed, --settings or user settings holds whatever ${us} say (false there still applies).`),network:kYe(),filesystem:PYe(),credentials:DYe(),ignoreViolations:q(h(),k(h())).optional().describe('Sandbox violations to leave unreported: a map of command patterns ("*" for every command) to the filesystem paths whose violations are ignored. Merged across settings sources. '+zc),enableWeakerNestedSandbox:v().optional().describe("Linux only: Run without the fresh /proc mount, for hosts such as unprivileged Docker containers that cannot create one. "+"**Reduces security** — the host /proc stays readable by sandboxed commands. Default: false. "+ly),allowNestedUserNamespaces:v().optional().describe("Linux/WSL only: Let sandboxed commands create user namespaces of their own, which the sandbox refuses by default. Needed by tools that sandbox themselves that way, such as Chromium's and Electron's sandbox, a nested bubblewrap, and `unshare`. "+"**Removes code-execution isolation** — in any folder a hostile command may write, it can then bypass filesystem.denyWrite, filesystem.denyRead, credentials.files entries and the paths the sandbox always write-protects (such as .claude/settings.json, git hooks and git config), "+"and so plant code that later runs outside the sandbox; while autoAllowBashIfSandboxed is on, the command that plants it needs no approval. Default: false. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+`true from ${us} is ignored (false there still applies).`),enableWeakerNetworkIsolation:v().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. "+ly),allowAppleEvents:v().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:k(h()).optional().describe("Command patterns (Bash permission-rule syntax) for commands to run outside the sandbox. An entry takes a call out of the sandbox only when every command in the call matches an entry: in a Bash pipe or a chain such as `a && b`, each part needs its own match. Some calls stay sandboxed whatever the entries, such as one with a `cd`, a command substitution, or a redirect other than a file-descriptor duplication like `2>&1`, a heredoc included. A convenience, not a security boundary: excluded commands still go through the permission flow. Merged across settings sources. "+zc),ripgrep:O({command:h(),args:k(h()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support. "+"Only honored from user, managed/policy, or CLI (--settings) settings — "+"project settings (.claude/settings.json and .claude/settings.local.json) are ignored."),bwrapPath:Me((e)=>typeof e==="string"&&vY(e)?e:void 0,h()).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:Me((e)=>typeof e==="string"&&vY(e)?e:void 0,h()).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 Aa=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],LYe=[...Aa],MY=LYe;function jc(e){return e==="manual"?"default":e}var oUt=`Cannot set permission mode: must be one of ${Aa.join(", ")}`;var sUt={dangerousRemoval:{bypassImmune:!0,waivableInBypass:!0,classifierRouted:!0,autoModeDeny:!0,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},backgroundOperator:{bypassImmune:!1,waivableInBypass:!1,classifierRouted:!0,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},suspiciousWindowsPath:{bypassImmune:!1,waivableInBypass:!1,classifierRouted:!0,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},isolatePeerMachines:{bypassImmune:!0,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},restrictedMode:{bypassImmune:!0,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},outsideReadsBlocked:{bypassImmune:!0,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},claudeSettingsFile:{bypassImmune:!1,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!0,localProjectionOnly:!1,servedUnplaceable:!1},internalHardDeny:{bypassImmune:!1,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!0},connectorFileSend:{bypassImmune:!0,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!1,localProjectionOnly:!1,servedUnplaceable:!1},unfinishedCheck:{bypassImmune:!0,waivableInBypass:!1,classifierRouted:!1,autoModeDeny:!1,hostPersonOnly:!0,localProjectionOnly:!1,servedUnplaceable:!1},...{},...{},...{}};var MYe=["auto_mode_no_check_in_session","auto_mode_stop_no_check_in_session","auto_mode_stop_no_result_for_calls","auto_mode_stop_no_verdict"],iUt=["classifier_transcript_too_long","outside_reads_blocked","memory_paused",...MYe];var NY=["auto","iterm2","terminal_bell","iterm2_with_bell","kitty","ghostty","notifications_disabled"];var UY=["normal","vim"];var FY=["auto","12-hour","24-hour","24-hour-utc"],HY=["auto","tmux","iterm2","in-process"],NYe=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],$Y=["auto",...NYe],zY=["auto","alwaysAsk","disabled"],BY=1e5,jY=1e6;var UYe=Ge,FYe=Xe,iv=D("ZodDeferredOptional",(e,t)=>{UYe.init(e,t),FYe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Object.defineProperty(e._zod,"innerType",{get:t.built,configurable:!0}),e._zod.processJSONSchema=(n,r,o)=>{let s=t.getter();Je(s,n,o),n.seen.get(e).ref=s},cd(e._zod,"values",()=>{let n=t.getter()._zod.values;return n?new Set([...n,void 0]):void 0}),cd(e._zod,"pattern",()=>{let n=t.getter()._zod.pattern;return n?new RegExp(`^(${ld(n.source)})?$`):void 0}),cd(e._zod,"propValues",()=>t.getter()._zod.propValues),e._zod.parse=(n,r)=>{if(n.value===void 0)return n;return t.getter()._zod.run(n,r)},e.unwrap=t.getter});function or(e){let t;return new iv({type:"lazy",getter:()=>{if(t===void 0){let r=e();if(r._zod.optin!==void 0)throw Error("deferredOptional(): the schema the build callback returned already handles a missing key itself (.optional(), .catch(), .default(), .prefault(), z.preprocess(), or a union or wrapper holding one). Return the plain schema and let deferredOptional() make it optional, or use that schema with .optional() without deferring it.");t=r}return t},built:()=>t})}var HYe=String.raw`\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}`;function KY(e){return new RegExp(HYe).test(e)}var GY=/(?<![^\s\p{P}])\p{M}+/gu;function $Ye(e){return Sm(jYe(Fu(e))).replace(/ {2,}/g," ").trim()}var zYe=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/g,BYe=4;function jYe(e){let t=e;for(let n=0;n<BYe;n++){let r=t.replace(zYe,"");if(r===t)break;t=r}return t}function av(e,t=160){return KYe($Ye(GYe(e,t)).normalize("NFC").replace(/[`\uff40\u02cb\u1fef\u2035]/g,"'").replace(GY,""),t)}var SUt=new RegExp(`[^\\S ]|[${Ir}]`,"u");function KYe(e,t=2000){return e.length>t?`${ws(e,t)}…`:e}function GYe(e,t){let n=ws(e,t*8);if(n.length===e.length)return n;let r=/\x1b(?:[\]PX^_][^\x1b\x07]*\x1b?|\[[\x30-\x3f]*[\x20-\x2f]*)$/.exec(n);if(r===null)return n;let o=e.slice(r.index);return(o[1]==="["?/^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/.test(o):/^\x1b[\]PX^_][^\x1b\x07]*(?:\x07|\x1b\\)/.test(o))?n.slice(0,r.index):n}var CUt=Le({accepted:!1},(e)=>{e.accepted=!1});function lv(e){let t=XYe();return Object.hasOwn(t,e)?t[e]:e}var WY="workspace",xUt=`mcp__${WY}__bash`,kUt=`mcp__${WY}__web_fetch`;function qp(e){return e.includes("*")}function VYe(e){return e.replaceAll("\\","\\\\").replaceAll("(","\\(").replaceAll(")","\\)")}function qYe(e){return YYe(e).replaceAll("\\\\","\\")}function YYe(e){return e.replaceAll("\\(","(").replaceAll("\\)",")")}function cv(e){if(typeof e==="string"&&!e.includes("(")&&!e.includes(")"))return{kind:"bare"};let t=ZYe(e,"("),n=JYe(e,")");if(t===-1&&n===-1)return{kind:"bare"};let r=e.substring(0,t);if(t===-1||n<=t||n!==e.length-1||/[()]/.test(r))return{kind:"malformed"};return{kind:"call",toolName:r,rawContent:e.substring(t+1,n)}}function VY(e){let t=cv(e);if(t.kind!=="call"||!t.toolName)return{toolName:lv(e)};if(t.rawContent===""||t.rawContent==="*")return{toolName:lv(t.toolName)};let n=qYe(t.rawContent);return{toolName:lv(t.toolName),ruleContent:n}}function sr(e){if(!e.ruleContent)return e.toolName;let t=VYe(e.ruleContent);return`${e.toolName}(${t})`}function ZYe(e,t){for(let n=0;n<e.length;n++)if(e[n]===t){let r=0,o=n-1;while(o>=0&&e[o]==="\\")r++,o--;if(r%2===0)return n}return-1}function JYe(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){let r=0,o=n-1;while(o>=0&&e[o]==="\\")r++,o--;if(r%2===0)return n}return-1}function XYe(){return u_}function Yp(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");if(e.startsWith("claude.ai "))t=t.replace(/_+/g,"_").replace(/^_|_$/g,"");return t}function qY(){return{active:!1,enforcesGrants:!1,readLegacyKeyOwner:()=>{return},claimLegacyKeyOwner:async()=>{return},legacyKeyOwners:new Map,unsavedLegacyKeys:new Set,refusedLegacyKeys:new Map,claimedMayNotOwn:new Set,notedMayNotOwn:new Set,needsRebuild:!1,servers:new Map,tools:new Map,wireByInternal:new Map,internalByWire:new Map,wireKeyByInternalKey:new Map,internalKeyByWireKey:new Map,keptLegacyNames:0,serverKeyMoved:!1,sessionKeyById:new Map,formerKeys:new Map,formerSessionKeys:new Map,spelledKeys:new Map,otherDenyOrAskNames:new Map,retiredWireNames:new Map,wireHolders:new Map,sentWires:new Map}}var n0t=new Rs(qY),r0t=new Te(()=>({used:!1})),o0t=qY();function QYe(e,t){return e.value===!t&&e.source==="payload"&&e.defaultHost?!t:t}class uv{reader=null;register(e){let t=this.reader;return this.reader=e,t}read(e,t){let n=this.reader;if(!n)return t;try{return QYe(n(e,t),t)}catch{return t}}}var l0t=new uv;var e4e={always_allow:!0,always_ask:!0,always_deny:!0};function t4e(e){return typeof e==="string"&&Object.hasOwn(e4e,e)}function dv(e){if(!oe(e)||typeof e.name!=="string")return;let{name:t,permission_policy:n}=e;if(n===void 0)return{policy:{name:t},rewritten:!1};return t4e(n)?{policy:{name:t,permission_policy:n},rewritten:!1}:{policy:{name:t,permission_policy:"always_ask"},rewritten:!0}}function YY(e,t){if(e===void 0||t===void 0)return e===t;return e.length===t.length&&e.every((n,r)=>n.name===t[r]?.name&&n.permission_policy===t[r]?.permission_policy)}var n4e=64,r4e=128;function pv(e){if(!oe(e))return{settings:{},ignored:[]};let{timeout:t,disableAutoBackground:n,tools:r,connectorId:o,autoModeVerdictTools:s}=e,i=o_(t),a=[];if(t!==void 0&&i===void 0)a.push("timeout");if(n!==void 0&&typeof n!=="boolean")a.push("disableAutoBackground");let l=o4e(r);if(fv(e)!==void 0)a.push("tools");let c=typeof o==="string"&&o!=="";if(o!==void 0&&!c)a.push("connectorId");let d=Array.isArray(s)?s.filter((f)=>typeof f==="string"&&f.length<=r4e):[],p=Array.isArray(s)&&s.length<=n4e&&d.length===s.length;if(s!==void 0&&!p)a.push("autoModeVerdictTools");return{settings:{...i!==void 0&&{timeout:i},...n===!0&&{disableAutoBackground:n},...l!==void 0&&{tools:l},...c&&{connectorId:o},...p&&{autoModeVerdictTools:d}},ignored:a}}function fv(e){let t=oe(e)?e.tools:void 0;if(t===void 0)return;if(!Array.isArray(t))return{kind:"not_a_list"};let n=0,r=0;for(let o of t){let s=dv(o);if(s===void 0)n++;else if(s.rewritten)r++}return n+r>0?{kind:"entries",dropped:n,rewritten:r,kept:t.length-n}:void 0}function ZY(e){if(e.kind==="not_a_list")return"tools[] is not a list; no per-tool policy taken";let t=[];if(e.dropped>0)t.push(`dropped ${e.dropped} malformed tools[] ${e.dropped===1?"entry":"entries"}`);if(e.rewritten>0)t.push(`read ${e.rewritten} tools[] ${e.rewritten===1?"entry":"entries"} with an invalid permission_policy as always_ask`);return`${t.join(", ")}; kept ${e.kept}`}function o4e(e){if(!Array.isArray(e))return;let t=[];for(let n of e){let r=dv(n);if(r!==void 0)t.push(r.policy)}return t}var s4e="mcp__";function Kc(e){let t=e.split("__"),[n,r,...o]=t;if(n!=="mcp"||!r)return null;let s=o.length>0?o.join("__"):void 0;return{serverName:r,toolName:s}}function mv(e){return`${s4e}${Yp(e)}__`}function JY(e){return Kc(`${mv(e)}t`)===null}function XY(e){return e in Object.prototype&&JY(e)}var fy="server names may only contain letters, numbers, hyphens and underscores, and may not be constructor, prototype, __proto__, __defineGetter__, __defineSetter__, __lookupGetter__ or __lookupSetter__";var U0t=P(()=>K(["local","user","project","dynamic","enterprise","claudeai","managed","agent"]));var i4e=/^[A-Za-z0-9_-]+$/;var Gc=P(()=>U("comms").optional().catch(void 0)),Ti=P(()=>Y().int().positive()),a4e=300000,QY=P(()=>Y().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));function e4({request_timeout_ms:e,...t}){return{...t,...t.timeout===void 0&&e!==void 0&&{timeout:Math.min(e,a4e)}}}var l4e=P(()=>O({type:U("stdio").optional(),command:h().min(1,"Command cannot be empty"),args:k(h()).default([]),env:q(h(),h()).optional(),timeout:Ti().optional(),alwaysLoad:v().optional(),bareElicitationCapability:v().optional(),role:Gc()})),c4e=P(()=>v()),u4e=65536,Wc=()=>h().refine((e)=>e.length<=u4e,{abort:!0,message:"url is too long"}),d4e=4096,t4=P(()=>O({clientId:h().optional(),callbackPort:Y().int().positive().optional(),authServerMetadataUrl:h().refine((e)=>e.length<=d4e,{abort:!0,message:"authServerMetadataUrl is too long"}).url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:h().min(1).optional(),xaa:c4e().optional()})),gv=P(()=>O({name:h(),permission_policy:K(["always_allow","always_ask","always_deny"]).optional()})),n4=P(()=>O({type:U("sse"),url:Wc(),headers:q(h(),h()).optional(),headersHelper:h().optional(),oauth:t4().optional(),timeout:Ti().optional(),request_timeout_ms:QY(),tools:k(gv()).optional(),alwaysLoad:v().optional(),displayName:h().optional().catch(void 0),bareElicitationCapability:v().optional(),discoveryCache:v().optional(),role:Gc(),toolPermissions:q(h(),Sv()).optional()}).transform(e4)),p4e=P(()=>O({type:U("sse-ide"),url:Wc(),ideName:h(),ideRunningInWindows:v().optional(),timeout:Ti().optional(),alwaysLoad:v().optional(),role:Gc()})),f4e=P(()=>O({type:U("ws-ide"),url:Wc(),ideName:h(),authToken:h().optional(),ideRunningInWindows:v().optional(),timeout:Ti().optional(),alwaysLoad:v().optional(),role:Gc()})),r4=P(()=>O({type:K(["http","streamable-http"]).transform(()=>"http"),url:Wc(),headers:q(h(),h()).optional(),headersHelper:h().optional(),oauth:t4().optional(),timeout:Ti().optional(),request_timeout_ms:QY(),tools:k(gv()).optional(),alwaysLoad:v().optional(),displayName:h().optional().catch(void 0),bareElicitationCapability:v().optional(),discoveryCache:v().optional(),role:Gc(),toolPermissions:q(h(),Sv()).optional()}).transform(e4)),m4e=["command","args","env","headersHelper"],g4e=new Set(["http","streamable-http","sse"]),h4e=/[\p{Cc}\p{Cf}\u2028\u2029]/u,_4e=/[\p{Cc}\p{Cf}\u2028\u2029]/gu;function hv(e){return/^[A-Za-z0-9_-]+$/.test(e)&&!XY(e)&&e!=="constructor"&&e!=="prototype"}function y4e(e){try{let t=new URL(e);return t.protocol==="https:"&&t.hostname!==""}catch{return!1}}function o4(e,t="",n=0){if(typeof e==="string")return[[t,e,!1]];if(n>4||e===null||typeof e!=="object")return[];return Object.entries(e).flatMap(([r,o])=>{let s=r.replace(_4e,(a)=>`\\u${a.codePointAt(0).toString(16).padStart(4,"0")}`),i=t?`${t}.${s}`:s;return[[i,r,!0],...o4(o,i,n+1)]})}var _v=P(()=>q(h(),me()).check((e)=>{let t=(r,o)=>{e.issues.push({code:"custom",path:r,message:o,input:e.value})};for(let r of m4e)if(Object.hasOwn(e.value,r))t([r],`"${r}" is not allowed in managed settings: only http/sse URL servers can be delivered this way, and a managed settings document must not name a program to run`);if(!g4e.has(e.value.type))t(["type"],'managed settings can only deliver "http" or "sse" servers');let n=e.value.url;if(typeof n==="string"&&!y4e(n))t(["url"],"managed settings servers must use a valid https:// url");for(let[r,o,s]of o4(e.value))if(h4e.test(o))t(r.split("."),"contains control or invisible format characters (in a key or a value); a managed settings document must not be able to print escape sequences");else if(!s&&KY(o))t(r.split("."),"${VAR} references are not expanded in managed settings; use a literal value (a managed settings document must not read the user's environment)")}).pipe(ie([r4(),n4()]))),yv=`"managedMcpServers" must be an object keyed by server name (the .mcp.json mcpServers shape; Claude Desktop's array form of its same-named key is not accepted here: use the server name as the key and "type" instead of "transport"). No managed MCP servers are installed from it until it is fixed.`;function my(e,t){if(e===void 0)return;if(e===null||typeof e!=="object"||Array.isArray(e)){t("",yv);return}let n=Object.create(null);for(let[r,o]of Object.entries(e)){if(!hv(r)){t("<invalid name>",fy);continue}let s=_v().safeParse(o);if(s.success){n[r]=s.data;continue}let i=s.error.issues[0];t(r,i?[i.path.join("."),i.message].filter(Boolean).join(": "):"failed validation")}return n}var S4e=P(()=>O({type:U("ws"),url:Wc(),headers:q(h(),h()).optional(),headersHelper:h().optional(),timeout:Ti().optional(),alwaysLoad:v().optional(),bareElicitationCapability:v().optional(),role:Gc()})),E4e=P(()=>O({type:U("sdk"),name:h(),timeout:Ti().optional(),alwaysLoad:v().optional(),disableAutoBackground:v().optional().catch(void 0),tools:k(gv()).optional().catch(void 0),connectorId:h().min(1).optional().catch(void 0),autoModeVerdictTools:k(h()).optional().catch(void 0)})),Sv=P(()=>K(["allow","ask","blocked"])),b4e=P(()=>O({type:U("claudeai-proxy"),url:Wc(),id:h().regex(i4e),displayName:h().optional(),urlReportable:v().optional(),noDirectoryEntry:v().optional(),iconUrl:h().optional(),timeout:Ti().optional(),alwaysLoad:v().optional(),toolPermissions:q(h(),Sv()).optional(),stateless:v().optional(),cachedInitResponse:q(h(),me()).nullish(),discoverSupport:K(["supported","legacy","unknown"]).optional().catch(void 0),cachedDiscoverResponse:q(h(),me()).nullish(),eligible:v().nullish(),ineligibleReason:h().nullish(),enterpriseManaged:v().optional()})),gy=P(()=>ie([l4e(),n4(),p4e(),f4e(),r4(),S4e(),E4e(),b4e()]));var F0t=P(()=>O({mcpServers:q(h(),gy())}));var Zp=["anthropic","customEndpoint","bedrock","vertex","foundry","anthropicAws","mantle","gateway"],C4e=/^anthropic[A-Z][A-Za-z0-9]*$/,A4e=new Set(Zp);function Ev(e){return typeof e==="string"&&A4e.has(e)}function bv(e){return Ev(e)||typeof e==="string"&&C4e.test(e)}var Ra="Your session can't run on this machine",z0t=`${Ra}: its requests must go to Anthropic's API or a cloud provider this machine is set up for, so a gateway, a custom endpoint, or a project's provider, credential or model settings aren't allowed. Remove the setting, such as ANTHROPIC_BASE_URL, from wherever it's set, or ask whoever runs this machine to.`,B0t=`${Ra}: an env entry in a project's .claude settings file changes the provider settings, credentials, proxy, certificates, headers, request body or auto mode settings this machine is set up with. Remove that entry, set the same value on the machine, or ask whoever runs this machine to.`,j0t=`${Ra}: none of the models allowed for its auto mode check can be used here. Ask whoever runs this machine to update Claude Code or use a provider that offers one of them, and ask your organization's administrator whether its model settings block them or, on Microsoft Foundry, to map one to a deployment.`,K0t=[`${Ra}: its requests must go straight to Anthropic's API, and this machine sends them somewhere else. Remove what does that, or ask whoever runs this machine to. It is usually a setting such as CLAUDE_CODE_USE_BEDROCK or ANTHROPIC_BASE_URL, in the environment, in managed settings or in a Claude Code settings file such as the project's .claude/settings.json.`,`${Ra}: its requests must go to Anthropic's API, or straight to a cloud provider Anthropic allows for these sessions with no custom endpoint, and this machine sends them somewhere else. Remove the custom endpoint, gateway or provider setting that does that, in the environment, managed settings or a Claude Code settings file, or ask whoever runs this machine to.`,`${Ra}: it needs the server's auto mode check, and CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS turns that off here. Remove it from the environment, managed settings or the Claude Code settings file that sets it, or ask whoever runs this machine to.`],G0t=`${Ra}: it needs the server's auto mode check, and your organization's compliance policy rules that out, so this kind of session can't run for your organization.`;var q0t=st()==="macos"?"⏺":"●";var R4e=new Set(["Claude Preview","Claude Browser"]),O4e=new Set(["claude-in-chrome","Claude in Chrome"]),lFt=new Set([...O4e,...R4e]);var T4e=["Claude_Browser__"],w4e=["claude-in-chrome__","Claude_in_Chrome__"],cFt=[...T4e,...w4e];var SFt=P(()=>Me(jc,K(MY))),EFt=P(()=>Me(jc,K(Aa)));import{posix as K4e,win32 as G4e}from"path";var s4={".ts":"ts",".tsx":"tsx",".jsx":"jsx",".js":"js",".mjs":"js",".cjs":"js",".mts":"ts",".cts":"ts"};var Cv=Object.keys(s4);var k4e=`${Cv.slice(0,-1).join(", ")} or `+String(Cv.at(-1));import{isIPv4 as P4e,isIPv6 as I4e}from"net";var D4e=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal","ip6-localhost","ip6-loopback","localhost.localdomain","localhost4","localhost4.localdomain4","localhost6","localhost6.localdomain6"]),a4=new Set(["100.100.100.200","168.63.129.16","192.0.0.192"]);function l4(e,t,n,r){return e===127||e===169&&t===254||e===0}function L4e(e){let t=e.indexOf("%"),r=(t>=0?e.slice(0,t):e).toLowerCase().split("::");if(r.length>2)return;let o=r[0]?r[0].split(":"):[],s=r.length===2&&r[1]?r[1].split(":"):[],i=r.length===2?s:o,a=[],l=i.at(-1);if(l!==void 0&&l.includes(".")){let m=l.split(".").map(Number);if(m.length!==4||m.some((g)=>!Number.isInteger(g)||g<0||g>255))return;a=m,i.pop()}let c=(m)=>{let g=[];for(let _ of m){if(!/^[0-9a-f]{1,4}$/.test(_))return;let y=parseInt(_,16);g.push(y>>8,y&255)}return g},d=c(r.length===2?o:[]),p=c(i);if(d===void 0||p===void 0)return;let f=d.length+p.length+a.length;if(f>16||r.length===1&&f!==16)return;return[...d,...Array(16-f).fill(0),...p,...a]}function M4e(e){return c4(e)&&e[4]===0&&e[5]===1}function c4(e){return e[0]===0&&e[1]===100&&e[2]===255&&e[3]===155}function N4e(e){let t=[];if(e[0]===32&&e[1]===2)t.push(e.slice(2,6));let n=e.slice(0,10).every((a)=>a===0),r=n&&e[10]===255&&e[11]===255,o=n&&e[10]===0&&e[11]===0,s=c4(e)&&e.slice(4,12).every((a)=>a===0),i=(e[8]===0||e[8]===2)&&e[9]===0&&e[10]===94&&e[11]===254;if(r||o||s||i)t.push(e.slice(12,16));return t}function u4(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t.endsWith("."))t=t.slice(0,-1);if(t===""||t==="localhost"||t.endsWith(".localhost"))return!0;if(D4e.has(t))return!0;if(t.startsWith("instance-data.")&&t.endsWith(".compute.internal"))return!0;if(P4e(t)){if(a4.has(t))return!0;let[r=0,o=0,s=0,i=0]=t.split(".").map(Number);return l4(r,o,s,i)}if(!I4e(t))return!1;let n=L4e(t);if(n===void 0)return!0;if(M4e(n))return!0;if(n.every((r)=>r===0))return!0;if(n.slice(0,15).every((r)=>r===0)&&n[15]===1)return!0;if(t==="fd00:ec2::254")return!0;if(n[0]===254&&(n[1]??0)>=128&&(n[1]??0)<=191)return!0;return N4e(n).some((r)=>{let[o=0,s=0,i=0,a=0]=r;return l4(o,s,i,a)||a4.has(`${o}.${s}.${i}.${a}`)})}var d4=["bash","powershell"];var p4=P(()=>K(["continue","block"]).optional());var Jp=P(()=>h().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.')),f4=P(()=>p4().describe("What a failure of this hook does: it could not start (a missing script or plugin directory), timed out, exited with a code other than 0 or 2, or printed JSON that is invalid or fails validation. 'continue' (default): the failure is reported and the action goes ahead. 'block': the failure counts as exit code 2, so the action the event guards (a tool call, a permission request, a prompt) is blocked. Ignored for async hooks and on Stop, SubagentStop, TaskCompleted and TeammateIdle."));function U4e(){let e=O({type:U("command").describe("Shell command hook type"),command:h().describe("Shell command to execute"),args:k(h()).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:Jp(),shell:K(d4).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:Y().positive().optional().describe("Timeout in seconds for this specific command"),onFailure:f4(),statusMessage:h().optional().describe("Custom status message to display in spinner while hook runs"),once:v().optional().describe("If true, hook runs once and is removed after execution"),async:v().optional().describe("If true, hook runs in background without blocking"),asyncRewake:v().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:h().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:h().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".'),cloud:K(["device","skip"]).optional().catch("skip").describe("@internal Where this hook may run when a cloud session is driven from this machine. 'device': offer it to the cloud session and run it here even when its script sits where the cloud session can write on this machine or cannot be pinned — the author accepts that the session may have changed files this hook executes. 'skip': never offer it to cloud sessions. Omit for the default: a command hook whose script could be read and pinned and lies outside everything the cloud session can write here is offered; other command hooks are not. Applies to this entry only: the same hook written in another settings scope keeps its own setting. An unrecognised value reads as 'skip' (the file still loads; the hook stays on this machine).")}),t=O({type:U("prompt").describe("LLM prompt hook type"),prompt:h().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:Jp(),timeout:Y().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:h().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:v().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:h().optional().describe("Custom status message to display in spinner while hook runs"),once:v().optional().describe("If true, hook runs once and is removed after execution")}),n=O({type:U("mcp_tool").describe("MCP tool hook type"),server:h().describe("Name of an already-configured MCP server to invoke"),tool:h().describe("Name of the tool on that server to call"),input:q(h(),me()).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:Jp(),timeout:Y().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:h().optional().describe("Custom status message to display in spinner while hook runs"),once:v().optional().describe("If true, hook runs once and is removed after execution")}),r=O({type:U("http").describe("HTTP hook type"),url:h().url().describe("URL to POST the hook input JSON to"),if:Jp(),timeout:Y().positive().optional().describe("Timeout in seconds for this specific request"),onFailure:f4(),headers:q(h(),h()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:k(h()).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:h().optional().describe("Custom status message to display in spinner while hook runs"),once:v().optional().describe("If true, hook runs once and is removed after execution"),cloud:K(["device","skip"]).optional().catch("skip").describe("@internal Where this hook may run when a cloud session is driven from this machine. 'skip': never offer it to cloud sessions; 'device' or omitted: offered (an HTTP hook has no script to pin). Applies to this entry only. An unrecognised value reads as 'skip' (the file still loads).")}),o=O({type:U("agent").describe("Agentic verifier hook type"),prompt:h().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:Jp(),timeout:Y().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:h().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:h().optional().describe("Custom status message to display in spinner while hook runs"),once:v().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:r,AgentHookSchema:o,McpToolHookSchema:n}}var hy=P(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:r,McpToolHookSchema:o}=U4e();return oa("type",[...[e,t,n,r,o]])}),Av=P(()=>O({matcher:h().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:k(hy()).describe("List of hooks to execute when the matcher matches")})),wa=P(()=>J0(K(ts),k(Av())));function _y(){return new Set(hy().options.map((e)=>e.shape.type.value))}function F4e(e,t){if(!e||typeof e!=="object"||Array.isArray(e)){let o=Oa(e);return{problem:`Hook entry must be an object; received ${o}`,received:o,aboutType:!1}}let n=e.type;if(typeof n!=="string"){let o=Oa(n);return{problem:n===void 0?'Hook entry has no "type"':`Hook entry "type" must be a string; received ${o}`,received:o,aboutType:!0}}if(!t.has(n)){let o=hm(n);return{problem:`Unknown hook type "${o}"`,received:o,aboutType:!0}}let r=hy().safeParse(e);if(!r.success)return{problem:`Invalid ${n} hook (${m4(r.error)})`,received:n,aboutType:!1};return}function m4(e){return e.issues.map((t)=>t.path.length>0?`${t.path.join(".")}: ${t.message}`:t.message).join("; ")}function yy(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;if(!("matcher"in e)&&Object.keys(e).some((n)=>ts.includes(n)))return!1;let t=e.hooks;if(Array.isArray(t))return t.length>0;return!!t&&typeof t==="object"&&(("matcher"in e)||typeof t.type==="string")}function Ta(e,t=3,{matchersCount:n=!0,unscannedKeys:r=H4e,inHooksList:o=!1}={}){if(_4(e))return!0;if(n&&yy(e))return!0;if(t===0||!e||typeof e!=="object")return!1;if(Array.isArray(e))return e.some((s)=>Ta(s,t-1,{matchersCount:n,unscannedKeys:r,inHooksList:o}));if(o&&typeof e.type==="string")return!1;return Object.entries(e).some(([s,i])=>!r.has(s)&&Ta(i,t-1,{unscannedKeys:r,matchersCount:n&&!ts.includes(s),inHooksList:s==="hooks"&&Array.isArray(i)}))}function g4(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return!1;return _4(e)||Object.entries(e).some(([n,r])=>n!=="hooks"&&!t.has(n)&&Ta(r,3,{unscannedKeys:t,matchersCount:!ts.includes(n)}))}var H4e=new Set,h4=new Set(["mcpServers","managedMcpServers","lspServers","pluginConfigs","enabledPlugins","extraKnownMarketplaces","env","skillOverrides","modelSettings"]),$4e=new Set(["metadata","mcpServers","lspServers"]),zFt=new Set([...$4e,"experimental"]);function _4(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;return Object.entries(e).some(([t,n])=>Xp.has(t)&&n!==null&&n!==void 0&&!(Array.isArray(n)&&n.length===0))}function Rv(e){if(yy(e))return!0;if(Array.isArray(e))return e.some(Rv);if(!e||typeof e!=="object")return!1;return Object.entries(e).some(([t,n])=>Xp.has(t)&&n!==null&&n!==void 0&&!(Array.isArray(n)&&n.length===0))}var Xp=new Set(["PreToolUse","PermissionRequest"]);function y4(e,t){if(!Array.isArray(e))return{stripped:[],unloadableGuards:[]};let n=Xp.has(t),r=_y(),o=Av(),s=[],i=[];for(let a=e.length-1;a>=0;a--){let l=e[a],c=(m,g)=>{if(!n)e.splice(a,1);s.push({matcherIndex:a,hookIndex:void 0,path:`${a}`,problem:m,received:g,aboutType:!1})};if(Ta(l,3,{matchersCount:!1})){(n?s:i).push({matcherIndex:a,hookIndex:void 0,path:`${a}`,problem:"holds PreToolUse/PermissionRequest hooks where a matcher was expected",received:Oa(l),aboutType:!1});continue}if(!l||typeof l!=="object"||Array.isArray(l)){c(`Hook matcher must be an object; received ${Oa(l)}`,Oa(l));continue}let d=l.hooks;if(!Array.isArray(d)){c(`Hook matcher "hooks" must be an array of hook entries; received ${Oa(d)}`,Oa(d));continue}let p=[];for(let m=d.length-1;m>=0;m--){let g=F4e(d[m],r);if(g!==void 0){if(!n)d.splice(m,1);p.push({matcherIndex:a,hookIndex:m,path:`${a}.hooks.${m}`,...g})}}let f=o.safeParse(n?{...l,hooks:[]}:l);if(!f.success){c(`Invalid hook matcher (${m4(f.error)})`,"matcher");continue}s.push(...p)}return s.reverse(),i.reverse(),n?{stripped:[],unloadableGuards:s}:{stripped:s,unloadableGuards:i}}var ds="a PreToolUse/PermissionRequest hook that cannot be loaded may be what guards the permissions declared beside it, so nothing it sits in is applied until the entry is fixed or removed";function Oa(e){if(e===null||e===void 0)return String(e);if(Array.isArray(e))return"an array";let t=typeof e;return`${t==="object"?"an":"a"} ${t}`}var S4=new Set(["http","https","ws","wss","ftp"]);function va(e){e=e.replace(/^[\x00-\x20]+/,"").replace(/[\t\n\r]/g,"");let t=e.indexOf("://");if(t===-1)return!1;let n=e.slice(t+3),r=e.slice(0,t).toLowerCase();if(S4.has(r)){let i=n.match(/^[/\\]+/)?.[0]??"";if(i.includes("\\"))return!0;n=n.slice(i.length)}let o=n.search(/[/?#]/);return(o===-1?n:n.slice(0,o)).includes("\\")}var xn="github.com",VFt=[`git@${xn}:`,`ssh://git@${xn}/`],qFt=[`https://${xn}`,`https://${xn}/`,xn],YFt=`users.noreply.${xn}`;var z4e=/[:/\\?#@\s]/;function Qp(e){let t=b4(e.replace(/[\t\n\r]/g,"").toLowerCase());if(t===""||z4e.test(t))return t;try{let n=new URL(`https://${t}`);if(n.username!==""||n.password!==""||n.port!==""||n.pathname!=="/"||n.search!==""||n.hash!=="")return t;return b4(n.hostname)}catch{return t}}var C4=U_(function(t){let n=Qp(t);while(n.startsWith("www."))n=n.slice(4);return n},(e)=>e,50);function A4(e,t){return C4(e)===t}function wi(e){return A4(e,xn)}function E4(e){return/[%\x00-\x1f\x7f-\u{10FFFF}]/u.test(e)}function Ov(e){if(ol(e))return!0;if(e.includes("://")){if(va(e))return!0;try{let o=new URL(e);if(o.protocol==="http:"||o.protocol==="https:")return!1;return E4(o.hostname)}catch{return!0}}let t=e.indexOf(":"),n=e.indexOf("@");if(t>=0&&n>t)return!0;let r=e.match(/^(?:[^@]+@)?([^:]+):/)?.[1];return r?E4(r):!1}function b4(e){let t=e.length;while(t>0&&e[t-1]===".")t--;return e.slice(0,t)}function Tv(e){let t=Qp(e);return wi(t)?xn:t}function R4(e){let t=e.trimStart(),n=/^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(t);if(n===null||/^https?$/i.test(n[1]??""))return Fo(t);return Fo(n[0]+Ku(t.slice(n[0].length)))}function O4(e){let t=/^([^@:/[\]]+)@([^@:/[\]]+):(.*)$/s.exec(e);return t&&!ol(e)?{user:t[1],host:t[2],path:t[3]}:null}var j4e=64;class Vc{fields;activeWhenAbsent;keys;built=new Map;byPresentKeys=new Map;wholeSchema;constructor(e,t=new Set){this.fields=e;this.activeWhenAbsent=t;this.keys=Object.keys(e).filter((n)=>e[n]!==void 0)}has(e){return Object.hasOwn(this.fields,e)&&this.fields[e]!==void 0}field(e){let t=this.built.get(e);if(t)return t;let n=this.has(e)?this.fields[e]:void 0;if(!n)return;let r=n();return this.built.set(e,r),r}carries(e,t){return this.activeWhenAbsent.has(t)||typeof e==="object"&&e!==null&&t in e}whole(){return this.wholeSchema??=O(this.shapeOf(this.keys)).passthrough(),this.wholeSchema}forDocument(e,t="passthrough"){let n=this.keys.filter((a)=>this.carries(e,a));if(n.length===this.keys.length&&t==="passthrough")return this.whole();let r=`${t}
|
|
149
149
|
${n.join(`
|
|
150
|
-
`)}`,o=this.byPresentKeys.get(r);if(o)return this.byPresentKeys.delete(r),this.byPresentKeys.set(r,o),o;let s=this.shapeOf(n),i=t==="strip"?Me((a,l)=>{for(let c of this.wrongDocumentIssues(a,s))l.addIssue(c);return a},O(s)):O(s).passthrough().check((a)=>{a.issues.push(...this.wrongDocumentIssues(a.value,s))});if(this.byPresentKeys.size>=j4e)for(let a of this.byPresentKeys.keys()){this.byPresentKeys.delete(a);break}return this.byPresentKeys.set(r,i),i}wrongDocumentIssues(e,t){if(typeof e!=="object"||e===null)return[];let n=[];for(let r of Object.keys(e))if(!Object.hasOwn(t,r)&&this.has(r))n.push({code:"custom",input:e[r],path:[r],message:"This settings schema was built for a document without this key"});return n}shapeOf(e){let t={};for(let n of e){let r=this.field(n);if(r)t[n]=r}return t}}var T4=600;var Dv=500,W4e=32;function L4(){return{claudeaiPluginId:h().max(128).optional().catch(void 0),archiveSha256:gZ().optional().catch(void 0)}}function M4(){return{directoryRepositoryKey:h().max(4096).optional().catch(void 0)}}function Lv(e){if(!/^https?:\/\/[^/\\]/i.test(e))return!1;try{let{protocol:t}=new URL(e);return t==="https:"||t==="http:"}catch{return!1}}function N4(){return{npmVersionSpec:h().max(256).optional().catch(void 0),npmResolved:h().max(2048).optional().catch(void 0),npmIntegrity:h().max(256).optional().catch(void 0),npmRegistry:h().max(2048).refine(Lv).optional().catch(void 0)}}function U4(){return{sourceCommand:h().max(Dv+20).optional().catch(void 0).describe("The `command`-source command the user accepted at explicit install/update. The once-per-session background re-resolve only runs while the marketplace entry still declares this exact command; a changed command (or an entry that became command-sourced later) is skipped with a warning until the user runs an explicit update."),sourceProducerPath:h().max(4096).refine(w4,{message:"must be an absolute path"}).optional().catch(void 0).describe("The directory a `command`-source plugin was last resolved to (what its command printed). Served in place in link mode and re-copied every session in copy mode, so the sandbox write-denies it; refreshed on every install/update, including no-op updates that resolve to a new location."),previousProducerPaths:k(me()).transform((e)=>e.filter((t)=>typeof t==="string"&&t.length<=4096&&w4(t)).slice(-W4e)).optional().catch(void 0).describe("Producer directories this installation was resolved to before the current one (most recent last, bounded). A concurrent older session may still serve one of them, so the sandbox keeps write-denying them too.")}}function w4(e){return K4e.isAbsolute(e)||G4e.isAbsolute(e)}var F4=/[^\x20-\x7E]| {4,}/;function Mv(){return h().max(Dv,{message:"headersHelper must not be longer than the install consent UI can display"}).refine((e)=>!F4.test(e),{message:"headersHelper must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"})}var V4e="anthropic-plugin-directory",q4e=["healthcare"],H4=new Set(["claude-community","claude-plugins-community",...q4e]),$4=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins","claude-tag-plugins"]),Y4e=new Set([V4e,"claude-plugin-directory"]),Nv=new Set([...$4,...H4,...Y4e]);var z4=["marketplace","plugins","official"];function Z4e(){return z4}var B4="official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official",FHt=new RegExp(B4,"i");function j4(e){return new RegExp(`(?:${B4}|^(?:anthropic|claude)[^a-z0-9]*(${e.join("|")}))`,"i")}var J4e=j4(Z4e()),X4e=j4(z4),Q4e=/[^\u0020-\u007E]/;function K4(e){if(Nv.has(e.toLowerCase()))return!1;if(eZe(e))return!0;if(J4e.test(e))return!0;return!1}function eZe(e){return!Nv.has(e.toLowerCase())&&(Q4e.test(e)||X4e.test(e))}var ir=P(()=>h().startsWith("./")),xa=P(()=>ir().endsWith(".json")),v4=P(()=>ie([U("."),ir()])),x4=P(()=>ie([ir().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"),h().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),xv=P(()=>ir().endsWith(".md")),kv=P(()=>ie([xv(),ir()])),Uv={inline:"--plugin-dir session plugins",builtin:"built-in plugins","skills-dir":"plugins auto-loaded from .claude/skills/",synced:"plugins synced from your claude.ai account","claude-plugin-test":"plugins loaded by claude plugin test",npm:"plugins installed from an npm registry (`<package>@npm`); remove this marketplace and add it again under another name",pip:"plugins installed from a Python package index (reserved; not yet available)",uv:"plugins installed from a Python package index through uv (reserved; not yet available)",cargo:"plugins installed from a Rust crate registry (reserved; not yet available)",github:"plugins installed straight from a GitHub repository (`<owner>/<repo>@github`; reserved; not yet available)",gh:"plugins installed straight from a GitHub repository (reserved; not yet available)"},Fv="npm",tZe=["pip","uv","cargo","github","gh"];function Sy(e){return Object.hasOwn(Uv,e)}var nZe=[Fv,...tZe];function G4(e){return nZe.includes(e.toLowerCase())}function rZe(e,t){let n=e.toLowerCase();if(G4(n)&&Sy(n))t.addIssue({code:"custom",message:`Marketplace name "${n}" is reserved for ${Uv[n]}`})}var oZe="Marketplace name impersonates an official Anthropic/Claude marketplace",Hv=(e)=>h().min(1,"Marketplace must have a name").refine((t)=>!t.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine((t)=>!SZ.test(t),{message:"Marketplace name cannot contain control or bidirectional-formatting characters"}).refine((t)=>!t.includes("/")&&!t.includes("\\")&&!t.includes("..")&&t!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((t)=>!e(t),{message:oZe}).superRefine((t,n)=>{let r=t.toLowerCase();if(!Sy(r)||G4(r))return;n.addIssue({code:"custom",message:`Marketplace name "${r}" is reserved for ${Uv[r]}`})}),sZe=P(()=>Hv(K4)),iZe=P(()=>Hv(()=>!1));function aZe(e){return Hv(e).superRefine(rZe)}var Ey=P(()=>h().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).refine((e)=>!SZ.test(e),{message:"Plugin name cannot contain control or bidirectional-formatting characters"})),$v=P(()=>O({name:h().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:h().optional().describe("Contact email for support or feedback"),url:h().optional().describe("Website, GitHub profile, or organization URL")})),qn=P(()=>O({$schema:h().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:Ey().describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:h().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:h().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:h().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:$v().optional().describe("Information about the plugin creator or maintainer"),homepage:h().url().optional().describe("Plugin homepage or documentation URL"),repository:h().optional().describe("Source code repository URL"),license:h().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:k(h()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:v().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:k(r9e()).optional().describe(`Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin's own marketplace.`),metadata:Me((e)=>oe(e)?e:void 0,q(h(),me()).optional()).describe("Free-form metadata for the plugin author's own use (e.g. entitlement or catalog fields). Preserved on the parsed manifest but not read by Claude Code.")})),lZe=1,HHt=P(()=>O({$schema:h().optional().catch(void 0).describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),description:h().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:Sg(()=>wa()).optional().describe("The hooks provided by the plugin, in the same format as the one used for settings"),modules:k(h()).max(lZe,{message:"hooks.json `modules` names one hooks module per plugin; a second entry is refused"}).optional().describe(`The hooks module: one path, relative to this hooks.json, of a module exporting register(on). The module, and every file it imports from the plugin, is named like code (${k4e}; a file named otherwise is not loaded) and is an ES module whatever its suffix. What it hooks and calls is read from its source before it loads; \`claude plugin validate\` shows the result.`),surface:hg({error:'hooks.json `surface` is gone: name the module in the Client element, `Client({ module: "./board.tsx", key })`, a path relative to the file that builds it'}).optional()}).refine((e)=>e.hooks!==void 0||(e.modules?.length??0)>0,{message:"hooks.json must have `hooks` (the hook matchers) or `modules` (hooks modules), or both"})),W4=P(()=>O({hooks:ie([xa().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),Sg(()=>wa()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),k(ie([xa().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),Sg(()=>wa()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),cZe=P(()=>O({source:kv().optional().describe("Path to command markdown file, relative to plugin root"),content:h().optional().describe("Inline markdown content for the command"),description:h().optional().describe("Command description override"),argumentHint:h().optional().describe('Hint for command arguments (e.g., "[file]")'),model:h().optional().describe("Default model for this command"),allowedTools:k(h()).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'})),V4=P(()=>O({commands:ie([kv().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both."),k(kv().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."),q(h(),cZe()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),q4=P(()=>O({agents:ie([xv().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both."),k(xv().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.")])})),Y4=P(()=>O({skills:ie([v4().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself). Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan).'),k(v4().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself).')).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),uZe=P(()=>ie([h(),k(h())])),zv=P(()=>O({outputStyles:ie([ir().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — list its files here if you want both."),k(ir().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.")])})),dZe=P(()=>h().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),pZe=16,fZe=P(()=>O({id:dZe(),remote:h().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:h().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),mZe=P(()=>O({syntaxHighlighting:O({hljsLanguages:k(fZe()).max(pZe)}).strict()})),Bv=P(()=>O({themes:ie([ir().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — list its files here if you want both."),k(ir().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.")])})),Z4=P(()=>O({workflows:ie([ir().describe("Path to a workflows directory or .js file, relative to the plugin root. When set, the workflows/ directory is not auto-loaded — list its files here if you want both."),k(ir().describe("Path to a workflows directory or .js file, relative to the plugin root. When set, the workflows/ directory is not auto-loaded — list its files here if you want both.")).describe("List of workflow directory or .js file paths. When set, the workflows/ directory is not auto-loaded.")]).optional()})),k4=P(()=>h().min(1)),gZe=P(()=>h().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),J4=P(()=>O({mcpServers:ie([xa().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),x4().describe("Path or URL to MCPB file containing MCP server configuration"),q(h(),gy()).describe("MCP server configurations keyed by server name"),k(ie([xa().describe("Path to MCP servers configuration file"),x4().describe("Path or URL to MCPB file"),q(h(),gy()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),X4=P(()=>O({type:K(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:h().describe("Human-readable label shown in the config dialog"),description:h().describe("Help text shown beneath the field in the config dialog"),required:v().optional().describe("If true, validation fails when this field is empty"),default:ie([h(),Y(),v(),k(h())]).optional().describe("Default value used when the user provides nothing"),multiple:v().optional().describe("For string type: allow an array of strings"),sensitive:v().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:Y().optional().describe("Minimum value (number type only)"),max:Y().optional().describe("Maximum value (number type only)"),options:k(h().min(1,"An option cannot be empty").max(64,"An option can be at most 64 characters").refine((e)=>lD(e)===e,{message:"An option cannot contain control, invisible or bidirectional-formatting characters"}).refine((e)=>e.trim()===e,{message:"An option cannot start or end with a space"})).min(1,"options needs at least one value").refine((e)=>new Set(e.map((t)=>t.toLowerCase())).size===e.length,{message:"options cannot repeat a value (in any letter case)"}).readonly().optional().describe("For string type: the only values the field takes. /config shows the field as a picker over them, and a stored value outside them counts as unset")}).strict().superRefine((e,t)=>{if(e.options===void 0)return;if(e.type!=="string"||e.multiple===!0||e.sensitive===!0){t.addIssue({code:"custom",path:["options"],message:'options is only for a field of type "string" that is neither multiple nor sensitive'});return}if(e.default===void 0){if(e.required!==!0)t.addIssue({code:"custom",path:["default"],message:"a field with options needs a default among them, or required: true"});return}if(typeof e.default!=="string"||!e.options.includes(e.default))t.addIssue({code:"custom",path:["default"],message:`default must be one of the options: ${e.options.join(", ")}`})})),Q4=P(()=>O({userConfig:q(h().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"),X4()).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.")})),eZ=P(()=>O({channels:k(O({server:h().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:h().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:q(h(),X4()).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.")})),P4=P(()=>mO({command:h().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:k(k4()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:q(gZe(),k4()).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:K(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:q(h(),h()).optional().describe("Environment variables to set when starting the server"),initializationOptions:me().optional().describe("Initialization options passed to the server during initialization"),settings:me().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:h().optional().describe("Workspace folder path to use for the server"),startupTimeout:Y().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:Y().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),requestTimeout:Y().int().positive().max(2147483647).optional().describe("Maximum time to wait for the server to answer a request (milliseconds). Defaults to 60000."),restartOnCrash:v().optional().describe("Whether to restart the server if it crashes"),maxRestarts:Y().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:v().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.")})),hZe=P(()=>mO({name:h().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:h().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 (the named --project-config-root when a host set one) — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:h().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:ie([U("always"),h().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).')})),_Ze=P(()=>k(hZe()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),jv=P(()=>O({monitors:ie([xa().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),_Ze()]).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.")})),tZ=P(()=>O({lspServers:ie([xa().describe("Path to .lsp.json configuration file relative to plugin root"),q(h(),P4()).describe("LSP server configurations keyed by server name"),k(ie([xa().describe("Path to LSP configuration file"),q(h(),P4()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),yZe=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,SZe=/^[a-z0-9][a-z0-9-._]*$/,EZe=/^@[a-z0-9][a-z0-9-._]*\/\*$/;function Kv(e){return!e.includes("..")&&!e.includes("//")&&(yZe.test(e)||SZe.test(e))}var nZ=P(()=>h().refine((e)=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine((e)=>Kv(e),"Invalid npm package name format")),rZ=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,bZe=/^[0-9a-f]{64}$/;var CZe=64;var AZe=P(()=>O({sha256:h().regex(bZe)}));function RZe(e){let t=q(h(),me()).safeParse(e);if(!t.success)return;let n=Object.create(null),r=0;for(let[o,s]of Object.entries(t.data)){if(r>=CZe)break;let i=AZe().safeParse(s);if(rZ.test(o)&&i.success)n[o]=i.data,r++}return r>0?n:void 0}var oZ=P(()=>O({binaries:me().transform(RZe).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),sZ=P(()=>O({settings:q(h(),me()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),iZ=P(()=>O({types:ir().refine((e)=>e.endsWith(".d.ts"),{message:"types must name a TypeScript declaration file ending in '.d.ts'"}).refine((e)=>!e.split(/[\\/]/).includes(".."),{message:"types must stay inside the plugin directory (no '..' segment)"}).optional().describe("Path to the plugin's type contract, relative to the plugin root and starting with ./: a self-contained .d.ts (no import, export-from, require or reference) that exports the types of the noun the plugin's hooks module adds in engine.create at its top level and declares the noun in a `declare module 'claude-code' { interface EngineInterface { ... } }` block, nothing else. A mod that lists this plugin under dependencies gets the contract laid at .claude-plugin/types/<plugin>/index.d.ts each time the engine loads it from a folder the person owns, so it types against the noun with nothing copied; claude plugin validate checks the file.")})),aZ=P(()=>O({experimental:Me((e)=>oe(e)?e:void 0,O({...Bv().partial().shape,...mZe().partial().shape,...jv().partial().shape,...zv().partial().shape,evals:uZe().optional().describe("Directory of eval cases for the plugin evaluation harness, relative to the plugin root (default: evals/). A list is accepted; its first entry is the case directory.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))}));var OZe=P(()=>O({...qn().shape,...W4().partial().shape,...V4().partial().shape,...q4().partial().shape,...Y4().partial().shape,...zv().partial().shape,...Bv().partial().shape,...Z4().shape,...eZ().partial().shape,...J4().partial().shape,...tZ().partial().shape,...jv().partial().shape,...sZ().partial().shape,...iZ().partial().shape,...Q4().partial().shape,...oZ().partial().shape,...aZ().partial().shape})),$Ht=P(()=>new Vc({$schema:()=>qn().shape.$schema,name:()=>qn().shape.name,displayName:()=>qn().shape.displayName,version:()=>qn().shape.version,description:()=>qn().shape.description,author:()=>qn().shape.author,homepage:()=>qn().shape.homepage,repository:()=>qn().shape.repository,license:()=>qn().shape.license,keywords:()=>qn().shape.keywords,defaultEnabled:()=>qn().shape.defaultEnabled,dependencies:()=>qn().shape.dependencies,metadata:()=>qn().shape.metadata,hooks:()=>W4().partial().shape.hooks,commands:()=>V4().partial().shape.commands,agents:()=>q4().partial().shape.agents,skills:()=>Y4().partial().shape.skills,outputStyles:()=>zv().partial().shape.outputStyles,themes:()=>Bv().partial().shape.themes,workflows:()=>Z4().shape.workflows,channels:()=>eZ().partial().shape.channels,mcpServers:()=>J4().partial().shape.mcpServers,lspServers:()=>tZ().partial().shape.lspServers,monitors:()=>jv().partial().shape.monitors,settings:()=>sZ().partial().shape.settings,types:()=>iZ().partial().shape.types,userConfig:()=>Q4().partial().shape.userConfig,binaries:()=>oZ().partial().shape.binaries,experimental:()=>aZ().partial().shape.experimental},new Set(["name"])));var lZ=new Set(["url","github","git","npm","file","directory","skills-dir","hostPattern","pathPattern","settings"]);function cZ(e){try{return new RegExp(e),!0}catch{return!1}}function TZe(e){return va(e)||ol(e)}var uZ="ssh.github.com";function wv(e){return wi(e)||Qp(e)===uZ}var wZe=/^[A-Za-z0-9._-]+$/;function vZe(e){return wZe.test(e)&&!e.startsWith("-")&&e!=="."&&e!==".."}function dZ(e){if(!e.endsWith("/*"))return null;let t=e.slice(0,-2);return vZe(t)?t:null}function xZe(e){let t=[];for(let n of e.split("/")){if(n===".")continue;if(n===".."){t.pop();continue}t.push(n)}return t.filter((n)=>n!=="").join("/")}function kZe(e){let t=e.length;for(;;){let n=t;while(n>0&&e.charCodeAt(n-1)===47)n--;if(n>=4&&e.startsWith(".git",n-4))n-=4;if(n===t)return t===e.length?e:e.slice(0,t);t=n}}function I4(e){let t=Tv(e);return t===uZ?xn:t}function PZe(e,t){if(e.includes("://"))try{let r=R4(e);if(r===null)return e;r.hostname=I4(r.hostname),r.username="",r.password="",r.search="",r.hash="";try{r.pathname=decodeURIComponent(r.pathname)}catch{}let o=xZe(r.pathname);return r.pathname=t?.stripDotGit?kZe(o):o,r.toString()}catch{return e}let n=sl(e);return n?`${I4(n.host)}:${n.path}`:e}var IZe=new Set(["http:","https:","git:","git+http:","git+https:"]);function DZe(e){if(Ov(e))return e;if(e.includes("://"))try{let r=new URL(e);if(r.hostname=Tv(r.hostname),IZe.has(r.protocol)||wi(r.hostname))r.username="",r.password="";return r.toString()}catch{return e}let t=O4(e);if(!t)return e;let n=t.host.toLowerCase().replace(/\.+$/,"");return wi(n)?`${xn}:${t.path}`:`${t.user}@${n}:${t.path}`}function pZ(e){if(e.includes("://")){if(TZe(e))return!1;let s=sl(e)?.host;if(s!==void 0&&wv(s)&&PZe(e,{stripDotGit:!0}).includes("*"))return!0;let i=Fo(e)?.hostname;if(!i||!wv(i))return!1;let a=DZe(e);try{let l=new URL(a);return l.hostname.includes("*")||l.pathname.includes("*")}catch{return a.includes("*")}}let t=sl(e),n=t?.host,r=t?.path;if(!n||r===void 0||!wv(n))return!1;let o=r;try{o=decodeURIComponent(r)}catch{}return o.includes("*")}function fZ(e){return oa("source",[O({source:U("url"),url:h().url().describe("Direct URL to marketplace.json file"),headers:q(h(),h()).optional().describe("Custom HTTP headers (e.g., for authentication)"),headersHelper:Mv().optional().describe("Command that prints a JSON object of HTTP headers (e.g. a short-lived auth token). Its output overrides `headers` and, like `headers`, is inherited by same-origin archive downloads from this marketplace. Runs from a fixed directory (the Claude config home, never the session's), so give a bare command found via PATH or an absolute path; it is re-run on later refreshes of this marketplace.")}),O({source:U("github"),repo:h().describe('GitHub repository in owner/repo format. ONLY in the managed-settings policy lists (strictKnownMarketplaces / blockedMarketplaces) the owner-wildcard form "owner/*" matches every repository under exactly that owner. Everywhere else (marketplace add, extraKnownMarketplaces, known_marketplaces.json) the value '+"must name a single repository — a wildcard is taken literally and fails to clone."),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:h().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:k(h()).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:v().optional().describe("Has no effect; accepted so existing settings keep working. Claude Code's own git never downloads Git LFS content: LFS-tracked files in the marketplace repository are checked out as pointer files whether or not this is set, and adding or updating the marketplace says how many were. To fetch their content, run `git lfs pull` in the marketplace's checkout under ~/.claude/plugins/marketplaces/.")}),O({source:U("git"),url:h().describe("Full git repository URL"),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:h().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:k(h()).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:v().optional().describe("Has no effect; accepted so existing settings keep working. Claude Code's own git never downloads Git LFS content: LFS-tracked files in the marketplace repository are checked out as pointer files whether or not this is set, and adding or updating the marketplace says how many were. To fetch their content, run `git lfs pull` in the marketplace's checkout under ~/.claude/plugins/marketplaces/.")}),O({source:U("npm"),package:nZ().or(h().regex(EZe,"Invalid npm package name format")).describe('npm package containing marketplace.json (e.g. "@acme/claude-marketplace"). In strictKnownMarketplaces / blockedMarketplaces an entry also governs plugins installed straight from the npm marketplace (`<package>@npm`): an exact package name matches that package, and "@acme/*" matches every package under the scope.'),version:h().optional().describe('Version or range to fetch (e.g. "1.4.0", "^1.4"); defaults to the latest dist-tag'),registry:h().url().refine(Lv,"Registry must be an http(s) URL").optional().describe(`Registry URL. When adding a marketplace: a one-off registry override (otherwise your npm configuration decides). In a policy entry: the origin and path prefix the package's RESOLVED tarball URL must fall under (e.g. "https://npm.example.com/api/npm/internal/"); under allowManagedPermissionRulesOnly, an npm marketplace keeps plugin allowed-tools only when both the entry and the registration pin this same registry.`)}),O({source:U("file"),path:h().describe("Local file path to marketplace.json")}),O({source:U("directory"),path:h().describe("Local directory containing .claude-plugin/marketplace.json")}),O({source:U("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."),O({source:U("hostPattern"),hostPattern:h().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$").')}),O({source:U("pathPattern"),pathPattern:h().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.')}),O({source:U("settings"),name:e?iZe().describe("Marketplace name, as stored in known_marketplaces.json. A reserved name is refused per entry at load (revalidateReservedNameEntry); a look-alike name is judged when that marketplace's own catalog is parsed (catalogNameSchemaFor)."):sZe().refine((t)=>!Nv.has(t.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:k(FZe()).describe("Plugin entries declared inline in settings.json"),owner:$v().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).")])}var ef=P(()=>fZ(!1));var Gv=String.raw`[\w./+-]`,zHt=new RegExp(`^(?:#${Gv}*)?$`),BHt=new RegExp(String.raw`^(?:(?:git\+)?ssh:\/\/)?[^@:/\\?#%]+@[^@:/\\?#]+:[^@?#]*(?:#${Gv}*)?$`),jHt=new RegExp(String.raw`^(?:(?:github|gitlab|bitbucket):)?[^@:/\\?#%]+(?:\/[^@:/\\?#%]+)+(?:#${Gv}*)?$`);var LZe=P(()=>fZ(!0));function mZ(){return ef()}var Wv=P(()=>mZ()),by=P(()=>mZ()),vv=P(()=>h().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),gZ=P(()=>h().regex(/^[0-9a-fA-F]{64}$/,"Must be a 64-character hex SHA-256 digest")),MZe="Archive URLs must use https:// and must not point at a loopback, link-local, or cloud-metadata host";function NZe(e){try{let t=new URL(e);return t.protocol==="https:"&&!u4(t.hostname)}catch{return!1}}var UZe=P(()=>O({source:U("archive"),url:h().url().refine(NZe,{message:MZe}).describe("HTTPS URL of a zip archive containing the plugin. The plugin root (the directory holding .claude-plugin/) may be at the top of the archive "+"or nested one directory deep — a single wrapping directory is stripped."),sha256:gZ().optional().describe("SHA-256 digest of the archive. When set, every download is verified against it and the install is refused on mismatch. It also serves as the version identity when neither plugin.json nor the marketplace entry declares a `version`. Recommended. Note the update signal is the version string (plugin.json "+"version, else the entry version, else this digest) — changing only the digest "+"while a version is declared does not trigger an update.")}).describe("Plugin distributed as a zip archive fetched over HTTPS — for hosting on any "+"static file server or artifact repository (S3, GitLab, nginx) with no git or npm on the client. Authentication: the entry's own `headers` / `headersHelper` (bound to this URL), overlaid on the enclosing url-source marketplace's headers (static or `headersHelper`-minted) when the archive shares its origin.")),hZ=P(()=>ie([Me((e)=>e==="."?"./":e,ir()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),O({source:U("npm"),package:nZ().or(h().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:h().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:h().url().refine(Lv,"Registry must be an http(s) URL").optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),O({source:U("url"),url:h().describe("Full git repository URL (https:// or git@)"),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:vv().optional().describe("Specific commit SHA to use")}),O({source:U("github"),repo:h().describe("GitHub repository in owner/repo format"),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:vv().optional().describe("Specific commit SHA to use")}),O({source:U("git-subdir"),url:h().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:h().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). '+"Checked out sparsely — over https or ssh as a partial clone (--filter=tree:0) — to minimize bandwidth for monorepos."),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:vv().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."),UZe(),O({source:U("command"),command:h().min(1).max(Dv,{message:"command must not be longer than the install consent UI can display"}).refine((e)=>!F4.test(e),{message:"command must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"}).describe("Shell command that prints the absolute path of the plugin directory on stdout (exactly one line) and exits 0. It must leave a complete plugin in that directory before exiting; the directory is copied into the plugin cache, so the printed path may change between runs (it is re-resolved on every install and update, and once per session in the background). Runs through the platform shell (sh on macOS/Linux, cmd.exe on Windows) from the user's home directory with Claude Code's subprocess environment."),timeout:Y().int().positive().max(T4).optional().describe("Seconds to wait for the command before giving up (default: 60)"),mode:K(["copy","link"]).optional().describe("copy (default): the printed directory is copied into the plugin cache and content-hashed, so it may be deleted afterwards. link: the cache entry links to the printed directory "+"in place (no copy, no size limit; macOS/Linux) — for large exports; the directory must then stay "+"valid while Claude Code runs, and a different printed path is what signals new content.")}).describe("Plugin directory produced by a locally installed tool (e.g. an IDE that renders its plugin for the currently selected SDK). Claude Code runs the command, copies the directory it prints, and re-runs it in the background at startup to pick up changes."),O({source:U("unsupported"),error:h().optional()}).describe("Placeholder for source types this Claude Code version does not recognize, or a known type whose fields failed validation (then `error` "+"holds the reason). Never authored by hand — PluginMarketplaceSchema rewrites "+"unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with an actionable message.")])),FZe=P(()=>O({name:Ey().describe("Plugin name as it appears in the target repository"),source:hZ().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against. Under allowManagedPermissionRulesOnly, a settings marketplace keeps its plugins' allowed-tools only when every npm entry here pins a `registry` on a bare package name; unpinned, the package resolves through the member's own npm config, and a non-bare spelling (an `npm:` alias, a `name@range`, a URL or git spec) packs as an "+"exotic spec the pin does not bind — either way the marketplace "+"vouches no tool grants."),description:h().optional(),version:h().optional(),strict:v().optional(),headers:q(h(),h()).optional().describe("HTTP headers sent when downloading this entry's `archive` source."),headersHelper:Mv().optional().describe("Command that prints a JSON object of HTTP headers for downloading this entry's `archive` source. Runs only when a user explicitly installs or updates this plugin. Unlike a catalog entry, an entry written here does not need `strict: false`: it is declared in a settings file, which has no manifest fields to inline. A declaration in project settings is not operator-authored, so request-routing and client-identity header names are still filtered there. Use an absolute path.")}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url, archive, command). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine((e)=>typeof e.source==="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url, archive, command)."}));var HZe=P(()=>O({cli:k(h().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:k(h().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:k(h().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:k(O({file:h().max(256),pattern:h().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:k(h().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.`)})),$Ze=P(()=>O({topic:h().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:HZe().optional().describe("Matchers that determine when the plugin is relevant.")})),zZe=P(()=>OZe().partial().extend({name:Ey().describe("Unique identifier matching the plugin name"),source:hZ().describe("Where to fetch the plugin from"),headers:q(h(),h()).optional().describe("Custom HTTP headers for fetching this plugin's archive; overrides the marketplace's"),headersHelper:Mv().optional().describe("Command that prints a JSON object of HTTP headers for fetching this plugin's archive (e.g. a short-lived auth token); overrides this entry's `headers` and the marketplace's. Runs only when the user installs or updates this plugin, never during catalog browse. An entry that sets it must be `strict: false` with its manifest inlined here, so consent is informed from the entry alone before the command runs."),category:h().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:k(h()).optional().describe("Tags for searchability and discovery"),strict:v().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:Me((e)=>oe(e)?e:void 0,$Ze().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.`)})),BZe=P(()=>O({name:Ey()}));function jZe(e){let t=zZe();return e.flatMap((n,r)=>{let o=t.safeParse(n);if(o.success){let a=o.data.source;if(typeof a==="object"&&a.source==="unsupported"&&a.error!==void 0)return[{...o.data,source:{source:"unsupported"}}];return[o.data]}let s=BZe().safeParse(n).data?.name,i=o.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(s){G(`Stubbing unparseable marketplace plugin entry (${s}): ${i}`,{level:"warn"});let a=_Z(oe(n)?n.source:void 0)?ZZe:Vv(n)?void 0:GZe(o.error.issues)??Cy(o.error.issues);return[{name:s,source:{source:"unsupported",...a&&{error:a}},strict:!0}]}return G(`Dropping unparseable marketplace plugin entry (index ${r}): ${i}`,{level:"warn"}),[]})}var KZe=new Set(["npm","url","github","git-subdir","archive","command","unsupported"]);function Vv(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.source;return typeof n==="string"&&!KZe.has(n)}function GZe(e){let t=e.find((r)=>r.path.length===1&&r.path[0]==="source");if(!t||t.code!=="invalid_union")return;let n=t.errors.find((r)=>!r.some((o)=>o.path.length===0||o.code==="invalid_value"&&o.path[0]==="source"));if(!n||n.length===0)return;return Cy(n.map((r)=>({...r,path:["source",...r.path]})))}var WZe=/^[A-Za-z0-9_$.-]{1,40}$/;function ko(e){return WZe.test(e)?e:"<key>"}var VZe=3,qZe=160;function Cy(e){let t=e.slice(0,VZe).map((r)=>{let o=r.path.map(String).map((i)=>ko(i)).join("."),s=r.code==="unrecognized_keys"?`Unrecognized ${r.keys.length===1?"field":"fields"}: ${r.keys.map(ko).join(", ")}`:av(r.message,qZe);return o?`${o}: ${s}`:s}),n=e.length-t.length;return n>0?`${t.join(", ")} (+${n} more)`:t.join(", ")}var YZe=/^[A-Za-z0-9][-A-Za-z0-9._]*$/,ZZe='Bare source names resolve under metadata.pluginRoot, which this marketplace does not set (or sets to a path outside the marketplace root). Use a "./relative/path" source, or set metadata.pluginRoot to allow bare names.';function _Z(e){return typeof e==="string"&&YZe.test(e)&&!e.includes("..")}function JZe(e){if(typeof e!=="string"||e===""||e.startsWith("/")||e.includes("\\")||e.includes(":"))return;let t=e.replace(/^\.\//,"").replace(/\/+$/,"");if(t===""||t===".")return".";if(t.split("/").some((n)=>n===""||n==="."||n===".."))return;return t}function XZe(e,t){if(t===void 0||!oe(e)||!_Z(e.source))return e;let n=t==="."?`./${e.source}`:`./${t}/${e.source}`;return{...e,source:n}}function QZe(e){if(!oe(e)||!Array.isArray(e.plugins))return e;let t=oe(e.metadata)?JZe(e.metadata.pluginRoot):void 0;if(t===void 0)return e;return{...e,plugins:e.plugins.map((n)=>XZe(n,t))}}var e9e=P(()=>O({$schema:h().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:aZe(K4),version:h().optional().describe("Marketplace manifest version"),description:h().optional().describe("Human-readable description of this marketplace"),owner:$v().describe("Marketplace maintainer or curator information"),plugins:k(me()).transform(jZe).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:v().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:O({pluginRoot:h().optional().describe('Base directory for bare plugin source names, relative to the marketplace root (e.g. "./plugins" resolves "source": "formatter" as ./plugins/formatter). Sources that already start with "./" are unaffected.'),version:h().optional().describe("Marketplace version"),description:h().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:k(h()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:q(h(),h().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.")})),KHt=P(()=>Me(QZe,e9e()));var Pv="[A-Za-z0-9][-A-Za-z0-9._]*",GHt=new RegExp(`^${Pv}$`);var t9e=new RegExp(`^${Pv}@${Pv}$`),D4=`@${Fv}`;function yZ(e){return e.endsWith(D4)&&Kv(e.slice(0,-D4.length))}var qc=P(()=>h().refine((e)=>t9e.test(e)||yZ(e),"Plugin ID must be in format: plugin@marketplace")),WHt=new RegExp(`[@:\\s/\\\\${Ir}]`,"u"),VHt=new RegExp(`[${Ir}]`,"u"),SZ=/[\p{Cc}\u200E\u200F\u202A-\u202E\u2066-\u2069]/u,n9e=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,r9e=P(()=>ie([h().regex(n9e,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),O({name:h().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:h().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),o9e=P(()=>O({version:h().describe("Currently installed version"),installedAt:h().describe("ISO 8601 timestamp of installation"),lastUpdated:h().optional().describe("ISO 8601 timestamp of last update"),installPath:h().describe("Absolute path to the installed plugin directory"),gitCommitSha:h().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:h().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:v().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)."),...L4(),...M4(),...U4(),...N4()})),qHt=P(()=>O({version:U(1).describe("Schema version 1"),plugins:q(qc(),o9e()).describe("Map of plugin IDs to their installation metadata")})),s9e=P(()=>K(["managed","user","project","local"])),i9e=P(()=>O({scope:s9e().describe("Installation scope"),projectPath:h().optional().describe("Project path (required for project/local scopes)"),installPath:h().describe("Absolute path to the versioned plugin directory"),version:h().optional().describe("Currently installed version"),installedAt:h().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:h().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:h().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:h().optional().describe("Tag-derived semver this install resolved to"),auto:v().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep."),...L4(),...M4(),...U4(),...N4()})),YHt=P(()=>O({version:U(2).describe("Schema version 2"),plugins:q(qc(),k(i9e())).describe("Map of plugin IDs to arrays of installation entries")})),ZHt=P(()=>O({version:U(2),plugins:q(h(),me())}));var a9e=P(()=>O({source:LZe().describe("Where to fetch the marketplace from"),installLocation:h().describe("Local cache path where marketplace manifest is stored"),lastUpdated:h().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:v().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup"),declaredByManagedSettings:U(!0).optional().describe("Managed settings declared this source for this name: when they later declare another, it is the organization moving its marketplace, and what its plugins saved stays")})),JHt=P(()=>q(h(),a9e()));function Yc(e){return e==="true"?!0:e==="false"?!1:e}var Ay=["aspell","hunspell","ispell"];var Zc=2147483647;var l9e=["autoMode","deepLink","voice","briefView","screenReader"],c9e={},Yv={autoMode:{buildGate:()=>!0,shape:()=>({skipAutoPermissionPrompt:v().optional().describe("Whether the user has accepted the auto mode opt-in dialog"),useAutoModeDuringPlan:v().optional().describe("Whether plan mode uses auto mode semantics when auto mode is available (default: true)"),autoMode:O({allow:k(h()).optional().describe('Rules for the auto mode classifier allow section. Include the literal string "$defaults" to inherit the built-in rules at that position.'),soft_deny:k(h()).optional().describe('Rules for the auto mode classifier SOFT BLOCK section — destructive/irreversible actions that user intent can clear. Include the literal string "$defaults" to inherit the built-in rules at that position.'),hard_deny:k(h()).optional().describe('Rules for the auto mode classifier HARD BLOCK section — security boundaries that user intent does NOT clear. Include the literal string "$defaults" to inherit the built-in rules at that position.'),...!1,...{},environment:k(h()).optional().describe('Entries for the auto mode classifier environment section. Include the literal string "$defaults" to inherit the built-in entries at that position.'),classifyAllShell:v().optional().describe("When true, every Bash/PowerShell allow rule is suspended while auto mode is active so all shell commands are routed through the classifier (higher safety, more classifier calls). Default: false.")}).optional().describe("Auto mode classifier prompt customization")}),permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:K(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!0,shape:()=>({voiceEnabled:v().optional().describe("Enable voice mode (hold-to-talk dictation)")})},briefView:{buildGate:()=>!0,shape:()=>({defaultView:K(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>c9e}};function Jc(){return l9e.filter((e)=>Yv[e].buildGate())}function EZ(e){let t={};for(let n of e)t={...t,...Yv[n].shape()};return t}function Zv(e){let t=[];for(let n of e)t.push(...Yv[n].permissionModes?.()??[]);return t}var i$t=new RegExp("\x00ESCAPED_STAR\x00","g"),a$t=new RegExp("\x00ESCAPED_BACKSLASH\x00","g");var l$t=new RegExp("\x00GLOBSTAR\x00","g");function bZ(e){return e.match(/^(.+):\*$/)?.[1]??null}function CZ(e){let t=e.trimEnd();if(!t.endsWith("*"))return!1;let n=0,r=t.length-2;while(r>=0&&t[r]==="\\")n++,r--;return n%2===0}var Ry={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 Jv(e){return Ry.filePatternTools.includes(e)}function AZ(e){return Ry.bashPrefixTools.includes(e)}function RZ(e){return Object.hasOwn(Ry.customValidation,e)?Ry.customValidation[e]:void 0}function wZ(e,t){let n=0,r=t-1;while(r>=0&&e[r]==="\\")n++,r--;return n%2!==0}function OZ(e,t){let n=0;for(let r=0;r<e.length;r++)if(e[r]===t&&!wZ(e,r))n++;return n}var u9e=/(?:^|[^\\])\\[()]/;function d9e(e){return u9e.test(e)&&OZ(e,"(")!==OZ(e,")")}var p9e=/^(?:[|&;<>]|\d+[<>])/;function f9e(e){return p9e.test(e)}function Xv(e){for(let t=0;t<e.length;t++)if(e[t]==="*"&&!wZ(e,t))return!0;return!1}function m9e(e){if(e.endsWith(":*"))return;let t=e.trim().split(/\s+/).filter(Boolean),n=t[0];if(t.length<3||n===void 0||Xv(n))return;let r=!1;for(let o of t.slice(1)){if(f9e(o))return;if(Xv(o)){r=!0;continue}if(o.startsWith("-"))continue;return r?n:void 0}return}function TZ(e){if(!qp(e))return null;let t=Kc(e);if(t&&!qp(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 Qv(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=cv(e);if(n.kind==="malformed")return{valid:!1,error:"Malformed Tool(content) rule",suggestion:'Rules take the form Tool or Tool(content) and must end at the closing ")"; parentheses inside the content are literal'};if(n.kind==="call"&&n.rawContent===""){if(!n.toolName)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${n.toolName}" without parentheses`,examples:[`${n.toolName}`,`${n.toolName}(some-pattern)`]}}let r=VY(e),o=Kc(r.toolName);if(o){if(n.kind==="call"){let i=o.toolName&&!qp(o.toolName)?`${r.toolName}__*`:void 0;return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:i===void 0?`Use "${r.toolName}" without parentheses, or use "mcp__${o.serverName}__*" for all tools`:`Use "${r.toolName}" without parentheses. For all tools of a server, use "mcp__${o.serverName}__*" for the server "${o.serverName}", or "${i}" for a server named "${o.serverName}__${o.toolName}"`,examples:[`mcp__${o.serverName}`,`mcp__${o.serverName}__*`,o.toolName&&o.toolName!=="*"?`mcp__${o.serverName}__${o.toolName}`:void 0,i].filter(Boolean)}}if(t==="allow"){let i=TZ(r.toolName);if(i)return i}return{valid:!0}}if(!r.toolName||r.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let i=TZ(r.toolName);if(i)return i}if(!r.toolName.includes("_")&&r.toolName[0]!==r.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${Nu(String(r.toolName))}"`};if(n.kind==="call"&&d9e(n.rawContent)){let i=Jv(r.toolName);return{valid:!1,error:'Ambiguous "\\(" or "\\)" beside an unescaped parenthesis',suggestion:i?"Write a Windows path with forward slashes, or spell a literal parenthesis as [(] or [)]":'Double a backslash that is a path separator ("\\\\("), and escape literal parentheses in pairs',examples:i?[`${r.toolName}(C:/Projects/(drafts)/**)`,`${r.toolName}(C:\\Projects\\[(]drafts)\\**)`]:[`${r.toolName}(C:\\tools\\\\(x86)\\run.exe *)`]}}let s=RZ(r.toolName);if(s&&r.ruleContent!==void 0){let i=s(r.ruleContent);if(!i.valid)return i}if(AZ(r.toolName)&&r.ruleContent!==void 0){let i=r.ruleContent;if(i===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]};if(t==="allow"){let l=m9e(i);if(l!==void 0){let c=l==="git",d=c?" For git, options such as -c and --exec-path can run arbitrary commands.":"",p=c?" (for example Bash(git status *))":"";return{valid:!0,warning:`${sr(r)} has a wildcard before the rest of the command, so it also matches any options inserted at that position and approves them without a prompt.${d} Replace that * with the exact value you mean, or only use * after the subcommand${p}.`,securityNotice:`${sr(r)} allows any option at its * · use an exact value`}}}let a=bZ(i)?.trimEnd();if(a!==void 0){if(Xv(a)){let l=CZ(a),c=l?"matches only commands containing a literal * at that position":"will likely never match",d=l?a:`${a}*`,p=t==="allow"?" Replace that * with the exact value you mean.":d.endsWith(":*")?"":` Use ${sr({toolName:r.toolName,ruleContent:d})} for wildcard matching.`;return{valid:!0,warning:`${sr(r)} mixes * with the trailing :* prefix syntax, so it is matched as a literal prefix (the * is not expanded) and ${c}.${p}`,...t!=="allow"&&{securityNotice:`${sr(r)} reads its * literally${d.endsWith(":*")?"":` · use ${sr({toolName:r.toolName,ruleContent:d})}`}`}}}}else if(i.includes(":*")&&!i.endsWith(":*")){let l=t==="allow"?"Replace that :* with the exact value you mean.":"It already matches as a * wildcard; moving :* to the end would make it a literal prefix and change which commands match.";return{valid:!0,warning:`${sr(r)} has a :* that is not at the end, so it is matched as a * wildcard (the : is literal), not as the trailing :* prefix syntax. ${l}`,...t==="allow"&&{securityNotice:`${sr(r)} reads its :* as a wildcard · use an exact value`}}}}if(Jv(r.toolName)&&r.ruleContent!==void 0){if(r.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${r.toolName}(*.ts) - matches .ts files`,`${r.toolName}(src/**) - matches all files in src`,`${r.toolName}(**/*.test.ts) - matches test files`]}}if(r.ruleContent!==void 0){let i=r.toolName==="Write"||r.toolName==="NotebookEdit"||r.toolName==="MultiEdit"?"Edit":r.toolName==="Glob"?"Read":void 0;if(i!==void 0&&!r.ruleContent.includes(":*"))return{valid:!0,warning:`${sr(r)} is not matched by file permission checks — only ${i}(path) rules are. Use ${sr({toolName:i,ruleContent:r.ruleContent})} instead (${i} rules cover all file-${i==="Edit"?"editing":"reading"} tools).`,...t!=="allow"&&{securityNotice:`${sr(r)} never matches · use ${sr({toolName:i,ruleContent:r.ruleContent})}`}}}return{valid:!0}}var ex=P(()=>xZ()),vZ=P(()=>xZ("allow"));function xZ(e){return h().superRefine((t,n)=>{let r=Qv(t,e);if(!r.valid){let o=r.error;if(r.suggestion)o+=`. ${r.suggestion}`;if(r.examples&&r.examples.length>0)o+=`. Examples: ${r.examples.join(", ")}`;n.addIssue({code:fr.custom,message:o,params:{received:t}})}})}var of=["accept","hold","refuse"],xy=["off","basic","full"],g9e=P(()=>q(h(),fxe()));function BZ(e){return O({allow:k(vZ()).optional().describe("List of permission rules for allowed operations"),deny:k(ex()).optional().describe("List of permission rules for denied operations"),ask:k(ex()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:Me(jc,K([...Aa,...Zv(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:K(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),blockReadsOutsideWorkingDirectories:v().optional().describe('Refuse file-tool reads (Read, Grep, Glob, LSP) outside the working directories in every permission mode; true in any settings source wins. No allow rule lifts it. Also set when the user picks "block" on the one-time auto-mode prompt for a read outside the working directories.'),blockWritesOutsideWorkingDirectories:v().optional().describe("Refuse file-tool writes (Write, Edit, NotebookEdit) outside the working directories in every permission mode; true in any settings source wins. No allow rule lifts it. Files that Claude Code keeps for the session are not refused: its plan files, scratchpad and background job folder, and the auto-memory of this project, unless a repository settings file points it elsewhere. Nothing runs them unless the model asks. Also refuses file-tool writes to Claude Code settings files, inside the working directories too, and takes EnterWorktree and ExitWorktree, which move the working directory, out of the tools on offer. Does not limit shell commands, MCP tools, the programs that hooks run, or the memory tools. Cloud sessions (Claude Code on the web), whose file tools run in a container that is itself the boundary, may not apply it."),blockReadsExemptPaths:k(h().catch("")).optional().catch(void 0).describe('For the program that starts Claude Code: read only from --settings and from settings that program sends while the session runs; ignored in user, project, local and managed settings. Absolute paths, each a folder with all below it or one file, that blockReadsOutsideWorkingDirectories lets through beside the working directories. It allows nothing: an allow rule, the permission mode or the user still decides each read, as with that setting off, and a shell command that hands such a path to a program is still asked about unless a Read allow rule covers it. The paths do not become working directories, so blockWritesOutsideWorkingDirectories refuses writes to them, and they are not told to MCP servers or to the model. Each path counts as written: a link in it is not followed and a pattern is not expanded, so list every spelling that a read may arrive by. Ignored: an entry that starts with ~, has a ".." segment or has white space at either end (as written or once normalized), a relative or network path, and the root of a filesystem. Does not change what sandboxed commands may read (sandbox.filesystem.allowRead does).'),workingDirectoriesAsGiven:k(h().catch("")).optional().catch(void 0).describe("For the program that starts Claude Code: read only from --settings and from settings that program sends while the session runs; ignored in user, project, local and managed settings. Absolute paths of working directories, each spelled exactly as it is passed, letter case included (the session folder, --add-dir, permissions.additionalDirectories). To decide what lies inside a listed working directory, Claude Code takes it as written and follows no link at it, so a link that later stands in its place gives the file tools no access to where the link leads. List real paths: the files of a listed path that runs through a link count as outside the working directories, because where they really are lies outside it. List a mapped network drive by its drive-letter path: Claude Code still derives the UNC form of that path by itself and adds it, as for any mapped drive. A file path that is itself spelled as a UNC path is judged as written, so a link on the share is not seen by that spelling. It adds no working directory and allows nothing. Once listed, a path stays so until the process ends, also if later settings leave it out. Ignored: an entry that is not already normalized (a relative path, one that starts with ~, a \"..\" segment, a separator at its end unless it is a filesystem root, forward slashes on Windows, white space at either end). Does not change what sandboxed commands may write."),disableAutoMode:K(["disable"]).optional().describe("Disable auto mode"),denyInsteadOfPrompting:v().optional().describe("Never wait for a person to answer a tool permission prompt: a call that would prompt is denied at once, the model is told, and the turn carries on. This is what --permission-prompts none does for -p, in every kind of session, subagents and agent teams included. Allow rules, the permission mode, auto mode's classifier and PermissionRequest hooks decide first, as they do without it; it only ever denies, and allows nothing. Claude's questions and plan mode's tools are not offered to the model, and an MCP server's request for input is cancelled unless an Elicitation hook answers it. An app or script that answers prompts through canUseTool or --permission-prompt-tool is not asked either: answer from a PermissionRequest hook instead. Read from user settings, --settings and managed settings; project and local settings are ignored, and true in any of those sources wins."),additionalDirectories:k(h()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var X$t=P(()=>BZ(Jc())),h9e=P(()=>ie([h(),O({}).passthrough().describe('{ id: stable id (letters, digits, ".", "_", "-"; max 64), text: the tip (max 500 characters, one line), cooldownSessions?: sessions to wait before showing it again (default 0), priority?: tie-break weight among never-shown tips (default 0) }')])),_9e=P(()=>Me((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"||!!t&&typeof t==="object"&&!Array.isArray(t)):[],k(h9e()))),sx=P(()=>O({source:ef().describe("Where to fetch the marketplace from"),installLocation:h().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:v().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup"),pluginDigests:q(h(),k(h()).catch([])).optional().catch(void 0).describe('Managed settings only: the plugins of this marketplace that an organization delivers with its own tier, by plugin name, each with the digests of its releases. A plugin also enabled and listed in prependPlugins or appendPlugins by managed settings the session vouches for loads its hooks module only from a folder that proves one of them, and is then seated in that tier; any other copy does not load. A digest is sha256- and the base64 SHA-256 of, for every regular file in the folder in UTF-16 code unit order of its path, not normalized, "f PATH" NUL BYTE-LENGTH NUL BYTES, with / in paths; .git, .in_use, .orphaned_at, .claude-plugin-link and .links_materialized at the root are left out. The plugin keeps its manifest at .claude-plugin/plugin.json and names one module in hooks/hooks.json. A string of any other form, or a list that is empty or of any other shape, matches no folder. A symbolic link, or a surface module, proves nothing. A proved plugin ships bundled with no install step: the digest covers the whole folder, node_modules included. A checkout whose line endings were converted proves nothing.')})),ix=P(()=>{let e=()=>Y().min(0).max(1e4);return O({input:e(),output:e(),cacheRead:e(),cacheWrite:e()})}),ax=P(()=>Y().gt(0).lte(10).optional()),lx=P(()=>O({model:h().describe('Model to select, taken verbatim: an alias ("opus"), an Anthropic model ID, or a provider-format ID (Vertex, Bedrock, gateway). Same values --model accepts.'),label:h().optional().describe("Row title. Defaults to the model name."),description:h().optional().describe("Row subtitle. Defaults to a generic description."),behavesAs:h().optional().describe("For a model this version of Claude Code does not know: the ID of a model it does know "+'(e.g. "claude-opus-4-8") whose client-side handling — prompt profile, capability and effort '+"defaults — applies to it. Changes neither the row's label nor the model ID sent. Without it, "+"a model-catalog row for a model this version does not know is not offered until Claude Code is updated.")})),ky=P(()=>O({serverName:h().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:k(h()).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:h().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>ja([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"'})),Py=P(()=>O({serverName:h().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:k(h()).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:h().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>ja([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"'})),jZ=P(()=>O({marketplace:h(),plugin:h()})),y9e=P(()=>Me((e)=>{if(typeof e!=="string"||!qc().safeParse(e).success)return e;let t=e.indexOf("@");return{marketplace:e.slice(t+1),plugin:e.slice(0,t)}},jZ())),S9e=/[\x00-\x1f\x7f-\x9f\u2028\u2029]|\p{DI}/u;function E9e(e){let t=e.replaceAll("/","\\");if(Do(t))return!1;return/^\\{2}[^\\]/.test(t)}function b9e(e){return xr(e)||/^\/network\/servers(\/|$)/i.test(e)||Lo(e)}function C9e(e){return/^\/(proc|dev\/(fd|stdin|stdout|stderr))(\/|$)/i.test(e)}function A9e(e,t,n={}){if(t==="win32"){let r=e.replaceAll("/","\\");if(Do(r))return!1;let o=E9e(r);if(n.rejectUnc&&o)return!1;if(n.rejectDriveRelative){if(!/^[A-Za-z]:\\/.test(r)&&!o&&/^(\\|[A-Za-z]:)/.test(r))return!1}if(zZ.normalize(r)!==r)return!1;let s=r.split("\\");if(s.some((a)=>a==="."||a===".."))return!1;if(s.some((a,l)=>/[. ]$/.test(a)||a.includes(":")&&!(l===0&&/^[A-Za-z]:$/.test(a))))return!1;let i=r.startsWith("\\\\")?r.slice(2):r;if(/\\{2}/.test(i))return!1;return!r.endsWith("\\")||/^([A-Za-z]:)?\\$/.test(r)}if(n.rejectNetworkRoot&&b9e(e))return!1;if(n.rejectMagicLinkRoot&&C9e(e))return!1;if($Z.normalize(e)!==e)return!1;if(e.split("/").some((r)=>r==="."||r===".."))return!1;if(/\/{2}/.test(e))return!1;return!e.endsWith("/")||e==="/"}var R9e=/\.(exe|ps1)$/i;function O9e(e){return/\.ps1$/i.test(e)}function T9e(e){return O9e(e)&&/[[\]`*?]/.test(e)}var w9e='a .ps1 path must not contain "[", "]", "`", "*", or "?" on Windows (PowerShell resolves them as wildcard syntax)',v9e=()=>h().describe("Absolute path to the helper executable"),vi=(e)=>Me((t)=>t===null?void 0:t,e.optional()).optional(),x9e=Zc,kZ=(e)=>Y().int().min(e).transform((t)=>Math.min(t,x9e)),PZ=["path","script","defaultSettings"];function KZ(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;return PZ.some((n)=>t[n]===null)&&PZ.every((n)=>t[n]===null||t[n]===void 0)}var IZ=64,wy=P(()=>O({path:v9e(),timeoutMs:vi(kZ(1000)),refreshIntervalMs:vi(ie([U(0),kZ(60000)]))})),GZ=()=>K(["replace","merge"]).describe("How the helper's managedSettings compose with the settings of the source that delivered this entry: 'replace' (default) — the output is the policy; 'merge' — the output is deep-merged over that source's own settings the way merged managed sources compose (helper scalars win, arrays union, objects merge — except fallbackModel, forceLoginOrgUUID, gatewayInternalNetworks, sandbox.filesystem.allowRead, sandbox.credentials.awsPairs, sandbox.ripgrep and the restriction allowlists such as allowedMcpServers, allowedProviders, availableModels and allowedHttpHookUrls, which are the helper's whole value when it emits one; tighten a permission with a deny), so a failed helper costs only the delta");function WZ(e){return e==="continue"||e==="refuse"}var k9e=()=>Me((e)=>e===void 0||WZ(e)?e:"refuse",K(["continue","refuse"]).describe(`What happens when this entry's helper fails at startup (bad path, missing file or interpreter, non-zero exit, timeout, oversize or invalid output) and no static settings payload (this entry's own, the linux entry's on WSL, or the map's "default") applies in its place: 'refuse' — Claude Code does not start, naming the failure; 'continue' — Claude Code starts without the helper's output, on the delivering source's own settings, with a /status notice. Default: 'refuse' when the entry comes from MDM or the managed settings file, 'continue' when it comes from remote managed settings. Any other value is treated as 'refuse', with a /status notice. The install and update commands start no session and are never refused over a remote entry: they report the refusal in /status. An entry whose other fields fail validation runs no helper; from MDM or the managed settings file, any value but 'continue' on it then refuses to start Claude Code until the entry is fixed, unless a static settings payload (the entry's own, kept when it validates, the linux entry's for a wsl one, or the map's "default") serves in its place. From remote, a non-interactive session runs the helper off settings verified this session without the interactive approval, so 'refuse' there too means the helper ran and failed; a launch whose remote settings could not be verified this session (offline, fetch failed) starts without the helper regardless; and a failure first reached after the session has started (settings verified or approved mid-session, which on a machine that only ever runs non-interactively is every launch) ends a session no person watches (non-interactive, a background session no client is attached to, or a teammate session) as the refused start would have, and leaves a watched interactive one (a terminal, with or without remote control, or an attached background session) running under a /status notice with its next start refused. Background refresh failures always keep the last good output whatever this says`)),P9e=5,I9e=()=>Y().int().min(0).transform((e)=>Math.min(e,P9e)).describe("How many more times to run this entry's helper when a run fails to execute — it could not be launched, exited non-zero, or was stopped at timeoutMs — before that counts as a failure (a non-negative integer; default 0, a single attempt; above 5 is treated as 5). Attempts are separated by a short randomized backoff (from 250 ms, doubling per attempt, at most 4 s each) and each attempt gets the full timeoutMs, so a start that waits on the helper can wait up to (retries + 1) × timeoutMs plus the backoff. Output the helper did produce and that was refused — oversized, not a JSON object, an invalid envelope, or settings that fail validation — is not retried, and neither is an invalid path. Applies alike at startup and on each background refresh; only once the attempts are used up do the entry's failure rules (a static settings payload in its place, onFailure, the refresh notice) apply, naming the last attempt's failure"),D9e=(e)=>(e==="windows"?U("pwsh",{message:"interpreter must be 'pwsh' on windows ('sh' is not supported there)"}):U("sh",{message:"interpreter must be 'sh' on macos/linux/wsl"})).describe("Fixed interpreter for `script`: 'sh' (/bin/sh) on macos/linux/wsl entries; 'pwsh' (PowerShell at its fixed install locations, never PATH) on the windows entry"),L9e="exactly one of path/script must be configured",M9e='"script" and "interpreter" must be configured together',N9e="script must be ASCII-only on Windows (PowerShell decodes stdin with the console OEM code page); spell non-ASCII characters as escapes, e.g. [char]0x00E9",U9e=(e)=>h({message:"script must be a string"}).min(1,{message:"script must not be empty"}).max(65536,{message:"script must be at most 65536 characters"}).refine((t)=>!t.includes("\x00"),{message:"script must not contain NUL bytes"}).refine((t)=>Uu(t),{message:"script must be valid UTF-8 (no lone surrogates)"}).refine((t)=>e!=="windows"||!/[\u0080-\uffff]/.test(t),{message:N9e}).describe("Inline helper script, delivered to the fixed interpreter over stdin (never written to disk)");var Sn=["macos","linux","windows","wsl"];function cx(e){return e==="wsl"?["wsl","linux"]:[e]}function F9e(e){return e==="windows"?"win32":"posix"}function H9e(e){return{rejectDriveRelative:e==="windows",rejectUnc:e==="windows",rejectNetworkRoot:e!=="windows",rejectMagicLinkRoot:e!=="windows",requireWin32ExecutableSuffix:e==="windows"}}function $9e(e){let t=F9e(e),n=H9e(e);return h().max(1024,{message:"path must be at most 1024 characters"}).refine((r)=>!S9e.test(r),{message:"path must not contain control, line/paragraph-separator, or invisible (default-ignorable) characters"}).refine((r)=>(t==="win32"?zZ:$Z).isAbsolute(r),{message:"path must be absolute"}).refine((r)=>!(t==="win32"&&n.requireWin32ExecutableSuffix)||R9e.test(r),{message:"path must end in .exe or .ps1 on Windows"}).refine((r)=>t!=="win32"||!T9e(r),{message:w9e}).refine((r)=>A9e(r,t,n),{message:t==="win32"?'path must be in normalized form: no "." or ".." segments, no doubled or trailing separators, no component ending in "." or a space, no ":" outside the drive letter, no device-namespace (\\\\?\\) prefix, no drive-relative (\\dir or C:name) or UNC (\\\\server\\share) form':'path must be in normalized form: no "." or ".." segments, no doubled or trailing separators, and not under a network automount root (/net/<host>, /Network/Servers, or macOS /.vol /.file /.nofollow /.resolve) or a kernel magic-link root (/proc, /dev/fd)'}).describe("Absolute path to the helper executable")}var ux=[...Sn,"default"],tx=["path","script","interpreter","outputBehavior","onFailure","retries","timeoutMs","refreshIntervalMs","defaultSettings"],Ty=["managedSettings","appendSystemPrompt"],ka=P(()=>q(h(),me()).superRefine((e,t)=>{for(let n of["policyHelper","policyHelpers"])if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — the default payload is applied as managed settings and cannot configure further policy helpers`});for(let n of tx)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is a managed-settings object, not a policyHelpers entry; entry fields (${tx.join("/")}) belong on the per-OS entries (policyHelpers.${Sn.join("/")})`});for(let n of Ty)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is the managedSettings SUBTREE, not the helper's stdout envelope; paste the object your helper emits UNDER "managedSettings", not the envelope around it`});for(let n of ux)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is the VALUE of a policyHelpers key (a managed-settings object), never another policyHelpers map; don't paste the map or its "${n}" line inside the slot`})})),z9e='Entry must carry "path" (a helper executable) or "script" + "interpreter" (an inline helper), and/or "defaultSettings" (a static settings payload)';function B9e(e){let{path:t,script:n,interpreter:r,defaultSettings:o}=e;if(t!==void 0&&n!==void 0)return L9e;if(n===void 0!==(r===void 0))return M9e;if(t===void 0&&n===void 0&&o===void 0)return z9e;return null}function VZ(e,t){return wy().omit({path:!0}).extend({path:vi($9e(e)),script:vi(U9e(e)),interpreter:vi(D9e(e)),outputBehavior:vi(GZ()),onFailure:vi(k9e()),retries:vi(I9e()),defaultSettings:Me((n)=>n===null?void 0:n,t.optional()).optional()}).check((n)=>{if(n.issues.length>0)return;let r=B9e(n.value);if(r!==null)n.issues.push({code:"custom",message:r,input:n.value})})}var Q$t=P(()=>VZ("linux",ka()));function nx(e,t=ka()){return e==="default"?ka():VZ(e,t)}var j9e=P(()=>O(Object.fromEntries(ux.map((e)=>[e,Me((t)=>{if(t===null)return;if(e!=="default"&&KZ(t))return;return t},nx(e).optional()).optional()])))),rf=["skills","agents","hooks","mcp"];function qZ(e){return Me((t)=>{if(!Array.isArray(t))return t;let n=t.filter((r)=>rf.includes(r));if(n.length<t.length)e?.(t.length-n.length);return n},ie([v(),k(K(rf))]))}function YZ(){return ie([k(h()),v(),fO()])}var DZ=Object.freeze({type:"invalid-entry-stripped"}),K9e=P(()=>ie([O({type:U("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:h().describe("Regex matched against turn output (tool results and assistant text)"),url:h().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:h().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),O({type:h().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()])),LZ=()=>Y().int().min(BY).max(jY).optional().catch(void 0);function ZZ(e,{strictPolicyHelperKeys:t=!1}={}){function n(o){return q(h(),sx()).check((s)=>{for(let[i,a]of Object.entries(s.value))if(a.source.source==="settings"&&a.source.name!==i)s.issues.push({code:"custom",input:a.source.name,path:[i,"source","name"],message:`Settings-sourced marketplace name must match its ${o} key (got key "${i}" but source.name "${a.source.name}")`})})}let r=(o,s)=>t?Me((i)=>{if(i===null)return;return s?s(i):i},o):o.catch(void 0);return{$schema:()=>h().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:()=>h().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:()=>h().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:()=>h().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:()=>h().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:()=>h().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),processWrapper:()=>h().optional().describe("Corporate launcher argv prefix for the background-agent supervisor, the sessions and workers it hosts, and the other covered background processes listed in the Claude Code corporate-launcher documentation. Equivalent to the CLAUDE_CODE_PROCESS_WRAPPER environment variable, which takes precedence when set. Honored from managed settings, a --settings/SDK-supplied settings file, and user settings, in that precedence order; project and local settings are ignored."),policyHelper:()=>r(wy().optional(),(o)=>o&&typeof o==="object"&&!Array.isArray(o)&&o.path===null?void 0:o).describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),policyHelpers:()=>r(j9e().optional()).describe(`@internal Per-OS variant of policyHelper, keyed by platform: macos, linux, windows, wsl, plus an optional "default" entry that is a STATIC settings payload (a JSON object of managed settings, not a helper). Each per-OS entry carries a helper — a "path", or an inline "script" + "interpreter" delivered to a fixed interpreter over stdin, either with timeoutMs/refreshIntervalMs — its own static "defaultSettings" payload, or both; an entry may be payload-only. Selection for a platform walks its chain (the platform's own entry; on wsl the linux entry next): the first helper on the chain wins over policyHelper; if no helper is configured — or the selected helper fails at startup or refresh — the first payload applies (the chain's "defaultSettings" in platform-specific-first order, then the top-level "default", applied with no process spawned; unrecognized platforms reach only "default"); with no payload either, policyHelper. Honored from admin-controlled policy sources, and from remote managed settings — a payload of plain policy as delivered, like any other remote key; a helper, or a payload carrying anything the managed-settings approval dialog lists, only once the settings are verified this session and approved there (policyHelper itself is never honored from remote).`),...Dt.CLAUDE_CODE_ENABLE_XAA&&{xaaIdp:()=>O({issuer:h().url().describe("IdP issuer URL for OIDC discovery"),clientId:h().describe("Claude Code's client_id registered at the IdP"),callbackPort:Y().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:()=>O({type:U("command"),command:h()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:()=>v().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:()=>O({enabled:v().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:Y().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:Y().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:h().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:()=>O({enabled:v().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:h().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:h().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:()=>Y().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. Cleanup deletes data only on this computer, not anything stored by Anthropic."),desktopSessionCleanupPeriodDays:()=>Y().int().nonnegative().optional().describe("Retention ceiling in days for session transcripts created or last written by a desktop-host surface (Claude Desktop, Cowork), which are otherwise exempt from the cleanupPeriodDays sweep. 0 (the default) means no ceiling: such transcripts are kept until deleted another way. Unlike cleanupPeriodDays, 0 is allowed because this setting never disables writes — it only bounds an exemption from deletion. The ceiling is a hard cap: it also bounds an active archive grace, so the grace window of a release marker never keeps files past the ceiling. Ignored when cleanupPeriodDays is managed by org policy. A ceiling at or below cleanupPeriodDays effectively disables the exemption: those transcripts age out on the regular cleanupPeriodDays schedule, so the effective retention is whichever of the two periods is longer. Cleanup deletes data only on this computer, not anything stored by Anthropic."),syncClaudeAiSkills:()=>v().optional().describe("Set to false to turn off syncing of the skills you have enabled on claude.ai. In your user settings (or managed settings): nothing more is downloaded, previously synced skills (~/.claude/skills/synced) can no longer be run, are hidden from every session started afterwards, and are moved to ~/.claude/skills/.trash at the next launch (deleted after cleanupPeriodDays; re-downloaded, not restored, if you re-enable). In .claude/settings.local.json or --settings: downloads stop and synced skills are blocked and hidden for sessions in that workspace or invocation only (nothing is moved). Not read from project settings (.claude/settings.json). Only false is honored — the feature is enabled server-side for your account, so setting true does not turn it on early. While it is on, synced skills are available in every session, re-synced about every 10 minutes while a session is in use and a quarter as often otherwise, and removed when you disable them on claude.ai. Only applies when signed in with your Claude account."),syncClaudeAiPlugins:()=>v().optional().describe("Set to false to turn off syncing of the plugins you have enabled on claude.ai. In your user settings (or managed settings): nothing more is downloaded, previously synced plugins (~/.claude/plugins/synced) are hidden from every session started afterwards and moved to ~/.claude/plugins/.trash at the next launch (deleted after cleanupPeriodDays; re-downloaded, not restored, if you re-enable). In .claude/settings.local.json or --settings: downloads stop and synced plugins are hidden for sessions in that workspace or invocation only (nothing is moved). Not read from project settings (.claude/settings.json). Only false is honored — the feature is enabled server-side for your account, so setting true does not turn it on early. While it is on, synced plugins load in every session like plugins you installed yourself (a plugin you installed with the same name takes precedence), are re-synced at each launch, and are removed when you disable them on claude.ai. Only applies when signed in with your Claude account."),skillListingMaxDescChars:()=>Y().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:()=>Y().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:()=>v().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:()=>or(()=>g9e()).describe("Environment variables to set for Claude Code sessions"),attribution:()=>{let o=O({commit:h().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:h().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:v().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link."),...!1}).passthrough();return ie([v(),o],{error:(s)=>{let i=(s.errors??[]).flat().filter((l)=>l.path.length>0);if(i.length>0)return i.map((l)=>`${l.path.join(".")}: ${l.message.replace(/^Invalid input: /,"")}`).join("; ");return`Expected false, true, or an object such as { "commit": "", "pr": "" }, but received ${Array.isArray(s.input)?"array":s.input===null?"null":typeof s.input}`}}).transform((s)=>{if(typeof s!=="boolean")return s;return s?{}:{commit:"",pr:"",sessionUrl:!1}}).pipe(o).optional().describe('Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set. Set to false to hide all attribution, the same as { "commit": "", "pr": "", "sessionUrl": false }. Setting it to true is the same as leaving it out. Older Claude Code versions reject true or false here, so use the object form in settings files shared across versions.')},attributionProject:()=>h().optional().describe(`The claude.ai Project this session names for your organization's usage reports: the Project's ID, starting with "claude_proj_" or "chan_", or the UUID of a "claude_proj_" Project. An empty string names none and stops lower-precedence files from naming one; the organization default still applies. Sent only when Claude Code uses your claude.ai login, connects directly to the Anthropic API, is not in a cloud session, and CLAUDE_CODE_ATTRIBUTION_HEADER is not 0. CLAUDE_CODE_ATTRIBUTION_PROJECT takes precedence over it. Set in managed settings, it overrides people's own settings files. A project's .claude/settings.json and settings.local.json count only once the folder is trusted; for runs in a folder nobody has trusted, such as CI, use CLAUDE_CODE_ATTRIBUTION_PROJECT.`),attributionProjectPolicy:()=>O({default:h().optional().describe('The Project used when neither CLAUDE_CODE_ATTRIBUTION_PROJECT nor attributionProject names one: its ID, starting with "claude_proj_" or "chan_", or the UUID of a "claude_proj_" Project.')}).optional().describe("Your organization's default for attributionProject. Only honored from managed settings (server-managed, MDM / OS policy, or managed-settings.json); ignored in user, project, local and --settings sources."),includeCoAuthoredBy:()=>v().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,...!1,includeGitInstructions:()=>v().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:()=>or(()=>BZ(e)).describe("Tool usage permissions configuration"),model:()=>h().optional().describe("Override the default model used by Claude Code"),fallbackModel:()=>k(h()).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:()=>k(h()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows that version and any model ID that extends it, so "claude-opus-5" also allows "claude-opus-5-5"), 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:()=>v().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."),availableModelsMatch:()=>K(["prefix","exact"]).optional().describe('How availableModels entries match model IDs. "prefix" (the default) lets an entry also allow any model ID that extends it, so "claude-opus-5" allows "claude-opus-5-5". "exact" keeps that matching but stops a model ID entry from allowing other versions: "claude-opus-5" allows Opus 5 and its dated and -fast IDs, but not Opus 5.5 or a later release until it is listed, and a -latest ID needs a -latest entry. Family aliases ("opus") still allow the whole family; aliases whose model depends on the release or settings (best, opusplan, default) are ignored. With "exact" and a list that names at least one model, the Default option also uses only a listed model; if none can be used, Claude Code will not start. Haiku background models, and hooks and other helper requests that pick their own model, are not restricted (deniedModels covers them; allowManagedHooksOnly limits hooks). Read from managed settings only.'),deniedModels:()=>k(h()).optional().describe('Models users cannot select, even when availableModels allows them. A family alias ("opus") blocks that family. A model ID blocks that version in every spelling: dates, -fast and provider prefixes are ignored, so "claude-opus-5-5" blocks every Opus 5.5 ID but not Opus 5. An ID with no minor version ("claude-opus-5") also blocks later minor versions, as it allows them in availableModels. Aliases whose model depends on the release or settings (best, opusplan, default) are ignored. The Default option steps down past a blocked model; if the Default has no allowed model to step down to, Claude Code will not start. Read from managed settings only.'),modelOverrides:()=>q(h(),h()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),modelPicker:()=>O({options:k(lx()).describe("Rows to show in the /model picker, in order."),replaceBuiltInOptions:v().optional().describe("When true, the picker shows only the Default row and these options — the built-in "+"lineup, gateway-discovered models and ANTHROPIC_CUSTOM_MODEL_OPTION are hidden. When false or unset, these options are added after the built-in lineup.")}).optional().describe("Curate the /model picker: an ordered list of models with your own labels, independent of the built-in lineup and of Claude Code releases. availableModels still applies to these rows. Honored from managed, --settings/SDK, and user settings only (not from a project checkout); the highest-precedence of those that defines modelPicker wins outright (no merging across sources). Typically set in managed settings by enterprise administrators."),modelPricing:()=>O({multiplier:ax(),overrides:q(h(),ix()).optional()}).optional().describe("Price usage at your organization's contracted rates instead of list price. "+"Affects every spend figure Claude Code reports — /cost, the status line, the SDK total_cost_usd, "+"--max-budget-usd, and the OpenTelemetry cost metric and events — which remain USD estimates, not an invoice "+'(the per-Mtok price labels in /model stay at list). "overrides" maps a model ID to its USD-per-million-token rates (input, output, cacheRead, '+"cacheWrite — all four required, each 0 to 10000; cacheWrite prices both 5-minute and 1-hour cache writes). "+"A matching row is charged exactly as written; fast-mode and US-data-residency surcharges are not added on top. "+'A key Claude Code itself uses for a built-in model — its ID such as "claude-sonnet-4-6", or its '+"first-party, Bedrock (any or no region prefix), Vertex or Foundry ID — covers every dated and provider form "+"of that model; any other key — a gateway model alias, or a spelling Claude Code does not itself use — "+'matches that model ID only (case-insensitive), and such an exact match wins over a built-in row. On Bedrock an application inference profile is matched by its backing model. An invalid row or multiplier is reported and skipped; the rest still apply. "multiplier" in (0, 10] scales every computed cost, overridden or not (0.85 = 85% of the price, 1.2 = 120%). Only honored from managed settings (server-managed, MDM / OS policy, or managed-settings.json), '+"or — when none of those sets it — when supplied by a host application that manages the model "+"provider; ignored in user, project, local and --settings sources."),...!1,enableAllProjectMcpServers:()=>v().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:()=>k(h()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:()=>k(h()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:()=>v().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected, and a claudeai-proxy server passed explicitly (e.g. via --mcp-config or the SDK mcpServers option) does not connect either. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:()=>q(h(),K(["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:()=>v().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),managedMcpServers:()=>or(()=>q(h().refine(hv,{error:fy}),_v(),{error:yv})).describe(`MCP servers the organization provides to every user, keyed by server name, each with the .mcp.json entry shape; only "http" and "sse" servers are accepted (nothing that names a program to run, no \${VAR} references). Honored from managed settings only; users cannot remove them, deniedMcpServers still applies, and they need no allowedMcpServers entry. Not read in Claude Desktop's Code tab on a third-party deployment or in Cowork sessions, where Claude Desktop supplies and locks the session's MCP servers itself.`),allowedMcpServers:()=>or(()=>k(ky())).describe("Enterprise allowlist of the MCP servers users may use. Governs servers users add (user, project and local config, --mcp-config, agent frontmatter, plugins, claude.ai connectors); servers the organization itself delivers (managedMcpServers, and managed-mcp.json entries with no ${VAR} in their command, args, url or header values) are allowed without being listed; a managed-mcp.json entry with ${VAR} in any of those must match this list. If undefined, all servers are allowed. If empty array, users can use no servers of their own. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:()=>or(()=>k(Py())).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:()=>or(()=>wa()).describe("Custom commands to run before/after tool executions"),worktree:()=>O({symlinkDirectories:k(h()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:k(h()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos — only the listed paths are written to disk."),baseRef:K(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:K(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly."),location:h().optional().catch(void 0).describe("Directory under which Claude Code Desktop creates the worktrees of SSH sessions that run on this machine (an absolute path or one starting with ~/), instead of <project>/.claude/worktrees. Read by the desktop app from the SSH host user settings; a location chosen in the desktop app's SSH connection settings takes precedence. The CLI (--worktree, EnterWorktree, agent isolation) does not read it yet.")}).optional().describe("Git worktree configuration: the CLI --worktree flag, EnterWorktree and agent isolation, plus the location Claude Code Desktop uses for SSH-session worktrees on this machine."),disableAllHooks:()=>v().optional().describe("Disable all hooks and statusLine execution: the hooks defined in settings files and by installed plugins. Features built into Claude Code are not hooks in this sense and keep working; each has its own switch."),disableReplyCheck:()=>v().optional().describe("Disable the reply check in Claude Tag sessions on a self-hosted runner. The check re-prompts Claude, at most four times a turn, when a turn ends without a call to one of Claude Tag's reply tools. It is not a hook, so disableAllHooks does not affect it. Disabling it also stops two messages to Claude that Anthropic's service can request for such a session: a nudge after a long stretch of work with no visible update, and a reminder added to prompts. Claude Code's built-in reminder to give progress updates, on models that have it, is then no longer held back. Set it in managed settings; false there keeps the check on. Everywhere else it is ignored and the check stays on. Has no effect on sessions that Anthropic hosts."),disableAgentView:()=>v().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:()=>v().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:()=>v().optional().describe("Disable the Workflows feature. Code Review on pull requests and /ultrareview run in Anthropic's cloud and are not stopped by this setting, except an /ultrareview that has to restart partway through. A machine that runs a review itself refuses it when that machine's own administrator set this, or CLAUDE_CODE_DISABLE_WORKFLOWS in an `env` block, in its managed settings (MDM, the managed-settings file or an administrator's policy helper). Set in the environment before Claude Code starts, CLAUDE_CODE_DISABLE_WORKFLOWS disables Workflows. Beyond the cases above it stops a review only when the review's own session starts with it set."),disableArtifact:()=>v().optional().describe("Deprecated: use enableArtifact: false. Still honored — true disables the Artifact tool; false is ignored."),enableArtifact:()=>v().optional().describe("Turn the Artifact tool on or off. Off in any of managed, --settings, or user settings wins; project and local settings can only turn it off. Unset defaults to on once the feature is available."),enableWorkflows:()=>v().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowSizeGuideline:()=>K(["unrestricted","small","medium","large"]).optional().describe('Advisory size guideline for the dynamic workflows Claude writes: "small" aims for fewer than 5 agents, "medium" fewer than 10, "large" fewer than 50, and "unrestricted" sends no guideline. Unset defaults to "medium", or "small" on Pro plans. A value here — including from managed settings — takes precedence over the "Dynamic workflow size" choice in /config, and that /config row is hidden while a settings file provides the key. This is a guideline, not an enforced limit.'),workflowKeywordTriggerEnabled:()=>v().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:()=>v().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."),disableWindowsBashCommandSplit:()=>v().optional().describe("Windows only. Set to true to keep every Bash command in a single argument to bash, so that endpoint security tools that match text in process command lines see it whole. Otherwise Claude Code may split a long command over several arguments. With true, a command of about 7,000 characters or more, or fewer if it is full of quotes, may reach bash cut short, and then usually fails with a syntax error. Only honored from managed settings; ignored in user, project, local and --settings sources."),defaultShell:()=>K(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),bashEditDiffEnabled:()=>v().optional().describe("Whether the Bash tool shows a diff of the files a Bash command changed (PostToolUse Bash hooks get the changed-file list in tool_response). Set to false to turn that off. Default: off, except in auto and bypassPermissions modes when the Bash tool handles file edits or the model's configuration turns it on. Only user, flag or policy settings can turn it on in other modes."),bashOutputMaxChars:()=>Y().int().positive().optional().catch(void 0).describe("How many characters of a successful Bash or PowerShell command's output Claude receives inline (default 30000; values clamp to 4000-128000). Output past this is saved to a file and Claude receives a short preview plus the path. When set, this also replaces BASH_MAX_OUTPUT_LENGTH, which on its own only sizes the read-back window."),taskOutputMaxChars:()=>Y().int().positive().optional().catch(void 0).describe("Deprecated: no longer has any effect (the TaskOutput tool was removed). Read a background task's output file with the Read tool instead."),respondToBashCommands:()=>v().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:()=>v().optional().describe("When true (and set in managed settings), only hooks from managed settings and from plugins that managed settings enable run. User, project, and local hooks and the hooks of plugins the user installed are ignored. Features built into Claude Code are not hooks in this sense and keep working."),allowedHttpHookUrls:()=>k(h()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:()=>k(h()).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:()=>v().optional().describe("When true (and set in managed settings), permission rules from user, project, local, and --settings files and allow rules from --allowedTools are ignored; only managed settings can add allow rules through settings. "+"The allowed-tools frontmatter of skills and custom commands from user, project, and --add-dir sources, and of plugins no managed setting vouches for, is ignored too. Plugins keep theirs only on an admin-backed channel: host-delivered --plugin-dir plugins (in Claude Desktop, only while this is not set by the organization's own managed settings), the official marketplace registered from its unpinned anthropics source, claude.ai-synced plugins Anthropic attests, the saved login organization's claude.ai-hosted marketplaces, marketplaces whose registered source managed extraKnownMarketplaces declares or an exact or owner-pinned (owner/*) strictKnownMarketplaces entry names at the path it pins (an npm marketplace source only when the registration and the declared entry pin the same registry, and a settings marketplace source only when every nested npm plugin entry pins one on a bare package name — unpinned, the package resolves through the member's own npm config, and a non-bare spelling packs as an exotic spec the pin does not bind, so nothing an entry names is what was fetched), and npm-direct (package@npm) plugins whose recorded resolution a registry-pinned managed npm strictKnownMarketplaces entry names (host and path patterns and enabledPlugins ids do not vouch); managed and bundled skills keep theirs. "+"--disallowedTools, skill disallowed-tools, and other deny and ask rules from the command line or the current session still apply."),allowManagedMcpServersOnly:()=>v().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:()=>v().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."),allowClaudeInChromeWithManagedMcp:()=>v().optional().describe("When true (and set in device managed settings: MDM, the managed-settings.json file, or a policy helper those configure), the built-in Claude in Chrome MCP server can run alongside managed-mcp.json instead of being blocked by its exclusive-control lockdown. deniedMcpServers and the organization's Claude in Chrome setting still block it. Default off preserves the lockdown."),strictPluginOnlyCustomization:()=>qZ().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:()=>O({type:U("command"),command:h(),padding:Y().optional(),refreshInterval:Y().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:v().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:()=>h().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:()=>k(K9e().catch(DZ)).transform((o)=>o.filter((s)=>s!==DZ)).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:()=>O({type:U("command"),command:h()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:()=>q(h(),YZ()).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json — setting false in ~/.claude/settings.json is overridden by the project.'),prependPlugins:()=>k(h()).optional().catch(void 0).describe("Managed plugins (plugin@marketplace ids that managed enabledPlugins sets true) whose hooks run first, outermost, in the listed order: the first id listed sees every event before any other plugin and every result after it. Managed plugins not listed here or in appendPlugins follow the listed ones; user, project and marketplace plugins come after those; then appendPlugins; then the built-in plugins. The bundled cc-plugin-sec-default@builtin seats itself outermost (on a machine with managed settings and for Team and Enterprise organizations) unless this list is set, in which case list it where it should sit or leave it out. Name it there as sec-default@builtin, the id every release reads, for as long as any machine in the organization may run a release from before its rename; a release that knows the new id reads either. Any other id that is not an enabled managed plugin is skipped; an id listed in both keys is prepended. Only honored from managed settings (or, on a machine with none, from user settings for your own plugins); ignored in project, local and --settings sources."),appendPlugins:()=>k(h()).optional().catch(void 0).describe("Managed plugins (plugin@marketplace ids that managed enabledPlugins sets true) whose hooks run last among plugins, innermost, in the listed order: the last id listed sits just above the built-in plugins and sees each event as every other plugin left it. Only honored from managed settings (or, on a machine with none, from user settings for your own plugins); ignored in project, local and --settings sources."),extraKnownMarketplaces:()=>or(()=>n("extraKnownMarketplaces")).describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),additionalMarketplaces:()=>or(()=>n("additionalMarketplaces")).describe("Alias for extraKnownMarketplaces: this key is read exactly as if it were spelled "+"extraKnownMarketplaces. Do not set both in one file — if both appear, this key is ignored "+"with a warning. Claude Code may rewrite this key as extraKnownMarketplaces when it updates the file. Clients older than this alias ignore it, so prefer extraKnownMarketplaces while older Claude Code versions still share the same settings."),strictKnownMarketplaces:()=>or(()=>k(by())).describe('Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these sources can be added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to allow every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem. '+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),allowedMarketplaces:()=>or(()=>k(by())).describe("Alias for strictKnownMarketplaces (managed settings only): this key is read exactly as if it "+"were spelled strictKnownMarketplaces. Do not set both in one file — if both appear, this key "+"is ignored with a warning. Clients older than this alias ignore it, so keep using strictKnownMarketplaces when the allowlist must also bind older Claude Code versions."),blockedMarketplaces:()=>or(()=>k(Wv())).describe('Enterprise blocklist of marketplace sources. When set in managed settings, these sources are blocked from being added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to block every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem.'),disableCommandPluginSources:()=>v().optional().describe("Controls the `command` plugin source, whose plugin directory is produced by running a marketplace-declared command on this machine. true: command-sourced plugins are never installed, updated, or re-resolved (the command never runs). false: explicitly allowed. "+"Unset: follows allowManagedHooksOnly — an org that restricts hook execution to managed "+"settings gets command sources disabled too. Only honored from managed settings."),...!1,disableSideloadFlags:()=>v().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:()=>k(h()).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 tips for Anthropic's own plugins are 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:()=>K(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for a Claude subscription (individual, Team, or Enterprise plans), "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:()=>h().min(1).optional().catch(void 0).describe('Cloud gateway URL to pre-fill during login, alongside forceLoginMethod: "gateway". Honored from admin-controlled managed settings (MDM / managed-settings.json / policy helper) and, on a machine with none of those, from your own user settings; ignored in project, local, flag, and remote-delivered settings.'),gatewayInternalNetworks:()=>k(h()).optional().catch([XZ]).meta({default:void 0}).describe("IPv4 CIDR blocks (at most 4, each /8 to /32, not overlapping) your Cloud gateway sits in: the public block your organization numbers its internal network from, which lets /login reach a gateway there. A block must lie entirely outside private space, where /login accepts a gateway without this key. /login accepts a gateway inside a listed block over a direct connection only, and only when this machine's own address on that connection is inside the same block, so /login must happen from a machine whose own address is inside the block (not through a proxy, VPN pool, container or NAT segment outside it). A bar against copied settings files, not proof of location. Honored only from admin-controlled managed settings (MDM / managed-settings.json / policy helper); ignored in user, project, and remote-delivered settings."),parentSettingsBehavior:()=>K(["first-wins","merge"]).optional().describe(`Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" (the default, except in a gateway session Claude Desktop's Code `+'tab launched, where "merge" is): parent is dropped — admin tiers '+`are the only policy source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),managedSourcesBehavior:()=>K(["first-wins","merge"]).optional().describe('Controls how the managed settings sources compose. "first-wins" (default): the highest-priority source present (server-managed > MDM (managed plist / HKLM) > managed-settings.json) is the managed tier alone. "merge": every present source deep-merges with fixed '+"precedence server-managed > MDM > managed-settings.json — scalars "+"take the highest source's value (a restrictive boolean or enum — "+"the allowManaged*Only locks, the disable* switches, the sandbox "+"lock family — takes the strictest value any source sets) and "+"arrays union, except fallbackModel, the restriction allowlists allowedMcpServers, allowedProviders, availableModels, strictKnownMarketplaces and allowedChannelPlugins, and sandbox.credentials.awsPairs and sandbox.ripgrep (the highest source that sets one owns it whole), modelOverrides (the whole map of the highest source that sets it, dropped when that source sits below the one that sets availableModels), managedMcpServers (server names union; a name set by two sources takes the higher source's whole entry), and the keys taken from the highest source only: the auth pins forceLoginOrgUUID, forceLoginMethod, forceLoginGatewayUrl and gatewayInternalNetworks, the credential helpers apiKeyHelper, awsAuthRefresh, awsCredentialExport, gcpAuthRefresh, otelHeadersHelper and proxyAuthHelper, modelPicker, permissions.defaultMode, parentSettingsBehavior and the policyHelper configuration (env keeps its own per-key union). In both modes, a forceLoginOrgUUID, or a forceLoginMethod of claudeai or console, that this machine's own MDM policy or managed settings file sets applies ahead of server-managed settings. Honored only from the highest-priority source present; enable it only when every lower source is admin-controlled, since lower sources then contribute entries such as permissions.allow. HKCU and --managed-settings never take part in the merge."),forceLoginOrgUUID:()=>ie([h(),k(h())]).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."),allowedProviders:()=>Me((o)=>Array.isArray(o)?o.filter(Ev):o,k(K(Zp))).optional().catch(void 0).describe(`Managed settings only (managed-settings.json, MDM, or server-managed). The API providers Claude Code may use on this machine: "anthropic" (the Anthropic API on Anthropic's own host, via a claude.ai or Console sign-in or an API key; pair it with forceLoginMethod / forceLoginOrgUUID to require a sign-in), "bedrock", "vertex", "foundry", "anthropicAws", "mantle" (each meaning that provider's own service: its regional, FIPS, private-endpoint and sovereign-cloud hosts), "customEndpoint" (the `+"Anthropic API or a cloud provider's API sent to some other host — ANTHROPIC_BASE_URL, that "+"provider's ANTHROPIC_*_BASE_URL, a Foundry resource name that is not a bare name, or for "+"Bedrock the AWS SDK's AWS_ENDPOINT_URL[_BEDROCK[_RUNTIME]] — such as an LLM gateway; admitted "+`only for the value pinned in the "env" block of the same managed source), or "gateway" (the Cloud gateway sign-in). A session on a provider that is not listed is refused at startup, at login, and when it next contacts the API, with a message naming what selected the provider and the entry that would allow it. Under a list, where first-party traffic goes (ANTHROPIC_BASE_URL, a gateway sign-in) is honored only when the same managed source pins it in "env" (or forceLoginGatewayUrl), and a claude ssh tunnel into the machine is refused. A cloud provider's credential and tenancy variables, and the network path and TLS trust (HTTPS_PROXY, NODE_EXTRA_CA_CERTS, CLAUDE_CODE_CERT_STORE), are not judged by this list; set those for the fleet in the managed "env" block, whose values replace the user's. To route Bedrock through a gateway for a fleet, pin ANTHROPIC_BEDROCK_BASE_URL there (it is what the clients use, ahead of an endpoint_url in ~/.aws/config, which this list does not judge); the AWS SDK's AWS_ENDPOINT_URL* pins only sanction where the SDK's own clients go and never stand in for the "bedrock" entry. Unset allows every provider; an empty array allows none. Only a list in managed-settings.json or MDM is enforcement on the machine: it cannot be widened or hidden by server-managed settings and reaches every session. A list set `+"only in the admin console reaches only sessions that fetch your server-managed settings — not "+"a session on a cloud provider, another organization or a non-Anthropic ANTHROPIC_BASE_URL, one authenticating only with apiKeyHelper or ANTHROPIC_AUTH_TOKEN, a Pro/Max/Ultra login, --bare without "+"an API key, or a first launch before the fetch lands — all conditions the user controls. "+`Versions that predate this setting ignore it; pair it with a minimum-version policy on a mixed fleet. 'claude auth status' reports the Anthropic API as apiProvider "firstParty".`),...!1,forceRemoteSettingsRefresh:()=>v().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:()=>h().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:()=>h().optional().describe("Controls the output style for assistant responses"),viewMode:()=>K(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:()=>h().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:()=>v().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:()=>or(()=>sv()),...!1,feedbackSurveyRate:()=>Y().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),feedbackDrafts:()=>K(["notify","quiet","off"]).optional().describe('Model-drafted feedback (the SendFeedback tool). "notify" (default) shows a one-line notice when a draft is queued; "quiet" shows only the footer counter; "off" disables the tool entirely so drafts are never queued.'),spinnerTipsEnabled:()=>v().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:()=>O({mode:K(["append","replace"]),verbs:k(h())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:()=>O({excludeDefault:v().optional().catch(void 0),tips:_9e().optional(),tipsFile:h().optional().catch(void 0).describe("Absolute or ~/ local path to a JSON file holding an array of tips (same shapes as `tips`); honored from user, --settings and on-disk managed settings only. Read once per CLI process (restart to pick up edits)."),label:h().optional().catch(void 0).describe('Prefix shown before your tips in the spinner (default "Tip")')}).passthrough().optional().catch(void 0).describe("Add your organization's own tips to the spinner tip rotation. tips: strings or {id, text, cooldownSessions?, priority?} objects; tipsFile: a JSON file of the same; label: prefix shown before your tips; excludeDefault: if true, only show your tips (default: false)."),syntaxHighlightingDisabled:()=>v().optional().describe("Whether to disable syntax highlighting in diffs"),maxProseWidth:()=>Y().int().min(40).optional().catch(void 0).describe("Maximum width, in terminal columns, of the prose in Claude's responses (paragraphs, headings, lists, blockquotes). In a wider terminal the prose wraps at this width while tables and code blocks keep the full width; only the display wraps, the response text itself gains no line breaks. Minimum 40. Unset (the default) uses the full terminal width."),spellcheck:()=>O({enabled:v().optional().catch(void 0).describe("Turn on spell checking of the prompt input (default: false)"),checker:h().optional().catch(void 0).describe(`Which spell checker to run: ${Ay.map((o)=>`"${o}"`).join(", ")}, or "auto" (default) for the first of those found on PATH`),language:h().optional().catch(void 0).describe(`Dictionary to use, passed to the checker as-is (aspell --lang, hunspell -d, ispell -d), e.g. "en_GB"; names are checker-specific (letters, digits and _ - . , only). Default: the checker's own default`),color:h().optional().catch(void 0).describe(`Color of misspelled words (they are also underlined): a terminal color name such as "red" or "magenta", "#rrggbb", "rgb(r,g,b)", "ansi256(n)" or "ansi:<name>". Default: the theme's error color`)}).passthrough().optional().catch(void 0).describe(`Underline misspelled words in the prompt input as you type, using an installed ${Ay.slice(0,-1).join(", ")} or ${Ay.at(-1)} (off unless "enabled" is true; does nothing if none is installed). Read from user, flag and managed settings only (the whole block from the highest-precedence of those applies); ignored in project .claude/settings.json and .claude/settings.local.json.`),terminalTitleFromRename:()=>v().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),promptCacheTtl:()=>K(fl).optional().catch(void 0).describe('Prompt cache TTL for the main conversation (interactive, -p and SDK turns, plus the helpers that run inline with it): "5m" or "1h". Unset = automatic: 1 hour on a Claude subscription within its usage limits, 5 minutes on an API key, Bedrock, Vertex or Foundry. 1-hour cache writes are billed at a higher rate; the cache stays warm across longer breaks. The CLAUDE_CODE_PROMPT_CACHE_TTL environment variable takes precedence.'),subagentPromptCacheTtl:()=>K(fl).optional().catch(void 0).describe("Prompt cache TTL for everything outside the main conversation — subagents, workflows, background and helper requests: "+'"5m" or "1h". Unset = automatic (5 minutes unless ENABLE_PROMPT_CACHING_1H=1). The CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL environment variable takes precedence.'),alwaysThinkingEnabled:()=>v().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:()=>K(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),maxEffortLevel:()=>K(Fp).optional().catch(void 0).describe("Maximum effort level. Anything above it (an /effort or /model pick, --effort, CLAUDE_CODE_EFFORT_LEVEL, a model default) is clamped to it, on every provider including Bedrock, Vertex and Foundry. Combines with an organization's per-model effort cap by taking the lower of the two; across settings files the lowest value wins, and modelSettings.<model>.maxEffortLevel replaces it per model. Enforced client-side: an effort supplied through CLAUDE_CODE_EXTRA_BODY is not clamped."),modelSettings:()=>Me((o)=>typeof o==="object"&&o!==null&&!Array.isArray(o)?ba(o,(s,i)=>Object.hasOwn(Object.prototype,i)):o,q(h(),O({effortLevel:K(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for this model."),maxEffortLevel:K(Fp).optional().catch(void 0).describe('Maximum effort level for this model. Within one settings file it replaces the top-level maxEffortLevel for the model ("max" exempts it); across settings files the lowest applicable value wins. Keyed like effortLevel: the canonical model name also matches its dated, [1m], Bedrock and Vertex spellings.'),autoCompactWindow:ie([U("auto"),LZ()]).describe('Auto-compact window for this model, in tokens (100000 to 1000000), or "auto" for the window tuned for the model. Within one settings file it replaces the top-level autoCompactWindow for the model. /autocompact saves here. The canonical model name as key also matches its dated, [1m], Bedrock and Vertex spellings.')}).passthrough().optional().catch(void 0))).optional().catch(void 0).describe("Per-model settings keyed by canonical model name."),ultracode:()=>v().optional().catch(void 0).describe("Enable ultracode for the session: standing dynamic-workflow orchestration at any effort level. "+"Session-scoped — typically provided via --settings or the apply_flag_settings control request; "+"interactive toggles never persist it. Requires workflows to be enabled and a model that supports ultracode."),autoCompactWindow:()=>LZ().describe("Auto-compact window size"),...!1,advisorModel:()=>h().optional().describe("Advisor model for the server-side advisor tool."),fastMode:()=>v().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:()=>v().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:()=>v().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),emojiCompletionEnabled:()=>v().optional().describe("When false, the :emoji: shortcode typeahead (the suggestion popup and the :name: inline replacement) is disabled. When absent or true, it is enabled."),awaySummaryEnabled:()=>v().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."),responseComparisonEnabled:()=>v().optional().describe("@internal Set to false to stop Claude Code from showing two answers to one message and asking which is better. When absent or true, it may do so on some turns. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:()=>v().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:()=>K(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers "+"selected so far. Defaults to never — auto-continue only runs "+"when explicitly set to 60s/5m/10m."),dialogExpiry:()=>K(["60s","5m","10m","never"]).optional().catch(void 0).describe('Max time a permission/user dialog forwarded to a remote client stays parked awaiting an answer, and how long a HELD cross-session message awaits approval, before either resolves to its safe no-action default (cancelled / dropped-with-denial). Defaults to 5m to match the long-standing remote-dialog deadline; "never" disables the deadline. Local-only permission prompts (no remote client) are unaffected. The CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS env var, when set, overrides this. Read from trusted sources only (never a checked-in repo settings file).'),agent:()=>h().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),modelProposedGoals:()=>K(zY).optional().catch(void 0).describe("@internal Controls the ProposeGoal tool (model-proposed session goals). 'auto' (the default when absent) lets the model choose per proposal whether to ask for approval via its ask_user parameter; 'alwaysAsk' routes every model-proposed goal through the approval dialog; 'disabled' turns the tool off. A typed /goal is unaffected. Consent-affecting, so it is read "+"from trusted sources only (user/policy/flag) — "+"workspace-resident project and local settings are ignored."),companyAnnouncements:()=>k(h()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:()=>q(h(),O({mcpServers:q(h(),q(h(),ie([h(),Y(),v(),k(h())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:q(h(),ie([h(),Y(),v(),k(h())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(fO())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:()=>O({defaultEnvironmentId:h().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:()=>K(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:()=>h().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:()=>h().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:()=>h().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:()=>h().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:()=>K(["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:()=>O({enabled:v().optional(),mode:K(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:v().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:()=>v().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:()=>k(jZ()).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:()=>v().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),timeFormat:()=>ie([K(FY),h()]).optional().describe('Clock format for times shown in the UI: "auto" (default, follows the locale), "12-hour", "24-hour", "24-hour-utc" ("18:05Z"), or a strftime pattern such as "%H:%M" (any value containing "%"; other values read as "auto"). A pattern replaces the time everywhere; message timestamps show only the pattern, so include %Y-%m-%d for the date. /config offers the presets; a pattern is set here.'),timeZone:()=>h().optional().describe('IANA time zone for times shown in the UI, e.g. "UTC" or "Europe/Dublin". Default: the system time zone. An unknown name falls back to the system time zone.'),doneMeansMerged:()=>v().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:()=>K(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn "+"is on — task-budget semantics). Defaults to padded-countdown for a "+"model with the total_tokens_reminder capability, else off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:()=>Y().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:()=>v().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to on. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:()=>v().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:()=>h().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/."),...!1,autoDreamEnabled:()=>v().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:()=>v().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:()=>v().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:()=>v().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:()=>K(["disable"]).optional().describe("Disable auto mode"),remoteTools:()=>O({allowUnattendedServing:v().optional().describe("@internal When false in managed or user settings, a cloud session in auto mode may not run commands on this computer without a person approving each one, whatever consent the computer has given; a project, local or --settings value is ignored. Default: true.")}).optional().describe("@internal How this computer serves tool calls to cloud sessions"),sshConfigs:()=>k(O({id:h().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:h().describe("Display name for the SSH connection"),sshHost:h().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:Y().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:h().optional().describe("Path to SSH identity file (private key)"),startDirectory:h().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."),sshHostCommands:()=>me().meta({type:"array"}).optional().describe("SSH connections in Claude Desktop whose host comes from a command. A list of entries, each with `id`, `name` and `command`, and optionally `sshIdentityFile` and `startDirectory`. Desktop runs `command` on this computer when you create the connection or another host for it, not each time you connect. `command` is a program name or absolute path (single-quote a path with spaces), then plain arguments. Nothing else can be quoted. For pipes, variables or a leading `~`, use a script. On Windows, the program must be a full path from a drive letter, such as `C:/tools/acme.exe`, ending in `.exe`, `.cmd` or `.bat`. Quoted paths and Windows need Claude Desktop v4.16336.0 or later. The command must print only the host on standard output: `host` or `user@host` on one line, or a JSON object with `sshHost` and, optionally, `sshPort` and `startDirectory`. Desktop reads this key only from user settings and from this computer's managed settings. Claude Code itself does not use it."),claudeMd:()=>h().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:()=>k(h()).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:()=>h().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:()=>ie([K($Y),h().startsWith("custom:").transform((o)=>o)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:()=>K(UY).optional().catch(void 0).describe("Key binding mode for the prompt input"),keybindingFlavor:()=>K(["classic","readline"]).optional().catch(void 0).describe("Deprecated: no longer has any effect. The prompt's word-editing keys always follow Bash (readline) conventions."),vimInsertModeRemaps:()=>q(h(),me()).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:()=>v().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:()=>K(NY).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:()=>v().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:()=>v().optional().describe("Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),idleCompaction:()=>v().optional().describe("Set to false to stop Claude Code from compacting a long conversation while the session is idle. Defaults to true."),switchModelsOnFlag:()=>v().optional().describe("When safeguards flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoContinueAtUsageLimit:()=>v().optional().describe("When a claude.ai usage limit stops your session, wait for the limit to reset and continue the task automatically. When off, the limit dialog offers the wait as a choice instead."),autoScrollEnabled:()=>v().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:()=>v().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:()=>v().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:()=>v().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:()=>v().optional().describe("Stamp each message with its arrival time"),terminalProgressBarEnabled:()=>v().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:()=>v().optional().describe("Enable the todo / task tracking panel"),teammateMode:()=>K(HY).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:()=>v().optional().describe("Start Remote Control bridge automatically each session"),remoteControl:()=>O({shareHostProfile:K(xy).optional().catch(void 0).describe("@internal What a Remote Control environment reports about this machine when it registers: 'off' reports nothing, 'basic' the OS, architecture and detected developer tools, 'full' also the names of MCP servers configured on this machine (never a repository's .mcp.json). When unset, the level comes from the feature rollout, which may be any of the three. Managed, --settings and user settings choose the level (the most restrictive wins); project and local settings can only lower it, never raise it. Read when Remote Control starts; lowering it later applies from the next registration, raising it from the next start.")}).optional().describe("@internal Remote Control (`claude remote-control`) options"),isolatePeerMachines:()=>v().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:()=>K(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),crossSessionInbound:()=>K(of).optional().catch(void 0).describe("Inbound cross-session peer messages (SendMessage from your other sessions): 'accept' delivers them, 'hold' parks them for your review without letting Claude act, 'refuse' opts this session out. An explicit value always wins. Unset (mode parity): a message auto-delivers only when the sending session's permission-mode class matches yours (bypass↔bypass or prompting↔prompting); a mismatched sender's message is held for your approval; a sender that asserts no class is held only while this session bypasses permission prompts."),autoUploadSessions:()=>v().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:()=>v().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:()=>v().optional().describe("Allow Claude to push proactive mobile notifications"),...K_(EZ(e),(o)=>()=>o)}}function dx(e,t={}){let n=ZZ(e,t);return new Vc(n).whole()}var G9e=new Set,W9e=new Set,Iy=P(()=>new Vc(ZZ(Jc()),G9e)),V9e=P(()=>Iy().whole());function Dy(e){return Iy().forDocument(e)}var MZ=Object.freeze({serverName:"invalid-entry-stripped"});function JZ(e){for(let t of e){let n=t.path.length>0?`${t.path.map(String).join(".")}: `:"";if(t.code==="invalid_union"){for(let r of t.errors){let o=JZ(r);if(o!==null)return`${n}${o}`}if("note"in t&&typeof t.note==="string"&&t.note!=="")return`${n}${t.note}`}if(t.message!=="")return`${n}${t.message}`}return null}var px=P(()=>{let e=Iy();return xo().flatMap(({path:t,restrictive:n})=>{if(t.length!==1||t[0]==="strictPluginOnlyCustomization"||t[0]==="disableAllHooks"||typeof n!=="boolean"&&typeof n!=="string")return[];let r=t[0],o=e.field(r);if(o===void 0||o instanceof yg)return[];return[{key:r,restrictive:n,field:o}]})}),Ly=P(()=>["strictKnownMarketplaces","blockedMarketplaces","strictPluginOnlyCustomization",...px().map((e)=>e.key)]),xi=["managedSourcesBehavior","wslInheritsWindowsSettings"];function sf(e){return oe(e)&&Object.values(e).every(sf)}function fx(e){let t=e.wslInheritsWindowsSettings;if(t===void 0||t===null)return"disarmed";let n=Yc(t);return n===!0?"armed":n===!1?"disarmed":"unreadable"}function mx(e){let t=e.source==="hostPattern"?e.hostPattern:e.source==="pathPattern"?e.pathPattern:null;if(t!==null&&!cZ(t))return`${e.source}: regex does not compile; the entry cannot be enforced`;if(e.source==="github"&&e.repo.includes("*")&&dZ(e.repo)===null)return'github: an owner wildcard must be exactly "<owner>/*"; the entry cannot be enforced';if(e.source==="git"&&pZ(e.url))return'git: wildcards are only supported in github-form entries, as "<owner>/*"; the entry cannot be enforced';if((e.source==="github"||e.source==="git")&&e.ref!==void 0&&e.ref.includes("*"))return`${e.source}: ref contains "*", which git does not allow in ref names; the entry cannot be enforced`;return null}function NZ(e,t){return ie([ra().transform(()=>{return}),k(me()).transform((n)=>{let r=[];for(let[o,s]of n.entries()){let i=(e==="blockedMarketplaces"?Wv():by()).safeParse(s);if(i.success){let a=mx(i.data);if(a!==null){if(e==="blockedMarketplaces")t({path:`${e}[${o}]`,message:`Unenforceable entry was kept: ${a}; it can never match a marketplace source, but marketplace restrictions stay active`}),r.push(i.data);else t({path:`${e}[${o}]`,message:`Invalid entry was ignored: ${a}`});continue}r.push(i.data)}else t({path:`${e}[${o}]`,message:`Invalid entry was ignored: ${JZ(i.error.issues)??"failed validation"}`})}if(e==="blockedMarketplaces"&&n.length>0&&r.length===0)t({path:e,message:'Every entry of "blockedMarketplaces" was invalid; none of them can be enforced until it is fixed.'});return r})]).optional()}function UZ(e,t,n){return k(t.catch((r)=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${r.issues[0]?.message??"failed validation"}`}),MZ))).transform((r)=>r.filter((o)=>o!==MZ)).optional()}var XZ="(unreadable)";function Oy(e,t,n,r,o,s){return k(me()).transform((i)=>{let a=[];for(let[l,c]of i.entries()){let d=t.safeParse(c);if(d.success){a.push(d.data);let p=o?.(c,d.data);if(p!==void 0)n({path:`${e}[${l}]`,message:p,statusOnly:!0})}else{let p=d.error.issues[0],f=p===void 0?"failed validation":p.path.length?`${p.path.join(".")}: ${p.message}`:p.message;n({path:`${e}[${l}]`,message:`Invalid entry was ignored: ${f}`,...s?.invalidEntryIsStatusOnly&&{statusOnly:!0}})}}if(i.length>0&&a.length===0)n({path:e,message:`Every entry of "${e}" was invalid; enforcing an empty allowlist (${r}) until it is fixed.`});return a}).optional().catch(()=>(n({path:e,message:`"${e}" was present but invalid; enforcing an empty allowlist (${r}) until it is fixed.`}),[]))}var Xc=P(()=>new Map(xo().flatMap(({path:e,restrictive:t})=>e.length>1?[[e.join("."),Ea(t)[0]]]:[]))),Qc=["soft_deny","hard_deny","deny"],q9e=new Map([["permissions",{restrictions:["deny","ask"],grants:["allow","additionalDirectories","defaultMode"]}],["autoMode",{restrictions:Qc,grants:["allow","environment"],withholdOnEntryDrop:!0}],["sandbox.network",{restrictions:["deniedDomains"],grants:["allowedDomains"],withholdOnEntryDrop:!0}],["sandbox.filesystem",{restrictions:["denyWrite","denyRead"],grants:["allowWrite","allowRead"],withholdOnEntryDrop:!0}]]),My=new Map([["permissions.defaultMode",{read:(e)=>{let t=jc(e);return[...Aa,...Zv(Jc())].find((n)=>n===t)},inert:new Set(["default","dontAsk","plan"]),floor:"default"}]]);function gx(e,t,n,r){let o=[],s=q9e.get(e);if(s===void 0)return o;let i=s.restrictions.flatMap((l)=>{switch(n(l)){case"unreadable":return[`"${l}"`];case"trimmed":return s.withholdOnEntryDrop?[`an entry of "${l}"`]:[];case void 0:return[]}});if(i.length===0)return o;let a=i.join(" and ");for(let l of s.grants){let c=My.get(`${e}.${l}`),d=c===void 0?t[l]:c.read(t[l]);if(d===void 0||c?.inert.has(d)===!0)continue;if(c===void 0)delete t[l];else t[l]=c.floor,o.push(l);r({path:`${e}.${l}`,message:c===void 0?`"${l}" was withheld because ${a} in the same block could not be read; it takes effect again once that is fixed.`:`"${l}" was withheld because ${a} in the same block could not be read; treating it as ${nf(c.floor)} until that is fixed.`,...c!==void 0&&{substituted:!0}})}return o}function vy(e){for(let t of Xc().keys())if(t.startsWith(`${e}.`))return!0;return!1}function Ny(e){return e!=="sandbox.credentials"&&!e.startsWith("sandbox.credentials.")&&vy(e)}function hx(e){let t=e;while(t instanceof Rl||t instanceof iv||t instanceof Dd)t=t instanceof Dd?t.out:t.unwrap();return t instanceof Id?t:void 0}var FZ=new Set(["remoteTools","remoteControl"]);function QZ(e,t){return typeof t==="object"&&t!==null&&e.has(t)}function e9(e,t,n){let r={};for(let[o,s]of Object.entries(t.shape)){let i=`${e}.${o}`;if(n?.has(i))continue;let a=Xc().get(i),l=hx(s);if(a!==void 0)r[o]=a;else if(l!==void 0&&vy(i))r[o]=e9(i,l,n)}return r}function HZ(e,t){return{path:e,message:`"${t}" was null, which is read as key removal; this source does not set it.`,statusOnly:!0,removal:!0}}function nf(e){return typeof e==="string"?`"${e}"`:String(e)}function tf(e,t=0){let n=e===void 0||e.input===void 0?"failed validation":e.code==="custom"&&e.message!==void 0?e.message:("expected"in e)&&typeof e.expected==="string"?`expected ${e.expected}`:("values"in e)&&Array.isArray(e.values)?`expected ${e.values.map(nf).join(" or ")}`:"failed validation",r=(e?.path??[]).slice(t);if(r.length===0)return n;return r.every((o)=>typeof o==="number")?`${r.join(".")}: ${n}`:`nested value: ${n}`}function t9(e){return e===!1||e==="false"}function _x(e,t){if(t===null)return!0;return(e.includes(".")?Xc().get(e):px().find((r)=>r.key===e)?.restrictive)==="disable"&&t9(t)}function rx(e,t,n,r){let o=e.slice(e.lastIndexOf(".")+1);if(typeof t==="boolean")return Me((s)=>{let i=Yc(s);if(i!==s)r({path:e,message:`"${o}" holds the string "${String(i)}" where a boolean belongs; reading it as ${String(i)}. Write it without quotes.`,statusOnly:!0});return i},n);if(t==="disable")return Me((s)=>{if(t9(s)){r({path:e,message:`"${o}" was set to false; reading it as absent (the key's only value is "disable"). Remove the key instead.`,statusOnly:!0,removal:!0});return}return s},n);return n}function Y9e(e,t,n,r,o,s,i){let a=e.slice(e.lastIndexOf(".")+1),l=Xc().get(e),c=i?void 0:l,d=My.get(e),p=t instanceof yg?t.unwrap():void 0,f=p instanceof Xe?p:t;return rx(e,l,f,n).catch((g)=>{if(c!==void 0)return n({path:e,message:`"${a}" was present but invalid (${tf(g.issues[0])}); treating it as ${nf(c)}, its restrictive value, until it is fixed.`,substituted:!0}),r.add(a),c;if(d!==void 0)return n({path:e,message:`"${a}" was present but invalid (${tf(g.issues[0])}); treating it as ${nf(d.floor)} until it is fixed.`,substituted:!0}),r.add(a),d.floor;if(f.safeParse([]).success){let _=g.value;if(Array.isArray(_)){let y=new Map;for(let E of g.issues){let b=E.path?.[0];if(typeof b==="number"&&!y.has(b))y.set(b,tf(E,1))}let S=f.safeParse(_.filter((E,b)=>!y.has(b)));if(y.size>0&&y.size<_.length&&S.success){for(let[E,b]of y)n({path:`${e}[${E}]`,message:`Invalid entry was ignored (${b}); it cannot take effect until it is fixed.`});return s.add(a),S.data}}}n({path:e,message:l===void 0?`"${a}" was present but invalid (${tf(g.issues[0])}) and was ignored; it cannot take effect until it is fixed.`:`"${a}" was present but invalid (${tf(g.issues[0])}) and was ignored, not treated as ${nf(l)}; it cannot take effect until it is fixed.`}),o.add(a);return})}function ox(e,t,n,r={}){let o=e.slice(e.lastIndexOf(".")+1),s=new Set,i=new Set,a=new Set,l={};for(let[p,f]of Object.entries(t.shape)){let m=`${e}.${p}`,g=hx(f);l[p]=r.override?.[m]??(g!==void 0&&vy(m)?ox(m,g,n,{...r,strictField:f}):Y9e(m,f,n,s,i,a,r.neverSubstitute?.has(m)===!0))}let c=new Set([...r.skeletonExclude??[],...r.neverSubstitute??[]]),d=t.safeExtend(l);return me().transform((p)=>{if(p===null){n(HZ(e,o));return}s.clear(),i.clear(),a.clear();let f=oe(p)||r.strictField===void 0?void 0:r.strictField.safeParse(p),m=f?.success===!0&&oe(f.data)?f.data:p,g=oe(m)?d.safeParse(ba(m,(E)=>E===null||E===void 0)):void 0;if(!oe(m)||g?.success!==!0){let E=e9(e,t,c),b=Object.keys(E);if(n({path:e,message:b.length>0?`"${o}" was present but not an object; treating its locks as their restrictive values (${b.join(", ")}) until it is fixed.`:`"${o}" was present but not an object and was ignored; it cannot take effect until it is fixed.`,...b.length>0&&{substituted:!0}}),b.length===0)return;if(!FZ.has(e))r.synthesized?.add(E);return E}for(let[E,b]of Object.entries(m)){let C=`${e}.${E}`;if(b===null&&(Xc().has(C)||vy(C)))n(HZ(C,E))}let _={...g.data};for(let E of gx(e,_,(b)=>i.has(b)?"unreadable":a.has(b)?"trimmed":void 0,n))s.add(E);let y=ba(_,(E)=>E===void 0);if(Object.keys(y).length===0)return Object.entries(m).some(([E,b])=>b!==void 0&&Object.hasOwn(t.shape,E))?void 0:y;let S=r.synthesized;if(S!==void 0&&!FZ.has(e)&&Object.entries(y).every(([E,b])=>s.has(E)||QZ(S,b)||sf(b)))S.add(y);return y}).optional()}function yx(e,t,n){let r=Iy(),o=(T)=>W9e.has(T)||r.carries(n,T),s=(T)=>{let w=r.field(T);if(!w)throw Error("policyTolerantSettingsSchema: not a settings field of this build");return w},i=new Map,a=(T,w)=>{i.set(T,w)};for(let T of["prependPlugins","appendPlugins"])if(r.has(T))a(T,()=>k(h()).optional().catch((w)=>{e({path:T,message:`${w.issues[0]?.message??"Failed schema validation"}. This field was ignored; read as unset.`});return}));a("wslInheritsWindowsSettings",()=>ie([ra().transform(()=>{return}),Me((T)=>{let w=Yc(T);if(w!==T)e({path:"wslInheritsWindowsSettings",message:`"wslInheritsWindowsSettings" holds the string "${String(w)}" where a boolean belongs; reading it as ${String(w)}. Write it without quotes.`,statusOnly:!0});return w},s("wslInheritsWindowsSettings"))]).optional().catch(()=>{e({path:"wslInheritsWindowsSettings",message:`"wslInheritsWindowsSettings" was present but invalid (it takes true or false), so this source's WSL opt-in cannot be read until it is fixed. WSL fails it closed: in an administrator source it arms the Windows policy chain with no user-writable source (/etc/claude-code, HKCU) read beneath it; in HKCU it leaves HKCU unapplied.`});return})),a("strictKnownMarketplaces",()=>NZ("strictKnownMarketplaces",e).catch(()=>(e({path:"strictKnownMarketplaces",message:'"strictKnownMarketplaces" was present but invalid; enforcing an empty allowlist (no marketplaces admitted) until it is fixed.'}),[]))),a("blockedMarketplaces",()=>NZ("blockedMarketplaces",e).catch(()=>{e({path:"blockedMarketplaces",message:'"blockedMarketplaces" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return})),a("allowedMcpServers",()=>UZ("allowedMcpServers",ky(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[]))),a("deniedMcpServers",()=>UZ("deniedMcpServers",Py(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return})),a("managedMcpServers",()=>me().transform((T)=>my(T,(w,I)=>e({path:w?`managedMcpServers.${w}`:"managedMcpServers",message:w?`Managed MCP server was ignored: ${I}`:I,statusOnly:!0}))).optional());let l=new Set;for(let{key:T,restrictive:w,field:I}of px()){let M=typeof w==="string"?`"${w}"`:String(w);a(T,()=>ie([ra().transform(()=>{return}),rx(T,w,I,e)]).optional().catch(()=>(e({path:T,message:`"${T}" was present but invalid; treating it as ${M} (its restrictive value) until it is fixed.`,substituted:!0}),l.add(T),w)))}a("strictPluginOnlyCustomization",()=>ie([ra().transform(()=>{return}),qZ((T)=>e({path:"strictPluginOnlyCustomization",message:`"strictPluginOnlyCustomization" lists ${T} ${Ts(T,"entry","entries")} this version does not recognize as a surface (known: ${rf.join(", ")}); an unrecognized entry locks nothing, so check it for a typo.`,statusOnly:!0}))]).optional().catch(()=>(e({path:"strictPluginOnlyCustomization",message:'"strictPluginOnlyCustomization" was present but invalid; treating it as true (skills, agents, hooks and MCP servers load from managed settings and plugins only) until it is fixed.',substituted:!0}),l.add("strictPluginOnlyCustomization"),!0))),a("enabledPlugins",()=>{let T=YZ();return q(h(),me()).transform((w)=>{let I=[],M=0;for(let[z,J]of Object.entries(w)){let Q=T.safeParse(J);if(Q.success){I.push([z,Q.data]);continue}M++,e({path:qc().safeParse(z).success?`enabledPlugins.${z}`:"enabledPlugins.<invalid id>",message:"Invalid entry was ignored: the value must be true, false, or a list of version constraints. This plugin is neither force-enabled nor blocked until it is fixed."})}if(M>0&&I.length===0){e({path:"enabledPlugins",message:'Every entry of "enabledPlugins" was invalid; no plugin is force-enabled or blocked by it until it is fixed.'});return}return Object.fromEntries(I)}).optional().catch(()=>{e({path:"enabledPlugins",message:'"enabledPlugins" was present but invalid (not a map of plugin ids) and was ignored; no plugin is force-enabled or blocked by it until it is fixed.'});return})}),a("availableModels",()=>k(me()).transform((T)=>{let w=[];for(let I of T)if(typeof I==="string")w.push(I);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(I)}); the entry was ignored.`});return w}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[]))),a("deniedModels",()=>k(me()).transform((T)=>{let w=[];for(let I of T)if(typeof I==="string")w.push(I);else e({path:"deniedModels",message:`"deniedModels" contained a non-string entry (${I===null?"null":typeof I}); the entry was ignored.`});return w}).optional().catch(()=>{e({path:"deniedModels",message:'"deniedModels" was present but is not a list of model names, so it was ignored and blocks no models until it is fixed.'});return})),a("allowedHttpHookUrls",()=>Oy("allowedHttpHookUrls",h(),e,"no HTTP hooks may run")),a("httpHookAllowedEnvVars",()=>Oy("httpHookAllowedEnvVars",h(),e,"no environment variables may be interpolated into HTTP hook headers")),a("allowedChannelPlugins",()=>Oy("allowedChannelPlugins",y9e(),e,"no channel plugins admitted",(T,w)=>typeof T==="string"?`"allowedChannelPlugins" entry "${T}" was accepted; prefer the documented object form {"plugin": "${w.plugin}", "marketplace": "${w.marketplace}"}.`:void 0)),a("gatewayInternalNetworks",()=>k(h()).optional().catch(()=>(e({path:"gatewayInternalNetworks",message:'"gatewayInternalNetworks" was present but invalid; gateway sign-in governed by this source is refused until it is fixed.'}),[XZ]))),a("forceLoginOrgUUID",()=>s("forceLoginOrgUUID").catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[]))),a("allowedProviders",()=>Oy("allowedProviders",Eg(bv,{message:`not a known provider name (${Zp.join(", ")})`}),e,"no API provider may be used, so Claude Code will not start on this machine",void 0,{invalidEntryIsStatusOnly:!0}));let c=!1,d=(T,w)=>{let I=T.safeParse(w);if(I.success)return;return I.error.issues.slice(0,3).map((M)=>M.path.length?`${M.path.join(".")}: ${M.message}`:M.message).join("; ")},p;a("policyHelper",()=>Me((T)=>{if(c=!1,p=T,T&&typeof T==="object"&&!Array.isArray(T)){let w=T;for(let I of["defaultSettings","default",...Ty])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelper",message:`"${I}" on the singular policyHelper is ignored — static fallback payloads belong on the policyHelpers per-OS entries ("defaultSettings") or the map's "default" key. The intended fallback will NOT apply from here.`,statusOnly:!0});for(let I of["policyHelper","policyHelpers"])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelper",message:`"${I}" inside the singular policyHelper is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; nothing nests inside the singular entry. The nested config will NOT apply from here.`,statusOnly:!0});for(let I of Sn)if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelper",message:`"${I}" on the singular policyHelper is ignored — per-OS entries live on the policyHelpers MAP ("policyHelpers": {"${I}": ...}), not inside the singular key. The intended per-OS config will NOT apply from here.`,statusOnly:!0});if(w.claudeMd!==void 0&&w.claudeMd!==null)e({path:"policyHelper",message:`"claudeMd" on the singular policyHelper is ignored — "claudeMd" is a managed-settings key: put it at the settings top level or inside a static payload, or emit it from the helper's stdout envelope. The intended instructions will NOT apply from here.`,statusOnly:!0});if(w.outputBehavior!==void 0&&w.outputBehavior!==null)e({path:"policyHelper",message:`"outputBehavior" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Sn.join("/")}); this helper's output REPLACES the policy tier whatever the value says.`,statusOnly:!0});if(w.onFailure!==void 0&&w.onFailure!==null)e({path:"policyHelper",message:`"onFailure" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Sn.join("/")}); a failure of this helper REFUSES to start Claude Code whatever the value says.`,statusOnly:!0});if(w.retries!==void 0&&w.retries!==null)e({path:"policyHelper",message:`"retries" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Sn.join("/")}); this helper is run ONCE per start or refresh, never re-run, whatever the value says.`,statusOnly:!0});if(w.path===null||w.path===void 0)c=!0}return T===null?void 0:T},wy().optional()).catch((T)=>{e({path:"policyHelper",message:`${T.issues[0]?.message??d(wy(),p)??"Failed schema validation"}. This field was ignored.`,...c&&{statusOnly:!0}});return}));let f=(T,w)=>{e({path:T,message:`"${T}" is not a valid static settings payload: ${w??"failed validation"}. When delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0})},m=[],g=(T)=>{let w=!1,I,M=nx(T,ka().optional().catch((z)=>{w=!0,f(`policyHelpers.${T}.defaultSettings`,z.issues[0]?.message??d(ka(),I&&typeof I==="object"&&!Array.isArray(I)?I.defaultSettings:void 0));return}));return Me((z)=>{if(w=!1,I=z,T!=="default"&&z&&typeof z==="object"&&!Array.isArray(z)){let J=z;for(let W of[...Ty,"claudeMd"])if(J[W]!==void 0&&J[W]!==null)e({path:`policyHelpers.${T}`,message:`"${W}" on the policyHelpers.${T} entry is ignored — helper output cannot be pre-seeded on an entry; a static fallback payload goes under this entry's "defaultSettings" (a managed-settings object). The intended content will NOT apply from here.`,statusOnly:!0});for(let W of["policyHelper","policyHelpers"])if(J[W]!==void 0&&J[W]!==null)e({path:`policyHelpers.${T}`,message:`"${W}" on the policyHelpers.${T} entry is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; nothing nests inside an entry. The nested config will NOT apply from here.`,statusOnly:!0});for(let W of Sn)if(J[W]!==void 0&&J[W]!==null)e({path:`policyHelpers.${T}`,message:`"${W}" on the policyHelpers.${T} entry is ignored — per-OS entries are SIBLINGS on the policyHelpers map, not nested inside each other. The intended ${W} config will NOT apply from here.`,statusOnly:!0});if(J.default!==void 0&&J.default!==null)e({path:`policyHelpers.${T}`,message:`"default" on the policyHelpers.${T} entry is ignored — the per-entry static payload field is spelled "defaultSettings"; "default" is the MAP's any-platform catch-all key (a sibling of the OS entries). The intended fallback will NOT apply from here.`,statusOnly:!0});let Q=J.onFailure;if(Q!==void 0&&Q!==null&&!WZ(Q)){let W;if(typeof Q==="string"){let B=Q.replace(/[^\x20-\x7e]/gu,"?");W=JSON.stringify(B.length>IZ?`${B.slice(0,IZ-1)}…`:B)}else if(typeof Q==="number"||typeof Q==="boolean")W=String(Q);else W=`a non-string value (${Array.isArray(Q)?"array":typeof Q})`;e({path:`policyHelpers.${T}.onFailure`,message:`"onFailure": ${W} on the policyHelpers.${T} entry is not a recognized value ("continue" or "refuse"); it is treated as "refuse" — a startup failure of this entry's helper with no static payload in its place will not start Claude Code.`,statusOnly:!0})}if(KZ(z))return}return z===null?void 0:z},M.optional()).catch((z)=>{if(T==="default"){f("policyHelpers.default",z.issues[0]?.message??d(ka(),I));return}if(w)return;let J=d(nx(T),I)??"failed validation",Q=I,W=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null,B=W?.onFailure,it=B!==void 0&&B!==null&&B!=="continue",Ve=(ot)=>{let At=`policyHelpers.${T}`;if(it)m.push({entryKey:T,message:ot});else e({path:At,message:ot,statusOnly:!0})};if(W){let ot=W.defaultSettings;if(ot!==void 0&&ot!==null){let At=ka().safeParse(ot);if(At.success){let Zt=W.outputBehavior,Ke=Zt===void 0||Zt===null?null:GZ().safeParse(Zt);if(Ke&&!Ke.success){Ve(`Invalid entry was ignored: ${J}. Its "defaultSettings" static payload was NOT kept: "outputBehavior" is unrecognized, so whether the payload replaces or merges over this source's settings is unknown. No policy helper runs on ${T} from this entry.`);return}return e({path:`policyHelpers.${T}`,message:`Invalid entry: its helper fields were ignored (${J}), but its "defaultSettings" static payload was kept. No policy helper runs on ${T} from this entry.`,statusOnly:!0}),{defaultSettings:At.data,...Ke&&{outputBehavior:Ke.data}}}}}Ve(`Invalid entry was ignored: ${J}. No policy helper runs on ${T} from this entry.`);return})};a("policyHelpers",()=>Me((T)=>{if(m=[],T&&typeof T==="object"&&!Array.isArray(T)){let w=T;for(let I of["defaultSettings",...Ty,"claudeMd"])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelpers",message:`"${I}" directly on the policyHelpers map is ignored — static fallback payloads go on a per-OS entry's "defaultSettings" or the map's "default" key (a managed-settings object), and helper-output keys come from the helper's stdout. The intended content will NOT apply from here.`,statusOnly:!0});for(let I of["policyHelper","policyHelpers"])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelpers",message:`"${I}" inside the policyHelpers map is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; the map's keys are the per-OS entries and "default". The nested config will NOT apply from here.`,statusOnly:!0});for(let I of tx.filter((M)=>M!=="defaultSettings"))if(w[I]!==void 0&&w[I]!==null){let M=I==="script"||I==="interpreter"?"; inline scripts are per-OS only (the singular policyHelper key takes a path)":I==="outputBehavior"||I==="onFailure"||I==="retries"?"":", or on the singular policyHelper key";e({path:"policyHelpers",message:`"${I}" directly on the policyHelpers map is ignored — helper configs go on a per-OS entry (policyHelpers.${Sn.join("/")})${M}. No helper runs from this field here.`,statusOnly:!0})}}return T===null?void 0:T},O(Object.fromEntries(ux.map((T)=>[T,g(T)]))).transform((T)=>{for(let w of Object.keys(T))if(T[w]===void 0)delete T[w];for(let{entryKey:w,message:I}of m){let M=`policyHelpers.${w}`,z=cx(w).find((Q)=>T[Q]?.defaultSettings!==void 0&&T[Q]?.defaultSettings!==null),J=z!==void 0?`${z}.defaultSettings`:T.default!==void 0?"default":null;e(J!==null?{path:M,message:`${I} Its "onFailure" requires the helper; the "policyHelpers.${J}" static payload serves in its place.`,statusOnly:!0}:{path:M,message:`${I} Its "onFailure" requires the helper, so when delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0})}return m=[],T}).optional().catch((T)=>(e({path:"policyHelpers",message:`"policyHelpers" could not be parsed: expected an object mapping OS keys (${Sn.join(", ")}) to helper entries, plus an optional "default" settings payload (${T.issues[0]?.message??"failed schema validation"}). When delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0}),{}))));let _=new WeakSet;for(let T of r.keys){if(T==="sandbox"||!Ny(T))continue;a(T,()=>{let w=s(T),I=hx(w);if(I===void 0)return w.catch((M)=>{e({path:T,message:`${M.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});return ox(T,I,e,{synthesized:_,strictField:w})})}let y=Object.freeze({mode:"deny"}),S=Object.freeze({accessKeyIdVar:"_STRIPPED_",secretAccessKeyVar:"_STRIPPED_2_"}),E=0,b=[],C=new Set,A=new Set,R=t===void 0?"":`${[...t].reduce((T,w)=>Math.imul(T^w.charCodeAt(0),16777619)>>>0,2166136261).toString(16).toUpperCase().padStart(8,"0")}_`,x=(T,w)=>{if(typeof T!=="object"||T===null)return;let I=(we)=>w.some((ge)=>ge.path?.includes(we)),M=(we)=>{let ge=T[we];if(typeof ge==="string")return ge;return I(we)?"":void 0},z=M("accessKeyIdVar"),J=M("secretAccessKeyVar"),Q=M("sessionTokenVar"),W=Oi;if(![z,J,Q].some((we)=>we!==void 0&&W.includes(we)))return;let B=(we)=>we!==void 0&&Bc().safeParse(we).success;E+=1;let it=(we)=>`${ov}${we}_${R}${E}_`,Ve=B(z)?z:it("ACCESS_KEY_ID"),ot=B(J)&&J!==Ve?J:it("SECRET_ACCESS_KEY"),At=Q===void 0?void 0:B(Q)&&Q!==Ve&&Q!==ot?Q:it("SESSION_TOKEN"),Zt=(we)=>we.startsWith(ov);if(!Zt(Ve)&&!Zt(ot)){let we=W.includes(ot)?ot:void 0;if(ot=it("SECRET_ACCESS_KEY"),we!==void 0){let ge=x({accessKeyIdVar:we},[]);if(ge!==void 0)b.push(ge)}}let Ke=py().safeParse({accessKeyIdVar:Ve,secretAccessKeyVar:ot,...At!==void 0&&{sessionTokenVar:At}});return Ke.success?Ke.data:void 0},L=(T,w,I)=>k(w.catch((M)=>{let z=I(M.value);if(z!==void 0)return e({path:`sandbox.credentials.${T}[]`,message:`Invalid entry was degraded to mode "deny": ${M.issues[0]?.message??"failed validation"}. The credential stays blocked (not masked) until the entry is fixed.${T==="files"?" Under sandbox.filesystem.disabled, file read-denies are not enforced.":""}`,substituted:!0}),z;return e({path:`sandbox.credentials.${T}[]`,message:`Invalid entry was ignored: ${M.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),y})).transform((M)=>{let z=M.filter((J)=>J!==y);if(M.length>0&&z.length===0)C.add(T);return z}).optional().catch((M)=>{if(typeof M.value==="object"&&M.value!==null&&!Array.isArray(M.value)){let z=w.safeParse(M.value);if(z.success)return e({path:`sandbox.credentials.${T}`,message:`"${T}" must be an array; a lone entry object was accepted as a one-element list. Wrap it in [ ] to silence this warning.`}),[z.data];let J=I(M.value);if(J!==void 0)return e({path:`sandbox.credentials.${T}`,message:`"${T}" must be an array; its lone entry object was invalid and was degraded to mode "deny". The credential stays blocked (not masked) until it is fixed.`,substituted:!0}),[J]}return e({path:`sandbox.credentials.${T}`,message:`${M.issues[0]?.message??"Invalid value"}. "${T}" was ignored; these credential entries are NOT protected until it is fixed.`}),C.add(T),[]});a("sandbox",()=>{let T=O({files:L("files",cy(),(w)=>{if(typeof w!=="object"||w===null||!("mode"in w)||w.mode!=="mask"&&w.mode!=="deny"||!("path"in w)||typeof w.path!=="string")return;let I=cy().safeParse({path:w.path,mode:"deny"});return I.success?I.data:void 0}),envVars:L("envVars",uy(),(w)=>{if(typeof w!=="object"||w===null||!("mode"in w)||w.mode!=="mask"&&w.mode!=="deny"||!("name"in w)||typeof w.name!=="string")return;let I=uy().safeParse({name:w.name,mode:"deny"});return I.success?I.data:void 0}),allowPlaintextInject:rx("sandbox.credentials.allowPlaintextInject",Xc().get("sandbox.credentials.allowPlaintextInject"),v().optional(),e).catch((w)=>(e({path:"sandbox.credentials.allowPlaintextInject",message:`${w.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was degraded to an explicit false; plaintext credential injection stays disabled (lower-precedence values cannot enable it) until it is fixed.`,substituted:!0}),C.add("allowPlaintextInject"),!1)),awsPairs:k(py().catch((w)=>{let I=x(w.value,w.issues);if(I!==void 0)return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was degraded to a non-functional suppressor: ${w.issues[0]?.message??"failed validation"}. It keeps implicit AWS auto-pairing suppressed but re-signs nothing until it is fixed.`,substituted:!0}),I;return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was ignored: ${w.issues[0]?.message??"failed validation"}. SigV4 re-signing stays unconfigured for this pair until it is fixed.`}),S})).transform((w)=>{let I=w.filter((M)=>M!==S);if(b.length>0)I.push(...b),b.length=0;if(w.length>0&&I.length===0)C.add("awsPairs");return I}).optional().catch((w)=>{let I=typeof w.value==="object"&&w.value!==null?x(w.value,[]):void 0,M=typeof w.value==="object"&&w.value!==null&&(("accessKeyIdVar"in w.value)||("secretAccessKeyVar"in w.value)||("sessionTokenVar"in w.value));if(I===void 0&&M)return b.length=0,e({path:"sandbox.credentials.awsPairs",message:`${w.issues[0]?.message??"Invalid value"}. "awsPairs" must be an array; its lone pair-shaped entry claimed no conventional AWS name and was ignored. SigV4 re-signing stays unconfigured until it is fixed.`}),C.add("awsPairs"),[];let z=I!==void 0?[I]:Oi.flatMap((J)=>{let Q=x({accessKeyIdVar:J},[]);return Q!==void 0?[Q]:[]});if(b.length>0)z.push(...b),b.length=0;if(I===void 0)C.add("awsPairs");return e({path:"sandbox.credentials.awsPairs",message:`${w.issues[0]?.message??"Invalid value"}. "awsPairs" was degraded to non-functional suppressor pair(s); implicit AWS auto-pairing stays suppressed but nothing re-signs until it is fixed.`,substituted:!0}),z}),sigv4:O(Object.fromEntries(["streaming","presigned","sigv4a"].map((w)=>[w,K(["deny","passthrough"]).optional().catch((I)=>(e({path:`sandbox.credentials.sigv4.${w}`,message:`${I.issues[0]?.message??"Invalid value"}. "${w}" was degraded to an explicit deny; this SigV4 request shape stays denied until it is fixed.`,substituted:!0}),A.add(w),"deny"))]))).transform((w)=>{let I=Object.entries(w).filter(([,M])=>M!==void 0);if(I.length>0&&I.every(([M])=>A.has(M)))C.add("sigv4");return A.clear(),w}).optional().catch((w)=>(e({path:"sandbox.credentials.sigv4",message:`${w.issues[0]?.message??"Invalid value"}. "sigv4" was degraded to an all-deny block (all shapes stay denied, and lower-precedence sigv4 values cannot take effect) until it is fixed.`,substituted:!0}),A.clear(),C.add("sigv4"),{streaming:"deny",presigned:"deny",sigv4a:"deny"}))}).transform((w)=>{let I=Object.entries(w).filter(([,M])=>M!==void 0);if(I.length>0&&I.every(([M])=>C.has(M)))_.add(w);return C.clear(),w}).optional().catch((w)=>{e({path:"sandbox.credentials",message:`${w.issues[0]?.message??"Failed schema validation"}. The credentials block was degraded to a fail-closed skeleton (all-deny sigv4, implicit AWS auto-pairing suppressed, no masking) until it is fixed.`,substituted:!0});let I=Oi.flatMap((z)=>{let J=x({accessKeyIdVar:z},[]);return J!==void 0?[J]:[]});b.length=0,C.clear(),A.clear();let M={allowPlaintextInject:!1,awsPairs:I,sigv4:{streaming:"deny",presigned:"deny",sigv4a:"deny"}};return _.add(M),M});return ox("sandbox",sv(),e,{override:{"sandbox.credentials":T},skeletonExclude:new Set(["sandbox.enabled"]),neverSubstitute:new Set(["sandbox.failIfUnavailable"]),synthesized:_})});let F={};for(let T of r.keys){if(!o(T))continue;let w=i.get(T);F[T]=w?w():s(T).catch((I)=>{e({path:T,message:`${I.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return})}for(let[T,w]of i)if(!(T in F)&&o(T))F[T]=w();return O(F).passthrough().check((T)=>{T.issues.push(...r.wrongDocumentIssues(T.value,F))}).transform((T)=>{for(let M of Object.keys(T))if(T[M]===void 0)delete T[M];let w=Object.keys(T).filter((M)=>!xi.some((z)=>z===M)&&!sf(T[M])),I=w.length>0&&w.every((M)=>l.has(M)||QZ(_,T[M]));if(l.clear(),I)for(let M of w)e({path:M,message:`"${M}" holds nothing that could be applied as written and is this source's only policy content; its fail-closed reading binds (beside a lower managed settings source's policy, when one supplies it) until it is fixed.`,statusOnly:!0,onlySubstitutes:!0});return T})}var Z9e=65536,n9=new RegExp(`[${yD("<")}]`,"gu");function J9e(e){return wY(e)&&e.search(n9)===-1}function r9(e){let t={},n=Z9e,r=0,o=0;for(let s of Qc.toSorted((i,a)=>Number(a==="hard_deny")-Number(i==="hard_deny"))){let i=oe(e)?e[s]:void 0;if(i!==void 0&&i!==null&&!Array.isArray(i))r++;let a=[Vp];for(let l of Array.isArray(i)?i:[]){if(typeof l!=="string"){r++;continue}if(["",Vp].includes(l.trim()))continue;let c=l.length>2*n?1/0:_b(l);if(c>n){r++;continue}n-=c;let p=Array.from(oD(l),(m)=>iy(m)||ay(m)?" ":m).join("").replace(n9,"<");if(p.trim()===Vp)continue;let f=_b(p)-c;if(!J9e(p)||f>n){r++;continue}if(n-=f,a.push(p),p!==l)o++}if(a.length>1)t[s]=a}return{lists:t,leftOut:r,mended:o}}var o9=new Set(["disableAllHooks","disableReplyCheck"]),s9=["accessKeyIdVar","secretAccessKeyVar","sessionTokenVar"];function Sx(e){let t={};for(let g of xo()){let{path:_,restrictive:y}=g;if(o9.has(_[0]))continue;let S=F_(g,e);if((typeof S==="boolean"||typeof S==="string")&&Ea(y).includes(S))jt(t,_,S)}if(pt(e,["attribution"])===!1)jt(t,["attribution","sessionUrl"],!1);let n=Uy(e.permissions,["deny","ask","disableBypassPermissionsMode","disableAutoMode"]);if(n)t.permissions={...t.permissions,...n};for(let g of X9e)if(e[g]!==void 0)t[g]=e[g];for(let[g,_]of Object.entries(e))if((g.startsWith("disable")&&(_===!0||_==="disable")||g.startsWith("enable")&&_===!1)&&!o9.has(g))t[g]=_;if(e.disableAllHooks===!0)t.allowManagedHooksOnly=!0;if(Array.isArray(e.httpHookAllowedEnvVars)&&e.httpHookAllowedEnvVars.length===0)t.httpHookAllowedEnvVars=[];let r=Uy(e.sandbox?.filesystem,["denyRead","denyWrite","allowManagedReadPathsOnly"]),o=Uy(e.sandbox?.network,["deniedDomains","strictAllowlist","allowManagedDomainsOnly"]),s=Uy(e.sandbox?.credentials,["files","envVars"])??{},i=e.sandbox?.credentials?.awsPairs,a=oe(i)&&s9.some((g)=>(g in i)),c=(Array.isArray(i)?i:a?[i]:[]).flatMap((g)=>oe(g)?s9.map((_)=>g[_]):[]),d=i!==void 0&&!Array.isArray(i)&&!a,p=Oi.filter((g)=>d||c.includes(g));if(p.length>0)s.awsPairs=p.map((g,_)=>({accessKeyIdVar:g,secretAccessKeyVar:`${dy}${_+1}_`}));let f=e.sandbox?.credentials?.sigv4;if(f){let g={};for(let[_,y]of Object.entries(f))if(y==="deny")g[_]="deny";if(Object.keys(g).length>0)s.sigv4=g}let m=Object.keys(s).length>0;if(r||o||m){let g=t.sandbox??{};t.sandbox={...g,...r&&{filesystem:{...g.filesystem,...r}},...o&&{network:{...g.network,...o}},...m&&{credentials:{...g.credentials,...s}}}}return Object.keys(t).length>0?t:null}function Uy(e,t){if(!e)return;let n={};for(let r of t)if(e[r]!==void 0)n[r]=e[r];return Object.keys(n).length>0?n:void 0}var X9e=["allowedMcpServers","deniedMcpServers","allowManagedMcpServersOnly","disabledMcpjsonServers","allowManagedHooksOnly","allowedHttpHookUrls","strictKnownMarketplaces","allowedMarketplaces","blockedMarketplaces","strictPluginOnlyCustomization","availableModels","enforceAvailableModels","availableModelsMatch","deniedModels","allowedProviders"];var Q9e=["SSL_CERT_FILE","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE","HTTPLIB2_CA_CERTS"],e6e=["AWS_CA_BUNDLE","DENO_CERT","CARGO_HTTP_CAINFO","PIP_CERT","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","NIX_SSL_CERT_FILE","HEX_CACERTS_PATH"],i9=[...Q9e,...e6e],a9={UV_NATIVE_TLS:"true",DENO_TLS_CA_STORE:"system,mozilla"};var t6e=Object.freeze(["-c","core.hooksPath=/dev/null","-c","core.fsmonitor="]);var mzt=Object.freeze(["--no-optional-locks","status","--porcelain","--untracked-files=normal","--ignore-submodules=dirty"]),n6e=Object.freeze({GIT_LFS_SKIP_SMUDGE:"1"});var r6e=["'alias.remote-none=version'","'alias.remote-none.command=version'","'alias.remote-/.command=version'","'fetch.bundleURI='","'help.autocorrect=0'"],o6e=r6e.join(" "),gzt=Object.freeze({GIT_ALLOW_PROTOCOL:"/",GIT_CONFIG_PARAMETERS:o6e,GIT_NO_LAZY_FETCH:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_TERMINAL_PROMPT:"0",...n6e}),hzt=Object.freeze({LC_ALL:"C",LANGUAGE:"C"}),_zt=Object.freeze({GIT_SSH_COMMAND:"false"});var yzt=Object.freeze([...t6e,"-c","safe.bareRepository=explicit","-c","protocol.file.allow=never"]),Ex=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_SHALLOW_FILE","GIT_NAMESPACE","GIT_IMPLICIT_WORK_TREE","GIT_REFERENCE_BACKEND"],bx=[...Ex,"GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG"],s6e=/^GIT_CONFIG_(KEY|VALUE)_\d+$/,i6e=new RegExp(s6e.source,"i");var Szt=new Set(bx);function c9(e){let t=0,n=e.length;while(t<n&&l9(e.charCodeAt(t)))t++;while(n>t&&l9(e.charCodeAt(n-1)))n--;let r=a6e(e.slice(t,n));if(r!==-1)return{kind:"line_break",index:Cx(e,t+r)};for(let o=t;o<n;o++){let s=e.charCodeAt(o);if(s===0)return{kind:"nul",index:Cx(e,o)};if(s>255)return{kind:"non_ascii",index:Cx(e,o),codePoint:l6e(e,o)}}return null}function a6e(e){let t=e.indexOf(`
|
|
150
|
+
`)}`,o=this.byPresentKeys.get(r);if(o)return this.byPresentKeys.delete(r),this.byPresentKeys.set(r,o),o;let s=this.shapeOf(n),i=t==="strip"?Me((a,l)=>{for(let c of this.wrongDocumentIssues(a,s))l.addIssue(c);return a},O(s)):O(s).passthrough().check((a)=>{a.issues.push(...this.wrongDocumentIssues(a.value,s))});if(this.byPresentKeys.size>=j4e)for(let a of this.byPresentKeys.keys()){this.byPresentKeys.delete(a);break}return this.byPresentKeys.set(r,i),i}wrongDocumentIssues(e,t){if(typeof e!=="object"||e===null)return[];let n=[];for(let r of Object.keys(e))if(!Object.hasOwn(t,r)&&this.has(r))n.push({code:"custom",input:e[r],path:[r],message:"This settings schema was built for a document without this key"});return n}shapeOf(e){let t={};for(let n of e){let r=this.field(n);if(r)t[n]=r}return t}}var T4=600;var Dv=500,W4e=32;function L4(){return{claudeaiPluginId:h().max(128).optional().catch(void 0),archiveSha256:gZ().optional().catch(void 0)}}function M4(){return{directoryRepositoryKey:h().max(4096).optional().catch(void 0)}}function Lv(e){if(!/^https?:\/\/[^/\\]/i.test(e))return!1;try{let{protocol:t}=new URL(e);return t==="https:"||t==="http:"}catch{return!1}}function N4(){return{npmVersionSpec:h().max(256).optional().catch(void 0),npmResolved:h().max(2048).optional().catch(void 0),npmIntegrity:h().max(256).optional().catch(void 0),npmRegistry:h().max(2048).refine(Lv).optional().catch(void 0)}}function U4(){return{sourceCommand:h().max(Dv+20).optional().catch(void 0).describe("The `command`-source command the user accepted at explicit install/update. The once-per-session background re-resolve only runs while the marketplace entry still declares this exact command; a changed command (or an entry that became command-sourced later) is skipped with a warning until the user runs an explicit update."),sourceProducerPath:h().max(4096).refine(w4,{message:"must be an absolute path"}).optional().catch(void 0).describe("The directory a `command`-source plugin was last resolved to (what its command printed). Served in place in link mode and re-copied every session in copy mode, so the sandbox write-denies it; refreshed on every install/update, including no-op updates that resolve to a new location."),previousProducerPaths:k(me()).transform((e)=>e.filter((t)=>typeof t==="string"&&t.length<=4096&&w4(t)).slice(-W4e)).optional().catch(void 0).describe("Producer directories this installation was resolved to before the current one (most recent last, bounded). A concurrent older session may still serve one of them, so the sandbox keeps write-denying them too.")}}function w4(e){return K4e.isAbsolute(e)||G4e.isAbsolute(e)}var F4=/[^\x20-\x7E]| {4,}/;function Mv(){return h().max(Dv,{message:"headersHelper must not be longer than the install consent UI can display"}).refine((e)=>!F4.test(e),{message:"headersHelper must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"})}var V4e="anthropic-plugin-directory",q4e=["healthcare"],H4=new Set(["claude-community","claude-plugins-community",...q4e]),$4=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins","claude-tag-plugins"]),Y4e=new Set([V4e,"claude-plugin-directory"]),Nv=new Set([...$4,...H4,...Y4e]);var z4=["marketplace","plugins","official"];function Z4e(){return z4}var B4="official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official",FHt=new RegExp(B4,"i");function j4(e){return new RegExp(`(?:${B4}|^(?:anthropic|claude)[^a-z0-9]*(${e.join("|")}))`,"i")}var J4e=j4(Z4e()),X4e=j4(z4),Q4e=/[^\u0020-\u007E]/;function K4(e){if(Nv.has(e.toLowerCase()))return!1;if(eZe(e))return!0;if(J4e.test(e))return!0;return!1}function eZe(e){return!Nv.has(e.toLowerCase())&&(Q4e.test(e)||X4e.test(e))}var ir=P(()=>h().startsWith("./")),xa=P(()=>ir().endsWith(".json")),v4=P(()=>ie([U("."),ir()])),x4=P(()=>ie([ir().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"),h().url().refine((e)=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),xv=P(()=>ir().endsWith(".md")),kv=P(()=>ie([xv(),ir()])),Uv={inline:"--plugin-dir session plugins",builtin:"built-in plugins","skills-dir":"plugins auto-loaded from .claude/skills/",synced:"plugins synced from your claude.ai account","claude-plugin-test":"plugins loaded by claude plugin test",npm:"plugins installed from an npm registry (`<package>@npm`); remove this marketplace and add it again under another name",pip:"plugins installed from a Python package index (reserved; not yet available)",uv:"plugins installed from a Python package index through uv (reserved; not yet available)",cargo:"plugins installed from a Rust crate registry (reserved; not yet available)",github:"plugins installed straight from a GitHub repository (`<owner>/<repo>@github`; reserved; not yet available)",gh:"plugins installed straight from a GitHub repository (reserved; not yet available)"},Fv="npm",tZe=["pip","uv","cargo","github","gh"];function Sy(e){return Object.hasOwn(Uv,e)}var nZe=[Fv,...tZe];function G4(e){return nZe.includes(e.toLowerCase())}function rZe(e,t){let n=e.toLowerCase();if(G4(n)&&Sy(n))t.addIssue({code:"custom",message:`Marketplace name "${n}" is reserved for ${Uv[n]}`})}var oZe="Marketplace name impersonates an official Anthropic/Claude marketplace",Hv=(e)=>h().min(1,"Marketplace must have a name").refine((t)=>!t.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine((t)=>!SZ.test(t),{message:"Marketplace name cannot contain control or bidirectional-formatting characters"}).refine((t)=>!t.includes("/")&&!t.includes("\\")&&!t.includes("..")&&t!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine((t)=>!e(t),{message:oZe}).superRefine((t,n)=>{let r=t.toLowerCase();if(!Sy(r)||G4(r))return;n.addIssue({code:"custom",message:`Marketplace name "${r}" is reserved for ${Uv[r]}`})}),sZe=P(()=>Hv(K4)),iZe=P(()=>Hv(()=>!1));function aZe(e){return Hv(e).superRefine(rZe)}var Ey=P(()=>h().min(1,"Plugin name cannot be empty").refine((e)=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).refine((e)=>!SZ.test(e),{message:"Plugin name cannot contain control or bidirectional-formatting characters"})),$v=P(()=>O({name:h().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:h().optional().describe("Contact email for support or feedback"),url:h().optional().describe("Website, GitHub profile, or organization URL")})),qn=P(()=>O({$schema:h().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:Ey().describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:h().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:h().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:h().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:$v().optional().describe("Information about the plugin creator or maintainer"),homepage:h().url().optional().describe("Plugin homepage or documentation URL"),repository:h().optional().describe("Source code repository URL"),license:h().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:k(h()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:v().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:k(r9e()).optional().describe(`Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin's own marketplace.`),metadata:Me((e)=>oe(e)?e:void 0,q(h(),me()).optional()).describe("Free-form metadata for the plugin author's own use (e.g. entitlement or catalog fields). Preserved on the parsed manifest but not read by Claude Code.")})),lZe=1,HHt=P(()=>O({$schema:h().optional().catch(void 0).describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),description:h().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:Sg(()=>wa()).optional().describe("The hooks provided by the plugin, in the same format as the one used for settings"),modules:k(h()).max(lZe,{message:"hooks.json `modules` names one hooks module per plugin; a second entry is refused"}).optional().describe(`The hooks module: one path, relative to this hooks.json, of a module exporting register(on). The module, and every file it imports from the plugin, is named like code (${k4e}; a file named otherwise is not loaded) and is an ES module whatever its suffix. What it hooks and calls is read from its source before it loads; \`claude plugin validate\` shows the result.`),surface:hg({error:'hooks.json `surface` is gone: name the module in the Client element, `Client({ module: "./board.tsx", key })`, a path relative to the file that builds it'}).optional()}).refine((e)=>e.hooks!==void 0||(e.modules?.length??0)>0,{message:"hooks.json must have `hooks` (the hook matchers) or `modules` (hooks modules), or both"})),W4=P(()=>O({hooks:ie([xa().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),Sg(()=>wa()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),k(ie([xa().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),Sg(()=>wa()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),cZe=P(()=>O({source:kv().optional().describe("Path to command markdown file, relative to plugin root"),content:h().optional().describe("Inline markdown content for the command"),description:h().optional().describe("Command description override"),argumentHint:h().optional().describe('Hint for command arguments (e.g., "[file]")'),model:h().optional().describe("Default model for this command"),allowedTools:k(h()).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'})),V4=P(()=>O({commands:ie([kv().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded — list its files here if you want both."),k(kv().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."),q(h(),cZe()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")')])})),q4=P(()=>O({agents:ie([xv().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded — list its files here if you want both."),k(xv().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.")])})),Y4=P(()=>O({skills:ie([v4().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself). Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan).'),k(v4().describe('Path to a skill directory, relative to the plugin root ("." / "./" denote the plugin root itself).')).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),uZe=P(()=>ie([h(),k(h())])),zv=P(()=>O({outputStyles:ie([ir().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded — list its files here if you want both."),k(ir().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.")])})),dZe=P(()=>h().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),pZe=16,fZe=P(()=>O({id:dZe(),remote:h().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:h().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),mZe=P(()=>O({syntaxHighlighting:O({hljsLanguages:k(fZe()).max(pZe)}).strict()})),Bv=P(()=>O({themes:ie([ir().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded — list its files here if you want both."),k(ir().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.")])})),Z4=P(()=>O({workflows:ie([ir().describe("Path to a workflows directory or .js file, relative to the plugin root. When set, the workflows/ directory is not auto-loaded — list its files here if you want both."),k(ir().describe("Path to a workflows directory or .js file, relative to the plugin root. When set, the workflows/ directory is not auto-loaded — list its files here if you want both.")).describe("List of workflow directory or .js file paths. When set, the workflows/ directory is not auto-loaded.")]).optional()})),k4=P(()=>h().min(1)),gZe=P(()=>h().min(2).refine((e)=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),J4=P(()=>O({mcpServers:ie([xa().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),x4().describe("Path or URL to MCPB file containing MCP server configuration"),q(h(),gy()).describe("MCP server configurations keyed by server name"),k(ie([xa().describe("Path to MCP servers configuration file"),x4().describe("Path or URL to MCPB file"),q(h(),gy()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),X4=P(()=>O({type:K(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:h().describe("Human-readable label shown in the config dialog"),description:h().describe("Help text shown beneath the field in the config dialog"),required:v().optional().describe("If true, validation fails when this field is empty"),default:ie([h(),Y(),v(),k(h())]).optional().describe("Default value used when the user provides nothing"),multiple:v().optional().describe("For string type: allow an array of strings"),sensitive:v().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:Y().optional().describe("Minimum value (number type only)"),max:Y().optional().describe("Maximum value (number type only)"),options:k(h().min(1,"An option cannot be empty").max(64,"An option can be at most 64 characters").refine((e)=>lD(e)===e,{message:"An option cannot contain control, invisible or bidirectional-formatting characters"}).refine((e)=>e.trim()===e,{message:"An option cannot start or end with a space"})).min(1,"options needs at least one value").refine((e)=>new Set(e.map((t)=>t.toLowerCase())).size===e.length,{message:"options cannot repeat a value (in any letter case)"}).readonly().optional().describe("For string type: the only values the field takes. /config shows the field as a picker over them, and a stored value outside them counts as unset")}).strict().superRefine((e,t)=>{if(e.options===void 0)return;if(e.type!=="string"||e.multiple===!0||e.sensitive===!0){t.addIssue({code:"custom",path:["options"],message:'options is only for a field of type "string" that is neither multiple nor sensitive'});return}if(e.default===void 0){if(e.required!==!0)t.addIssue({code:"custom",path:["default"],message:"a field with options needs a default among them, or required: true"});return}if(typeof e.default!=="string"||!e.options.includes(e.default))t.addIssue({code:"custom",path:["default"],message:`default must be one of the options: ${e.options.join(", ")}`})})),Q4=P(()=>O({userConfig:q(h().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"),X4()).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.")})),eZ=P(()=>O({channels:k(O({server:h().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:h().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:q(h(),X4()).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.")})),P4=P(()=>mO({command:h().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:k(k4()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:q(gZe(),k4()).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:K(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:q(h(),h()).optional().describe("Environment variables to set when starting the server"),initializationOptions:me().optional().describe("Initialization options passed to the server during initialization"),settings:me().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:h().optional().describe("Workspace folder path to use for the server"),startupTimeout:Y().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:Y().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),requestTimeout:Y().int().positive().max(2147483647).optional().describe("Maximum time to wait for the server to answer a request (milliseconds). Defaults to 60000."),restartOnCrash:v().optional().describe("Whether to restart the server if it crashes"),maxRestarts:Y().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:v().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.")})),hZe=P(()=>mO({name:h().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:h().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 (the named --project-config-root when a host set one) — prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:h().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:ie([U("always"),h().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).')})),_Ze=P(()=>k(hZe()).refine((e)=>new Set(e.map((t)=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),jv=P(()=>O({monitors:ie([xa().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),_Ze()]).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.")})),tZ=P(()=>O({lspServers:ie([xa().describe("Path to .lsp.json configuration file relative to plugin root"),q(h(),P4()).describe("LSP server configurations keyed by server name"),k(ie([xa().describe("Path to LSP configuration file"),q(h(),P4()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),yZe=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,SZe=/^[a-z0-9][a-z0-9-._]*$/,EZe=/^@[a-z0-9][a-z0-9-._]*\/\*$/;function Kv(e){return!e.includes("..")&&!e.includes("//")&&(yZe.test(e)||SZe.test(e))}var nZ=P(()=>h().refine((e)=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine((e)=>Kv(e),"Invalid npm package name format")),rZ=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,bZe=/^[0-9a-f]{64}$/;var CZe=64;var AZe=P(()=>O({sha256:h().regex(bZe)}));function RZe(e){let t=q(h(),me()).safeParse(e);if(!t.success)return;let n=Object.create(null),r=0;for(let[o,s]of Object.entries(t.data)){if(r>=CZe)break;let i=AZe().safeParse(s);if(rZ.test(o)&&i.success)n[o]=i.data,r++}return r>0?n:void 0}var oZ=P(()=>O({binaries:me().transform(RZe).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),sZ=P(()=>O({settings:q(h(),me()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),iZ=P(()=>O({types:ir().refine((e)=>e.endsWith(".d.ts"),{message:"types must name a TypeScript declaration file ending in '.d.ts'"}).refine((e)=>!e.split(/[\\/]/).includes(".."),{message:"types must stay inside the plugin directory (no '..' segment)"}).optional().describe("Path to the plugin's type contract, relative to the plugin root and starting with ./: a self-contained .d.ts (no import, export-from, require or reference) that exports the types of the noun the plugin's hooks module adds in engine.create at its top level and declares the noun in a `declare module 'claude-code' { interface EngineInterface { ... } }` block, nothing else. A mod that lists this plugin under dependencies gets the contract laid at .claude-plugin/types/<plugin>/index.d.ts each time the engine loads it from a folder the person owns, so it types against the noun with nothing copied; claude plugin validate checks the file.")})),aZ=P(()=>O({experimental:Me((e)=>oe(e)?e:void 0,O({...Bv().partial().shape,...mZe().partial().shape,...jv().partial().shape,...zv().partial().shape,evals:uZe().optional().describe("Directory of eval cases for the plugin evaluation harness, relative to the plugin root (default: evals/). A list is accepted; its first entry is the case directory.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))}));var OZe=P(()=>O({...qn().shape,...W4().partial().shape,...V4().partial().shape,...q4().partial().shape,...Y4().partial().shape,...zv().partial().shape,...Bv().partial().shape,...Z4().shape,...eZ().partial().shape,...J4().partial().shape,...tZ().partial().shape,...jv().partial().shape,...sZ().partial().shape,...iZ().partial().shape,...Q4().partial().shape,...oZ().partial().shape,...aZ().partial().shape})),$Ht=P(()=>new Vc({$schema:()=>qn().shape.$schema,name:()=>qn().shape.name,displayName:()=>qn().shape.displayName,version:()=>qn().shape.version,description:()=>qn().shape.description,author:()=>qn().shape.author,homepage:()=>qn().shape.homepage,repository:()=>qn().shape.repository,license:()=>qn().shape.license,keywords:()=>qn().shape.keywords,defaultEnabled:()=>qn().shape.defaultEnabled,dependencies:()=>qn().shape.dependencies,metadata:()=>qn().shape.metadata,hooks:()=>W4().partial().shape.hooks,commands:()=>V4().partial().shape.commands,agents:()=>q4().partial().shape.agents,skills:()=>Y4().partial().shape.skills,outputStyles:()=>zv().partial().shape.outputStyles,themes:()=>Bv().partial().shape.themes,workflows:()=>Z4().shape.workflows,channels:()=>eZ().partial().shape.channels,mcpServers:()=>J4().partial().shape.mcpServers,lspServers:()=>tZ().partial().shape.lspServers,monitors:()=>jv().partial().shape.monitors,settings:()=>sZ().partial().shape.settings,types:()=>iZ().partial().shape.types,userConfig:()=>Q4().partial().shape.userConfig,binaries:()=>oZ().partial().shape.binaries,experimental:()=>aZ().partial().shape.experimental},new Set(["name"])));var lZ=new Set(["url","github","git","npm","file","directory","skills-dir","hostPattern","pathPattern","settings"]);function cZ(e){try{return new RegExp(e),!0}catch{return!1}}function TZe(e){return va(e)||ol(e)}var uZ="ssh.github.com";function wv(e){return wi(e)||Qp(e)===uZ}var wZe=/^[A-Za-z0-9._-]+$/;function vZe(e){return wZe.test(e)&&!e.startsWith("-")&&e!=="."&&e!==".."}function dZ(e){if(!e.endsWith("/*"))return null;let t=e.slice(0,-2);return vZe(t)?t:null}function xZe(e){let t=[];for(let n of e.split("/")){if(n===".")continue;if(n===".."){t.pop();continue}t.push(n)}return t.filter((n)=>n!=="").join("/")}function kZe(e){let t=e.length;for(;;){let n=t;while(n>0&&e.charCodeAt(n-1)===47)n--;if(n>=4&&e.startsWith(".git",n-4))n-=4;if(n===t)return t===e.length?e:e.slice(0,t);t=n}}function I4(e){let t=Tv(e);return t===uZ?xn:t}function PZe(e,t){if(e.includes("://"))try{let r=R4(e);if(r===null)return e;r.hostname=I4(r.hostname),r.username="",r.password="",r.search="",r.hash="";try{r.pathname=decodeURIComponent(r.pathname)}catch{}let o=xZe(r.pathname);return r.pathname=t?.stripDotGit?kZe(o):o,r.toString()}catch{return e}let n=sl(e);return n?`${I4(n.host)}:${n.path}`:e}var IZe=new Set(["http:","https:","git:","git+http:","git+https:"]);function DZe(e){if(Ov(e))return e;if(e.includes("://"))try{let r=new URL(e);if(r.hostname=Tv(r.hostname),IZe.has(r.protocol)||wi(r.hostname))r.username="",r.password="";return r.toString()}catch{return e}let t=O4(e);if(!t)return e;let n=t.host.toLowerCase().replace(/\.+$/,"");return wi(n)?`${xn}:${t.path}`:`${t.user}@${n}:${t.path}`}function pZ(e){if(e.includes("://")){if(TZe(e))return!1;let s=sl(e)?.host;if(s!==void 0&&wv(s)&&PZe(e,{stripDotGit:!0}).includes("*"))return!0;let i=Fo(e)?.hostname;if(!i||!wv(i))return!1;let a=DZe(e);try{let l=new URL(a);return l.hostname.includes("*")||l.pathname.includes("*")}catch{return a.includes("*")}}let t=sl(e),n=t?.host,r=t?.path;if(!n||r===void 0||!wv(n))return!1;let o=r;try{o=decodeURIComponent(r)}catch{}return o.includes("*")}function fZ(e){return oa("source",[O({source:U("url"),url:h().url().describe("Direct URL to marketplace.json file"),headers:q(h(),h()).optional().describe("Custom HTTP headers (e.g., for authentication)"),headersHelper:Mv().optional().describe("Command that prints a JSON object of HTTP headers (e.g. a short-lived auth token). Its output overrides `headers` and, like `headers`, is inherited by same-origin archive downloads from this marketplace. Runs from a fixed directory (the Claude config home, never the session's), so give a bare command found via PATH or an absolute path; it is re-run on later refreshes of this marketplace.")}),O({source:U("github"),repo:h().describe('GitHub repository in owner/repo format. ONLY in the managed-settings policy lists (strictKnownMarketplaces / blockedMarketplaces) the owner-wildcard form "owner/*" matches every repository under exactly that owner. Everywhere else (marketplace add, extraKnownMarketplaces, known_marketplaces.json) the value '+"must name a single repository — a wildcard is taken literally and fails to clone."),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:h().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:k(h()).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:v().optional().describe("Has no effect; accepted so existing settings keep working. Claude Code's own git never downloads Git LFS content: LFS-tracked files in the marketplace repository are checked out as pointer files whether or not this is set, and adding or updating the marketplace says how many were. To fetch their content, run `git lfs pull` in the marketplace's checkout under ~/.claude/plugins/marketplaces/.")}),O({source:U("git"),url:h().describe("Full git repository URL"),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:h().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:k(h()).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:v().optional().describe("Has no effect; accepted so existing settings keep working. Claude Code's own git never downloads Git LFS content: LFS-tracked files in the marketplace repository are checked out as pointer files whether or not this is set, and adding or updating the marketplace says how many were. To fetch their content, run `git lfs pull` in the marketplace's checkout under ~/.claude/plugins/marketplaces/.")}),O({source:U("npm"),package:nZ().or(h().regex(EZe,"Invalid npm package name format")).describe('npm package containing marketplace.json (e.g. "@acme/claude-marketplace"). In strictKnownMarketplaces / blockedMarketplaces an entry also governs plugins installed straight from the npm marketplace (`<package>@npm`): an exact package name matches that package, and "@acme/*" matches every package under the scope.'),version:h().optional().describe('Version or range to fetch (e.g. "1.4.0", "^1.4"); defaults to the latest dist-tag'),registry:h().url().refine(Lv,"Registry must be an http(s) URL").optional().describe(`Registry URL. When adding a marketplace: a one-off registry override (otherwise your npm configuration decides). In a policy entry: the origin and path prefix the package's RESOLVED tarball URL must fall under (e.g. "https://npm.example.com/api/npm/internal/"); under allowManagedPermissionRulesOnly, an npm marketplace keeps plugin allowed-tools only when both the entry and the registration pin this same registry.`)}),O({source:U("file"),path:h().describe("Local file path to marketplace.json")}),O({source:U("directory"),path:h().describe("Local directory containing .claude-plugin/marketplace.json")}),O({source:U("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."),O({source:U("hostPattern"),hostPattern:h().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$").')}),O({source:U("pathPattern"),pathPattern:h().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.')}),O({source:U("settings"),name:e?iZe().describe("Marketplace name, as stored in known_marketplaces.json. A reserved name is refused per entry at load (revalidateReservedNameEntry); a look-alike name is judged when that marketplace's own catalog is parsed (catalogNameSchemaFor)."):sZe().refine((t)=>!Nv.has(t.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:k(FZe()).describe("Plugin entries declared inline in settings.json"),owner:$v().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).")])}var ef=P(()=>fZ(!1));var Gv=String.raw`[\w./+-]`,zHt=new RegExp(`^(?:#${Gv}*)?$`),BHt=new RegExp(String.raw`^(?:(?:git\+)?ssh:\/\/)?[^@:/\\?#%]+@[^@:/\\?#]+:[^@?#]*(?:#${Gv}*)?$`),jHt=new RegExp(String.raw`^(?:(?:github|gitlab|bitbucket):)?[^@:/\\?#%]+(?:\/[^@:/\\?#%]+)+(?:#${Gv}*)?$`);var LZe=P(()=>fZ(!0));function mZ(){return ef()}var Wv=P(()=>mZ()),by=P(()=>mZ()),vv=P(()=>h().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),gZ=P(()=>h().regex(/^[0-9a-fA-F]{64}$/,"Must be a 64-character hex SHA-256 digest")),MZe="Archive URLs must use https:// and must not point at a loopback, link-local, or cloud-metadata host";function NZe(e){try{let t=new URL(e);return t.protocol==="https:"&&!u4(t.hostname)}catch{return!1}}var UZe=P(()=>O({source:U("archive"),url:h().url().refine(NZe,{message:MZe}).describe("HTTPS URL of a zip archive containing the plugin. The plugin root (the directory holding .claude-plugin/) may be at the top of the archive "+"or nested one directory deep — a single wrapping directory is stripped."),sha256:gZ().optional().describe("SHA-256 digest of the archive. When set, every download is verified against it and the install is refused on mismatch. It also serves as the version identity when neither plugin.json nor the marketplace entry declares a `version`. Recommended. Note the update signal is the version string (plugin.json "+"version, else the entry version, else this digest) — changing only the digest "+"while a version is declared does not trigger an update.")}).describe("Plugin distributed as a zip archive fetched over HTTPS — for hosting on any "+"static file server or artifact repository (S3, GitLab, nginx) with no git or npm on the client. Authentication: the entry's own `headers` / `headersHelper` (bound to this URL), overlaid on the enclosing url-source marketplace's headers (static or `headersHelper`-minted) when the archive shares its origin.")),hZ=P(()=>ie([Me((e)=>e==="."?"./":e,ir()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),O({source:U("npm"),package:nZ().or(h().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:h().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:h().url().refine(Lv,"Registry must be an http(s) URL").optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),O({source:U("url"),url:h().describe("Full git repository URL (https:// or git@)"),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:vv().optional().describe("Specific commit SHA to use")}),O({source:U("github"),repo:h().describe("GitHub repository in owner/repo format"),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:vv().optional().describe("Specific commit SHA to use")}),O({source:U("git-subdir"),url:h().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:h().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). '+"Checked out sparsely — over https or ssh as a partial clone (--filter=tree:0) — to minimize bandwidth for monorepos."),ref:h().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:vv().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."),UZe(),O({source:U("command"),command:h().min(1).max(Dv,{message:"command must not be longer than the install consent UI can display"}).refine((e)=>!F4.test(e),{message:"command must be printable ASCII (letters, digits, punctuation, single spaces) with no runs of 4 or more spaces"}).describe("Shell command that prints the absolute path of the plugin directory on stdout (exactly one line) and exits 0. It must leave a complete plugin in that directory before exiting; the directory is copied into the plugin cache, so the printed path may change between runs (it is re-resolved on every install and update, and once per session in the background). Runs through the platform shell (sh on macOS/Linux, cmd.exe on Windows) from the user's home directory with Claude Code's subprocess environment."),timeout:Y().int().positive().max(T4).optional().describe("Seconds to wait for the command before giving up (default: 60)"),mode:K(["copy","link"]).optional().describe("copy (default): the printed directory is copied into the plugin cache and content-hashed, so it may be deleted afterwards. link: the cache entry links to the printed directory "+"in place (no copy, no size limit; macOS/Linux) — for large exports; the directory must then stay "+"valid while Claude Code runs, and a different printed path is what signals new content.")}).describe("Plugin directory produced by a locally installed tool (e.g. an IDE that renders its plugin for the currently selected SDK). Claude Code runs the command, copies the directory it prints, and re-runs it in the background at startup to pick up changes."),O({source:U("unsupported"),error:h().optional()}).describe("Placeholder for source types this Claude Code version does not recognize, or a known type whose fields failed validation (then `error` "+"holds the reason). Never authored by hand — PluginMarketplaceSchema rewrites "+"unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with an actionable message.")])),FZe=P(()=>O({name:Ey().describe("Plugin name as it appears in the target repository"),source:hZ().describe("Where to fetch the plugin from. Must be a remote source — relative "+"paths have no marketplace repository to resolve against. Under allowManagedPermissionRulesOnly, a settings marketplace keeps its plugins' allowed-tools only when every npm entry here pins a `registry` on a bare package name; unpinned, the package resolves through the member's own npm config, and a non-bare spelling (an `npm:` alias, a `name@range`, a URL or git spec) packs as an "+"exotic spec the pin does not bind — either way the marketplace "+"vouches no tool grants."),description:h().optional(),version:h().optional(),strict:v().optional(),headers:q(h(),h()).optional().describe("HTTP headers sent when downloading this entry's `archive` source."),headersHelper:Mv().optional().describe("Command that prints a JSON object of HTTP headers for downloading this entry's `archive` source. Runs only when a user explicitly installs or updates this plugin. Unlike a catalog entry, an entry written here does not need `strict: false`: it is declared in a settings file, which has no manifest fields to inline. A declaration in project settings is not operator-authored, so request-routing and client-identity header names are still filtered there. Use an absolute path.")}).refine((e)=>typeof e.source!=="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url, archive, command). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine((e)=>typeof e.source==="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url, archive, command)."}));var HZe=P(()=>O({cli:k(h().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) — exact match against commands run this session.'),hosts:k(h().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:k(h().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:k(O({file:h().max(256),pattern:h().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:k(h().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.`)})),$Ze=P(()=>O({topic:h().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:HZe().optional().describe("Matchers that determine when the plugin is relevant.")})),zZe=P(()=>OZe().partial().extend({name:Ey().describe("Unique identifier matching the plugin name"),source:hZ().describe("Where to fetch the plugin from"),headers:q(h(),h()).optional().describe("Custom HTTP headers for fetching this plugin's archive; overrides the marketplace's"),headersHelper:Mv().optional().describe("Command that prints a JSON object of HTTP headers for fetching this plugin's archive (e.g. a short-lived auth token); overrides this entry's `headers` and the marketplace's. Runs only when the user installs or updates this plugin, never during catalog browse. An entry that sets it must be `strict: false` with its manifest inlined here, so consent is informed from the entry alone before the command runs."),category:h().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:k(h()).optional().describe("Tags for searchability and discovery"),strict:v().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:Me((e)=>oe(e)?e:void 0,$Ze().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.`)})),BZe=P(()=>O({name:Ey()}));function jZe(e){let t=zZe();return e.flatMap((n,r)=>{let o=t.safeParse(n);if(o.success){let a=o.data.source;if(typeof a==="object"&&a.source==="unsupported"&&a.error!==void 0)return[{...o.data,source:{source:"unsupported"}}];return[o.data]}let s=BZe().safeParse(n).data?.name,i=o.error.issues.map((a)=>`${a.path.join(".")}: ${a.message}`).join(", ");if(s){G(`Stubbing unparseable marketplace plugin entry (${s}): ${i}`,{level:"warn"});let a=_Z(oe(n)?n.source:void 0)?ZZe:Vv(n)?void 0:GZe(o.error.issues)??Cy(o.error.issues);return[{name:s,source:{source:"unsupported",...a&&{error:a}},strict:!0}]}return G(`Dropping unparseable marketplace plugin entry (index ${r}): ${i}`,{level:"warn"}),[]})}var KZe=new Set(["npm","url","github","git-subdir","archive","command","unsupported"]);function Vv(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.source;return typeof n==="string"&&!KZe.has(n)}function GZe(e){let t=e.find((r)=>r.path.length===1&&r.path[0]==="source");if(!t||t.code!=="invalid_union")return;let n=t.errors.find((r)=>!r.some((o)=>o.path.length===0||o.code==="invalid_value"&&o.path[0]==="source"));if(!n||n.length===0)return;return Cy(n.map((r)=>({...r,path:["source",...r.path]})))}var WZe=/^[A-Za-z0-9_$.-]{1,40}$/;function ko(e){return WZe.test(e)?e:"<key>"}var VZe=3,qZe=160;function Cy(e){let t=e.slice(0,VZe).map((r)=>{let o=r.path.map(String).map((i)=>ko(i)).join("."),s=r.code==="unrecognized_keys"?`Unrecognized ${r.keys.length===1?"field":"fields"}: ${r.keys.map(ko).join(", ")}`:av(r.message,qZe);return o?`${o}: ${s}`:s}),n=e.length-t.length;return n>0?`${t.join(", ")} (+${n} more)`:t.join(", ")}var YZe=/^[A-Za-z0-9][-A-Za-z0-9._]*$/,ZZe='Bare source names resolve under metadata.pluginRoot, which this marketplace does not set (or sets to a path outside the marketplace root). Use a "./relative/path" source, or set metadata.pluginRoot to allow bare names.';function _Z(e){return typeof e==="string"&&YZe.test(e)&&!e.includes("..")}function JZe(e){if(typeof e!=="string"||e===""||e.startsWith("/")||e.includes("\\")||e.includes(":"))return;let t=e.replace(/^\.\//,"").replace(/\/+$/,"");if(t===""||t===".")return".";if(t.split("/").some((n)=>n===""||n==="."||n===".."))return;return t}function XZe(e,t){if(t===void 0||!oe(e)||!_Z(e.source))return e;let n=t==="."?`./${e.source}`:`./${t}/${e.source}`;return{...e,source:n}}function QZe(e){if(!oe(e)||!Array.isArray(e.plugins))return e;let t=oe(e.metadata)?JZe(e.metadata.pluginRoot):void 0;if(t===void 0)return e;return{...e,plugins:e.plugins.map((n)=>XZe(n,t))}}var e9e=P(()=>O({$schema:h().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:aZe(K4),version:h().optional().describe("Marketplace manifest version"),description:h().optional().describe("Human-readable description of this marketplace"),owner:$v().describe("Marketplace maintainer or curator information"),plugins:k(me()).transform(jZe).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:v().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:O({pluginRoot:h().optional().describe('Base directory for bare plugin source names, relative to the marketplace root (e.g. "./plugins" resolves "source": "formatter" as ./plugins/formatter). Sources that already start with "./" are unaffected.'),version:h().optional().describe("Marketplace version"),description:h().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:k(h()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies — no transitive trust."),renames:q(h(),h().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.")})),KHt=P(()=>Me(QZe,e9e()));var Pv="[A-Za-z0-9][-A-Za-z0-9._]*",GHt=new RegExp(`^${Pv}$`);var t9e=new RegExp(`^${Pv}@${Pv}$`),D4=`@${Fv}`;function yZ(e){return e.endsWith(D4)&&Kv(e.slice(0,-D4.length))}var qc=P(()=>h().refine((e)=>t9e.test(e)||yZ(e),"Plugin ID must be in format: plugin@marketplace")),WHt=new RegExp(`[@:\\s/\\\\${Ir}]`,"u"),VHt=new RegExp(`[${Ir}]`,"u"),SZ=/[\p{Cc}\u200E\u200F\u202A-\u202E\u2066-\u2069]/u,n9e=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,r9e=P(()=>ie([h().regex(n9e,"Dependency must be a plugin name, optionally qualified with @marketplace").transform((e)=>e.replace(/@\^[^@]*$/,"")),O({name:h().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:h().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform((e)=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),o9e=P(()=>O({version:h().describe("Currently installed version"),installedAt:h().describe("ISO 8601 timestamp of installation"),lastUpdated:h().optional().describe("ISO 8601 timestamp of last update"),installPath:h().describe("Absolute path to the installed plugin directory"),gitCommitSha:h().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:h().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:v().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)."),...L4(),...M4(),...U4(),...N4()})),qHt=P(()=>O({version:U(1).describe("Schema version 1"),plugins:q(qc(),o9e()).describe("Map of plugin IDs to their installation metadata")})),s9e=P(()=>K(["managed","user","project","local"])),i9e=P(()=>O({scope:s9e().describe("Installation scope"),projectPath:h().optional().describe("Project path (required for project/local scopes)"),installPath:h().describe("Absolute path to the versioned plugin directory"),version:h().optional().describe("Currently installed version"),installedAt:h().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:h().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:h().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:h().optional().describe("Tag-derived semver this install resolved to"),auto:v().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep."),...L4(),...M4(),...U4(),...N4()})),YHt=P(()=>O({version:U(2).describe("Schema version 2"),plugins:q(qc(),k(i9e())).describe("Map of plugin IDs to arrays of installation entries")})),ZHt=P(()=>O({version:U(2),plugins:q(h(),me())}));var a9e=P(()=>O({source:LZe().describe("Where to fetch the marketplace from"),installLocation:h().describe("Local cache path where marketplace manifest is stored"),lastUpdated:h().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:v().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup"),declaredByManagedSettings:U(!0).optional().describe("Managed settings declared this source for this name: when they later declare another, it is the organization moving its marketplace, and what its plugins saved stays")})),JHt=P(()=>q(h(),a9e()));function Yc(e){return e==="true"?!0:e==="false"?!1:e}var Ay=["aspell","hunspell","ispell"];var Zc=2147483647;var l9e=["autoMode","deepLink","voice","briefView","screenReader"],c9e={},Yv={autoMode:{buildGate:()=>!0,shape:()=>({skipAutoPermissionPrompt:v().optional().describe("Whether the user has accepted the auto mode opt-in dialog"),useAutoModeDuringPlan:v().optional().describe("Whether plan mode uses auto mode semantics when auto mode is available (default: true)"),autoMode:O({allow:k(h()).optional().describe('Rules for the auto mode classifier allow section. Include the literal string "$defaults" to inherit the built-in rules at that position.'),soft_deny:k(h()).optional().describe('Rules for the auto mode classifier SOFT BLOCK section — destructive/irreversible actions that user intent can clear. Include the literal string "$defaults" to inherit the built-in rules at that position.'),hard_deny:k(h()).optional().describe('Rules for the auto mode classifier HARD BLOCK section — security boundaries that user intent does NOT clear. Include the literal string "$defaults" to inherit the built-in rules at that position.'),...!1,...{},environment:k(h()).optional().describe('Entries for the auto mode classifier environment section. Include the literal string "$defaults" to inherit the built-in entries at that position.'),classifyAllShell:v().optional().describe("When true, every Bash/PowerShell allow rule is suspended while auto mode is active so all shell commands are routed through the classifier (higher safety, more classifier calls). Default: false.")}).optional().describe("Auto mode classifier prompt customization")}),permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:K(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!0,shape:()=>({voiceEnabled:v().optional().describe("Enable voice mode (hold-to-talk dictation)")})},briefView:{buildGate:()=>!0,shape:()=>({defaultView:K(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>c9e}};function Jc(){return l9e.filter((e)=>Yv[e].buildGate())}function EZ(e){let t={};for(let n of e)t={...t,...Yv[n].shape()};return t}function Zv(e){let t=[];for(let n of e)t.push(...Yv[n].permissionModes?.()??[]);return t}var i$t=new RegExp("\x00ESCAPED_STAR\x00","g"),a$t=new RegExp("\x00ESCAPED_BACKSLASH\x00","g");var l$t=new RegExp("\x00GLOBSTAR\x00","g");function bZ(e){return e.match(/^(.+):\*$/)?.[1]??null}function CZ(e){let t=e.trimEnd();if(!t.endsWith("*"))return!1;let n=0,r=t.length-2;while(r>=0&&t[r]==="\\")n++,r--;return n%2===0}var Ry={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 Jv(e){return Ry.filePatternTools.includes(e)}function AZ(e){return Ry.bashPrefixTools.includes(e)}function RZ(e){return Object.hasOwn(Ry.customValidation,e)?Ry.customValidation[e]:void 0}function wZ(e,t){let n=0,r=t-1;while(r>=0&&e[r]==="\\")n++,r--;return n%2!==0}function OZ(e,t){let n=0;for(let r=0;r<e.length;r++)if(e[r]===t&&!wZ(e,r))n++;return n}var u9e=/(?:^|[^\\])\\[()]/;function d9e(e){return u9e.test(e)&&OZ(e,"(")!==OZ(e,")")}var p9e=/^(?:[|&;<>]|\d+[<>])/;function f9e(e){return p9e.test(e)}function Xv(e){for(let t=0;t<e.length;t++)if(e[t]==="*"&&!wZ(e,t))return!0;return!1}function m9e(e){if(e.endsWith(":*"))return;let t=e.trim().split(/\s+/).filter(Boolean),n=t[0];if(t.length<3||n===void 0||Xv(n))return;let r=!1;for(let o of t.slice(1)){if(f9e(o))return;if(Xv(o)){r=!0;continue}if(o.startsWith("-"))continue;return r?n:void 0}return}function TZ(e){if(!qp(e))return null;let t=Kc(e);if(t&&!qp(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 Qv(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=cv(e);if(n.kind==="malformed")return{valid:!1,error:"Malformed Tool(content) rule",suggestion:'Rules take the form Tool or Tool(content) and must end at the closing ")"; parentheses inside the content are literal'};if(n.kind==="call"&&n.rawContent===""){if(!n.toolName)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${n.toolName}" without parentheses`,examples:[`${n.toolName}`,`${n.toolName}(some-pattern)`]}}let r=VY(e),o=Kc(r.toolName);if(o){if(n.kind==="call"){let i=o.toolName&&!qp(o.toolName)?`${r.toolName}__*`:void 0;return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:i===void 0?`Use "${r.toolName}" without parentheses, or use "mcp__${o.serverName}__*" for all tools`:`Use "${r.toolName}" without parentheses. For all tools of a server, use "mcp__${o.serverName}__*" for the server "${o.serverName}", or "${i}" for a server named "${o.serverName}__${o.toolName}"`,examples:[`mcp__${o.serverName}`,`mcp__${o.serverName}__*`,o.toolName&&o.toolName!=="*"?`mcp__${o.serverName}__${o.toolName}`:void 0,i].filter(Boolean)}}if(t==="allow"){let i=TZ(r.toolName);if(i)return i}return{valid:!0}}if(!r.toolName||r.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let i=TZ(r.toolName);if(i)return i}if(!r.toolName.includes("_")&&r.toolName[0]!==r.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${Nu(String(r.toolName))}"`};if(n.kind==="call"&&d9e(n.rawContent)){let i=Jv(r.toolName);return{valid:!1,error:'Ambiguous "\\(" or "\\)" beside an unescaped parenthesis',suggestion:i?"Write a Windows path with forward slashes, or spell a literal parenthesis as [(] or [)]":'Double a backslash that is a path separator ("\\\\("), and escape literal parentheses in pairs',examples:i?[`${r.toolName}(C:/Projects/(drafts)/**)`,`${r.toolName}(C:\\Projects\\[(]drafts)\\**)`]:[`${r.toolName}(C:\\tools\\\\(x86)\\run.exe *)`]}}let s=RZ(r.toolName);if(s&&r.ruleContent!==void 0){let i=s(r.ruleContent);if(!i.valid)return i}if(AZ(r.toolName)&&r.ruleContent!==void 0){let i=r.ruleContent;if(i===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]};if(t==="allow"){let l=m9e(i);if(l!==void 0){let c=l==="git",d=c?" For git, options such as -c and --exec-path can run arbitrary commands.":"",p=c?" (for example Bash(git status *))":"";return{valid:!0,warning:`${sr(r)} has a wildcard before the rest of the command, so it also matches any options inserted at that position and approves them without a prompt.${d} Replace that * with the exact value you mean, or only use * after the subcommand${p}.`,securityNotice:`${sr(r)} allows any option at its * · use an exact value`}}}let a=bZ(i)?.trimEnd();if(a!==void 0){if(Xv(a)){let l=CZ(a),c=l?"matches only commands containing a literal * at that position":"will likely never match",d=l?a:`${a}*`,p=t==="allow"?" Replace that * with the exact value you mean.":d.endsWith(":*")?"":` Use ${sr({toolName:r.toolName,ruleContent:d})} for wildcard matching.`;return{valid:!0,warning:`${sr(r)} mixes * with the trailing :* prefix syntax, so it is matched as a literal prefix (the * is not expanded) and ${c}.${p}`,...t!=="allow"&&{securityNotice:`${sr(r)} reads its * literally${d.endsWith(":*")?"":` · use ${sr({toolName:r.toolName,ruleContent:d})}`}`}}}}else if(i.includes(":*")&&!i.endsWith(":*")){let l=t==="allow"?"Replace that :* with the exact value you mean.":"It already matches as a * wildcard; moving :* to the end would make it a literal prefix and change which commands match.";return{valid:!0,warning:`${sr(r)} has a :* that is not at the end, so it is matched as a * wildcard (the : is literal), not as the trailing :* prefix syntax. ${l}`,...t==="allow"&&{securityNotice:`${sr(r)} reads its :* as a wildcard · use an exact value`}}}}if(Jv(r.toolName)&&r.ruleContent!==void 0){if(r.ruleContent.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${r.toolName}(*.ts) - matches .ts files`,`${r.toolName}(src/**) - matches all files in src`,`${r.toolName}(**/*.test.ts) - matches test files`]}}if(r.ruleContent!==void 0){let i=r.toolName==="Write"||r.toolName==="NotebookEdit"||r.toolName==="MultiEdit"?"Edit":r.toolName==="Glob"?"Read":void 0;if(i!==void 0&&!r.ruleContent.includes(":*"))return{valid:!0,warning:`${sr(r)} is not matched by file permission checks — only ${i}(path) rules are. Use ${sr({toolName:i,ruleContent:r.ruleContent})} instead (${i} rules cover all file-${i==="Edit"?"editing":"reading"} tools).`,...t!=="allow"&&{securityNotice:`${sr(r)} never matches · use ${sr({toolName:i,ruleContent:r.ruleContent})}`}}}return{valid:!0}}var ex=P(()=>xZ()),vZ=P(()=>xZ("allow"));function xZ(e){return h().superRefine((t,n)=>{let r=Qv(t,e);if(!r.valid){let o=r.error;if(r.suggestion)o+=`. ${r.suggestion}`;if(r.examples&&r.examples.length>0)o+=`. Examples: ${r.examples.join(", ")}`;n.addIssue({code:fr.custom,message:o,params:{received:t}})}})}var of=["accept","hold","refuse"],xy=["off","basic","full"],g9e=P(()=>q(h(),fxe()));function BZ(e){return O({allow:k(vZ()).optional().describe("List of permission rules for allowed operations"),deny:k(ex()).optional().describe("List of permission rules for denied operations"),ask:k(ex()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:Me(jc,K([...Aa,...Zv(e)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:K(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),blockReadsOutsideWorkingDirectories:v().optional().describe('Refuse file-tool reads (Read, Grep, Glob, LSP) outside the working directories in every permission mode; true in any settings source wins. No allow rule lifts it. Also set when the user picks "block" on the one-time auto-mode prompt for a read outside the working directories.'),blockWritesOutsideWorkingDirectories:v().optional().describe("Refuse file-tool writes (Write, Edit, NotebookEdit) outside the working directories in every permission mode; true in any settings source wins. No allow rule lifts it. Files that Claude Code keeps for the session are not refused: its plan files, scratchpad and background job folder, and the auto-memory of this project, unless a repository settings file points it elsewhere. Nothing runs them unless the model asks. Also refuses file-tool writes to Claude Code settings files, inside the working directories too, and takes EnterWorktree and ExitWorktree, which move the working directory, out of the tools on offer. Does not limit shell commands, MCP tools, the programs that hooks run, or the memory tools. Cloud sessions (Claude Code on the web), whose file tools run in a container that is itself the boundary, may not apply it."),blockReadsExemptPaths:k(h().catch("")).optional().catch(void 0).describe('For the program that starts Claude Code: read only from --settings and from settings that program sends while the session runs; ignored in user, project, local and managed settings. Absolute paths, each a folder with all below it or one file, that blockReadsOutsideWorkingDirectories lets through beside the working directories. It allows nothing: an allow rule, the permission mode or the user still decides each read, as with that setting off, and a shell command that hands such a path to a program is still asked about unless a Read allow rule covers it. The paths do not become working directories, so blockWritesOutsideWorkingDirectories refuses writes to them, and they are not told to MCP servers or to the model. Each path counts as written: a link in it is not followed and a pattern is not expanded, so list every spelling that a read may arrive by. Ignored: an entry that starts with ~, has a ".." segment or has white space at either end (as written or once normalized), a relative or network path, and the root of a filesystem. Does not change what sandboxed commands may read (sandbox.filesystem.allowRead does).'),workingDirectoriesAsGiven:k(h().catch("")).optional().catch(void 0).describe("For the program that starts Claude Code: read only from --settings and from settings that program sends while the session runs; ignored in user, project, local and managed settings. Absolute paths of working directories, each spelled exactly as it is passed, letter case included (the session folder, --add-dir, permissions.additionalDirectories). To decide what lies inside a listed working directory, Claude Code takes it as written and follows no link at it, so a link that later stands in its place gives the file tools no access to where the link leads. List real paths: the files of a listed path that runs through a link count as outside the working directories, because where they really are lies outside it. List a mapped network drive by its drive-letter path: Claude Code still derives the UNC form of that path by itself and adds it, as for any mapped drive. A file path that is itself spelled as a UNC path is judged as written, so a link on the share is not seen by that spelling. It adds no working directory and allows nothing. Once listed, a path stays so until the process ends, also if later settings leave it out. Ignored: an entry that is not already normalized (a relative path, one that starts with ~, a \"..\" segment, a separator at its end unless it is a filesystem root, forward slashes on Windows, white space at either end). Does not change what sandboxed commands may write."),disableAutoMode:K(["disable"]).optional().describe("Disable auto mode"),denyInsteadOfPrompting:v().optional().describe("Never wait for a person to answer a tool permission prompt: a call that would prompt is denied at once, the model is told, and the turn carries on. This is what --permission-prompts none does for -p, in every kind of session, subagents and agent teams included. Allow rules, the permission mode, auto mode's classifier and PermissionRequest hooks decide first, as they do without it; it only ever denies, and allows nothing. Claude's questions and plan mode's tools are not offered to the model, and an MCP server's request for input is cancelled unless an Elicitation hook answers it. An app or script that answers prompts through canUseTool or --permission-prompt-tool is not asked either: answer from a PermissionRequest hook instead. Read from user settings, --settings and managed settings; project and local settings are ignored, and true in any of those sources wins."),additionalDirectories:k(h()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}var X$t=P(()=>BZ(Jc())),h9e=P(()=>ie([h(),O({}).passthrough().describe('{ id: stable id (letters, digits, ".", "_", "-"; max 64), text: the tip (max 500 characters, one line), cooldownSessions?: sessions to wait before showing it again (default 0), priority?: tie-break weight among never-shown tips (default 0) }')])),_9e=P(()=>Me((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"||!!t&&typeof t==="object"&&!Array.isArray(t)):[],k(h9e()))),sx=P(()=>O({source:ef().describe("Where to fetch the marketplace from"),installLocation:h().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:v().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup"),pluginDigests:q(h(),k(h()).catch([])).optional().catch(void 0).describe('Managed settings only: the plugins of this marketplace that an organization delivers with its own tier, by plugin name, each with the digests of its releases. A plugin also enabled and listed in prependPlugins or appendPlugins by managed settings the session vouches for loads its hooks module only from a folder that proves one of them, and is then seated in that tier; any other copy does not load. A digest is sha256- and the base64 SHA-256 of, for every regular file in the folder in UTF-16 code unit order of its path, not normalized, "f PATH" NUL BYTE-LENGTH NUL BYTES, with / in paths; .git, .in_use, .orphaned_at, .claude-plugin-link and .links_materialized at the root are left out. The plugin keeps its manifest at .claude-plugin/plugin.json and names one module in hooks/hooks.json. A string of any other form, or a list that is empty or of any other shape, matches no folder. A symbolic link, or a surface module, proves nothing. A proved plugin ships bundled with no install step: the digest covers the whole folder, node_modules included. A checkout whose line endings were converted proves nothing.')})),ix=P(()=>{let e=()=>Y().min(0).max(1e4);return O({input:e(),output:e(),cacheRead:e(),cacheWrite:e()})}),ax=P(()=>Y().gt(0).lte(10).optional()),lx=P(()=>O({model:h().describe('Model to select, taken verbatim: an alias ("opus"), an Anthropic model ID, or a provider-format ID (Vertex, Bedrock, gateway). Same values --model accepts.'),label:h().optional().describe("Row title. Defaults to the model name."),description:h().optional().describe("Row subtitle. Defaults to a generic description."),behavesAs:h().optional().describe("For a model this version of Claude Code does not know: the ID of a model it does know "+'(e.g. "claude-opus-4-8") whose client-side handling — prompt profile, capability and effort '+"defaults — applies to it. Changes neither the row's label nor the model ID sent. Without it, "+"a model-catalog row for a model this version does not know is not offered until Claude Code is updated.")})),ky=P(()=>O({serverName:h().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:k(h()).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:h().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine((e)=>ja([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"'})),Py=P(()=>O({serverName:h().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:k(h()).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:h().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine((e)=>ja([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"'})),jZ=P(()=>O({marketplace:h(),plugin:h()})),y9e=P(()=>Me((e)=>{if(typeof e!=="string"||!qc().safeParse(e).success)return e;let t=e.indexOf("@");return{marketplace:e.slice(t+1),plugin:e.slice(0,t)}},jZ())),S9e=/[\x00-\x1f\x7f-\x9f\u2028\u2029]|\p{DI}/u;function E9e(e){let t=e.replaceAll("/","\\");if(Do(t))return!1;return/^\\{2}[^\\]/.test(t)}function b9e(e){return xr(e)||/^\/network\/servers(\/|$)/i.test(e)||Lo(e)}function C9e(e){return/^\/(proc|dev\/(fd|stdin|stdout|stderr))(\/|$)/i.test(e)}function A9e(e,t,n={}){if(t==="win32"){let r=e.replaceAll("/","\\");if(Do(r))return!1;let o=E9e(r);if(n.rejectUnc&&o)return!1;if(n.rejectDriveRelative){if(!/^[A-Za-z]:\\/.test(r)&&!o&&/^(\\|[A-Za-z]:)/.test(r))return!1}if(zZ.normalize(r)!==r)return!1;let s=r.split("\\");if(s.some((a)=>a==="."||a===".."))return!1;if(s.some((a,l)=>/[. ]$/.test(a)||a.includes(":")&&!(l===0&&/^[A-Za-z]:$/.test(a))))return!1;let i=r.startsWith("\\\\")?r.slice(2):r;if(/\\{2}/.test(i))return!1;return!r.endsWith("\\")||/^([A-Za-z]:)?\\$/.test(r)}if(n.rejectNetworkRoot&&b9e(e))return!1;if(n.rejectMagicLinkRoot&&C9e(e))return!1;if($Z.normalize(e)!==e)return!1;if(e.split("/").some((r)=>r==="."||r===".."))return!1;if(/\/{2}/.test(e))return!1;return!e.endsWith("/")||e==="/"}var R9e=/\.(exe|ps1)$/i;function O9e(e){return/\.ps1$/i.test(e)}function T9e(e){return O9e(e)&&/[[\]`*?]/.test(e)}var w9e='a .ps1 path must not contain "[", "]", "`", "*", or "?" on Windows (PowerShell resolves them as wildcard syntax)',v9e=()=>h().describe("Absolute path to the helper executable"),vi=(e)=>Me((t)=>t===null?void 0:t,e.optional()).optional(),x9e=Zc,kZ=(e)=>Y().int().min(e).transform((t)=>Math.min(t,x9e)),PZ=["path","script","defaultSettings"];function KZ(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;return PZ.some((n)=>t[n]===null)&&PZ.every((n)=>t[n]===null||t[n]===void 0)}var IZ=64,wy=P(()=>O({path:v9e(),timeoutMs:vi(kZ(1000)),refreshIntervalMs:vi(ie([U(0),kZ(60000)]))})),GZ=()=>K(["replace","merge"]).describe("How the helper's managedSettings compose with the settings of the source that delivered this entry: 'replace' (default) — the output is the policy; 'merge' — the output is deep-merged over that source's own settings the way merged managed sources compose (helper scalars win, arrays union, objects merge — except fallbackModel, forceLoginOrgUUID, gatewayInternalNetworks, sandbox.filesystem.allowRead, sandbox.credentials.awsPairs, sandbox.ripgrep and the restriction allowlists such as allowedMcpServers, allowedProviders, availableModels and allowedHttpHookUrls, which are the helper's whole value when it emits one; tighten a permission with a deny), so a failed helper costs only the delta");function WZ(e){return e==="continue"||e==="refuse"}var k9e=()=>Me((e)=>e===void 0||WZ(e)?e:"refuse",K(["continue","refuse"]).describe(`What happens when this entry's helper fails at startup (bad path, missing file or interpreter, non-zero exit, timeout, oversize or invalid output) and no static settings payload (this entry's own, the linux entry's on WSL, or the map's "default") applies in its place: 'refuse' — Claude Code does not start, naming the failure; 'continue' — Claude Code starts without the helper's output, on the delivering source's own settings, with a /status notice. Default: 'refuse' when the entry comes from MDM or the managed settings file, 'continue' when it comes from remote managed settings. Any other value is treated as 'refuse', with a /status notice. The install and update commands start no session and are never refused over a remote entry: they report the refusal in /status. An entry whose other fields fail validation runs no helper; from MDM or the managed settings file, any value but 'continue' on it then refuses to start Claude Code until the entry is fixed, unless a static settings payload (the entry's own, kept when it validates, the linux entry's for a wsl one, or the map's "default") serves in its place. From remote, a non-interactive session runs the helper off settings verified this session without the interactive approval, so 'refuse' there too means the helper ran and failed; a launch whose remote settings could not be verified this session (offline, fetch failed) starts without the helper regardless; and a failure first reached after the session has started (settings verified or approved mid-session, which on a machine that only ever runs non-interactively is every launch) ends a session no person watches (non-interactive, a background session no client is attached to, or a teammate session) as the refused start would have, and leaves a watched interactive one (a terminal, with or without remote control, or an attached background session) running under a /status notice with its next start refused. Background refresh failures always keep the last good output whatever this says`)),P9e=5,I9e=()=>Y().int().min(0).transform((e)=>Math.min(e,P9e)).describe("How many more times to run this entry's helper when a run fails to execute — it could not be launched, exited non-zero, or was stopped at timeoutMs — before that counts as a failure (a non-negative integer; default 0, a single attempt; above 5 is treated as 5). Attempts are separated by a short randomized backoff (from 250 ms, doubling per attempt, at most 4 s each) and each attempt gets the full timeoutMs, so a start that waits on the helper can wait up to (retries + 1) × timeoutMs plus the backoff. Output the helper did produce and that was refused — oversized, not a JSON object, an invalid envelope, or settings that fail validation — is not retried, and neither is an invalid path. Applies alike at startup and on each background refresh; only once the attempts are used up do the entry's failure rules (a static settings payload in its place, onFailure, the refresh notice) apply, naming the last attempt's failure"),D9e=(e)=>(e==="windows"?U("pwsh",{message:"interpreter must be 'pwsh' on windows ('sh' is not supported there)"}):U("sh",{message:"interpreter must be 'sh' on macos/linux/wsl"})).describe("Fixed interpreter for `script`: 'sh' (/bin/sh) on macos/linux/wsl entries; 'pwsh' (PowerShell at its fixed install locations, never PATH) on the windows entry"),L9e="exactly one of path/script must be configured",M9e='"script" and "interpreter" must be configured together',N9e="script must be ASCII-only on Windows (PowerShell decodes stdin with the console OEM code page); spell non-ASCII characters as escapes, e.g. [char]0x00E9",U9e=(e)=>h({message:"script must be a string"}).min(1,{message:"script must not be empty"}).max(65536,{message:"script must be at most 65536 characters"}).refine((t)=>!t.includes("\x00"),{message:"script must not contain NUL bytes"}).refine((t)=>Uu(t),{message:"script must be valid UTF-8 (no lone surrogates)"}).refine((t)=>e!=="windows"||!/[\u0080-\uffff]/.test(t),{message:N9e}).describe("Inline helper script, delivered to the fixed interpreter over stdin (never written to disk)");var Sn=["macos","linux","windows","wsl"];function cx(e){return e==="wsl"?["wsl","linux"]:[e]}function F9e(e){return e==="windows"?"win32":"posix"}function H9e(e){return{rejectDriveRelative:e==="windows",rejectUnc:e==="windows",rejectNetworkRoot:e!=="windows",rejectMagicLinkRoot:e!=="windows",requireWin32ExecutableSuffix:e==="windows"}}function $9e(e){let t=F9e(e),n=H9e(e);return h().max(1024,{message:"path must be at most 1024 characters"}).refine((r)=>!S9e.test(r),{message:"path must not contain control, line/paragraph-separator, or invisible (default-ignorable) characters"}).refine((r)=>(t==="win32"?zZ:$Z).isAbsolute(r),{message:"path must be absolute"}).refine((r)=>!(t==="win32"&&n.requireWin32ExecutableSuffix)||R9e.test(r),{message:"path must end in .exe or .ps1 on Windows"}).refine((r)=>t!=="win32"||!T9e(r),{message:w9e}).refine((r)=>A9e(r,t,n),{message:t==="win32"?'path must be in normalized form: no "." or ".." segments, no doubled or trailing separators, no component ending in "." or a space, no ":" outside the drive letter, no device-namespace (\\\\?\\) prefix, no drive-relative (\\dir or C:name) or UNC (\\\\server\\share) form':'path must be in normalized form: no "." or ".." segments, no doubled or trailing separators, and not under a network automount root (/net/<host>, /Network/Servers, or macOS /.vol /.file /.nofollow /.resolve) or a kernel magic-link root (/proc, /dev/fd)'}).describe("Absolute path to the helper executable")}var ux=[...Sn,"default"],tx=["path","script","interpreter","outputBehavior","onFailure","retries","timeoutMs","refreshIntervalMs","defaultSettings"],Ty=["managedSettings","appendSystemPrompt"],ka=P(()=>q(h(),me()).superRefine((e,t)=>{for(let n of["policyHelper","policyHelpers"])if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — the default payload is applied as managed settings and cannot configure further policy helpers`});for(let n of tx)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is a managed-settings object, not a policyHelpers entry; entry fields (${tx.join("/")}) belong on the per-OS entries (policyHelpers.${Sn.join("/")})`});for(let n of Ty)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is the managedSettings SUBTREE, not the helper's stdout envelope; paste the object your helper emits UNDER "managedSettings", not the envelope around it`});for(let n of ux)if(e[n]!==void 0&&e[n]!==null)t.addIssue({code:"custom",message:`must not contain "${n}" — a static payload is the VALUE of a policyHelpers key (a managed-settings object), never another policyHelpers map; don't paste the map or its "${n}" line inside the slot`})})),z9e='Entry must carry "path" (a helper executable) or "script" + "interpreter" (an inline helper), and/or "defaultSettings" (a static settings payload)';function B9e(e){let{path:t,script:n,interpreter:r,defaultSettings:o}=e;if(t!==void 0&&n!==void 0)return L9e;if(n===void 0!==(r===void 0))return M9e;if(t===void 0&&n===void 0&&o===void 0)return z9e;return null}function VZ(e,t){return wy().omit({path:!0}).extend({path:vi($9e(e)),script:vi(U9e(e)),interpreter:vi(D9e(e)),outputBehavior:vi(GZ()),onFailure:vi(k9e()),retries:vi(I9e()),defaultSettings:Me((n)=>n===null?void 0:n,t.optional()).optional()}).check((n)=>{if(n.issues.length>0)return;let r=B9e(n.value);if(r!==null)n.issues.push({code:"custom",message:r,input:n.value})})}var Q$t=P(()=>VZ("linux",ka()));function nx(e,t=ka()){return e==="default"?ka():VZ(e,t)}var j9e=P(()=>O(Object.fromEntries(ux.map((e)=>[e,Me((t)=>{if(t===null)return;if(e!=="default"&&KZ(t))return;return t},nx(e).optional()).optional()])))),rf=["skills","agents","hooks","mcp"];function qZ(e){return Me((t)=>{if(!Array.isArray(t))return t;let n=t.filter((r)=>rf.includes(r));if(n.length<t.length)e?.(t.length-n.length);return n},ie([v(),k(K(rf))]))}function YZ(){return ie([k(h()),v(),fO()])}var DZ=Object.freeze({type:"invalid-entry-stripped"}),K9e=P(()=>ie([O({type:U("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:h().describe("Regex matched against turn output (tool results and assistant text)"),url:h().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:h().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),O({type:h().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()])),LZ=()=>Y().int().min(BY).max(jY).optional().catch(void 0);function ZZ(e,{strictPolicyHelperKeys:t=!1}={}){function n(o){return q(h(),sx()).check((s)=>{for(let[i,a]of Object.entries(s.value))if(a.source.source==="settings"&&a.source.name!==i)s.issues.push({code:"custom",input:a.source.name,path:[i,"source","name"],message:`Settings-sourced marketplace name must match its ${o} key (got key "${i}" but source.name "${a.source.name}")`})})}let r=(o,s)=>t?Me((i)=>{if(i===null)return;return s?s(i):i},o):o.catch(void 0);return{$schema:()=>h().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:()=>h().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:()=>h().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:()=>h().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:()=>h().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:()=>h().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),processWrapper:()=>h().optional().describe("Corporate launcher argv prefix for the background-agent supervisor, the sessions and workers it hosts, and the other covered background processes listed in the Claude Code corporate-launcher documentation. Equivalent to the CLAUDE_CODE_PROCESS_WRAPPER environment variable, which takes precedence when set. Honored from managed settings, a --settings/SDK-supplied settings file, and user settings, in that precedence order; project and local settings are ignored."),policyHelper:()=>r(wy().optional(),(o)=>o&&typeof o==="object"&&!Array.isArray(o)&&o.path===null?void 0:o).describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),policyHelpers:()=>r(j9e().optional()).describe(`@internal Per-OS variant of policyHelper, keyed by platform: macos, linux, windows, wsl, plus an optional "default" entry that is a STATIC settings payload (a JSON object of managed settings, not a helper). Each per-OS entry carries a helper — a "path", or an inline "script" + "interpreter" delivered to a fixed interpreter over stdin, either with timeoutMs/refreshIntervalMs — its own static "defaultSettings" payload, or both; an entry may be payload-only. Selection for a platform walks its chain (the platform's own entry; on wsl the linux entry next): the first helper on the chain wins over policyHelper; if no helper is configured — or the selected helper fails at startup or refresh — the first payload applies (the chain's "defaultSettings" in platform-specific-first order, then the top-level "default", applied with no process spawned; unrecognized platforms reach only "default"); with no payload either, policyHelper. Honored from admin-controlled policy sources, and from remote managed settings — a payload of plain policy as delivered, like any other remote key; a helper, or a payload carrying anything the managed-settings approval dialog lists, only once the settings are verified this session and approved there (policyHelper itself is never honored from remote).`),...Dt.CLAUDE_CODE_ENABLE_XAA&&{xaaIdp:()=>O({issuer:h().url().describe("IdP issuer URL for OIDC discovery"),clientId:h().describe("Claude Code's client_id registered at the IdP"),callbackPort:Y().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:()=>O({type:U("command"),command:h()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:()=>v().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:()=>O({enabled:v().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:Y().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:Y().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:h().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:()=>O({enabled:v().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:h().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:h().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:()=>Y().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. Cleanup deletes data only on this computer, not anything stored by Anthropic."),desktopSessionCleanupPeriodDays:()=>Y().int().nonnegative().optional().describe("Retention ceiling in days for session transcripts created or last written by a desktop-host surface (Claude Desktop, Cowork), which are otherwise exempt from the cleanupPeriodDays sweep. 0 (the default) means no ceiling: such transcripts are kept until deleted another way. Unlike cleanupPeriodDays, 0 is allowed because this setting never disables writes — it only bounds an exemption from deletion. The ceiling is a hard cap: it also bounds an active archive grace, so the grace window of a release marker never keeps files past the ceiling. Ignored when cleanupPeriodDays is managed by org policy. A ceiling at or below cleanupPeriodDays effectively disables the exemption: those transcripts age out on the regular cleanupPeriodDays schedule, so the effective retention is whichever of the two periods is longer. Cleanup deletes data only on this computer, not anything stored by Anthropic."),syncClaudeAiSkills:()=>v().optional().describe("Set to false to turn off syncing of the skills you have enabled on claude.ai. In your user settings (or managed settings): nothing more is downloaded, previously synced skills (~/.claude/skills/synced) can no longer be run, are hidden from every session started afterwards, and are moved to ~/.claude/skills/.trash at the next launch (deleted after cleanupPeriodDays; re-downloaded, not restored, if you re-enable). In .claude/settings.local.json or --settings: downloads stop and synced skills are blocked and hidden for sessions in that workspace or invocation only (nothing is moved). Not read from project settings (.claude/settings.json). Only false is honored — the feature is enabled server-side for your account, so setting true does not turn it on early. While it is on, synced skills are available in every session, re-synced about every 10 minutes while a session is in use and a quarter as often otherwise, and removed when you disable them on claude.ai. Only applies when signed in with your Claude account."),syncClaudeAiPlugins:()=>v().optional().describe("Set to false to turn off syncing of the plugins you have enabled on claude.ai. In your user settings (or managed settings): nothing more is downloaded, previously synced plugins (~/.claude/plugins/synced) are hidden from every session started afterwards and moved to ~/.claude/plugins/.trash at the next launch (deleted after cleanupPeriodDays; re-downloaded, not restored, if you re-enable). In .claude/settings.local.json or --settings: downloads stop and synced plugins are hidden for sessions in that workspace or invocation only (nothing is moved). Not read from project settings (.claude/settings.json). Only false is honored — the feature is enabled server-side for your account, so setting true does not turn it on early. While it is on, synced plugins load in every session like plugins you installed yourself (a plugin you installed with the same name takes precedence), are re-synced at each launch, and are removed when you disable them on claude.ai. Only applies when signed in with your Claude account."),skillListingMaxDescChars:()=>Y().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:()=>Y().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:()=>v().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:()=>or(()=>g9e()).describe("Environment variables to set for Claude Code sessions"),attribution:()=>{let o=O({commit:h().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:h().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:v().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link."),...!1}).passthrough();return ie([v(),o],{error:(s)=>{let i=(s.errors??[]).flat().filter((l)=>l.path.length>0);if(i.length>0)return i.map((l)=>`${l.path.join(".")}: ${l.message.replace(/^Invalid input: /,"")}`).join("; ");return`Expected false, true, or an object such as { "commit": "", "pr": "" }, but received ${Array.isArray(s.input)?"array":s.input===null?"null":typeof s.input}`}}).transform((s)=>{if(typeof s!=="boolean")return s;return s?{}:{commit:"",pr:"",sessionUrl:!1}}).pipe(o).optional().describe('Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set. Set to false to hide all attribution, the same as { "commit": "", "pr": "", "sessionUrl": false }. Setting it to true is the same as leaving it out. Older Claude Code versions reject true or false here, so use the object form in settings files shared across versions.')},attributionProject:()=>h().optional().describe(`The claude.ai Project this session names for your organization's usage reports: the Project's ID, starting with "claude_proj_" or "chan_", or the UUID of a "claude_proj_" Project. An empty string names none and stops lower-precedence files from naming one; the organization default still applies. Sent only when Claude Code uses your claude.ai login, connects directly to the Anthropic API, is not in a cloud session, and CLAUDE_CODE_ATTRIBUTION_HEADER is not 0. CLAUDE_CODE_ATTRIBUTION_PROJECT takes precedence over it. Set in managed settings, it overrides people's own settings files. A project's .claude/settings.json and settings.local.json count only once the folder is trusted; for runs in a folder nobody has trusted, such as CI, use CLAUDE_CODE_ATTRIBUTION_PROJECT.`),attributionProjectPolicy:()=>O({default:h().optional().describe('The Project used when neither CLAUDE_CODE_ATTRIBUTION_PROJECT nor attributionProject names one: its ID, starting with "claude_proj_" or "chan_", or the UUID of a "claude_proj_" Project.')}).optional().describe("Your organization's default for attributionProject. Only honored from managed settings (server-managed, MDM / OS policy, or managed-settings.json); ignored in user, project, local and --settings sources."),includeCoAuthoredBy:()=>v().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),...!1,...!1,includeGitInstructions:()=>v().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:()=>or(()=>BZ(e)).describe("Tool usage permissions configuration"),model:()=>h().optional().describe("Override the default model used by Claude Code"),fallbackModel:()=>k(h()).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:()=>k(h()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows that version and any model ID that extends it, so "claude-opus-5" also allows "claude-opus-5-5"), 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:()=>v().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."),availableModelsMatch:()=>K(["prefix","exact"]).optional().describe('How availableModels entries match model IDs. "prefix" (the default) lets an entry also allow any model ID that extends it, so "claude-opus-5" allows "claude-opus-5-5". "exact" keeps that matching but stops a model ID entry from allowing other versions: "claude-opus-5" allows Opus 5 and its dated and -fast IDs, but not Opus 5.5 or a later release until it is listed, and a -latest ID needs a -latest entry. Family aliases ("opus") still allow the whole family; aliases whose model depends on the release or settings (best, opusplan, default) are ignored. With "exact" and a list that names at least one model, the Default option also uses only a listed model; if none can be used, Claude Code will not start. Haiku background models, and hooks and other helper requests that pick their own model, are not restricted (deniedModels covers them; allowManagedHooksOnly limits hooks). Read from managed settings only.'),deniedModels:()=>k(h()).optional().describe('Models users cannot select, even when availableModels allows them. A family alias ("opus") blocks that family. A model ID blocks that version in every spelling: dates, -fast and provider prefixes are ignored, so "claude-opus-5-5" blocks every Opus 5.5 ID but not Opus 5. An ID with no minor version ("claude-opus-5") also blocks later minor versions, as it allows them in availableModels. Aliases whose model depends on the release or settings (best, opusplan, default) are ignored. The Default option steps down past a blocked model; if the Default has no allowed model to step down to, Claude Code will not start. Read from managed settings only.'),modelOverrides:()=>q(h(),h()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),modelPicker:()=>O({options:k(lx()).describe("Rows to show in the /model picker, in order."),replaceBuiltInOptions:v().optional().describe("When true, the picker shows only the Default row and these options — the built-in "+"lineup, gateway-discovered models and ANTHROPIC_CUSTOM_MODEL_OPTION are hidden. When false or unset, these options are added after the built-in lineup.")}).optional().describe("Curate the /model picker: an ordered list of models with your own labels, independent of the built-in lineup and of Claude Code releases. availableModels still applies to these rows. Honored from managed, --settings/SDK, and user settings only (not from a project checkout); the highest-precedence of those that defines modelPicker wins outright (no merging across sources). Typically set in managed settings by enterprise administrators."),modelPricing:()=>O({multiplier:ax(),overrides:q(h(),ix()).optional()}).optional().describe("Price usage at your organization's contracted rates instead of list price. "+"Affects every spend figure Claude Code reports — /cost, the status line, the SDK total_cost_usd, "+"--max-budget-usd, and the OpenTelemetry cost metric and events — which remain USD estimates, not an invoice "+'(the per-Mtok price labels in /model stay at list). "overrides" maps a model ID to its USD-per-million-token rates (input, output, cacheRead, '+"cacheWrite — all four required, each 0 to 10000; cacheWrite prices both 5-minute and 1-hour cache writes). "+"A matching row is charged exactly as written; fast-mode and US-data-residency surcharges are not added on top. "+'A key Claude Code itself uses for a built-in model — its ID such as "claude-sonnet-4-6", or its '+"first-party, Bedrock (any or no region prefix), Vertex or Foundry ID — covers every dated and provider form "+"of that model; any other key — a gateway model alias, or a spelling Claude Code does not itself use — "+'matches that model ID only (case-insensitive), and such an exact match wins over a built-in row. On Bedrock an application inference profile is matched by its backing model. An invalid row or multiplier is reported and skipped; the rest still apply. "multiplier" in (0, 10] scales every computed cost, overridden or not (0.85 = 85% of the price, 1.2 = 120%). Only honored from managed settings (server-managed, MDM / OS policy, or managed-settings.json), '+"or — when none of those sets it — when supplied by a host application that manages the model "+"provider; ignored in user, project, local and --settings sources."),...!1,enableAllProjectMcpServers:()=>v().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:()=>k(h()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:()=>k(h()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:()=>v().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected, and a claudeai-proxy server passed explicitly (e.g. via --mcp-config or the SDK mcpServers option) does not connect either. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:()=>q(h(),K(["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:()=>v().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),managedMcpServers:()=>or(()=>q(h().refine(hv,{error:fy}),_v(),{error:yv})).describe(`MCP servers the organization provides to every user, keyed by server name, each with the .mcp.json entry shape; only "http" and "sse" servers are accepted (nothing that names a program to run, no \${VAR} references). Honored from managed settings only; users cannot remove them, deniedMcpServers still applies, and they need no allowedMcpServers entry. Not read in Claude Desktop's Code tab on a third-party deployment or in Cowork sessions, where Claude Desktop supplies and locks the session's MCP servers itself.`),allowedMcpServers:()=>or(()=>k(ky())).describe("Enterprise allowlist of the MCP servers users may use. Governs servers users add (user, project and local config, --mcp-config, agent frontmatter, plugins, claude.ai connectors); servers the organization itself delivers (managedMcpServers, and managed-mcp.json entries with no ${VAR} in their command, args, url or header values) are allowed without being listed; a managed-mcp.json entry with ${VAR} in any of those must match this list. If undefined, all servers are allowed. If empty array, users can use no servers of their own. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:()=>or(()=>k(Py())).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:()=>or(()=>wa()).describe("Custom commands to run before/after tool executions"),worktree:()=>O({symlinkDirectories:k(h()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:k(h()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos — only the listed paths are written to disk."),baseRef:K(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:K(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly."),location:h().optional().catch(void 0).describe("Directory under which Claude Code Desktop creates the worktrees of SSH sessions that run on this machine (an absolute path or one starting with ~/), instead of <project>/.claude/worktrees. Read by the desktop app from the SSH host user settings; a location chosen in the desktop app's SSH connection settings takes precedence. The CLI (--worktree, EnterWorktree, agent isolation) does not read it yet.")}).optional().describe("Git worktree configuration: the CLI --worktree flag, EnterWorktree and agent isolation, plus the location Claude Code Desktop uses for SSH-session worktrees on this machine."),disableAllHooks:()=>v().optional().describe("Disable all hooks and statusLine execution: the hooks defined in settings files and by installed plugins. Features built into Claude Code are not hooks in this sense and keep working; each has its own switch."),disableReplyCheck:()=>v().optional().describe("Disable the reply check in Claude Tag sessions on a self-hosted runner. The check re-prompts Claude, at most four times a turn, when a turn ends without a call to one of Claude Tag's reply tools. It is not a hook, so disableAllHooks does not affect it. Disabling it also stops two messages to Claude that Anthropic's service can request for such a session: a nudge after a long stretch of work with no visible update, and a reminder added to prompts. Claude Code's built-in reminder to give progress updates, on models that have it, is then no longer held back. Set it in managed settings; false there keeps the check on. Everywhere else it is ignored and the check stays on. Has no effect on sessions that Anthropic hosts."),disableAgentView:()=>v().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:()=>v().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:()=>v().optional().describe("Disable the Workflows feature. Code Review on pull requests and /ultrareview run in Anthropic's cloud and are not stopped by this setting, except an /ultrareview that has to restart partway through. A machine that runs a review itself refuses it when that machine's own administrator set this, or CLAUDE_CODE_DISABLE_WORKFLOWS in an `env` block, in its managed settings (MDM, the managed-settings file or an administrator's policy helper). Set in the environment before Claude Code starts, CLAUDE_CODE_DISABLE_WORKFLOWS disables Workflows. Beyond the cases above it stops a review only when the review's own session starts with it set."),disableArtifact:()=>v().optional().describe("Deprecated: use enableArtifact: false. Still honored — true disables the Artifact tool; false is ignored."),enableArtifact:()=>v().optional().describe("Turn the Artifact tool on or off. Off in any of managed, --settings, or user settings wins; project and local settings can only turn it off. Unset defaults to on once the feature is available."),enableWorkflows:()=>v().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowSizeGuideline:()=>K(["unrestricted","small","medium","large"]).optional().describe('Advisory size guideline for the dynamic workflows Claude writes: "small" aims for fewer than 5 agents, "medium" fewer than 10, "large" fewer than 50, and "unrestricted" sends no guideline. Unset defaults to "medium", or "small" on Pro plans. A value here — including from managed settings — takes precedence over the "Dynamic workflow size" choice in /config, and that /config row is hidden while a settings file provides the key. This is a guideline, not an enforced limit.'),workflowKeywordTriggerEnabled:()=>v().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:()=>v().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."),disableWindowsBashCommandSplit:()=>v().optional().describe("Windows only. Set to true to keep every Bash command in a single argument to bash, so that endpoint security tools that match text in process command lines see it whole. Otherwise Claude Code may split a long command over several arguments. With true, a command of about 7,000 characters or more, or fewer if it is full of quotes, may reach bash cut short, and then usually fails with a syntax error. Only honored from managed settings; ignored in user, project, local and --settings sources."),defaultShell:()=>K(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),bashEditDiffEnabled:()=>v().optional().describe("Whether the Bash tool shows a diff of the files a Bash command changed (PostToolUse Bash hooks get the changed-file list in tool_response). Set to false to turn that off. Default: off, except in auto and bypassPermissions modes when the Bash tool handles file edits or the model's configuration turns it on. Only user, flag or policy settings can turn it on in other modes."),bashOutputMaxChars:()=>Y().int().positive().optional().catch(void 0).describe("How many characters of a successful Bash or PowerShell command's output Claude receives inline (default 30000; values clamp to 4000-128000). Output past this is saved to a file and Claude receives a short preview plus the path. When set, this also replaces BASH_MAX_OUTPUT_LENGTH, which on its own only sizes the read-back window."),taskOutputMaxChars:()=>Y().int().positive().optional().catch(void 0).describe("Deprecated: no longer has any effect (the TaskOutput tool was removed). Read a background task's output file with the Read tool instead."),respondToBashCommands:()=>v().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:()=>v().optional().describe("When true (and set in managed settings), only hooks from managed settings and from plugins that managed settings enable run. User, project, and local hooks and the hooks of plugins the user installed are ignored. Features built into Claude Code are not hooks in this sense and keep working."),allowedHttpHookUrls:()=>k(h()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:()=>k(h()).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:()=>v().optional().describe("When true (and set in managed settings), permission rules from user, project, local, and --settings files and allow rules from --allowedTools are ignored; only managed settings can add allow rules through settings. "+"The allowed-tools frontmatter of skills and custom commands from user, project, and --add-dir sources, and of plugins no managed setting vouches for, is ignored too. Plugins keep theirs only on an admin-backed channel: host-delivered --plugin-dir plugins (in Claude Desktop, only while this is not set by the organization's own managed settings), the official marketplace registered from its unpinned anthropics source, claude.ai-synced plugins Anthropic attests, the saved login organization's claude.ai-hosted marketplaces, marketplaces whose registered source managed extraKnownMarketplaces declares or an exact or owner-pinned (owner/*) strictKnownMarketplaces entry names at the path it pins (an npm marketplace source only when the registration and the declared entry pin the same registry, and a settings marketplace source only when every nested npm plugin entry pins one on a bare package name — unpinned, the package resolves through the member's own npm config, and a non-bare spelling packs as an exotic spec the pin does not bind, so nothing an entry names is what was fetched), and npm-direct (package@npm) plugins whose recorded resolution a registry-pinned managed npm strictKnownMarketplaces entry names (host and path patterns and enabledPlugins ids do not vouch); managed and bundled skills keep theirs. "+"--disallowedTools, skill disallowed-tools, and other deny and ask rules from the command line or the current session still apply."),allowManagedMcpServersOnly:()=>v().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:()=>v().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."),allowClaudeInChromeWithManagedMcp:()=>v().optional().describe("When true (and set in device managed settings: MDM, the managed-settings.json file, or a policy helper those configure), the built-in Claude in Chrome MCP server can run alongside managed-mcp.json instead of being blocked by its exclusive-control lockdown. deniedMcpServers and the organization's Claude in Chrome setting still block it. Default off preserves the lockdown."),strictPluginOnlyCustomization:()=>qZ().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:()=>O({type:U("command"),command:h(),padding:Y().optional(),refreshInterval:Y().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:v().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:()=>h().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:()=>k(K9e().catch(DZ)).transform((o)=>o.filter((s)=>s!==DZ)).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:()=>O({type:U("command"),command:h()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:()=>q(h(),YZ()).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json — setting false in ~/.claude/settings.json is overridden by the project.'),prependPlugins:()=>k(h()).optional().catch(void 0).describe("Managed plugins (plugin@marketplace ids that managed enabledPlugins sets true) whose hooks run first, outermost, in the listed order: the first id listed sees every event before any other plugin and every result after it. Managed plugins not listed here or in appendPlugins follow the listed ones; user, project and marketplace plugins come after those; then appendPlugins; then the built-in plugins. The bundled cc-plugin-sec-default@builtin seats itself outermost (on a machine with managed settings and for Team and Enterprise organizations) unless this list is set, in which case list it where it should sit or leave it out. Name it there as sec-default@builtin, the id every release reads, for as long as any machine in the organization may run a release from before its rename; a release that knows the new id reads either. Any other id that is not an enabled managed plugin is skipped; an id listed in both keys is prepended. Only honored from managed settings (or, on a machine with none, from user settings for your own plugins); ignored in project, local and --settings sources."),appendPlugins:()=>k(h()).optional().catch(void 0).describe("Managed plugins (plugin@marketplace ids that managed enabledPlugins sets true) whose hooks run last among plugins, innermost, in the listed order: the last id listed sits just above the built-in plugins and sees each event as every other plugin left it. Only honored from managed settings (or, on a machine with none, from user settings for your own plugins); ignored in project, local and --settings sources."),extraKnownMarketplaces:()=>or(()=>n("extraKnownMarketplaces")).describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),additionalMarketplaces:()=>or(()=>n("additionalMarketplaces")).describe("Alias for extraKnownMarketplaces: this key is read exactly as if it were spelled "+"extraKnownMarketplaces. Do not set both in one file — if both appear, this key is ignored "+"with a warning. Claude Code may rewrite this key as extraKnownMarketplaces when it updates the file. Clients older than this alias ignore it, so prefer extraKnownMarketplaces while older Claude Code versions still share the same settings."),strictKnownMarketplaces:()=>or(()=>k(by())).describe('Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these sources can be added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to allow every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem. '+"Note: this is a policy gate only — it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),allowedMarketplaces:()=>or(()=>k(by())).describe("Alias for strictKnownMarketplaces (managed settings only): this key is read exactly as if it "+"were spelled strictKnownMarketplaces. Do not set both in one file — if both appear, this key "+"is ignored with a warning. Clients older than this alias ignore it, so keep using strictKnownMarketplaces when the allowlist must also bind older Claude Code versions."),blockedMarketplaces:()=>or(()=>k(Wv())).describe('Enterprise blocklist of marketplace sources. When set in managed settings, these sources are blocked from being added as marketplaces. Entries match exactly, except that a github entry may use the owner-wildcard form {"source":"github","repo":"owner/*"} to block every repository under that owner. The check happens BEFORE downloading, so blocked sources never touch the filesystem.'),disableCommandPluginSources:()=>v().optional().describe("Controls the `command` plugin source, whose plugin directory is produced by running a marketplace-declared command on this machine. true: command-sourced plugins are never installed, updated, or re-resolved (the command never runs). false: explicitly allowed. "+"Unset: follows allowManagedHooksOnly — an org that restricts hook execution to managed "+"settings gets command sources disabled too. Only honored from managed settings."),...!1,disableSideloadFlags:()=>v().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:()=>k(h()).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 tips for Anthropic's own plugins are 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:()=>K(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for a Claude subscription (individual, Team, or Enterprise plans), "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:()=>h().min(1).optional().catch(void 0).describe('Cloud gateway URL to pre-fill during login, alongside forceLoginMethod: "gateway". Honored from admin-controlled managed settings (MDM / managed-settings.json / policy helper) and, on a machine with none of those, from your own user settings; ignored in project, local, flag, and remote-delivered settings.'),gatewayInternalNetworks:()=>k(h()).optional().catch([XZ]).meta({default:void 0}).describe("IPv4 CIDR blocks (at most 4, each /8 to /32, not overlapping) your Cloud gateway sits in: the public block your organization numbers its internal network from, which lets /login reach a gateway there. A block must lie entirely outside private space, where /login accepts a gateway without this key. /login accepts a gateway inside a listed block over a direct connection only, and only when this machine's own address on that connection is inside the same block, so /login must happen from a machine whose own address is inside the block (not through a proxy, VPN pool, container or NAT segment outside it). A bar against copied settings files, not proof of location. Honored only from admin-controlled managed settings (MDM / managed-settings.json / policy helper); ignored in user, project, and remote-delivered settings."),parentSettingsBehavior:()=>K(["first-wins","merge"]).optional().describe(`Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" (the default, except in a gateway session Claude Desktop's Code `+'tab launched, where "merge" is): parent is dropped — admin tiers '+`are the only policy source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),managedSourcesBehavior:()=>K(["first-wins","merge"]).optional().describe('Controls how the managed settings sources compose. "first-wins" (default): the highest-priority source present (server-managed > MDM (managed plist / HKLM) > managed-settings.json) is the managed tier alone. "merge": every present source deep-merges with fixed '+"precedence server-managed > MDM > managed-settings.json — scalars "+"take the highest source's value (a restrictive boolean or enum — "+"the allowManaged*Only locks, the disable* switches, the sandbox "+"lock family — takes the strictest value any source sets) and "+"arrays union, except fallbackModel, the restriction allowlists allowedMcpServers, allowedProviders, availableModels, strictKnownMarketplaces and allowedChannelPlugins, and sandbox.credentials.awsPairs and sandbox.ripgrep (the highest source that sets one owns it whole), modelOverrides (the whole map of the highest source that sets it, dropped when that source sits below the one that sets availableModels), managedMcpServers (server names union; a name set by two sources takes the higher source's whole entry), and the keys taken from the highest source only: the auth pins forceLoginOrgUUID, forceLoginMethod, forceLoginGatewayUrl and gatewayInternalNetworks, the credential helpers apiKeyHelper, awsAuthRefresh, awsCredentialExport, gcpAuthRefresh, otelHeadersHelper and proxyAuthHelper, modelPicker, permissions.defaultMode, parentSettingsBehavior and the policyHelper configuration (env keeps its own per-key union). In both modes, a forceLoginOrgUUID, or a forceLoginMethod of claudeai or console, that this machine's own MDM policy or managed settings file sets applies ahead of server-managed settings. Honored only from the highest-priority source present; enable it only when every lower source is admin-controlled, since lower sources then contribute entries such as permissions.allow. HKCU and --managed-settings never take part in the merge."),forceLoginOrgUUID:()=>ie([h(),k(h())]).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."),allowedProviders:()=>Me((o)=>Array.isArray(o)?o.filter(Ev):o,k(K(Zp))).optional().catch(void 0).describe(`Managed settings only (managed-settings.json, MDM, or server-managed). The API providers Claude Code may use on this machine: "anthropic" (the Anthropic API on Anthropic's own host, via a claude.ai or Console sign-in or an API key; pair it with forceLoginMethod / forceLoginOrgUUID to require a sign-in), "bedrock", "vertex", "foundry", "anthropicAws", "mantle" (each meaning that provider's own service: its regional, FIPS, private-endpoint and sovereign-cloud hosts), "customEndpoint" (the `+"Anthropic API or a cloud provider's API sent to some other host — ANTHROPIC_BASE_URL, that "+"provider's ANTHROPIC_*_BASE_URL, a Foundry resource name that is not a bare name, or for "+"Bedrock the AWS SDK's AWS_ENDPOINT_URL[_BEDROCK[_RUNTIME]] — such as an LLM gateway; admitted "+`only for the value pinned in the "env" block of the same managed source), or "gateway" (the Cloud gateway sign-in). A session on a provider that is not listed is refused at startup, at login, and when it next contacts the API, with a message naming what selected the provider and the entry that would allow it. Under a list, where first-party traffic goes (ANTHROPIC_BASE_URL, a gateway sign-in) is honored only when the same managed source pins it in "env" (or forceLoginGatewayUrl), and a claude ssh tunnel into the machine is refused. A cloud provider's credential and tenancy variables, and the network path and TLS trust (HTTPS_PROXY, NODE_EXTRA_CA_CERTS, CLAUDE_CODE_CERT_STORE), are not judged by this list; set those for the fleet in the managed "env" block, whose values replace the user's. To route Bedrock through a gateway for a fleet, pin ANTHROPIC_BEDROCK_BASE_URL there (it is what the clients use, ahead of an endpoint_url in ~/.aws/config, which this list does not judge); the AWS SDK's AWS_ENDPOINT_URL* pins only sanction where the SDK's own clients go and never stand in for the "bedrock" entry. Unset allows every provider; an empty array allows none. Only a list in managed-settings.json or MDM is enforcement on the machine: it cannot be widened or hidden by server-managed settings and reaches every session. A list set `+"only in the admin console reaches only sessions that fetch your server-managed settings — not "+"a session on a cloud provider, another organization or a non-Anthropic ANTHROPIC_BASE_URL, one authenticating only with apiKeyHelper or ANTHROPIC_AUTH_TOKEN, a Pro/Max/Ultra login, --bare without "+"an API key, or a first launch before the fetch lands — all conditions the user controls. "+`Versions that predate this setting ignore it; pair it with a minimum-version policy on a mixed fleet. 'claude auth status' reports the Anthropic API as apiProvider "firstParty".`),...!1,forceRemoteSettingsRefresh:()=>v().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:()=>h().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:()=>h().optional().describe("Controls the output style for assistant responses"),viewMode:()=>K(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:()=>h().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:()=>v().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:()=>or(()=>sv()),...!1,feedbackSurveyRate:()=>Y().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),feedbackDrafts:()=>K(["notify","quiet","off"]).optional().describe('Model-drafted feedback (the SendFeedback tool). "notify" (default) shows a one-line notice when a draft is queued; "quiet" shows only the footer counter; "off" disables the tool entirely so drafts are never queued.'),spinnerTipsEnabled:()=>v().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:()=>O({mode:K(["append","replace"]),verbs:k(h())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:()=>O({excludeDefault:v().optional().catch(void 0),tips:_9e().optional(),tipsFile:h().optional().catch(void 0).describe("Absolute or ~/ local path to a JSON file holding an array of tips (same shapes as `tips`); honored from user, --settings and on-disk managed settings only. Read once per CLI process (restart to pick up edits)."),label:h().optional().catch(void 0).describe('Prefix shown before your tips in the spinner (default "Tip")')}).passthrough().optional().catch(void 0).describe("Add your organization's own tips to the spinner tip rotation. tips: strings or {id, text, cooldownSessions?, priority?} objects; tipsFile: a JSON file of the same; label: prefix shown before your tips; excludeDefault: if true, only show your tips (default: false)."),syntaxHighlightingDisabled:()=>v().optional().describe("Whether to disable syntax highlighting in diffs"),maxProseWidth:()=>Y().int().min(40).optional().catch(void 0).describe("Maximum width, in terminal columns, of the prose in Claude's responses (paragraphs, headings, lists, blockquotes). In a wider terminal the prose wraps at this width while tables and code blocks keep the full width; only the display wraps, the response text itself gains no line breaks. Minimum 40. Unset (the default) uses the full terminal width."),spellcheck:()=>O({enabled:v().optional().catch(void 0).describe("Turn on spell checking of the prompt input (default: false)"),checker:h().optional().catch(void 0).describe(`Which spell checker to run: ${Ay.map((o)=>`"${o}"`).join(", ")}, or "auto" (default) for the first of those found on PATH`),language:h().optional().catch(void 0).describe(`Dictionary to use, passed to the checker as-is (aspell --lang, hunspell -d, ispell -d), e.g. "en_GB"; names are checker-specific (letters, digits and _ - . , only). Default: the checker's own default`),color:h().optional().catch(void 0).describe(`Color of misspelled words (they are also underlined): a terminal color name such as "red" or "magenta", "#rrggbb", "rgb(r,g,b)", "ansi256(n)" or "ansi:<name>". Default: the theme's error color`)}).passthrough().optional().catch(void 0).describe(`Underline misspelled words in the prompt input as you type, using an installed ${Ay.slice(0,-1).join(", ")} or ${Ay.at(-1)} (off unless "enabled" is true; does nothing if none is installed). Read from user, flag and managed settings only (the whole block from the highest-precedence of those applies); ignored in project .claude/settings.json and .claude/settings.local.json.`),terminalTitleFromRename:()=>v().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),promptCacheTtl:()=>K(fl).optional().catch(void 0).describe('Prompt cache TTL for the main conversation (interactive, -p and SDK turns, plus the helpers that run inline with it): "5m" or "1h". Unset = automatic: 1 hour on a Claude subscription within its usage limits, 5 minutes on an API key, Bedrock, Vertex or Foundry. 1-hour cache writes are billed at a higher rate; the cache stays warm across longer breaks. The CLAUDE_CODE_PROMPT_CACHE_TTL environment variable takes precedence.'),subagentPromptCacheTtl:()=>K(fl).optional().catch(void 0).describe("Prompt cache TTL for everything outside the main conversation — subagents, workflows, background and helper requests: "+'"5m" or "1h". Unset = automatic (5 minutes unless ENABLE_PROMPT_CACHING_1H=1). The CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL environment variable takes precedence.'),alwaysThinkingEnabled:()=>v().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:()=>K(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),maxEffortLevel:()=>K(Fp).optional().catch(void 0).describe("Maximum effort level. Anything above it (an /effort or /model pick, --effort, CLAUDE_CODE_EFFORT_LEVEL, a model default) is clamped to it, on every provider including Bedrock, Vertex and Foundry. Combines with an organization's per-model effort cap by taking the lower of the two; across settings files the lowest value wins, and modelSettings.<model>.maxEffortLevel replaces it per model. Enforced client-side: an effort supplied through CLAUDE_CODE_EXTRA_BODY is not clamped."),modelSettings:()=>Me((o)=>typeof o==="object"&&o!==null&&!Array.isArray(o)?ba(o,(s,i)=>Object.hasOwn(Object.prototype,i)):o,q(h(),O({effortLevel:K(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for this model."),maxEffortLevel:K(Fp).optional().catch(void 0).describe('Maximum effort level for this model. Within one settings file it replaces the top-level maxEffortLevel for the model ("max" exempts it); across settings files the lowest applicable value wins. Keyed like effortLevel: the canonical model name also matches its dated, [1m], Bedrock and Vertex spellings.'),autoCompactWindow:ie([U("auto"),LZ()]).describe('Auto-compact window for this model, in tokens (100000 to 1000000), or "auto" for the window tuned for the model. Within one settings file it replaces the top-level autoCompactWindow for the model. /autocompact saves here. The canonical model name as key also matches its dated, [1m], Bedrock and Vertex spellings.')}).passthrough().optional().catch(void 0))).optional().catch(void 0).describe("Per-model settings keyed by canonical model name."),ultracode:()=>v().optional().catch(void 0).describe("Enable ultracode for the session: standing dynamic-workflow orchestration at any effort level. "+"Session-scoped — typically provided via --settings or the apply_flag_settings control request; "+"interactive toggles never persist it. Requires workflows to be enabled and a model that supports ultracode."),autoCompactWindow:()=>LZ().describe("Auto-compact window size"),...!1,advisorModel:()=>h().optional().describe("Advisor model for the server-side advisor tool."),fastMode:()=>v().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off. On Vertex a saved value is ignored: use /fast each session."),fastModePerSessionOptIn:()=>v().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:()=>v().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),emojiCompletionEnabled:()=>v().optional().describe("When false, the :emoji: shortcode typeahead (the suggestion popup and the :name: inline replacement) is disabled. When absent or true, it is enabled."),awaySummaryEnabled:()=>v().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."),responseComparisonEnabled:()=>v().optional().describe("@internal Set to false to stop Claude Code from showing two answers to one message and asking which is better. When absent or true, it may do so on some turns. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:()=>v().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:()=>K(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers "+"selected so far. Defaults to never — auto-continue only runs "+"when explicitly set to 60s/5m/10m."),dialogExpiry:()=>K(["60s","5m","10m","never"]).optional().catch(void 0).describe('Max time a permission/user dialog forwarded to a remote client stays parked awaiting an answer, and how long a HELD cross-session message awaits approval, before either resolves to its safe no-action default (cancelled / dropped-with-denial). Defaults to 5m to match the long-standing remote-dialog deadline; "never" disables the deadline. Local-only permission prompts (no remote client) are unaffected. The CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS env var, when set, overrides this. Read from trusted sources only (never a checked-in repo settings file).'),agent:()=>h().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),modelProposedGoals:()=>K(zY).optional().catch(void 0).describe("@internal Controls the ProposeGoal tool (model-proposed session goals). 'auto' (the default when absent) lets the model choose per proposal whether to ask for approval via its ask_user parameter; 'alwaysAsk' routes every model-proposed goal through the approval dialog; 'disabled' turns the tool off. A typed /goal is unaffected. Consent-affecting, so it is read "+"from trusted sources only (user/policy/flag) — "+"workspace-resident project and local settings are ignored."),companyAnnouncements:()=>k(h()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:()=>q(h(),O({mcpServers:q(h(),q(h(),ie([h(),Y(),v(),k(h())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:q(h(),ie([h(),Y(),v(),k(h())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(fO())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:()=>O({defaultEnvironmentId:h().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:()=>K(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:()=>h().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:()=>h().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:()=>h().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:()=>h().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:()=>K(["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:()=>O({enabled:v().optional(),mode:K(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:v().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:()=>v().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:()=>k(jZ()).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:()=>v().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),timeFormat:()=>ie([K(FY),h()]).optional().describe('Clock format for times shown in the UI: "auto" (default, follows the locale), "12-hour", "24-hour", "24-hour-utc" ("18:05Z"), or a strftime pattern such as "%H:%M" (any value containing "%"; other values read as "auto"). A pattern replaces the time everywhere; message timestamps show only the pattern, so include %Y-%m-%d for the date. /config offers the presets; a pattern is set here.'),timeZone:()=>h().optional().describe('IANA time zone for times shown in the UI, e.g. "UTC" or "Europe/Dublin". Default: the system time zone. An unknown name falls back to the system time zone.'),doneMeansMerged:()=>v().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:()=>K(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn "+"is on — task-budget semantics). Defaults to padded-countdown for a "+"model with the total_tokens_reminder capability, else off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:()=>Y().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:()=>v().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to on. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:()=>v().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:()=>h().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/."),...!1,autoDreamEnabled:()=>v().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:()=>v().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:()=>v().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:()=>v().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:()=>K(["disable"]).optional().describe("Disable auto mode"),remoteTools:()=>O({allowUnattendedServing:v().optional().describe("@internal When false in managed or user settings, a cloud session in auto mode may not run commands on this computer without a person approving each one, whatever consent the computer has given; a project, local or --settings value is ignored. Default: true.")}).optional().describe("@internal How this computer serves tool calls to cloud sessions"),sshConfigs:()=>k(O({id:h().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:h().describe("Display name for the SSH connection"),sshHost:h().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:Y().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:h().optional().describe("Path to SSH identity file (private key)"),startDirectory:h().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."),sshHostCommands:()=>me().meta({type:"array"}).optional().describe("SSH connections in Claude Desktop whose host comes from a command. A list of entries, each with `id`, `name` and `command`, and optionally `sshIdentityFile` and `startDirectory`. Desktop runs `command` on this computer when you create the connection or another host for it, not each time you connect. `command` is a program name or absolute path (single-quote a path with spaces), then plain arguments. Nothing else can be quoted. For pipes, variables or a leading `~`, use a script. On Windows, the program must be a full path from a drive letter, such as `C:/tools/acme.exe`, ending in `.exe`, `.cmd` or `.bat`. Quoted paths and Windows need Claude Desktop v4.16336.0 or later. The command must print only the host on standard output: `host` or `user@host` on one line, or a JSON object with `sshHost` and, optionally, `sshPort` and `startDirectory`. Desktop reads this key only from user settings and from this computer's managed settings. Claude Code itself does not use it."),claudeMd:()=>h().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:()=>k(h()).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:()=>h().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:()=>ie([K($Y),h().startsWith("custom:").transform((o)=>o)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:()=>K(UY).optional().catch(void 0).describe("Key binding mode for the prompt input"),keybindingFlavor:()=>K(["classic","readline"]).optional().catch(void 0).describe("Deprecated: no longer has any effect. The prompt's word-editing keys always follow Bash (readline) conventions."),vimInsertModeRemaps:()=>q(h(),me()).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:()=>v().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:()=>K(NY).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:()=>v().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:()=>v().optional().describe("Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),idleCompaction:()=>v().optional().describe("Set to false to stop Claude Code from compacting a long conversation while the session is idle. Defaults to true."),switchModelsOnFlag:()=>v().optional().describe("When safeguards flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoContinueAtUsageLimit:()=>v().optional().describe("When a claude.ai usage limit stops your session, wait for the limit to reset and continue the task automatically. When off, the limit dialog offers the wait as a choice instead."),autoScrollEnabled:()=>v().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:()=>v().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:()=>v().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:()=>v().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:()=>v().optional().describe("Stamp each message with its arrival time"),terminalProgressBarEnabled:()=>v().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:()=>v().optional().describe("Enable the todo / task tracking panel"),teammateMode:()=>K(HY).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:()=>v().optional().describe("Start Remote Control bridge automatically each session"),remoteControl:()=>O({shareHostProfile:K(xy).optional().catch(void 0).describe("@internal What a Remote Control environment reports about this machine when it registers: 'off' reports nothing, 'basic' the OS, architecture and detected developer tools, 'full' also the names of MCP servers configured on this machine (never a repository's .mcp.json). When unset, the level comes from the feature rollout, which may be any of the three. Managed, --settings and user settings choose the level (the most restrictive wins); project and local settings can only lower it, never raise it. Read when Remote Control starts; lowering it later applies from the next registration, raising it from the next start.")}).optional().describe("@internal Remote Control (`claude remote-control`) options"),isolatePeerMachines:()=>v().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:()=>K(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),crossSessionInbound:()=>K(of).optional().catch(void 0).describe("Inbound cross-session peer messages (SendMessage from your other sessions): 'accept' delivers them, 'hold' parks them for your review without letting Claude act, 'refuse' opts this session out. An explicit value always wins. Unset (mode parity): a message auto-delivers only when the sending session's permission-mode class matches yours (bypass↔bypass or prompting↔prompting); a mismatched sender's message is held for your approval; a sender that asserts no class is held only while this session bypasses permission prompts."),autoUploadSessions:()=>v().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:()=>v().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:()=>v().optional().describe("Allow Claude to push proactive mobile notifications"),...K_(EZ(e),(o)=>()=>o)}}function dx(e,t={}){let n=ZZ(e,t);return new Vc(n).whole()}var G9e=new Set,W9e=new Set,Iy=P(()=>new Vc(ZZ(Jc()),G9e)),V9e=P(()=>Iy().whole());function Dy(e){return Iy().forDocument(e)}var MZ=Object.freeze({serverName:"invalid-entry-stripped"});function JZ(e){for(let t of e){let n=t.path.length>0?`${t.path.map(String).join(".")}: `:"";if(t.code==="invalid_union"){for(let r of t.errors){let o=JZ(r);if(o!==null)return`${n}${o}`}if("note"in t&&typeof t.note==="string"&&t.note!=="")return`${n}${t.note}`}if(t.message!=="")return`${n}${t.message}`}return null}var px=P(()=>{let e=Iy();return xo().flatMap(({path:t,restrictive:n})=>{if(t.length!==1||t[0]==="strictPluginOnlyCustomization"||t[0]==="disableAllHooks"||typeof n!=="boolean"&&typeof n!=="string")return[];let r=t[0],o=e.field(r);if(o===void 0||o instanceof yg)return[];return[{key:r,restrictive:n,field:o}]})}),Ly=P(()=>["strictKnownMarketplaces","blockedMarketplaces","strictPluginOnlyCustomization",...px().map((e)=>e.key)]),xi=["managedSourcesBehavior","wslInheritsWindowsSettings"];function sf(e){return oe(e)&&Object.values(e).every(sf)}function fx(e){let t=e.wslInheritsWindowsSettings;if(t===void 0||t===null)return"disarmed";let n=Yc(t);return n===!0?"armed":n===!1?"disarmed":"unreadable"}function mx(e){let t=e.source==="hostPattern"?e.hostPattern:e.source==="pathPattern"?e.pathPattern:null;if(t!==null&&!cZ(t))return`${e.source}: regex does not compile; the entry cannot be enforced`;if(e.source==="github"&&e.repo.includes("*")&&dZ(e.repo)===null)return'github: an owner wildcard must be exactly "<owner>/*"; the entry cannot be enforced';if(e.source==="git"&&pZ(e.url))return'git: wildcards are only supported in github-form entries, as "<owner>/*"; the entry cannot be enforced';if((e.source==="github"||e.source==="git")&&e.ref!==void 0&&e.ref.includes("*"))return`${e.source}: ref contains "*", which git does not allow in ref names; the entry cannot be enforced`;return null}function NZ(e,t){return ie([ra().transform(()=>{return}),k(me()).transform((n)=>{let r=[];for(let[o,s]of n.entries()){let i=(e==="blockedMarketplaces"?Wv():by()).safeParse(s);if(i.success){let a=mx(i.data);if(a!==null){if(e==="blockedMarketplaces")t({path:`${e}[${o}]`,message:`Unenforceable entry was kept: ${a}; it can never match a marketplace source, but marketplace restrictions stay active`}),r.push(i.data);else t({path:`${e}[${o}]`,message:`Invalid entry was ignored: ${a}`});continue}r.push(i.data)}else t({path:`${e}[${o}]`,message:`Invalid entry was ignored: ${JZ(i.error.issues)??"failed validation"}`})}if(e==="blockedMarketplaces"&&n.length>0&&r.length===0)t({path:e,message:'Every entry of "blockedMarketplaces" was invalid; none of them can be enforced until it is fixed.'});return r})]).optional()}function UZ(e,t,n){return k(t.catch((r)=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${r.issues[0]?.message??"failed validation"}`}),MZ))).transform((r)=>r.filter((o)=>o!==MZ)).optional()}var XZ="(unreadable)";function Oy(e,t,n,r,o,s){return k(me()).transform((i)=>{let a=[];for(let[l,c]of i.entries()){let d=t.safeParse(c);if(d.success){a.push(d.data);let p=o?.(c,d.data);if(p!==void 0)n({path:`${e}[${l}]`,message:p,statusOnly:!0})}else{let p=d.error.issues[0],f=p===void 0?"failed validation":p.path.length?`${p.path.join(".")}: ${p.message}`:p.message;n({path:`${e}[${l}]`,message:`Invalid entry was ignored: ${f}`,...s?.invalidEntryIsStatusOnly&&{statusOnly:!0}})}}if(i.length>0&&a.length===0)n({path:e,message:`Every entry of "${e}" was invalid; enforcing an empty allowlist (${r}) until it is fixed.`});return a}).optional().catch(()=>(n({path:e,message:`"${e}" was present but invalid; enforcing an empty allowlist (${r}) until it is fixed.`}),[]))}var Xc=P(()=>new Map(xo().flatMap(({path:e,restrictive:t})=>e.length>1?[[e.join("."),Ea(t)[0]]]:[]))),Qc=["soft_deny","hard_deny","deny"],q9e=new Map([["permissions",{restrictions:["deny","ask"],grants:["allow","additionalDirectories","defaultMode"]}],["autoMode",{restrictions:Qc,grants:["allow","environment"],withholdOnEntryDrop:!0}],["sandbox.network",{restrictions:["deniedDomains"],grants:["allowedDomains"],withholdOnEntryDrop:!0}],["sandbox.filesystem",{restrictions:["denyWrite","denyRead"],grants:["allowWrite","allowRead"],withholdOnEntryDrop:!0}]]),My=new Map([["permissions.defaultMode",{read:(e)=>{let t=jc(e);return[...Aa,...Zv(Jc())].find((n)=>n===t)},inert:new Set(["default","dontAsk","plan"]),floor:"default"}]]);function gx(e,t,n,r){let o=[],s=q9e.get(e);if(s===void 0)return o;let i=s.restrictions.flatMap((l)=>{switch(n(l)){case"unreadable":return[`"${l}"`];case"trimmed":return s.withholdOnEntryDrop?[`an entry of "${l}"`]:[];case void 0:return[]}});if(i.length===0)return o;let a=i.join(" and ");for(let l of s.grants){let c=My.get(`${e}.${l}`),d=c===void 0?t[l]:c.read(t[l]);if(d===void 0||c?.inert.has(d)===!0)continue;if(c===void 0)delete t[l];else t[l]=c.floor,o.push(l);r({path:`${e}.${l}`,message:c===void 0?`"${l}" was withheld because ${a} in the same block could not be read; it takes effect again once that is fixed.`:`"${l}" was withheld because ${a} in the same block could not be read; treating it as ${nf(c.floor)} until that is fixed.`,...c!==void 0&&{substituted:!0}})}return o}function vy(e){for(let t of Xc().keys())if(t.startsWith(`${e}.`))return!0;return!1}function Ny(e){return e!=="sandbox.credentials"&&!e.startsWith("sandbox.credentials.")&&vy(e)}function hx(e){let t=e;while(t instanceof Rl||t instanceof iv||t instanceof Dd)t=t instanceof Dd?t.out:t.unwrap();return t instanceof Id?t:void 0}var FZ=new Set(["remoteTools","remoteControl"]);function QZ(e,t){return typeof t==="object"&&t!==null&&e.has(t)}function e9(e,t,n){let r={};for(let[o,s]of Object.entries(t.shape)){let i=`${e}.${o}`;if(n?.has(i))continue;let a=Xc().get(i),l=hx(s);if(a!==void 0)r[o]=a;else if(l!==void 0&&vy(i))r[o]=e9(i,l,n)}return r}function HZ(e,t){return{path:e,message:`"${t}" was null, which is read as key removal; this source does not set it.`,statusOnly:!0,removal:!0}}function nf(e){return typeof e==="string"?`"${e}"`:String(e)}function tf(e,t=0){let n=e===void 0||e.input===void 0?"failed validation":e.code==="custom"&&e.message!==void 0?e.message:("expected"in e)&&typeof e.expected==="string"?`expected ${e.expected}`:("values"in e)&&Array.isArray(e.values)?`expected ${e.values.map(nf).join(" or ")}`:"failed validation",r=(e?.path??[]).slice(t);if(r.length===0)return n;return r.every((o)=>typeof o==="number")?`${r.join(".")}: ${n}`:`nested value: ${n}`}function t9(e){return e===!1||e==="false"}function _x(e,t){if(t===null)return!0;return(e.includes(".")?Xc().get(e):px().find((r)=>r.key===e)?.restrictive)==="disable"&&t9(t)}function rx(e,t,n,r){let o=e.slice(e.lastIndexOf(".")+1);if(typeof t==="boolean")return Me((s)=>{let i=Yc(s);if(i!==s)r({path:e,message:`"${o}" holds the string "${String(i)}" where a boolean belongs; reading it as ${String(i)}. Write it without quotes.`,statusOnly:!0});return i},n);if(t==="disable")return Me((s)=>{if(t9(s)){r({path:e,message:`"${o}" was set to false; reading it as absent (the key's only value is "disable"). Remove the key instead.`,statusOnly:!0,removal:!0});return}return s},n);return n}function Y9e(e,t,n,r,o,s,i){let a=e.slice(e.lastIndexOf(".")+1),l=Xc().get(e),c=i?void 0:l,d=My.get(e),p=t instanceof yg?t.unwrap():void 0,f=p instanceof Xe?p:t;return rx(e,l,f,n).catch((g)=>{if(c!==void 0)return n({path:e,message:`"${a}" was present but invalid (${tf(g.issues[0])}); treating it as ${nf(c)}, its restrictive value, until it is fixed.`,substituted:!0}),r.add(a),c;if(d!==void 0)return n({path:e,message:`"${a}" was present but invalid (${tf(g.issues[0])}); treating it as ${nf(d.floor)} until it is fixed.`,substituted:!0}),r.add(a),d.floor;if(f.safeParse([]).success){let _=g.value;if(Array.isArray(_)){let y=new Map;for(let E of g.issues){let b=E.path?.[0];if(typeof b==="number"&&!y.has(b))y.set(b,tf(E,1))}let S=f.safeParse(_.filter((E,b)=>!y.has(b)));if(y.size>0&&y.size<_.length&&S.success){for(let[E,b]of y)n({path:`${e}[${E}]`,message:`Invalid entry was ignored (${b}); it cannot take effect until it is fixed.`});return s.add(a),S.data}}}n({path:e,message:l===void 0?`"${a}" was present but invalid (${tf(g.issues[0])}) and was ignored; it cannot take effect until it is fixed.`:`"${a}" was present but invalid (${tf(g.issues[0])}) and was ignored, not treated as ${nf(l)}; it cannot take effect until it is fixed.`}),o.add(a);return})}function ox(e,t,n,r={}){let o=e.slice(e.lastIndexOf(".")+1),s=new Set,i=new Set,a=new Set,l={};for(let[p,f]of Object.entries(t.shape)){let m=`${e}.${p}`,g=hx(f);l[p]=r.override?.[m]??(g!==void 0&&vy(m)?ox(m,g,n,{...r,strictField:f}):Y9e(m,f,n,s,i,a,r.neverSubstitute?.has(m)===!0))}let c=new Set([...r.skeletonExclude??[],...r.neverSubstitute??[]]),d=t.safeExtend(l);return me().transform((p)=>{if(p===null){n(HZ(e,o));return}s.clear(),i.clear(),a.clear();let f=oe(p)||r.strictField===void 0?void 0:r.strictField.safeParse(p),m=f?.success===!0&&oe(f.data)?f.data:p,g=oe(m)?d.safeParse(ba(m,(E)=>E===null||E===void 0)):void 0;if(!oe(m)||g?.success!==!0){let E=e9(e,t,c),b=Object.keys(E);if(n({path:e,message:b.length>0?`"${o}" was present but not an object; treating its locks as their restrictive values (${b.join(", ")}) until it is fixed.`:`"${o}" was present but not an object and was ignored; it cannot take effect until it is fixed.`,...b.length>0&&{substituted:!0}}),b.length===0)return;if(!FZ.has(e))r.synthesized?.add(E);return E}for(let[E,b]of Object.entries(m)){let C=`${e}.${E}`;if(b===null&&(Xc().has(C)||vy(C)))n(HZ(C,E))}let _={...g.data};for(let E of gx(e,_,(b)=>i.has(b)?"unreadable":a.has(b)?"trimmed":void 0,n))s.add(E);let y=ba(_,(E)=>E===void 0);if(Object.keys(y).length===0)return Object.entries(m).some(([E,b])=>b!==void 0&&Object.hasOwn(t.shape,E))?void 0:y;let S=r.synthesized;if(S!==void 0&&!FZ.has(e)&&Object.entries(y).every(([E,b])=>s.has(E)||QZ(S,b)||sf(b)))S.add(y);return y}).optional()}function yx(e,t,n){let r=Iy(),o=(T)=>W9e.has(T)||r.carries(n,T),s=(T)=>{let w=r.field(T);if(!w)throw Error("policyTolerantSettingsSchema: not a settings field of this build");return w},i=new Map,a=(T,w)=>{i.set(T,w)};for(let T of["prependPlugins","appendPlugins"])if(r.has(T))a(T,()=>k(h()).optional().catch((w)=>{e({path:T,message:`${w.issues[0]?.message??"Failed schema validation"}. This field was ignored; read as unset.`});return}));a("wslInheritsWindowsSettings",()=>ie([ra().transform(()=>{return}),Me((T)=>{let w=Yc(T);if(w!==T)e({path:"wslInheritsWindowsSettings",message:`"wslInheritsWindowsSettings" holds the string "${String(w)}" where a boolean belongs; reading it as ${String(w)}. Write it without quotes.`,statusOnly:!0});return w},s("wslInheritsWindowsSettings"))]).optional().catch(()=>{e({path:"wslInheritsWindowsSettings",message:`"wslInheritsWindowsSettings" was present but invalid (it takes true or false), so this source's WSL opt-in cannot be read until it is fixed. WSL fails it closed: in an administrator source it arms the Windows policy chain with no user-writable source (/etc/claude-code, HKCU) read beneath it; in HKCU it leaves HKCU unapplied.`});return})),a("strictKnownMarketplaces",()=>NZ("strictKnownMarketplaces",e).catch(()=>(e({path:"strictKnownMarketplaces",message:'"strictKnownMarketplaces" was present but invalid; enforcing an empty allowlist (no marketplaces admitted) until it is fixed.'}),[]))),a("blockedMarketplaces",()=>NZ("blockedMarketplaces",e).catch(()=>{e({path:"blockedMarketplaces",message:'"blockedMarketplaces" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return})),a("allowedMcpServers",()=>UZ("allowedMcpServers",ky(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[]))),a("deniedMcpServers",()=>UZ("deniedMcpServers",Py(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'});return})),a("managedMcpServers",()=>me().transform((T)=>my(T,(w,I)=>e({path:w?`managedMcpServers.${w}`:"managedMcpServers",message:w?`Managed MCP server was ignored: ${I}`:I,statusOnly:!0}))).optional());let l=new Set;for(let{key:T,restrictive:w,field:I}of px()){let M=typeof w==="string"?`"${w}"`:String(w);a(T,()=>ie([ra().transform(()=>{return}),rx(T,w,I,e)]).optional().catch(()=>(e({path:T,message:`"${T}" was present but invalid; treating it as ${M} (its restrictive value) until it is fixed.`,substituted:!0}),l.add(T),w)))}a("strictPluginOnlyCustomization",()=>ie([ra().transform(()=>{return}),qZ((T)=>e({path:"strictPluginOnlyCustomization",message:`"strictPluginOnlyCustomization" lists ${T} ${Ts(T,"entry","entries")} this version does not recognize as a surface (known: ${rf.join(", ")}); an unrecognized entry locks nothing, so check it for a typo.`,statusOnly:!0}))]).optional().catch(()=>(e({path:"strictPluginOnlyCustomization",message:'"strictPluginOnlyCustomization" was present but invalid; treating it as true (skills, agents, hooks and MCP servers load from managed settings and plugins only) until it is fixed.',substituted:!0}),l.add("strictPluginOnlyCustomization"),!0))),a("enabledPlugins",()=>{let T=YZ();return q(h(),me()).transform((w)=>{let I=[],M=0;for(let[z,J]of Object.entries(w)){let Q=T.safeParse(J);if(Q.success){I.push([z,Q.data]);continue}M++,e({path:qc().safeParse(z).success?`enabledPlugins.${z}`:"enabledPlugins.<invalid id>",message:"Invalid entry was ignored: the value must be true, false, or a list of version constraints. This plugin is neither force-enabled nor blocked until it is fixed."})}if(M>0&&I.length===0){e({path:"enabledPlugins",message:'Every entry of "enabledPlugins" was invalid; no plugin is force-enabled or blocked by it until it is fixed.'});return}return Object.fromEntries(I)}).optional().catch(()=>{e({path:"enabledPlugins",message:'"enabledPlugins" was present but invalid (not a map of plugin ids) and was ignored; no plugin is force-enabled or blocked by it until it is fixed.'});return})}),a("availableModels",()=>k(me()).transform((T)=>{let w=[];for(let I of T)if(typeof I==="string")w.push(I);else e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(I)}); the entry was ignored.`});return w}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[]))),a("deniedModels",()=>k(me()).transform((T)=>{let w=[];for(let I of T)if(typeof I==="string")w.push(I);else e({path:"deniedModels",message:`"deniedModels" contained a non-string entry (${I===null?"null":typeof I}); the entry was ignored.`});return w}).optional().catch(()=>{e({path:"deniedModels",message:'"deniedModels" was present but is not a list of model names, so it was ignored and blocks no models until it is fixed.'});return})),a("allowedHttpHookUrls",()=>Oy("allowedHttpHookUrls",h(),e,"no HTTP hooks may run")),a("httpHookAllowedEnvVars",()=>Oy("httpHookAllowedEnvVars",h(),e,"no environment variables may be interpolated into HTTP hook headers")),a("allowedChannelPlugins",()=>Oy("allowedChannelPlugins",y9e(),e,"no channel plugins admitted",(T,w)=>typeof T==="string"?`"allowedChannelPlugins" entry "${T}" was accepted; prefer the documented object form {"plugin": "${w.plugin}", "marketplace": "${w.marketplace}"}.`:void 0)),a("gatewayInternalNetworks",()=>k(h()).optional().catch(()=>(e({path:"gatewayInternalNetworks",message:'"gatewayInternalNetworks" was present but invalid; gateway sign-in governed by this source is refused until it is fixed.'}),[XZ]))),a("forceLoginOrgUUID",()=>s("forceLoginOrgUUID").catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[]))),a("allowedProviders",()=>Oy("allowedProviders",Eg(bv,{message:`not a known provider name (${Zp.join(", ")})`}),e,"no API provider may be used, so Claude Code will not start on this machine",void 0,{invalidEntryIsStatusOnly:!0}));let c=!1,d=(T,w)=>{let I=T.safeParse(w);if(I.success)return;return I.error.issues.slice(0,3).map((M)=>M.path.length?`${M.path.join(".")}: ${M.message}`:M.message).join("; ")},p;a("policyHelper",()=>Me((T)=>{if(c=!1,p=T,T&&typeof T==="object"&&!Array.isArray(T)){let w=T;for(let I of["defaultSettings","default",...Ty])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelper",message:`"${I}" on the singular policyHelper is ignored — static fallback payloads belong on the policyHelpers per-OS entries ("defaultSettings") or the map's "default" key. The intended fallback will NOT apply from here.`,statusOnly:!0});for(let I of["policyHelper","policyHelpers"])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelper",message:`"${I}" inside the singular policyHelper is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; nothing nests inside the singular entry. The nested config will NOT apply from here.`,statusOnly:!0});for(let I of Sn)if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelper",message:`"${I}" on the singular policyHelper is ignored — per-OS entries live on the policyHelpers MAP ("policyHelpers": {"${I}": ...}), not inside the singular key. The intended per-OS config will NOT apply from here.`,statusOnly:!0});if(w.claudeMd!==void 0&&w.claudeMd!==null)e({path:"policyHelper",message:`"claudeMd" on the singular policyHelper is ignored — "claudeMd" is a managed-settings key: put it at the settings top level or inside a static payload, or emit it from the helper's stdout envelope. The intended instructions will NOT apply from here.`,statusOnly:!0});if(w.outputBehavior!==void 0&&w.outputBehavior!==null)e({path:"policyHelper",message:`"outputBehavior" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Sn.join("/")}); this helper's output REPLACES the policy tier whatever the value says.`,statusOnly:!0});if(w.onFailure!==void 0&&w.onFailure!==null)e({path:"policyHelper",message:`"onFailure" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Sn.join("/")}); a failure of this helper REFUSES to start Claude Code whatever the value says.`,statusOnly:!0});if(w.retries!==void 0&&w.retries!==null)e({path:"policyHelper",message:`"retries" on the singular policyHelper is ignored — it is only honored on the policyHelpers per-OS entries (policyHelpers.${Sn.join("/")}); this helper is run ONCE per start or refresh, never re-run, whatever the value says.`,statusOnly:!0});if(w.path===null||w.path===void 0)c=!0}return T===null?void 0:T},wy().optional()).catch((T)=>{e({path:"policyHelper",message:`${T.issues[0]?.message??d(wy(),p)??"Failed schema validation"}. This field was ignored.`,...c&&{statusOnly:!0}});return}));let f=(T,w)=>{e({path:T,message:`"${T}" is not a valid static settings payload: ${w??"failed validation"}. When delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0})},m=[],g=(T)=>{let w=!1,I,M=nx(T,ka().optional().catch((z)=>{w=!0,f(`policyHelpers.${T}.defaultSettings`,z.issues[0]?.message??d(ka(),I&&typeof I==="object"&&!Array.isArray(I)?I.defaultSettings:void 0));return}));return Me((z)=>{if(w=!1,I=z,T!=="default"&&z&&typeof z==="object"&&!Array.isArray(z)){let J=z;for(let W of[...Ty,"claudeMd"])if(J[W]!==void 0&&J[W]!==null)e({path:`policyHelpers.${T}`,message:`"${W}" on the policyHelpers.${T} entry is ignored — helper output cannot be pre-seeded on an entry; a static fallback payload goes under this entry's "defaultSettings" (a managed-settings object). The intended content will NOT apply from here.`,statusOnly:!0});for(let W of["policyHelper","policyHelpers"])if(J[W]!==void 0&&J[W]!==null)e({path:`policyHelpers.${T}`,message:`"${W}" on the policyHelpers.${T} entry is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; nothing nests inside an entry. The nested config will NOT apply from here.`,statusOnly:!0});for(let W of Sn)if(J[W]!==void 0&&J[W]!==null)e({path:`policyHelpers.${T}`,message:`"${W}" on the policyHelpers.${T} entry is ignored — per-OS entries are SIBLINGS on the policyHelpers map, not nested inside each other. The intended ${W} config will NOT apply from here.`,statusOnly:!0});if(J.default!==void 0&&J.default!==null)e({path:`policyHelpers.${T}`,message:`"default" on the policyHelpers.${T} entry is ignored — the per-entry static payload field is spelled "defaultSettings"; "default" is the MAP's any-platform catch-all key (a sibling of the OS entries). The intended fallback will NOT apply from here.`,statusOnly:!0});let Q=J.onFailure;if(Q!==void 0&&Q!==null&&!WZ(Q)){let W;if(typeof Q==="string"){let B=Q.replace(/[^\x20-\x7e]/gu,"?");W=JSON.stringify(B.length>IZ?`${B.slice(0,IZ-1)}…`:B)}else if(typeof Q==="number"||typeof Q==="boolean")W=String(Q);else W=`a non-string value (${Array.isArray(Q)?"array":typeof Q})`;e({path:`policyHelpers.${T}.onFailure`,message:`"onFailure": ${W} on the policyHelpers.${T} entry is not a recognized value ("continue" or "refuse"); it is treated as "refuse" — a startup failure of this entry's helper with no static payload in its place will not start Claude Code.`,statusOnly:!0})}if(KZ(z))return}return z===null?void 0:z},M.optional()).catch((z)=>{if(T==="default"){f("policyHelpers.default",z.issues[0]?.message??d(ka(),I));return}if(w)return;let J=d(nx(T),I)??"failed validation",Q=I,W=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null,B=W?.onFailure,it=B!==void 0&&B!==null&&B!=="continue",Ve=(ot)=>{let At=`policyHelpers.${T}`;if(it)m.push({entryKey:T,message:ot});else e({path:At,message:ot,statusOnly:!0})};if(W){let ot=W.defaultSettings;if(ot!==void 0&&ot!==null){let At=ka().safeParse(ot);if(At.success){let Zt=W.outputBehavior,Ke=Zt===void 0||Zt===null?null:GZ().safeParse(Zt);if(Ke&&!Ke.success){Ve(`Invalid entry was ignored: ${J}. Its "defaultSettings" static payload was NOT kept: "outputBehavior" is unrecognized, so whether the payload replaces or merges over this source's settings is unknown. No policy helper runs on ${T} from this entry.`);return}return e({path:`policyHelpers.${T}`,message:`Invalid entry: its helper fields were ignored (${J}), but its "defaultSettings" static payload was kept. No policy helper runs on ${T} from this entry.`,statusOnly:!0}),{defaultSettings:At.data,...Ke&&{outputBehavior:Ke.data}}}}}Ve(`Invalid entry was ignored: ${J}. No policy helper runs on ${T} from this entry.`);return})};a("policyHelpers",()=>Me((T)=>{if(m=[],T&&typeof T==="object"&&!Array.isArray(T)){let w=T;for(let I of["defaultSettings",...Ty,"claudeMd"])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelpers",message:`"${I}" directly on the policyHelpers map is ignored — static fallback payloads go on a per-OS entry's "defaultSettings" or the map's "default" key (a managed-settings object), and helper-output keys come from the helper's stdout. The intended content will NOT apply from here.`,statusOnly:!0});for(let I of["policyHelper","policyHelpers"])if(w[I]!==void 0&&w[I]!==null)e({path:"policyHelpers",message:`"${I}" inside the policyHelpers map is ignored — "policyHelper" and "policyHelpers" are TOP-LEVEL settings keys; the map's keys are the per-OS entries and "default". The nested config will NOT apply from here.`,statusOnly:!0});for(let I of tx.filter((M)=>M!=="defaultSettings"))if(w[I]!==void 0&&w[I]!==null){let M=I==="script"||I==="interpreter"?"; inline scripts are per-OS only (the singular policyHelper key takes a path)":I==="outputBehavior"||I==="onFailure"||I==="retries"?"":", or on the singular policyHelper key";e({path:"policyHelpers",message:`"${I}" directly on the policyHelpers map is ignored — helper configs go on a per-OS entry (policyHelpers.${Sn.join("/")})${M}. No helper runs from this field here.`,statusOnly:!0})}}return T===null?void 0:T},O(Object.fromEntries(ux.map((T)=>[T,g(T)]))).transform((T)=>{for(let w of Object.keys(T))if(T[w]===void 0)delete T[w];for(let{entryKey:w,message:I}of m){let M=`policyHelpers.${w}`,z=cx(w).find((Q)=>T[Q]?.defaultSettings!==void 0&&T[Q]?.defaultSettings!==null),J=z!==void 0?`${z}.defaultSettings`:T.default!==void 0?"default":null;e(J!==null?{path:M,message:`${I} Its "onFailure" requires the helper; the "policyHelpers.${J}" static payload serves in its place.`,statusOnly:!0}:{path:M,message:`${I} Its "onFailure" requires the helper, so when delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0})}return m=[],T}).optional().catch((T)=>(e({path:"policyHelpers",message:`"policyHelpers" could not be parsed: expected an object mapping OS keys (${Sn.join(", ")}) to helper entries, plus an optional "default" settings payload (${T.issues[0]?.message??"failed schema validation"}). When delivered from an OS-admin policy source (MDM or the managed settings file), Claude Code will not start until this is fixed.`,startupFatal:!0}),{}))));let _=new WeakSet;for(let T of r.keys){if(T==="sandbox"||!Ny(T))continue;a(T,()=>{let w=s(T),I=hx(w);if(I===void 0)return w.catch((M)=>{e({path:T,message:`${M.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return});return ox(T,I,e,{synthesized:_,strictField:w})})}let y=Object.freeze({mode:"deny"}),S=Object.freeze({accessKeyIdVar:"_STRIPPED_",secretAccessKeyVar:"_STRIPPED_2_"}),E=0,b=[],C=new Set,A=new Set,R=t===void 0?"":`${[...t].reduce((T,w)=>Math.imul(T^w.charCodeAt(0),16777619)>>>0,2166136261).toString(16).toUpperCase().padStart(8,"0")}_`,x=(T,w)=>{if(typeof T!=="object"||T===null)return;let I=(we)=>w.some((ge)=>ge.path?.includes(we)),M=(we)=>{let ge=T[we];if(typeof ge==="string")return ge;return I(we)?"":void 0},z=M("accessKeyIdVar"),J=M("secretAccessKeyVar"),Q=M("sessionTokenVar"),W=Oi;if(![z,J,Q].some((we)=>we!==void 0&&W.includes(we)))return;let B=(we)=>we!==void 0&&Bc().safeParse(we).success;E+=1;let it=(we)=>`${ov}${we}_${R}${E}_`,Ve=B(z)?z:it("ACCESS_KEY_ID"),ot=B(J)&&J!==Ve?J:it("SECRET_ACCESS_KEY"),At=Q===void 0?void 0:B(Q)&&Q!==Ve&&Q!==ot?Q:it("SESSION_TOKEN"),Zt=(we)=>we.startsWith(ov);if(!Zt(Ve)&&!Zt(ot)){let we=W.includes(ot)?ot:void 0;if(ot=it("SECRET_ACCESS_KEY"),we!==void 0){let ge=x({accessKeyIdVar:we},[]);if(ge!==void 0)b.push(ge)}}let Ke=py().safeParse({accessKeyIdVar:Ve,secretAccessKeyVar:ot,...At!==void 0&&{sessionTokenVar:At}});return Ke.success?Ke.data:void 0},L=(T,w,I)=>k(w.catch((M)=>{let z=I(M.value);if(z!==void 0)return e({path:`sandbox.credentials.${T}[]`,message:`Invalid entry was degraded to mode "deny": ${M.issues[0]?.message??"failed validation"}. The credential stays blocked (not masked) until the entry is fixed.${T==="files"?" Under sandbox.filesystem.disabled, file read-denies are not enforced.":""}`,substituted:!0}),z;return e({path:`sandbox.credentials.${T}[]`,message:`Invalid entry was ignored: ${M.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),y})).transform((M)=>{let z=M.filter((J)=>J!==y);if(M.length>0&&z.length===0)C.add(T);return z}).optional().catch((M)=>{if(typeof M.value==="object"&&M.value!==null&&!Array.isArray(M.value)){let z=w.safeParse(M.value);if(z.success)return e({path:`sandbox.credentials.${T}`,message:`"${T}" must be an array; a lone entry object was accepted as a one-element list. Wrap it in [ ] to silence this warning.`}),[z.data];let J=I(M.value);if(J!==void 0)return e({path:`sandbox.credentials.${T}`,message:`"${T}" must be an array; its lone entry object was invalid and was degraded to mode "deny". The credential stays blocked (not masked) until it is fixed.`,substituted:!0}),[J]}return e({path:`sandbox.credentials.${T}`,message:`${M.issues[0]?.message??"Invalid value"}. "${T}" was ignored; these credential entries are NOT protected until it is fixed.`}),C.add(T),[]});a("sandbox",()=>{let T=O({files:L("files",cy(),(w)=>{if(typeof w!=="object"||w===null||!("mode"in w)||w.mode!=="mask"&&w.mode!=="deny"||!("path"in w)||typeof w.path!=="string")return;let I=cy().safeParse({path:w.path,mode:"deny"});return I.success?I.data:void 0}),envVars:L("envVars",uy(),(w)=>{if(typeof w!=="object"||w===null||!("mode"in w)||w.mode!=="mask"&&w.mode!=="deny"||!("name"in w)||typeof w.name!=="string")return;let I=uy().safeParse({name:w.name,mode:"deny"});return I.success?I.data:void 0}),allowPlaintextInject:rx("sandbox.credentials.allowPlaintextInject",Xc().get("sandbox.credentials.allowPlaintextInject"),v().optional(),e).catch((w)=>(e({path:"sandbox.credentials.allowPlaintextInject",message:`${w.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was degraded to an explicit false; plaintext credential injection stays disabled (lower-precedence values cannot enable it) until it is fixed.`,substituted:!0}),C.add("allowPlaintextInject"),!1)),awsPairs:k(py().catch((w)=>{let I=x(w.value,w.issues);if(I!==void 0)return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was degraded to a non-functional suppressor: ${w.issues[0]?.message??"failed validation"}. It keeps implicit AWS auto-pairing suppressed but re-signs nothing until it is fixed.`,substituted:!0}),I;return e({path:"sandbox.credentials.awsPairs[]",message:`Invalid pair was ignored: ${w.issues[0]?.message??"failed validation"}. SigV4 re-signing stays unconfigured for this pair until it is fixed.`}),S})).transform((w)=>{let I=w.filter((M)=>M!==S);if(b.length>0)I.push(...b),b.length=0;if(w.length>0&&I.length===0)C.add("awsPairs");return I}).optional().catch((w)=>{let I=typeof w.value==="object"&&w.value!==null?x(w.value,[]):void 0,M=typeof w.value==="object"&&w.value!==null&&(("accessKeyIdVar"in w.value)||("secretAccessKeyVar"in w.value)||("sessionTokenVar"in w.value));if(I===void 0&&M)return b.length=0,e({path:"sandbox.credentials.awsPairs",message:`${w.issues[0]?.message??"Invalid value"}. "awsPairs" must be an array; its lone pair-shaped entry claimed no conventional AWS name and was ignored. SigV4 re-signing stays unconfigured until it is fixed.`}),C.add("awsPairs"),[];let z=I!==void 0?[I]:Oi.flatMap((J)=>{let Q=x({accessKeyIdVar:J},[]);return Q!==void 0?[Q]:[]});if(b.length>0)z.push(...b),b.length=0;if(I===void 0)C.add("awsPairs");return e({path:"sandbox.credentials.awsPairs",message:`${w.issues[0]?.message??"Invalid value"}. "awsPairs" was degraded to non-functional suppressor pair(s); implicit AWS auto-pairing stays suppressed but nothing re-signs until it is fixed.`,substituted:!0}),z}),sigv4:O(Object.fromEntries(["streaming","presigned","sigv4a"].map((w)=>[w,K(["deny","passthrough"]).optional().catch((I)=>(e({path:`sandbox.credentials.sigv4.${w}`,message:`${I.issues[0]?.message??"Invalid value"}. "${w}" was degraded to an explicit deny; this SigV4 request shape stays denied until it is fixed.`,substituted:!0}),A.add(w),"deny"))]))).transform((w)=>{let I=Object.entries(w).filter(([,M])=>M!==void 0);if(I.length>0&&I.every(([M])=>A.has(M)))C.add("sigv4");return A.clear(),w}).optional().catch((w)=>(e({path:"sandbox.credentials.sigv4",message:`${w.issues[0]?.message??"Invalid value"}. "sigv4" was degraded to an all-deny block (all shapes stay denied, and lower-precedence sigv4 values cannot take effect) until it is fixed.`,substituted:!0}),A.clear(),C.add("sigv4"),{streaming:"deny",presigned:"deny",sigv4a:"deny"}))}).transform((w)=>{let I=Object.entries(w).filter(([,M])=>M!==void 0);if(I.length>0&&I.every(([M])=>C.has(M)))_.add(w);return C.clear(),w}).optional().catch((w)=>{e({path:"sandbox.credentials",message:`${w.issues[0]?.message??"Failed schema validation"}. The credentials block was degraded to a fail-closed skeleton (all-deny sigv4, implicit AWS auto-pairing suppressed, no masking) until it is fixed.`,substituted:!0});let I=Oi.flatMap((z)=>{let J=x({accessKeyIdVar:z},[]);return J!==void 0?[J]:[]});b.length=0,C.clear(),A.clear();let M={allowPlaintextInject:!1,awsPairs:I,sigv4:{streaming:"deny",presigned:"deny",sigv4a:"deny"}};return _.add(M),M});return ox("sandbox",sv(),e,{override:{"sandbox.credentials":T},skeletonExclude:new Set(["sandbox.enabled"]),neverSubstitute:new Set(["sandbox.failIfUnavailable"]),synthesized:_})});let F={};for(let T of r.keys){if(!o(T))continue;let w=i.get(T);F[T]=w?w():s(T).catch((I)=>{e({path:T,message:`${I.issues[0]?.message??"Failed schema validation"}. This field was ignored.`});return})}for(let[T,w]of i)if(!(T in F)&&o(T))F[T]=w();return O(F).passthrough().check((T)=>{T.issues.push(...r.wrongDocumentIssues(T.value,F))}).transform((T)=>{for(let M of Object.keys(T))if(T[M]===void 0)delete T[M];let w=Object.keys(T).filter((M)=>!xi.some((z)=>z===M)&&!sf(T[M])),I=w.length>0&&w.every((M)=>l.has(M)||QZ(_,T[M]));if(l.clear(),I)for(let M of w)e({path:M,message:`"${M}" holds nothing that could be applied as written and is this source's only policy content; its fail-closed reading binds (beside a lower managed settings source's policy, when one supplies it) until it is fixed.`,statusOnly:!0,onlySubstitutes:!0});return T})}var Z9e=65536,n9=new RegExp(`[${yD("<")}]`,"gu");function J9e(e){return wY(e)&&e.search(n9)===-1}function r9(e){let t={},n=Z9e,r=0,o=0;for(let s of Qc.toSorted((i,a)=>Number(a==="hard_deny")-Number(i==="hard_deny"))){let i=oe(e)?e[s]:void 0;if(i!==void 0&&i!==null&&!Array.isArray(i))r++;let a=[Vp];for(let l of Array.isArray(i)?i:[]){if(typeof l!=="string"){r++;continue}if(["",Vp].includes(l.trim()))continue;let c=l.length>2*n?1/0:_b(l);if(c>n){r++;continue}n-=c;let p=Array.from(oD(l),(m)=>iy(m)||ay(m)?" ":m).join("").replace(n9,"<");if(p.trim()===Vp)continue;let f=_b(p)-c;if(!J9e(p)||f>n){r++;continue}if(n-=f,a.push(p),p!==l)o++}if(a.length>1)t[s]=a}return{lists:t,leftOut:r,mended:o}}var o9=new Set(["disableAllHooks","disableReplyCheck"]),s9=["accessKeyIdVar","secretAccessKeyVar","sessionTokenVar"];function Sx(e){let t={};for(let g of xo()){let{path:_,restrictive:y}=g;if(o9.has(_[0]))continue;let S=F_(g,e);if((typeof S==="boolean"||typeof S==="string")&&Ea(y).includes(S))jt(t,_,S)}if(pt(e,["attribution"])===!1)jt(t,["attribution","sessionUrl"],!1);let n=Uy(e.permissions,["deny","ask","disableBypassPermissionsMode","disableAutoMode"]);if(n)t.permissions={...t.permissions,...n};for(let g of X9e)if(e[g]!==void 0)t[g]=e[g];for(let[g,_]of Object.entries(e))if((g.startsWith("disable")&&(_===!0||_==="disable")||g.startsWith("enable")&&_===!1)&&!o9.has(g))t[g]=_;if(e.disableAllHooks===!0)t.allowManagedHooksOnly=!0;if(Array.isArray(e.httpHookAllowedEnvVars)&&e.httpHookAllowedEnvVars.length===0)t.httpHookAllowedEnvVars=[];let r=Uy(e.sandbox?.filesystem,["denyRead","denyWrite","allowManagedReadPathsOnly"]),o=Uy(e.sandbox?.network,["deniedDomains","strictAllowlist","allowManagedDomainsOnly"]),s=Uy(e.sandbox?.credentials,["files","envVars"])??{},i=e.sandbox?.credentials?.awsPairs,a=oe(i)&&s9.some((g)=>(g in i)),c=(Array.isArray(i)?i:a?[i]:[]).flatMap((g)=>oe(g)?s9.map((_)=>g[_]):[]),d=i!==void 0&&!Array.isArray(i)&&!a,p=Oi.filter((g)=>d||c.includes(g));if(p.length>0)s.awsPairs=p.map((g,_)=>({accessKeyIdVar:g,secretAccessKeyVar:`${dy}${_+1}_`}));let f=e.sandbox?.credentials?.sigv4;if(f){let g={};for(let[_,y]of Object.entries(f))if(y==="deny")g[_]="deny";if(Object.keys(g).length>0)s.sigv4=g}let m=Object.keys(s).length>0;if(r||o||m){let g=t.sandbox??{};t.sandbox={...g,...r&&{filesystem:{...g.filesystem,...r}},...o&&{network:{...g.network,...o}},...m&&{credentials:{...g.credentials,...s}}}}return Object.keys(t).length>0?t:null}function Uy(e,t){if(!e)return;let n={};for(let r of t)if(e[r]!==void 0)n[r]=e[r];return Object.keys(n).length>0?n:void 0}var X9e=["allowedMcpServers","deniedMcpServers","allowManagedMcpServersOnly","disabledMcpjsonServers","allowManagedHooksOnly","allowedHttpHookUrls","strictKnownMarketplaces","allowedMarketplaces","blockedMarketplaces","strictPluginOnlyCustomization","availableModels","enforceAvailableModels","availableModelsMatch","deniedModels","allowedProviders"];var Q9e=["SSL_CERT_FILE","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE","HTTPLIB2_CA_CERTS"],e6e=["AWS_CA_BUNDLE","DENO_CERT","CARGO_HTTP_CAINFO","PIP_CERT","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","NIX_SSL_CERT_FILE","HEX_CACERTS_PATH"],i9=[...Q9e,...e6e],a9={UV_NATIVE_TLS:"true",DENO_TLS_CA_STORE:"system,mozilla"};var t6e=Object.freeze(["-c","core.hooksPath=/dev/null","-c","core.fsmonitor="]);var mzt=Object.freeze(["--no-optional-locks","status","--porcelain","--untracked-files=normal","--ignore-submodules=dirty"]),n6e=Object.freeze({GIT_LFS_SKIP_SMUDGE:"1"});var r6e=["'alias.remote-none=version'","'alias.remote-none.command=version'","'alias.remote-/.command=version'","'fetch.bundleURI='","'help.autocorrect=0'"],o6e=r6e.join(" "),gzt=Object.freeze({GIT_ALLOW_PROTOCOL:"/",GIT_CONFIG_PARAMETERS:o6e,GIT_NO_LAZY_FETCH:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_TERMINAL_PROMPT:"0",...n6e}),hzt=Object.freeze({LC_ALL:"C",LANGUAGE:"C"}),_zt=Object.freeze({GIT_SSH_COMMAND:"false"});var yzt=Object.freeze([...t6e,"-c","safe.bareRepository=explicit","-c","protocol.file.allow=never"]),Ex=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_SHALLOW_FILE","GIT_NAMESPACE","GIT_IMPLICIT_WORK_TREE","GIT_REFERENCE_BACKEND"],bx=[...Ex,"GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG"],s6e=/^GIT_CONFIG_(KEY|VALUE)_\d+$/,i6e=new RegExp(s6e.source,"i");var Szt=new Set(bx);function c9(e){let t=0,n=e.length;while(t<n&&l9(e.charCodeAt(t)))t++;while(n>t&&l9(e.charCodeAt(n-1)))n--;let r=a6e(e.slice(t,n));if(r!==-1)return{kind:"line_break",index:Cx(e,t+r)};for(let o=t;o<n;o++){let s=e.charCodeAt(o);if(s===0)return{kind:"nul",index:Cx(e,o)};if(s>255)return{kind:"non_ascii",index:Cx(e,o),codePoint:l6e(e,o)}}return null}function a6e(e){let t=e.indexOf(`
|
|
151
151
|
`),n=e.indexOf("\r");if(t===-1)return n;return n===-1?t:Math.min(t,n)}function l9(e){return e===9||e===32||e===10||e===13}function l6e(e,t){return e.codePointAt(t)??e.charCodeAt(t)}function Cx(e,t){let n=0;for(let r=0;r<t;r++){let o=e.charCodeAt(r);if(o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320)r++;n++}return n}var Ax=["NODE_TLS_REJECT_UNAUTHORIZED","BUN_TLS_REFUSE_DISTRUSTED_KEYS"];var u9=["YARN_HTTP_PROXY","YARN_HTTPS_PROXY","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy","GLOBAL_AGENT_HTTP_PROXY","GLOBAL_AGENT_HTTPS_PROXY","GLOBAL_AGENT_NO_PROXY","DOCKER_HTTP_PROXY","DOCKER_HTTPS_PROXY","ELECTRON_GET_USE_PROXY","CLOUDSDK_PROXY_TYPE","CLOUDSDK_PROXY_ADDRESS","CLOUDSDK_PROXY_PORT","CLOUDSDK_PROXY_USERNAME","CLOUDSDK_PROXY_PASSWORD","FSSPEC_GCS","JAVA_TOOL_OPTIONS"];var Rx=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","ANTHROPIC_GOOGLE_CLOUD_PROJECT","ANTHROPIC_GOOGLE_CLOUD_LOCATION","ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID","CLOUD_ML_REGION"],d9=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE"];var p9="OTEL_EXPORTER_OTLP_",Ox=["OTEL_LOG_RAW_API_BODIES","OTEL_LOG_USER_PROMPTS","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_MANAGED_SETTINGS","OTEL_LOGS_EXPORTER","ENABLE_BETA_TRACING_DETAILED","BETA_TRACING_ENDPOINT","ANT_OTEL_LOGS_EXPORTER"],f9=[p9,`ANT_${p9}`];var m9={apiKeyHelper:["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],awsAuthRefresh:[...d9,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],awsCredentialExport:[...d9,"ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL"],gcpAuthRefresh:["CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL"]},g9=["CLAUDE_CODE_MEMORY_API_BASE_URL","CLAUDE_CODE_MEMORY_API_TOKEN"];var h9=["CLAUDE_CODE_ARTIFACTS_API_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_TOKEN","CLAUDE_CODE_ARTIFACT_ASSET_BASE_URL","CLAUDE_CODE_ARTIFACT_LIVE_BASE_URL","CLAUDE_CODE_ARTIFACT_SYNC_BASE_URL","CLAUDE_CODE_ARTIFACT_VIEWER_BASE_URL"],Tx=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL",...h9,...g9],c6e=[{endpoint:"ANTHROPIC_BASE_URL",companions:["_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_BEDROCK_BASE_URL",selection:"CLAUDE_CODE_USE_BEDROCK",companions:["CLAUDE_CODE_SKIP_BEDROCK_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_VERTEX_BASE_URL",selection:"CLAUDE_CODE_USE_VERTEX",companions:["CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_FOUNDRY_BASE_URL",selection:"CLAUDE_CODE_USE_FOUNDRY",companions:["CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_AWS_BASE_URL",selection:"CLAUDE_CODE_USE_ANTHROPIC_AWS",companions:["CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_GOOGLE_CLOUD_BASE_URL",selection:"CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",companions:["CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","ANTHROPIC_CUSTOM_HEADERS"]},{endpoint:"ANTHROPIC_BEDROCK_MANTLE_BASE_URL",selection:"CLAUDE_CODE_USE_MANTLE",companions:["CLAUDE_CODE_SKIP_MANTLE_AUTH","ANTHROPIC_CUSTOM_HEADERS"]}],Nzt=Nt(c6e.flatMap((e)=>[e.endpoint,...e.companions])),wx=["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"];var vx=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],xx=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL","CLAUDE_CODE_3P_PROBE_WROTE_SONNET_DEFAULT","CLAUDE_CODE_3P_PROBE_WROTE_OPUS_DEFAULT","CLAUDE_CODE_3P_PROBE_WROTE_HAIKU_DEFAULT","CLAUDE_CODE_3P_SEEDED_SONNET_DEFAULT","CLAUDE_CODE_3P_SEEDED_OPUS_DEFAULT"],kx=["ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES"],u6e=["CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR","CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR","CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR","CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR","CCR_AGENT_PROXY_TOKEN_FILE_DESCRIPTOR"],Uzt=[...h9,...g9,"CLAUDE_CODE_API_BASE_URL","CLAUDE_BRIDGE_BASE_URL","CLAUDE_BRIDGE_SESSION_INGRESS_URL","CLAUDE_REMOTE_TOOLS_BRIDGE_URL","CLAUDE_CODE_GB_BASE_URL","VOICE_STREAM_BASE_URL"],Fzt=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_SESSIONS_OAUTH_TOKEN",...u6e,"CLAUDE_CODE_ARTIFACTS_API_TOKEN","CLAUDE_CODE_SLACK_TAG_TOKEN","CLAUDE_CODE_HFI_BEARER_TOKEN","CLAUDE_BRIDGE_OAUTH_TOKEN","CLAUDE_TRUSTED_DEVICE_TOKEN","AGENT_PROXY_AUTH_TOKEN","CLAUDE_CODE_MCP_SERVE_AUTH_TOKEN","CLAUDE_BG_AUTH_SNAPSHOT_PATH","CLAUDE_BG_SOCKET_TOKENS_PATH","CLAUDE_BG_RV_AUTH","CLAUDE_BG_PTY_AUTH","CLAUDE_BG_CLAIM_AUTH"],d6e=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Px=[...d6e,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"];var af=["AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","AWS_EC2_METADATA_SERVICE_ENDPOINT","AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN"],Ix=["GCE_METADATA_HOST","GCE_METADATA_ROOT","GCE_METADATA_IP","METADATA_SERVER_DETECTION"],Hzt=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...Rx,...Tx,...wx,...vx,"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",...Px,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT",...Ix,...af,"AWS_REGION","AWS_DEFAULT_REGION",...xx,"ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_BEDROCK_REGION_PREFIX","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_DISABLE_FEATURE_FLAGS","DISABLE_GROWTHBOOK","CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE",...kx]);var _9=["SSL_CERT_FILE","SSL_CERT_DIR","ALL_PROXY"],p6e=["NPM_CONFIG_HTTPS_PROXY","NPM_CONFIG_HTTP_PROXY","NPM_CONFIG_PROXY"],f6e=new Set(Ex),m6e=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_HTTP_PROXY","CLAUDE_CODE_HTTPS_PROXY","NPM_CONFIG_PROXY","NPM_CONFIG_HTTP_PROXY","NPM_CONFIG_HTTPS_PROXY"]);var g6e=Nt([...i9,...Object.keys(a9),...u9.map((e)=>e.toUpperCase()),..._9,...bx.filter((e)=>!f6e.has(e))]).filter((e)=>e!=="NODE_EXTRA_CA_CERTS"&&e!=="JAVA_TOOL_OPTIONS"&&!m6e.has(e));var $zt=new Set(["CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_DISABLE_LOOPED_CROSS_CERT_DROP","CLAUDE_CODE_DISABLE_SELF_NAMED_CERT_DROP",...Ax,"CLAUDE_CODE_OAUTH_SCOPES",...g6e]);var y9=["HTTPS_PROXY","HTTP_PROXY","NO_PROXY",..._9,...p6e,"NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_DISABLE_LOOPED_CROSS_CERT_DROP","CLAUDE_CODE_DISABLE_SELF_NAMED_CERT_DROP","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE",...Ax];var S9=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","fileSuggestion","gcpAuthRefresh","otelHeadersHelper","processWrapper","policyHelpers","proxyAuthHelper","statusLine","subagentStatusLine"],Dx=["bwrapPath","ripgrep","socatPath"],E9=["allowAppleEvents","allowNestedUserNamespaces","credentials","enableWeakerNestedSandbox","enableWeakerNetworkIsolation","filesystem.disabled","network.allowAllUnixSockets","network.allowMachLookup","network.allowUnixSockets","network.httpProxyPort","network.socksProxyPort","network.tlsTerminate"],b9=["required","egress"],h6e=new Set(["ANTHROPIC_BEDROCK_REGION_PREFIX","ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_CUSTOM_MODEL_OPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION","ANTHROPIC_CUSTOM_MODEL_OPTION_NAME","ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","ANTHROPIC_SMALL_FAST_MODEL","AWS_DEFAULT_REGION","AWS_PROFILE","AWS_REGION","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_FEATURE_FLAGS","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_ENABLE_AUTO_MODE","CLAUDE_CODE_ENABLE_DESIGN_SYNC","CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL","CLAUDE_CODE_ENABLE_TELEMETRY","CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_MCP_DESCRIPTION_LENGTH","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_GOOGLE_CLOUD_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD","CLAUDE_CODE_USE_GATEWAY","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_POWERSHELL_TOOL","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_FEEDBACK_COMMAND","DISABLE_GROWTHBOOK","DISABLE_INSTALLATION_CHECKS","DISABLE_UPDATES","ENABLE_TOOL_SEARCH","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_CONNECT_TIMEOUT_MS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","OTEL_EXPORTER_OTLP_COMPRESSION","OTEL_EXPORTER_OTLP_HEADERS","OTEL_EXPORTER_OTLP_LOGS_COMPRESSION","OTEL_EXPORTER_OTLP_LOGS_HEADERS","OTEL_EXPORTER_OTLP_LOGS_PROTOCOL","OTEL_EXPORTER_OTLP_METRICS_COMPRESSION","OTEL_EXPORTER_OTLP_METRICS_HEADERS","OTEL_EXPORTER_OTLP_METRICS_PROTOCOL","OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE","OTEL_EXPORTER_OTLP_PROTOCOL","OTEL_EXPORTER_OTLP_TRACES_COMPRESSION","OTEL_EXPORTER_OTLP_TRACES_HEADERS","OTEL_EXPORTER_OTLP_TRACES_PROTOCOL","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_USER_PROMPTS","OTEL_LOGS_EXPORT_INTERVAL","OTEL_LOGS_EXPORTER","OTEL_METRIC_EXPORT_INTERVAL","OTEL_METRICS_EXPORTER","OTEL_METRICS_INCLUDE_ACCOUNT_UUID","OTEL_METRICS_INCLUDE_ENTRYPOINT","OTEL_METRICS_INCLUDE_REPOSITORY","OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES","OTEL_METRICS_INCLUDE_SESSION_ID","OTEL_METRICS_INCLUDE_VERSION","OTEL_RESOURCE_ATTRIBUTES","OTEL_SERVICE_NAME","OTEL_TRACES_EXPORT_INTERVAL","OTEL_TRACES_EXPORTER","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_5_SONNET","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS","VERTEX_REGION_CLAUDE_4_5_OPUS","VERTEX_REGION_CLAUDE_4_6_OPUS","VERTEX_REGION_CLAUDE_4_7_OPUS","VERTEX_REGION_CLAUDE_4_8_OPUS","VERTEX_REGION_CLAUDE_5_OPUS","VERTEX_REGION_CLAUDE_5_5_OPUS","VERTEX_REGION_CLAUDE_FABLE_5","VERTEX_REGION_CLAUDE_FABLE_5_1","VERTEX_REGION_CLAUDE_FABLE_5_2","VERTEX_REGION_CLAUDE_4_5_SONNET","VERTEX_REGION_CLAUDE_4_6_SONNET","VERTEX_REGION_CLAUDE_5_SONNET","VERTEX_REGION_CLAUDE_5_5_SONNET","VERTEX_REGION_CLAUDE_HAIKU_4_5","VERTEX_REGION_CLAUDE_HAIKU_5_5","CLAUDE_AUTOCOMPACT_PCT_OVERRIDE","CLAUDE_CODE_AUTO_COMPACT_WINDOW","CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT","CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS","CLAUDE_CODE_MAX_CONTEXT_TOKENS","DISABLE_AUTO_COMPACT","DISABLE_COMPACT","CLAUDE_CODE_ALWAYS_ENABLE_EFFORT","CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING","CLAUDE_CODE_DISABLE_FAST_MODE","CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP","CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK","CLAUDE_CODE_DISABLE_THINKING","CLAUDE_CODE_EFFORT_LEVEL","CLAUDE_CODE_MAX_EFFORT_REMINDER","CLAUDE_CODE_SUBAGENT_EFFORT","CLAUDE_CODE_MESSAGES_PROMPT_CACHE_TTL","CLAUDE_CODE_PROMPT_CACHE_TTL","CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL","DISABLE_INTERLEAVED_THINKING","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_FABLE","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","ENABLE_PROMPT_CACHING_1H","ENABLE_PROMPT_CACHING_1H_BEDROCK","FALLBACK_FOR_ALL_PRIMARY_MODELS","FORCE_PROMPT_CACHING_5M","CLAUDE_AUTO_BACKGROUND_TASKS","CLAUDE_CODE_DISABLE_ADVISOR_TOOL","CLAUDE_CODE_DISABLE_AGENT_VIEW","CLAUDE_CODE_DISABLE_ARTIFACT","CLAUDE_CODE_DISABLE_BACKGROUND_TASKS","CLAUDE_CODE_DISABLE_BUNDLED_SKILLS","CLAUDE_CODE_DISABLE_CRON","CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS","CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY","CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING","CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND","CLAUDE_CODE_DISABLE_MEMORY_RO_UNSAVED_NOTICE","CLAUDE_CODE_DISABLE_WORKFLOWS","CLAUDE_CODE_ENABLE_AWAY_SUMMARY","CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING","CLAUDE_CODE_ENABLE_FUNCTION_HOOKS","CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION","CLAUDE_CODE_ENABLE_TASKS","CLAUDE_CODE_FORK_SUBAGENT","CLAUDE_CODE_PLAN_MODE_REQUIRED","DISABLE_DOCTOR_COMMAND","DISABLE_EXTRA_USAGE_COMMAND","DISABLE_INSTALL_GITHUB_APP_COMMAND","DISABLE_LOGIN_COMMAND","DISABLE_LOGOUT_COMMAND","DISABLE_UPGRADE_COMMAND","CLAUDE_AX_SCREEN_READER","CLAUDE_CODE_ACCESSIBILITY","CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN","CLAUDE_CODE_DISABLE_MOUSE","CLAUDE_CODE_DISABLE_MOUSE_CLICKS","CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL","CLAUDE_CODE_FORCE_STRIKETHROUGH","CLAUDE_CODE_FORCE_TERMINAL_IMAGES","CLAUDE_CODE_HIDE_CWD","CLAUDE_CODE_NATIVE_CURSOR","CLAUDE_CODE_NO_FLICKER","CLAUDE_CODE_SCROLL_SPEED","CLAUDE_CODE_SYNTAX_HIGHLIGHT","API_TIMEOUT_MS","CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS","CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS","CLAUDE_CODE_GLOB_TIMEOUT_SECONDS","CLAUDE_CODE_MAX_RETRIES","CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION","CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY","CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION","CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS","CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT","CLAUDE_CODE_TEAM_TEARDOWN_PARK_TIMEOUT_MS","CLAUDE_CODE_WEB_SEARCH_REFILLS_PER_HOUR","CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS","CLAUDE_STREAM_IDLE_TIMEOUT_MS","MAX_STRUCTURED_OUTPUT_RETRIES","MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE","MCP_SERVER_CONNECTION_BATCH_SIZE","SLASH_COMMAND_TOOL_CHAR_BUDGET","TASK_MAX_OUTPUT_LENGTH","MCP_CONNECTION_NONBLOCKING","CLAUDE_ENABLE_BYTE_WATCHDOG","CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK","CLAUDE_ENABLE_STREAM_WATCHDOG"]),_6e=new Set(["API_FORCE_IDLE_TIMEOUT","CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES","CLAUDE_CODE_DISABLE_MCP_TASKS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_RESPONSE_COMPARISON","CLAUDE_CODE_DISABLE_ULTRATHINK","CLAUDE_CODE_DISABLE_WEB_FETCH","DISABLE_ERROR_REPORTING","DISABLE_TELEMETRY","DO_NOT_TRACK"]),y6e=new Set([...[],"ENABLE_BETA_TRACING_DETAILED","OTEL_LOG_RAW_API_BODIES"]),S6e=/auth|key|token|cookie|secret|credential|session|signature|passw|jwt|assertion|cert|oidc|org|tenant|account|project|workspace|user|email|identity|principal|consumer|client|host|url|base|target|upstream|endpoint|proxy|forward|route|fallback|override|apigw|x-goog-|l5d-|bypass|guardrail|amz|x-ms-|azureml|extra-parameters|envoy|helicone|litellm|cf-aig|cf-access|beta|version/;function E6e(e){if(/\r(?!\n)/.test(e))return!0;return e.split(/\n|\r\n/).some((t)=>{let n=t.indexOf(":");if(n===-1)return!1;let r=t.slice(0,n).trim();return!b6e.test(r)||c9(t.slice(n+1))!==null||S6e.test(r.toLowerCase())})}var b6e=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function C9(e,t){let n=e.toUpperCase();return h6e.has(n)||C6e(n,t)||n==="ANTHROPIC_CUSTOM_HEADERS"&&!E6e(t)}function C6e(e,t){return _6e.has(e)&&Ae(t)||y6e.has(e)&&Zr(t)}function Lx(){let e=xm();return e!==void 0&&dl(e)}function A9(){let e=st(),t=e==="wsl"&&!Lx()?"linux":e;switch(t){case"unknown":return{platform:t,chain:[]};default:return{platform:t,chain:cx(t)}}}var R9="anthropic-skills";var A6e=[/^agent-a[0-9a-f]{16}$/,/^agent-a[0-9a-f]{7}$/,/^wf_[0-9a-f]{8}-[0-9a-f]{3}-\d+$/];var hBt=[...A6e,/^wf-\d+$/,/^bridge-[A-Za-z0-9_]+(-[A-Za-z0-9_]+)*$/,/^job-[a-zA-Z0-9._-]{1,55}-[0-9a-f]{8}$/,/^bg-[a-zA-Z0-9._-]{1,55}-[0-9a-f]{8}$/];var w9=/[\u200c-\u200f\u202a-\u202e\u206a-\u206f\ufeff]/,R6e=new RegExp(w9,"g");function Mx(e){return O6e(e,!0)}function O6e(e,t){let n=e.toLowerCase().replace(/\u0131/g,"i").replace(/\u017f/g,"s"),r=n.replace(R6e,"");return(t?r.replace(/:.*$/,""):r).replace(/[. ]+$/,"")||n}var v9=String.raw`[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\.?`,Fy="[A-Za-z0-9._-]+",Nx="[A-Za-z0-9._~-]",T6e=`${Nx}+(?::${Nx}*)?@`,w6e=":[1-9][0-9]{0,4}",v6e=`(?:/(?:${Nx}|%[0-9A-Fa-f]{2})*)*`,DBt=new RegExp(`^${Fy}/${Fy}$`),LBt=new RegExp(`^git@(${v9}):(${Fy}(?:/${Fy})*)/?$`),x9=`(?:${T6e})?(${v9})(?:${w6e})?(${v6e})$`,MBt=new RegExp(`^https://${x9}`),NBt=new RegExp(`^https?://${x9}`),UBt=`ssh.${xn}`;class k9{reader=null;register(e){let t=this.reader;return this.reader=e,t}}var zBt=new k9;var x6e="inline",ejt=`${R9}@${x6e}`;var P9="builtin";function I9(e){let t=e.toLowerCase();return Sy(t)?t:e}function Ux(e){return e.normalize("NFC").toLowerCase()}var eu=[{alias:"additionalMarketplaces",canonical:"extraKnownMarketplaces"},{alias:"allowedMarketplaces",canonical:"strictKnownMarketplaces"}];function D9(e,t,n){if(!oe(e))return[];let r=[];for(let{alias:o,canonical:s}of eu){if(!(o in e))continue;if(e[o]===null){if(!(s in e)&&n?.loneNullAlias==="rename")e[s]=null;delete e[o];continue}if(s in e&&e[s]!==null)r.push({file:t,path:o,message:`"${o}" is an alias for "${s}" and this file sets both; the "${o}" value was ignored. Use only "${s}".`,severity:"warning",alias:o,canonical:s});else e[s]=e[o];delete e[o]}return r}function Rr(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var I6e=["enabled","enabledPlatforms"],lf="network.allowedDomains",D6e=new Set(["OTEL_LOG_MANAGED_SETTINGS"]);function N9(e){if(!e)return{shellSettings:{},envVars:{},sandboxSettings:{},isolationSettings:{},hasHooks:!1,payloadSlots:{}};let t=[["top",e],...cf(e),...cf(e).map(([a])=>[a,{slotPresent:!0}]),...Sn.map((a)=>[`policyHelpers.${a}`,{outputBehavior:ki(e,`policyHelpers.${a}.outputBehavior`)}])],n=U9(e,t),r=L6e(e,t);M6e([n,...r.map(([,a])=>a)]);let o={};for(let[a,l]of r){let c={shellSettings:l.hasHooks?{...l.shellSettings,hooks:ps(l.hooks)}:l.shellSettings,envVars:l.envVars,sandboxSettings:l.sandboxSettings,isolationSettings:l.isolationSettings};if($9(c))o[a]=c}let{sandboxSwitches:s,...i}=n;return{...i,payloadSlots:o}}function U9(e,t){let n={},r;for(let f of S9){let m=e[f];if(f==="policyHelpers"){if(m!==null&&typeof m==="object")for(let _ of Sn){let y=j6e(m[_]);if(y){if(n[`policyHelpers.${_}`]=y.command,y.scriptSize)r??={},r[`policyHelpers.${_}`]=y.scriptSize}}continue}let g;if(typeof m==="string")g=m;else if(m!==null&&typeof m==="object"&&"command"in m&&typeof m.command==="string")g=m.command;if(g!==void 0&&g.length>0)n[f]=g}let o=Z6e(e);if(o&&typeof o==="object")for(let[f,m]of Object.entries(o)){let g=m?.pluginDigests;if(g!==void 0&&g!==null&&Object.keys(g).length>0)n[`extraKnownMarketplaces[${ce(f)}].pluginDigests`]=ps({pluginDigests:g,arming:q6e(t,f,g)});let _=m?.source;if(!_||typeof _!=="object")continue;if(_.source==="url"&&typeof _.headersHelper==="string"&&_.headersHelper.length>0)n[`extraKnownMarketplaces[${ce(f)}].source.headersHelper`]=M9(_.headersHelper,"url",_.url);if(_.source==="settings"&&Array.isArray(_.plugins)){let y=new Map;for(let S of _.plugins){let E=ce(S?.name),b=y.get(E)??0;y.set(E,b+1);let C=S?.source;if(C!==null&&typeof C==="object"&&"source"in C&&C.source==="command"&&"command"in C&&typeof C.command==="string"&&C.command.length>0)n[`extraKnownMarketplaces[${ce(f)}].plugins[${ce(S.name)}][${b}].source.command`]=C.command;if(typeof S?.headersHelper==="string"&&S.headersHelper.length>0){let A=S.source,R=A!==null&&typeof A==="object";n[`extraKnownMarketplaces[${ce(f)}].plugins[${ce(S.name)}][${b}].headersHelper`]=M9(S.headersHelper,R&&"source"in A?A.source:void 0,R&&"url"in A?A.url:void 0)}}}}let s=e.sandbox,i={},a={enabled:ki(s,"enabled"),enabledPlatforms:ki(s,"enabledPlatforms"),[lf]:ki(s,lf)};if(s!==null&&typeof s==="object"){let f={enabled:a.enabled,enabledPlatforms:a.enabledPlatforms};for(let m of Dx){let g=W6e(s[m]);if(g)n[`sandbox.${m}`]=ps({value:g,...f})}for(let m of E9){let g=ki(s,m);if(N6e(m,g))i[`sandbox.${m}`]=ps({value:g,...f,...z9.has(m)&&{allowedDomains:B9(a[lf])}})}}let l=e.isolation,c={};for(let f of b9){let m=ki(l,f);if(U6e(f,m))c[`isolation.${f}`]=ps({value:m})}let d={};if(e.env&&typeof e.env==="object")for(let[f,m]of Object.entries(e.env)){if(m===void 0)continue;let g=String(m);if(g.length>0&&!D6e.has(f.toUpperCase())&&!C9(f,g))d[f]=g}let p=e.hooks!==void 0&&e.hooks!==null&&typeof e.hooks==="object"&&Object.keys(e.hooks).length>0;return{shellSettings:n,inlineHelperScriptSizes:r,envVars:d,sandboxSettings:i,isolationSettings:c,hasHooks:p,hooks:p?e.hooks:void 0,sandboxSwitches:a}}function L6e(e,t){return cf(e).map(([n,r])=>[n,U9(r,t)])}function cf(e){let t=[];for(let n of H9){let r=`policyHelpers.${n}`,o=ki(e,r);if(!Rr(o))continue;let{policyHelper:s,policyHelpers:i,...a}=o;t.push([r,a])}return t}function Hx(e){return Sn.find((t)=>e===`policyHelpers.${t}.defaultSettings`)}function F9(e,t){let n=Hx(t);return n!==void 0&&ki(e,`policyHelpers.${n}.outputBehavior`)==="merge"}function M6e(e){let t=e.map((r)=>Object.keys(r.sandboxSettings).length>0||Dx.some((o)=>r.shellSettings[`sandbox.${o}`]!==void 0)),n=e.map((r)=>[...z9].some((o)=>r.sandboxSettings[`sandbox.${o}`]!==void 0));e.forEach((r,o)=>{if(t.some((s,i)=>s&&i!==o))for(let s of I6e){let i=r.sandboxSwitches[s];if(i!==void 0)r.sandboxSettings[`sandbox.${s}`]=ps({value:i})}if(n.some((s,i)=>s&&i!==o)){let s=r.sandboxSwitches[lf];if(s!==void 0)r.sandboxSettings[`sandbox.${lf}`]=ps({value:B9(s)??s})}})}var H9=[...Sn.map((e)=>`${e}.defaultSettings`),"default"];function Fx(e){let t=[];for(let n of H9){let r=`policyHelpers.${n}`,o=e.payloadSlots[r];if(o!==void 0&&$9(o))t.push([r,o])}return t}function $9(e){return Object.keys(e.shellSettings).length>0||Object.keys(e.envVars).length>0||Object.keys(e.sandboxSettings).length>0||Object.keys(e.isolationSettings).length>0}var z9=new Set(["credentials","network.tlsTerminate"]);function B9(e){return Array.isArray(e)?Nt(e.filter((t)=>typeof t==="string")).sort():void 0}function ki(e,t){let n=e;for(let r of t.split(".")){if(n===null||typeof n!=="object")return;n=n[r]}return n}function N6e(e,t){if(t===void 0||t===null||t===!1)return!1;if(Array.isArray(t)&&t.length===0)return!1;return!(e==="credentials"&&H6e(t))}function U6e(e,t){if(t===void 0||t===null)return!1;switch(e){case"required":return t!==!1;case"egress":return!Rr(t)||Object.entries(t).some(([n,r])=>F6e.has(n)?r!==void 0&&r!==null&&!(Array.isArray(r)&&r.length===0):r!==void 0)}}var F6e=new Set(["allowedHosts","deniedHosts"]);function H6e(e){if(typeof e!=="object"||e===null)return!1;return Object.entries(e).every(([t,n])=>{if(n===void 0)return!0;if(t==="files"||t==="envVars")return Array.isArray(n)&&n.every((r)=>typeof r==="object"&&r!==null&&r.mode==="deny");if(t==="sigv4")return typeof n==="object"&&n!==null&&Object.values(n).every((r)=>r===void 0||r==="deny");return t==="allowPlaintextInject"&&n===!1})}function $6e(e){return Object.keys(e.shellSettings).some(z6e)}function z6e(e){return Sn.some((t)=>e===`policyHelpers.${t}`)}function j9(e){return $6e(e)||Object.keys(e.shellSettings).some((t)=>t.startsWith("extraKnownMarketplaces["))||Fx(e).length>0}function B6e(e){return e==="sh"||e==="pwsh"}function j6e(e){if(e===null||typeof e!=="object")return;let{path:t,script:n,interpreter:r,timeoutMs:o,refreshIntervalMs:s}=e,i,a;if(typeof t==="string"&&t)i=t;else if(typeof n==="string"&&n&&B6e(r))i={interpreter:r,script:G6e(n)},a=K6e(n);else return;return{command:ce([i,o??null,s??null]),scriptSize:a}}function K6e(e){return{bytes:Buffer.byteLength(e,"utf8"),lines:iD(e,`
|
|
152
152
|
`)+(e.endsWith(`
|
|
153
153
|
`)?0:1)}}function G6e(e){return Ol(ce(e))}function W6e(e){if(typeof e==="string")return e||void 0;if(e===null||typeof e!=="object"||!("command"in e)||typeof e.command!=="string"||!e.command)return;let t="args"in e&&Array.isArray(e.args)?e.args.map(String):[];return ce([e.command,...t])}function V6e(e){return ps(K9(e))}function K9(e){return{shellSettings:e.shellSettings,envVars:e.envVars,sandboxSettings:Object.keys(e.sandboxSettings).length>0?e.sandboxSettings:void 0,...L9(e),hooks:e.hooks,payloadSlots:Fx(e).length>0?Object.fromEntries(Fx(e).map(([t,n])=>{let{isolationSettings:r,...o}=n;return[t,{...o,...L9(n)}]})):void 0}}function L9(e){return Object.keys(e.isolationSettings).length>0?{isolationSettings:e.isolationSettings}:{}}function q6e(e,t,n){let r=new Set(Object.keys(n).map((o)=>Ux(`${o}@${t}`)));return e.flatMap(([o,s])=>["enabledPlugins","prependPlugins","appendPlugins","managedSourcesBehavior","outputBehavior","slotPresent"].flatMap((i)=>{let a=s[i],l=i==="enabledPlugins"?Rr(a):Array.isArray(a);if(a===void 0)return[];if(!l)return[[o,`${i}:whole`,a]];return(Rr(a)?Object.entries(a).toSorted():[a].flat().map((d)=>[d])).filter(([d])=>typeof d!=="string"||r.has(Ux(d))).map((d)=>[o,i,...d])}))}function ps(e){return ce(Gp(e))}function G9(e){return Ol(V6e(e))}function W9(e,t,n){if(G9(t)===e)return!0;return typeof n==="string"&&n.length>0&&Ol(ps({...K9(t),claudeMd:n}))===e}function M9(e,t,n){return ce([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}var Y6e=new Set(["dns","unix","ipv4","ipv6"]),kjt=new Set([...Y6e,"http","https","ws","wss","ftp","file","grpc","grpcs","otlp","xds","tcp","udp","tls","h2","h2c","http2"]);function V9(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function Z6e(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of eu){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var Q6e="remote-settings.json",e3e=5000;var e6="remote-settings-helper-consent";function t3e(){return Q9(Ut(),e6)}function n3e(e){let t=N9(e);return j9(t)?t:void 0}function r3e(e){let t=ba(e,(n,r)=>r.startsWith("$")&&r!=="$schema");if(Object.keys(t).length!==Object.keys(e).length)t6.set(t,e);return t}function q9(e){return t6.get(e)??e}var t6=new WeakMap;class n6{sessionCache=null;storedAccountReader=null;storedCopyGateCovers=!0;storedCopyOrgPin={kind:"unreadable"};mayHideDialog=()=>!1;writesForHiddenDialog=()=>!1;seededUnjudged=null;storedCopyTrust="not_asked";storedCopyRefusal=null;helperTierReadAtMs=null;refusedCopyHelperTier=null;droppedHelperTier=null;eligible=void 0;eligibilityMemo=void 0;machinePinsSignInMemo=void 0;ineligibleReason=void 0;evalPolicySnapshotOnly=!1;hybridTokenRenewalDue=!1;hybridOrganizationUuid=null;usesGatewayVariable=!1;hybridSignInEnded=!1;hybridBlockFilter=null;hybridHostsWithheld=!1;hybridProviderFromOrganization=!1;hybridOnlyForConnection=!1;hybridLeftOut=null;hybridCacheLeftOut=null;lastLoadStatus=void 0;loadCycleEnded=!1;loadCycleBegun=!1;loadCycleEndedSignal=He();loadBackstopReleased=!1;lastLoadStatusChanged=He();policySettingsNotified=!1;verifiedPayload=null;verifiedByGateway=void 0;unverifiedView=null;projectedView=null;projectedParse=null;consentedPayload=null;deferredPayload=null;resetEpoch=0;backendView=void 0;coworkCloudHolds={};heldSoFar(e){let t=Object.keys(this.coworkCloudHolds).length>0;if(!t&&!$p())return e;if(e!==null){let n=Xw(this.coworkCloudHolds,e);return this.coworkCloudHolds=$_(n),n}return t?this.coworkCloudHolds:null}replaceSessionCache(e,t){let n=t?.verified===!0||!$p();if(!n&&e!==null&&e===this.sessionCache)return;let r=this.heldSoFar(n?c3e(e):null);if(this.keepHelperLeaving(),this.sessionCache=r,t?.verified){if(this.seededUnjudged=null,this.verifiedPayload=r,this.verifiedByGateway=RI()?.url,this.projectedView=null,this.projectedParse=null,t.consentDeferred)this.deferredPayload=r}}seedFromDisk(e){let t=Object.keys(this.coworkCloudHolds).length>0?Xw(this.coworkCloudHolds,e):e;this.sessionCache=t,this.seedConsentBaseline(t)}seedConsentBaseline(e){let t=n3e(e);if(t!==void 0){let n=m3e();if(n===void 0||!W9(n,t,e.claudeMd))return}this.consentedPayload??=e}markConsented(e){this.consentedPayload=e}dropConsentDeferral(){this.deferredPayload=null}markPolicySettingsNotified(){this.policySettingsNotified=!0}recordEligibility(e,t){if(this.eligible=e,t.memoize)this.eligibilityMemo=e,this.ineligibleReason=e?void 0:t.ineligibleReason}resetListener=null;registerResetListener(e){if(this.resetListener!==null)throw Error("registerSyncCacheResetListener: a listener is already registered; a second one would unhook the first");this.resetListener=e}keepHelperLeaving(){if(this.sessionCache===this.verifiedPayload){let e=$x(this.sessionCache);this.droppedHelperTier=e===null?this.droppedHelperTier:{...e,env:{...this.droppedHelperTier?.env,...e.env}}}}reset(){this.keepHelperLeaving(),this.sessionCache=null,this.helperTierReadAtMs=null,this.storedCopyTrust="not_asked",this.storedCopyRefusal=null,this.refusedCopyHelperTier=null,this.storedAccountReader=null,this.storedCopyGateCovers=!0,this.storedCopyOrgPin={kind:"unreadable"},this.mayHideDialog=()=>!1,this.writesForHiddenDialog=()=>!1,this.seededUnjudged=null,this.eligible=void 0,this.eligibilityMemo=void 0,this.machinePinsSignInMemo=void 0,this.ineligibleReason=void 0,this.hybridTokenRenewalDue=!1,this.evalPolicySnapshotOnly=!1,this.hybridOrganizationUuid=null,this.usesGatewayVariable=!1,this.hybridSignInEnded=!1,this.hybridBlockFilter=null,this.hybridHostsWithheld=!1,this.hybridProviderFromOrganization=!1,this.hybridOnlyForConnection=!1,this.hybridLeftOut=null,this.hybridCacheLeftOut=null,this.lastLoadStatus=void 0,this.loadCycleEnded=!1,this.loadCycleBegun=!1,this.loadBackstopReleased=!1,this.policySettingsNotified=!1,this.verifiedPayload=null,this.verifiedByGateway=void 0,this.unverifiedView=null,this.projectedView=null,this.projectedParse=null,this.consentedPayload=null,this.deferredPayload=null,this.resetEpoch++,this.emitLoadStatusChanged(void 0)}emitLoadStatusChanged(e){try{this.lastLoadStatusChanged.emit(e)}catch(t){G(`Remote settings: load-status listener threw: ${ft(t)}`,{level:"error"})}}}var o3e=new Te(()=>new n6);function ar(){return o3e.of(Gt().host)}function Hy(){return oY()||(!CI()&&!AI()||nY())&&ar().mayHideDialog()}function r6(){return ar().lastLoadStatus}function tu(){return}function s3e(){return ar().evalPolicySnapshotOnly}var DKt=new Te(()=>new Map);var LKt=new Te(()=>new Map);var MKt=new Te(()=>({held:void 0,running:void 0,afterRefusal:!1}));var NKt=new Te(()=>({value:!0}));function zx(){return tt()||s3e()}function o6(e){let{projectedView:t,projectedParse:n}=ar();return e!==null&&(t?.view===e||n?.view===e||i3e(e))}function i3e(e){return Fc()&&Object.keys(e).length>0&&Gr($_(e),e)}var a3e=[["allowedHttpHookUrls"],["httpHookAllowedEnvVars"],["isolation","required"]],s6=[{path:["sandbox","credentials","files"],names:"path"},{path:["sandbox","credentials","envVars"],names:"name"}];function i6(e){for(let n of a3e)jt(e,n,void 0);for(let{path:n,names:r}of s6){let o=pt(e,n),s=(Array.isArray(o)?o:[o]).flatMap((i)=>oe(i)&&typeof i[r]==="string"?[{[r]:i[r],mode:"deny"}]:[]);jt(e,n,s.length>0?s:void 0)}for(let n of[["permissions","deny"],["permissions","ask"]]){let r=pt(e,n);if(Array.isArray(r)){let o=r.filter((s)=>typeof s!=="string"||!Hp.test(s));jt(e,n,o)}}for(let{path:n,restrictive:r}of xo()){let o=pt(e,n),s=n[0]==="strictPluginOnlyCustomization"?o:Yc(o);if(r===!0&&s===!1)jt(e,n,void 0)}let t=e.strictPluginOnlyCustomization;if(Array.isArray(t)&&!t.some((n)=>rf.includes(n)))delete e.strictPluginOnlyCustomization;if(e.availableModelsMatch==="prefix")delete e.availableModelsMatch}function a6(e){let t={...Sx(e)};if(i6(t),e.parentSettingsBehavior==="merge")t.parentSettingsBehavior="merge";let n=Object.fromEntries([...N2,Uc].flatMap((s)=>Object.entries(e.pluginConfigs?.[s]?.options??{}))),r=Jw({pluginConfigs:{[Uc]:{options:n}}});if(r!==void 0)t.pluginConfigs=r;let o=Object.entries(e.enabledPlugins??{}).filter(([s,i])=>i===!1&&!(s.includes("@")&&I9(s.slice(s.lastIndexOf("@")+1))===P9));return o.length===0?t:{...t,enabledPlugins:Object.fromEntries(o)}}function Y9(e){if(!e||!zx())return e;let t={...Sx(e)};if(tt()){if(i6(t),e.fastMode===!1)t.fastMode=!1;if(e.fastModePerSessionOptIn===!0)t.fastModePerSessionOptIn=!0;let n=Object.entries(oe(e.skillOverrides)?e.skillOverrides:{}).flatMap(([r,o])=>o==="off"?[[r,"off"]]:[]);if(n.length>0)t.skillOverrides=Object.fromEntries(n);if(e===ar().verifiedPayload){if(typeof e.claudeMd==="string"&&e.claudeMd!=="")t.claudeMd=e.claudeMd;for(let[r,o]of Object.entries(r9(e.autoMode).lists))jt(t,["autoMode",r],o)}}return{...t,managedSourcesBehavior:"merge"}}function l3e(){return RY(()=>$p()||Dt.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST&&x2.has(Dt.CLAUDE_CODE_ENTRYPOINT??"")||Up())}function l6(){return tu()??Q9(Ut(),Q6e)}var c6=8388608;function c3e(e){if(e===null||!$p())return e;let t=$_(e);return Gr(t,e)?e:t}function u3e(){if(l3e())return null;let e=ar(),t=e.storedCopyRefusal;if(t!==null&&Hy()&&Date.now()-t.atMs<e3e)return e.storedCopyTrust={trusted:!1,reason:t.reason},null;e.storedCopyTrust="not_asked",e.storedCopyRefusal=null,e.refusedCopyHelperTier=null;try{let n=g3e();if(n===null)return null;let r=je(Lc(n));if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=r3e(r);return d3e(o)?o:null}catch(n){if(ZV(n))G(`Remote settings: Disk cache exceeds ${c6} bytes; ignoring it as if absent`);return null}}function d3e(e){let t=ar();if(!Hy()||!t.storedCopyGateCovers||tu()!==void 0||t.evalPolicySnapshotOnly)return t.storedCopyTrust="not_asked",!0;let n=t.storedCopyOrgPin;if(n.kind==="read"){let o=Z9(e,n.orgs);if(o.trusted)return t.storedCopyTrust=o,!0;return J9(e,o.reason,oy(o.reason)),!1}let r=e.forceRemoteSettingsRefresh===!0?Z9(e,void 0):void 0;return J9(e,"org_pin_unknown",r!==void 0&&(r.trusted||oy(r.reason))),!1}function Z9(e,t){try{return yY({kind:"managed-settings",cachePath:l6(),body:q9(e),bodySha:sY(q9(e)),account:ar().storedAccountReader?.(),pinnedOrgs:t,nowMs:Date.now(),roots:CY()})}catch(n){return G(`Remote settings: the gate on a stored copy failed: ${ft(n)}`,{level:"error"}),{trusted:!1,reason:"error"}}}function J9(e,t,n){let r=ar();r.storedCopyTrust={trusted:!1,reason:t},r.storedCopyRefusal={atMs:Date.now(),reason:t,forcesRefresh:n&&e.forceRemoteSettingsRefresh===!0},r.refusedCopyHelperTier=oy(t)?p3e(e):null,r.seedConsentBaseline(e),G(`Remote settings: the stored copy is not trusted at rest (${t}); treating it as absent`)}function $x(e){if(e===null)return null;let{apiKeyHelper:t,env:n}=e;return typeof t==="string"&&t.trim()!==""?{apiKeyHelper:t,env:Dc(oe(n)?n:{},(r)=>typeof r==="string")}:null}function p3e(e){let[t]=d6(e);if(e===null||t===void 0)return $x(e);let[n,r]=t;return $x(F9(e,n)?{...e,...r,env:{...e.env,...r.env}}:r)}var f3e=4096;function m3e(){let e=Bx();if(e!==void 0)return e.attestation;if(tt())return;try{return bi(t3e(),f3e).trim()||void 0}catch{return}}function g3e(){let e=Bx();if(e!==void 0)return e.content;if(tt()&&tu()===void 0)return null;return bi(l6(),c6)}function Bx(){let e=ar().backendView;if(!be()||e===void 0||!e.ready||e.stoodDown||tu()!==void 0)return;if(!FI(e.configHome)){e.standDown("config home changed");return}return e}var UKt=Ht.state("remote-settings"),FKt=Ht.state(e6);var h3e=new Set([...y9,"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","CLAUDE_CODE_DISABLE_HTTPS_AGENT_KEEPING","NODE_OPTIONS",...Rx,...Tx,"AWS_ENDPOINT_URL_STS","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_SSO","AWS_ENDPOINT_URL_SSO_OIDC","AWS_ENDPOINT_URL_BEDROCK","AWS_ENDPOINT_URL_BEDROCK_RUNTIME",...Px,...af,...Ix,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...wx,"CLAUDE_CODE_API_BASE_URL","CLAUDE_CODE_OAUTH_REFRESH_TOKEN","CLAUDE_CODE_OAUTH_SCOPES","CLAUDE_CODE_OAUTH_CLIENT_ID","CLAUDE_CODE_SESSION_ACCESS_TOKEN","CLAUDE_SESSION_INGRESS_TOKEN_FILE","CLAUDE_CODE_ENVIRONMENT_KIND","CLAUDE_CODE_REMOTE_SESSION_ID","ANTHROPIC_FEDERATION_RULE_ID","ANTHROPIC_ORGANIZATION_ID","ANTHROPIC_WORKSPACE_ID","ANTHROPIC_SERVICE_ACCOUNT_ID","ANTHROPIC_IDENTITY_TOKEN","ANTHROPIC_IDENTITY_TOKEN_FILE","ANTHROPIC_SCOPE","ANTHROPIC_PROFILE","ANTHROPIC_CONFIG_DIR","CLAUDE_CODE_FEDERATION_CACHE_DIR","HOME","XDG_CONFIG_HOME","APPDATA","USERPROFILE","HOMEDRIVE","HOMEPATH","PROGRAMDATA","ALLUSERSPROFILE","ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MANAGED_SETTINGS_PATH","CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE","CLAUDE_LOCAL_OAUTH_APPS_BASE","CLAUDE_LOCAL_OAUTH_CONSOLE_BASE","CLAUDE_BRIDGE_BASE_URL","CLAUDE_BRIDGE_OAUTH_TOKEN","CLAUDE_BRIDGE_SESSION_INGRESS_URL","CLAUDE_REMOTE_TOOLS_BRIDGE_URL","CLAUDE_CODE_GB_BASE_URL"].map((e)=>e.toUpperCase()));function _3e(e){if(!e||!e.env&&!("managedMcpServers"in e))return e;let{managedMcpServers:t,...n}=e;return e.env?{...n,env:ba(e.env,(r,o)=>h3e.has(o.toUpperCase()))}:n}function u6(){let e=f6();if(e===null||zx()||p6(ar(),e))return!1;if(X9(e))return!0;return d6(e).some(([,t])=>X9(t))}function d6(e){let t=cf(e);if(t.length===0)return[];return[...A9().chain,void 0].flatMap((n)=>t.filter(([r])=>Hx(r)===n))}function X9(e){let t=e.managedMcpServers;return oe(t)&&Object.keys(t).length>0}function p6(e,t){return t===e.verifiedPayload||Boolean(tu())}function f6(){let e=ar();if(!tu()&&e.eligible!==!0)return e.heldSoFar(null);if(e.sessionCache){if(e.sessionCache!==e.seededUnjudged||!Hy())return e.sessionCache;e.sessionCache=null,e.seededUnjudged=null,Qw()}let t=Bx()!==void 0,n=u3e();if(n){if(e.seedFromDisk(n),e.seededUnjudged=Hy()?null:e.sessionCache,t)ls().invalidatePolicyLayer();else Qw();return e.sessionCache}return e.heldSoFar(null)}function m6(e){let t=f6(),n=ar(),r=p6(n,t)?t:y3e(n,t);if(r===null||!zx())return r;if(n.projectedView?.raw!==r)n.projectedView={raw:r,view:Y9(r)};let o=n.projectedView.view;if(!e)return o;if(n.projectedParse?.raw!==r){let s={...o};if(g6(s,Y9(e(r))??{}),tt())for(let{path:i,names:a}of s6){let l=[o,s].flatMap((c)=>pt(c,i)??[]);if(l.length>0)jt(s,i,tY(l,a))}n.projectedParse={raw:r,view:s}}return n.projectedParse.view}function g6(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(o!==r&&oe(o)&&oe(r)){let s={...o};g6(s,r),e[n]=s}else e[n]=r}}function y3e(e,t){if(t===null)return null;if(e.unverifiedView?.raw!==t)e.unverifiedView={raw:t,view:_3e(t)};return e.unverifiedView.view}var S3e=Le(new Set,(e)=>e.clear());function h6(e){S3e.add(e)}var ZKt=Le({noFollowAny:"untried",localVolumes:void 0},(e)=>{e.noFollowAny="untried",e.localVolumes=void 0});var JKt=Symbol("no procfs"),XKt=Symbol("descriptor path unreadable");var QKt=Symbol("boundRead.linkToNothing");var E3e={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"},b3e=["ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL"],_6=[...Ca,"AWS_REGION","AWS_PROFILE",...b3e,"AWS_BEARER_TOKEN_BEDROCK",...vx,"ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","ANTHROPIC_FOUNDRY_RESOURCE"],o1t=[..._6,"AWS_ENDPOINT_URL_BEDROCK_RUNTIME","AWS_ENDPOINT_URL_BEDROCK","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_STS","AWS_ENDPOINT_URL_SSO","AWS_ENDPOINT_URL_SSO_OIDC","AWS_ENDPOINT_URL_SIGNIN","ANTHROPIC_BEDROCK_REGION_PREFIX","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN",...af],y6=[...Ca,"AWS_BEARER_TOKEN_BEDROCK","AWS_REGION","AWS_DEFAULT_REGION","AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","GOOGLE_APPLICATION_CREDENTIALS","CLOUD_ML_REGION","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_BEDROCK_SERVICE_TIER"];function S6(e,t){let n=new Map(Object.entries(e).map(([a,l])=>[a.toUpperCase(),l])),r=Boolean(n.get("AWS_CONFIG_FILE"))&&n.get("AWS_ACCESS_KEY_ID")==="",o=t.has("AWS_PROFILE")||t.has("AWS_ACCESS_KEY_ID"),s=t.has("AWS_CONFIG_FILE")||t.has("AWS_SHARED_CREDENTIALS_FILE"),i=t.has("AWS_ACCESS_KEY_ID");if(!(t.has("AWS_PROFILE")||s||i))return{dropped:[],cleared:[]};return{dropped:["AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE",...r||i?["AWS_PROFILE"]:[],...r&&!o?["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK"]:[]],cleared:i&&!n.has("AWS_SESSION_TOKEN")&&!t.has("AWS_SESSION_TOKEN")?["AWS_SESSION_TOKEN"]:[]}}var E6=[..._6,"AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_BEDROCK_SERVICE_TIER",...Object.values(E3e),"ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","ANTHROPIC_CUSTOM_HEADERS"];var C3e=["ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_GOOGLE_CLOUD_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_FOUNDRY_RESOURCE","AWS_ENDPOINT_URL_BEDROCK_RUNTIME","AWS_ENDPOINT_URL_BEDROCK","AWS_ENDPOINT_URL"],A3e=new Set(["AWS_ENDPOINT_URL_BEDROCK_RUNTIME","AWS_ENDPOINT_URL_BEDROCK","AWS_ENDPOINT_URL"]);function b6(e,t){let n=new Set([...Ca,"CLAUDE_CODE_USE_GATEWAY"]),r=new Set([...C3e,"ANTHROPIC_BASE_URL"]),o=t?.CLAUDE_CODE_USE_BEDROCK==="1";return Object.entries(e??{}).some(([s,i])=>{let a=s.toUpperCase();return n.has(a)&&Ae(i)||r.has(a)&&i.trim()!==""&&(o||!A3e.has(a))})}var C6=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var R3e=["userSettings","projectSettings","localSettings"],O3e=["projectSettings","localSettings"],_1t=new Set(O3e),T3e={userSettings:"user",projectSettings:"project",localSettings:"local"},y1t=R3e.map((e)=>[T3e[e],e]);var A6="--settings (inline JSON)",R6=["auto","bypassPermissions"],jx="organizationFreeFormSettings";function O6(e,t,n){if(e===t)return 0;let r=e.length,o=t.length,s=n+1;if(Math.abs(r-o)>n)return s;let i=new Int32Array(o+2).fill(s),a=new Int32Array(o+2).fill(s),l=new Int32Array(o+2).fill(s);for(let c=0;c<=Math.min(o,n);c++)a[c]=c;for(let c=1;c<=r;c++){let d=Math.max(1,c-n),p=Math.min(o,c+n);l[d-1]=d===1?Math.min(c,s):s;let f=l[d-1];for(let m=d;m<=p;m++){let g=Math.min(a[m]+1,l[m-1]+1,a[m-1]+(e[c-1]===t[m-1]?0:1),s);if(c>1&&m>1&&e[c-1]===t[m-2]&&e[c-2]===t[m-1])g=Math.min(g,i[m-2]+1);l[m]=g,f=Math.min(f,g)}if(l[p+1]=s,f>n)return s;[i,a,l]=[a,l,i]}return a[o]}var T6=["claude-3-5-haiku","claude-3-5-sonnet","claude-3-7-sonnet","claude-fable-5","claude-fable-5-1","claude-fable-5-2","claude-haiku-4-5","claude-haiku-5-5","claude-mythos-5","claude-mythos-5-1","claude-mythos-5-2","claude-opus-4-0","claude-opus-4-1","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-opus-5-5","claude-sonnet-4-0","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-5","claude-sonnet-5-5"],w6=["sonnet","opus","haiku","fable","best","sonnet[1m]","opus[1m]","fable[1m]","opusplan"],Pi=["sonnet","opus","haiku","fable"];function $y(e){return w6.includes(e)}function Kx(e){return e.replace(/\[1m\]$/i,"")}function v6(e){return e.replace(/\[(1|2)m\]/gi,"")}function Pa(e){return Pi.includes(e)}function fs(e){let t=e.trim().toLowerCase();if(t===""||/\s/.test(t))return null;t=t.replace(/\[[12]m\]$/,"");let n=t.lastIndexOf("/");if(n!==-1)t=t.slice(n+1);let r=/^(?:([a-z-]+)\.)?anthropic\.(claude-.*)$/.exec(t);if(r){let[,a,l=""]=r;if(a!==void 0&&!pM.includes(a))return null;t=l}let o=v3e(t);if(!o)return null;let s=t.slice(o.base.length);if(s!==""&&!/^[-@]/.test(s))return null;let i={family:o.family,major:o.major,legacyVersionFirst:o.legacyVersionFirst,base:o.base};if(o.minor!==void 0)i.minor=o.minor;if(!w3e(s))i.trailer=s;else{let a=/(?:-v\d+@|[-@])(\d{8})/.exec(s)?.[1];if(a!==void 0)i.date=a}return i}function w3e(e){return/^(?:-fast|-latest)?(?:-v\d{1,3}@\d{8}|[-@]\d{8})?(?:-v\d{1,3}(?::\d{1,3})?)?$/.test(e)}function x6(e,t){return e.major-t.major||(e.minor??0)-(t.minor??0)}function v3e(e){let t=/^claude-([a-z]+)-(\d{1,2})(?!\d)(?:-(\d{1,2})(?!\d))?/.exec(e);if(t){let[r,o="",s="",i]=t;return{family:o,major:Number(s),minor:i===void 0?void 0:Number(i),legacyVersionFirst:!1,base:r}}let n=/^claude-(\d{1,2})(?!\d)(?:-(\d{1,2})(?!\d))?-([a-z]+)/.exec(e);if(n){let[r,o="",s,i=""]=n;return{family:i,major:Number(o),minor:s===void 0?void 0:Number(s),legacyVersionFirst:!0,base:r}}return null}function lr(e){let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g,"?");return t.length>128?`${t.slice(0,128)}…`:t}function x3e(){let e=[...Pi],t=e.pop();return e.length===0?t??"":`${e.join(", ")} or ${t}`}function zy(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k6(e){let t=e.trim().toLowerCase(),n=v6(t).trim(),r=n!==t?" Context-size tags such as [1m] are ignored: the entry blocks the model at every context size.":"";if(n==="")return{entry:null,warning:"An empty deniedModels entry was ignored."};if(Pa(n))return{entry:{kind:"family",family:n},...r!==""&&{warning:`"${lr(e)}" blocks every ${zy(n)} model.${r}`}};if($y(n)||n==="default")return{entry:null,warning:`"${lr(e)}" was ignored: it names a different model depending on the release and settings. Name the model instead, for example "claude-opus-5-5".`};let o=fs(n),s=o!==null||n.startsWith("claude-")?n:`claude-${n}`,i=o??(s!==n?fs(s):null);if(i){let a=s.lastIndexOf(i.base),l=a===-1?"":s.slice(a+i.base.length),c=i.trailer===void 0&&l!==""?` "${lr(l)}" is ignored.`:"";return{entry:{kind:"model",id:i},...(r!==""||c!=="")&&{warning:`"${lr(e)}" blocks ${k3e(i)}.${c}${r}`}}}return{entry:{kind:"literal",value:n},warning:P3e(e,n)}}function k3e(e){let t=zy(e.family);return e.minor===void 0?`every ${t} ${e.major}.x model`:`${t} ${e.major}.${e.minor} in every spelling and snapshot`}function P3e(e,t){let n=`"${lr(e)}" blocks only the exact model name "${lr(t)}"; other spellings of the same model are not blocked.`,r=t.replace(/(\d)\.(\d)/g,"$1-$2");if(r!==t){let s=r.startsWith("claude-")?r:`claude-${r}`;if(fs(s)!==null)return`${n} To block a version, write it with a hyphen: "${lr(s)}".`}let o=new RegExp(`^(${Pi.join("|")})\\s+(\\d+)(?:\\.(\\d+))?$`).exec(t);if(o){let[,s,i,a]=o;return a!==void 0?`${n} To block a version, write its model ID, for example "claude-${s}-${i}-${a}".`:`${n} To block only version ${i}, write "claude-${s}-${i}-0"; "claude-${s}-${i}" blocks every ${zy(s)} ${i}.x model.`}if(/^[a-z]+$/.test(t)){let s=Pi.find((i)=>O6(t,i,1)===1);return s!==void 0?`${n} If you meant the ${zy(s)} family, write "${s}".`:`${n} To block a model family other than ${x3e()}, list its versioned IDs.`}return n}function P6(e){let t=Kx(e.trim().toLowerCase());if(t==="")return{kind:"ignored"};if(Pa(t))return{kind:"family",family:t};let n=t.startsWith("claude-")?t.slice(7):"";if(Pa(n))return{kind:"family",family:n};if($y(t)||t==="default")return{kind:"ignored"};let r=fs(t)!==null||t.startsWith("claude-")?t:`claude-${t}`,o=fs(r);return o!==null?{kind:"model",id:o,latest:D3e(r,o),spelling:r}:{kind:"literal",value:t}}function I3e(e,t){let n=e.toLowerCase(),r=n.lastIndexOf(t.base);return r===-1?"":n.slice(r+t.base.length)}function D3e(e,t){return t.trailer===void 0&&I3e(e,t).startsWith("-latest")}function L3e(e,t){for(let n of t){if(Pa(n))continue;let r=n.indexOf(e);if(r===-1)continue;let o=r+e.length;if(o===n.length||n[o]==="-")return!0}return!1}function M3e(e){return e.charAt(0).toUpperCase()+e.slice(1)}function I6(e){let t;for(let n of T6){let r=fs(n);if(r!==null&&r.family===e&&!r.legacyVersionFirst&&(t===void 0||x6(r,t)>0))t=r}return t?.base}function D6(e,t){let n=P6(e);switch(n.kind){case"ignored":{if(e.trim()==="")return"An empty availableModels entry was ignored.";let r=I6("opus");return`"${lr(e)}" in availableModels was ignored, because "availableModelsMatch" is "exact" and this name means a different model depending on the release and settings. List the model IDs you want to allow instead${r===void 0?"":`, for example "${r}"`}.`}case"family":{let r=t.filter((s)=>P6(s).kind!=="ignored").map((s)=>Kx(s.trim().toLowerCase()));if(Pa(e.trim().toLowerCase())&&L3e(n.family,r))return;let o=I6(n.family);return`"${lr(e)}" in availableModels allows every ${M3e(n.family)} model, including future releases, even though "availableModelsMatch" is "exact". To allow only some versions, list their model IDs instead${o===void 0?"":`, for example "${o}"`}.`}case"model":return;case"literal":return N3e(e,n.value)}}function N3e(e,t){let n=`"${lr(e)}" in availableModels allows only a model named exactly "${lr(t)}".`,r=t.replace(/(\d)\.(\d)/g,"$1-$2");if(r!==t){let s=r.startsWith("claude-")?r:`claude-${r}`;if(fs(s)!==null)return`${n} To allow a version, write it with a hyphen: "${lr(s)}".`}let o=new RegExp(`^(${Pi.join("|")})\\s+(\\d+)(?:\\.(\\d+))?$`).exec(t);if(o){let[,s,i,a]=o;return`${n} To allow a version, write its model ID, for example "claude-${s}-${i}${a!==void 0?`-${a}`:""}".`}return}function U3e(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function L6(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&U3e(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}import{closeSync as H3e,lstatSync as $3e,openSync as z3e,readdirSync as B1t,readSync as B3e,realpath as j3e,realpathSync as j1t,statSync as K1t}from"node:fs";import{join as W1t,posix as V1t,resolve as K3e}from"node:path";import{promisify as G3e}from"node:util";import{constants as Gx}from"fs";function M6(){return Gx.O_RDONLY|F3e()}function F3e(){if(st()==="windows")return 0;return Gx.O_NOFOLLOW|Gx.O_NONBLOCK}var oGt=G3e(j3e.native),W3e="connector-downloads";function V3e(e){if(typeof e!=="string")return!1;return e.split(/[\\/]/).slice(0,-1).some(N6)}function N6(e){return Mx(e)===W3e}var sGt=Le(new Map,(e)=>e.clear());function q3e(e){return e.replace(/[\\/][^\\/]*$/,"")}var By=Le(new Map,(e)=>e.clear());function jy(e){let t=By.get(e);if(t!==void 0)return t;let n=K3e(e).split(/[\\/]/),r=!1;for(let o=0;o<n.length&&!r;o++)if(N6(n[o]))r=J3e(`${n.slice(0,o+1).join("/")}/.gitignore`);if(By.size>=64)By.clear();return By.set(e,r),r}var Y3e=/^(download-[0-9a-f]{8}(-\d+)?(\.[^./\\]*)?|\.download-[0-9a-f]{8}(-\d+)?(\.[^./\\]*)?\.from\.json)$/;function Z3e(e){let t=$3e(e);if(!t.isFile()||t.size>3)return"";let n=z3e(e,M6());try{let r=Buffer.alloc(4),o=B3e(n,r,0,r.length,0);return r.subarray(0,o).toString("utf8")}finally{H3e(n)}}function J3e(e){let t=Oe();try{let n=Mu(t,e);if(t.readdirSync(q3e(e)).some((o)=>Y3e.test(o.name)))return!0;if(n.absentAt!==void 0)return!1;return["*",`*
|
|
154
154
|
`,`*\r
|
|
155
155
|
`].includes(Z3e(e))}catch{return!0}}function uf(e){return V3e(`${e}/.`)}var X3e=["allowManagedMcpServersOnly","allowedMcpServers","deniedMcpServers","disabledMcpjsonServers","enabledMcpjsonServers","enableAllProjectMcpServers","disableClaudeAiConnectors","managedMcpServers"];function Ky({slot:e,adminTiers:t}){return e?.allowManagedMcpServersOnly===!0||t.some((n)=>n.allowManagedMcpServersOnly===!0)}function Wx({slot:e,adminTiers:t}){return e?.allowedMcpServers??t.find((n)=>n.allowedMcpServers!==void 0)?.allowedMcpServers}function U6(e,t){return X3e.filter((n)=>e[n]!==void 0&&!Q3e(n,e,t))}function Q3e(e,t,n){let r=n.slot??{};switch(e){case"deniedMcpServers":return!0;case"allowManagedMcpServersOnly":return t.allowManagedMcpServersOnly===Ky(n);case"disableClaudeAiConnectors":return t.disableClaudeAiConnectors===(r.disableClaudeAiConnectors===!0||n.adminTiers.some((o)=>o.disableClaudeAiConnectors===!0));case"allowedMcpServers":return Gr(t.allowedMcpServers,Ky(n)?Wx(n):r.allowedMcpServers);case"disabledMcpjsonServers":return(t.disabledMcpjsonServers??[]).every((o)=>r.disabledMcpjsonServers?.includes(o)===!0);case"enabledMcpjsonServers":return(t.enabledMcpjsonServers??[]).every((o)=>r.enabledMcpjsonServers?.includes(o)===!0);case"enableAllProjectMcpServers":return(t.enableAllProjectMcpServers??!1)===(r.enableAllProjectMcpServers??!1);case"managedMcpServers":{let o=r.managedMcpServers??{};return Object.entries(t.managedMcpServers??{}).every(([s,i])=>Object.hasOwn(o,s)&&Gr(o[s],i))}}}import{userInfo as eJe}from"os";var F6="com.anthropic.claudecode",Gy="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Wy="HKCU\\SOFTWARE\\Policies\\ClaudeCode",df="Settings",qx="/usr/bin/plutil",H6=["-convert","json","-o","-","--"],$6=["-lint","-s","--"],Yx=5000,Vy=2097152,Ii="/mnt/c/Windows/System32/reg.exe",z6="unable to find the specified registry key or value",kn="/mnt/c/Program Files/ClaudeCode",Vx=Le({isCoworkCloud:void 0},(e)=>{e.isCoworkCloud=void 0});function Zx(){if(Vx.isCoworkCloud===void 0){let e=process.env.CLAUDE_CODE_ENTRYPOINT;Vx.isCoworkCloud=Np.some((t)=>t===e)}return Vx.isCoworkCloud}function pf(){if(process.platform!=="linux")return!1;let e=Zx();if(process.env.WSL_DISTRO_NAME&&!e)return!0;try{let t=iX("fs").readFileSync("/proc/version","utf8").toLowerCase();return dl(t)}catch{return!1}}function B6(){let e="";try{e=eJe().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${F6}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${F6}.plist`,label:"device-level managed preferences"}),t}var j6=512;function Jx(e){return e.map(tJe)}function tJe(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,loadedWithoutGuardHook:i,errorClass:a,errno:l,unreadCause:c,preserveOnWrite:d,mcpErrorMetadata:p,userWritable:f,wslIgnored:m,substituted:g,onlySubstitutes:_,removal:y,path:S,message:E,expected:b,suggestion:C,invalidValue:A,...R}=e,x=R;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,loadedWithoutGuardHook:i,errorClass:a,errno:l,unreadCause:c,preserveOnWrite:d,mcpErrorMetadata:p,userWritable:f,wslIgnored:m,substituted:g,onlySubstitutes:_,removal:y,path:ff(S),message:ff(E),expected:b===void 0?void 0:ff(b),suggestion:C===void 0?void 0:ff(C),invalidValue:typeof A==="string"?ff(A):void 0}}function ff(e){let t=V9(e.replace(/\s+/gu," "));return t.length>j6?`${t.slice(0,j6-1)}…`:t}function K6(e,t){if(t===null)return e;let n=[...t.values];return{settings:mn(vn(e.settings,n.filter(([,r])=>r===void 0).map(([r])=>r)),dr(Object.fromEntries(n.filter(([,r])=>r!==void 0))),(r,o)=>o),errors:[...e.errors,...t.errors]}}var ms="https://code.claude.com/docs/en",nJe=[{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:`${ms}/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:`${ms}/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==="hooks"&&e.code==="unrecognized_keys",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${ms}/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:`${ms}/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:`${ms}/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:`${ms}/iam#working-directories`}}],rJe={permissions:`${ms}/iam#configuring-permissions`,env:`${ms}/settings#environment-variables`,hooks:`${ms}/hooks`};function G6(e){let t=nJe.find((r)=>r.matches(e));if(!t)return null;let n={...t.tip};if(e.code==="invalid_value"&&e.enumValues&&!n.suggestion)n.suggestion=`Valid values: ${e.enumValues.map((r)=>`"${r}"`).join(", ")}`;if(!n.docLink&&e.path)n.docLink=rJe[Hu(e.path,".")];return n}var XGt=P(()=>dx(Jc(),{strictPolicyHelperKeys:!0}).strict());function W6(e){return e.code==="invalid_type"}function V6(e){return e.code==="invalid_value"}function oJe(e){return e.code==="unrecognized_keys"}function q6(e){return e.code==="too_small"}var sJe='a PreToolUse/PermissionRequest hook that cannot be loaded does not run, nor does any other hook of the document where "hooks" is listed here as ignored; fix or remove the entry. The managed settings document is not skipped for it, unlike a user or project settings file';function J6(e){return e.map((t)=>t.severity!=="warning"&&t.message.includes(ds)?{...t,message:t.message.replace(ds,()=>sJe),loadedWithoutGuardHook:!0}:t)}function Pn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function Y6(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function mf(e,t){return e.issues.flatMap((r)=>{if(r.code!=="invalid_union"||r.path.join(".")!=="attribution")return[r];let o=r.errors.flat().filter((s)=>s.path.length>0);return o.length>0?o.map((s)=>({...s,path:[...r.path,...s.path]})):[r]}).map((r)=>{let o=r.path.map(String).join("."),s=r.message,i,a,l,c,d;if(V6(r))a=r.values.map((f)=>String(f)),l=a.join(" | "),c=void 0,d=void 0;else if(W6(r)){l=r.expected;let f=Y6(r.message);c=f??Pn(r.input),d=f??Pn(r.input)}else if(q6(r))l=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,d=c;let p=G6({path:o,code:r.code,expected:l,received:c,enumValues:a,message:r.message,value:c});if(V6(r))i=a?.map((f)=>`"${f}"`).join(", "),s=`Invalid value. Expected one of: ${i}`;else if(W6(r)){let f=Y6(r.message)??Pn(r.input);if(r.expected==="object"&&f==="null"&&o==="")s="Invalid or malformed JSON";else s=`Expected ${r.expected}, but received ${f}`}else if(oJe(r)){let f=r.keys.join(", ");s=`Unrecognized ${Ts(r.keys.length,"field")}: ${f}`}else if(q6(r))s=`Number must be greater than or equal to ${r.minimum}`,i=String(r.minimum);return{file:t,path:o,message:s,expected:i,invalidValue:d,suggestion:p?.suggestion,docLink:p?.docLink}})}function iJe(e,t,n){if(!e||typeof e!=="object")return[];let r=e;if(!r.permissions||typeof r.permissions!=="object")return[];let o=r.permissions,s=[],i=new Map;for(let a of["allow","deny","ask"]){let l=o[a];if(!Array.isArray(l))continue;let c=l.filter((d)=>{if(typeof d!=="string")return s.push({file:t,path:`permissions.${a}`,message:`Non-string value in ${a} array was removed`,severity:"warning",invalidValue:d}),!1;let p=Qv(d,a);if(!p.valid){let f=`Invalid permission rule "${d}" was skipped: ${p.error}`;if(p.suggestion)f+=`. ${p.suggestion}`;return s.push({file:t,path:`permissions.${a}`,message:f,severity:"warning",invalidValue:d}),!1}return!0});if(n?.policySource&&a!=="allow"&&l.length>0&&c.length===0){if(!n.strictParseFollows)continue;i.set(a,"unreadable")}else if(c.length<l.length)i.set(a,"trimmed");o[a]=c}return gx("permissions",o,(a)=>i.get(a),(a)=>s.push({file:t,path:a.path,message:a.message,severity:"warning",...a.substituted&&{substituted:a.substituted}})),s}var aJe=new Set(ts);function lJe(e,t){if(!e||typeof e!=="object")return[];return[...g4(e,h4)?[{file:t,path:"hooks",message:`PreToolUse/PermissionRequest hooks are declared outside "hooks" (at the top level or under another key) — ${ds}.`,severity:"fatal",docLink:"https://code.claude.com/docs/en/hooks"}]:[],...cJe(e,t)]}function cJe(e,t){if(!("hooks"in e))return[];if(e.hooks===null||typeof e.hooks!=="object"||Array.isArray(e.hooks)){let o=Pn(e.hooks);if(Array.isArray(e.hooks)&&(e.hooks.some(oe)||Rv(e.hooks)))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o} — ${ds}.`,invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}];return delete e.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o}. This field was ignored.`,severity:"warning",invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}]}let n=e.hooks;if(yy(n))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received a single matcher — ${ds}.`,docLink:"https://code.claude.com/docs/en/hooks"}];let r=[];for(let o of Object.keys(n)){let s=hm(o);if(!aJe.has(o)){if(Ta(n[o],3,{matchersCount:!Array.isArray(n[o])})){r.push({file:t,path:`hooks.${s}`,message:`"${s}" is not a hook event, but it holds PreToolUse/PermissionRequest hooks — ${ds}.`,docLink:"https://code.claude.com/docs/en/hooks"});continue}delete n[o],r.push({file:t,path:`hooks.${s}`,message:`Unknown hook event "${s}" was ignored. Valid events: ${ts.join(", ")}`,severity:"warning",invalidValue:s,docLink:"https://code.claude.com/docs/en/hooks",preserveOnWrite:!0});continue}if(!Array.isArray(n[o])){let i=n[o],a=Pn(i);if(Xp.has(o)&&i!==null||Ta(i,3,{matchersCount:!1})){r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a} — ${ds}.`,invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks"});continue}delete n[o],r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a}. This entry was ignored.`,severity:"warning",invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks",...i!==null&&{preserveOnWrite:!0}})}}for(let[o,s]of Object.entries(n)){let{stripped:i,unloadableGuards:a}=y4(s,o);for(let l of a)r.push({file:t,path:l.aboutType?`hooks.${o}.${l.path}.type`:`hooks.${o}.${l.path}`,message:`${l.problem} — ${ds}.${l.aboutType?` Valid types: ${[..._y()].join(", ")}`:""}`,severity:"fatal",invalidValue:l.received,docLink:"https://code.claude.com/docs/en/hooks"});for(let l of i)r.push({file:t,path:l.aboutType?`hooks.${o}.${l.path}.type`:`hooks.${o}.${l.path}`,message:l.aboutType?`${l.problem}; entry ignored. Valid types: ${[..._y()].join(", ")}`:`${l.problem}; ${l.hookIndex===void 0?"matcher":"entry"} ignored.`,severity:"warning",invalidValue:l.received,docLink:"https://code.claude.com/docs/en/hooks",preserveOnWrite:!0})}if(r.length>0&&Object.keys(n).length===0)delete e.hooks;return r}var uJe=[{key:"allowedMcpServers",schema:ky},{key:"deniedMcpServers",schema:Py}];function dJe(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of uJe){if(!(s in r))continue;if(!Array.isArray(r[s])){if(n?.keepWholeFieldInvalid)continue;let c=r[s];delete r[s],o.push({file:t,path:s,message:`"${s}" must be an array; received ${Pn(c)}. This field was ignored.`,severity:"warning",invalidValue:c});continue}let a=r[s],l=[];for(let c=0;c<a.length;c++){let d=i().safeParse(a[c]);if(d.success)l.push(a[c]);else o.push({file:t,path:`${s}[${c}]`,message:`Invalid entry was ignored: ${d.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:a[c]})}if(l.length<a.length)r[s]=l}return o}var pJe=["strictKnownMarketplaces","blockedMarketplaces"];function fJe(e){if(!oe(e)||!Object.values(e).includes(null))return;for(let t of Ly())if(e[t]===null)delete e[t]}function mJe(e,t,n){if(!oe(e))return[];let r=[];for(let o of pJe){let s=e[o];if(!Array.isArray(s))continue;let i=[],a=[];for(let l=0;l<s.length;l++){let c=ef().safeParse(s[l]);if(!c.success){i.push(s[l]),a.push(l);continue}let d=mx(c.data);if(d===null){i.push(s[l]),a.push(l);continue}if(o==="blockedMarketplaces"){i.push(s[l]),a.push(l),r.push({file:t,path:`${o}[${l}]`,message:`Unenforceable entry was kept: ${d}; it can never match a marketplace source, but marketplace restrictions stay active`,severity:"warning"});continue}r.push({file:t,path:`${o}[${l}]`,message:`Invalid entry was ignored: ${d}`,severity:"warning"})}if(i.length<s.length)e[o]=i,n?.set(o,a)}return r}function gJe(e,t){if(!oe(e)||e.managedMcpServers===void 0)return[];let r=[],o=my(e.managedMcpServers,(s,i)=>r.push({file:t,path:s?`managedMcpServers.${s}`:"managedMcpServers",message:s?`Managed MCP server was ignored: ${i}`:i,severity:"warning"}));if(o===void 0)delete e.managedMcpServers;else e.managedMcpServers=o;return r}function hJe(e){if(!e||typeof e!=="object")return;let t=e.source;if(!t||typeof t!=="object")return;let n=t.source;return typeof n==="string"?n:void 0}function _Je(e){if(!e||typeof e!=="object")return!1;let t=e.source;if(!t||typeof t!=="object")return!1;let n=t.plugins;return Array.isArray(n)&&n.some(Vv)}function yJe(e,t){if(!e||typeof e!=="object")return[];let n=e,r="extraKnownMarketplaces";if(!(r in n))return[];let o=n[r];if(!o||typeof o!=="object"||Array.isArray(o)){let a=Pn(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object mapping marketplace names to declarations; received ${a}. This field was ignored.`,severity:"warning",invalidValue:a}]}let s=o,i=[];for(let a of Object.keys(s)){let l=sx().safeParse(s[a]),c,d=!1;if(!l.success){let p=hJe(s[a]);if(p!==void 0&&!lZ.has(p)||_Je(s[a]))continue;c=Cy(l.error.issues)}else if(l.data.source.source==="settings"&&l.data.source.name!==a)c=`key "${ko(a)}" must match the settings source name "${ko(l.data.source.name)}"`;if(c!==void 0)i.push({file:t,path:`${r}.${ko(a)}`,message:d?"Marketplace entry was ignored: its name reads like an official Anthropic or Claude marketplace. It stays in this file: rename it (the key and the source's name) to use it, or delete it. If /plugin also shows a marketplace of this name as refused, remove that one in /plugin → Marketplaces once this entry is renamed or deleted.":`Invalid marketplace entry was ignored: ${c}`,severity:"warning",...d&&{preserveOnWrite:!0}}),delete s[a]}return i}function SJe(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!oe(o)||!Array.isArray(o.options)){let l=oe(o)?`options: ${Pn(o.options)}`:Pn(o);return delete n[r],[{file:t,path:r,message:`"${r}" must be an object with an "options" array of { model, label?, description?, behavesAs? } rows; received ${l}. This field was ignored.`,severity:"warning",invalidValue:l}]}let s=[];if("replaceBuiltInOptions"in o&&typeof o.replaceBuiltInOptions!=="boolean"){let l=Pn(o.replaceBuiltInOptions);delete o.replaceBuiltInOptions,s.push({file:t,path:`${r}.replaceBuiltInOptions`,message:`"replaceBuiltInOptions" must be true or false; received ${l}. This entry was ignored (the rows are added to the built-in lineup).`,severity:"warning",invalidValue:l})}let i=o.options,a=[];for(let l=0;l<i.length;l++){let c=lx().safeParse(i[l]);if(c.success){a.push(i[l]);continue}s.push({file:t,path:`${r}.options.${l}`,message:`${bJe(c.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:Pn(i[l])})}if(a.length!==i.length)o.options=a;return s}function EJe(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let n=e;if(!("modelPricing"in n)||n.modelPricing===void 0)return[];let r=n.modelPricing;if(!r||typeof r!=="object"||Array.isArray(r))return delete n.modelPricing,[{file:t,path:"modelPricing",message:`"modelPricing" must be an object; received ${Pn(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!ax().safeParse(o.multiplier).success)s.push({file:t,path:"modelPricing.multiplier",message:'"multiplier" must be a number greater than 0 and at most 10. It was ignored.',severity:"warning",invalidValue:o.multiplier}),delete o.multiplier;if(o.overrides!==void 0){let i=o.overrides;if(!i||typeof i!=="object"||Array.isArray(i))s.push({file:t,path:"modelPricing.overrides",message:`"overrides" must be an object mapping model ID to rates; received ${Pn(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let l of Object.keys(a)){let c=ix().safeParse(a[l]);if(c.success&&l!=="constructor"&&l!=="__proto__")continue;let d=c.success?void 0:c.error.issues[0];s.push({file:t,path:`modelPricing.overrides.${ko(l)}`,message:`Invalid pricing row was ignored (${d?`${d.path.join(".")||"row"}: ${d.message}`:"not a model ID"}).`,severity:"warning",invalidValue:a[l]}),delete a[l]}}}return s}function bJe(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function CJe(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||AJe(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[TJe(o,t,n?.policySource===!0)]}function AJe(e){return typeof e==="string"&&of.includes(e)}var RJe="crossSessionInbound";function OJe(e){let t=of.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${ko(e).replace(/^<key>$/,"<value>")}"`:Pn(e);return`must be one of ${t}; received ${n}`}function TJe(e,t,n=!1){let r=of.map((s)=>`"${s}"`).join(", "),o=n?'In managed settings an unrecognized value is treated as "refuse" (the most restrictive): cross-session messages to this session are turned away until an administrator fixes it.':"This value was ignored; while it is present, cross-session messages are held for your approval instead of being delivered. Set it to one of the values above.";return{file:t,path:RJe,message:`"crossSessionInbound" ${OJe(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}var Z6="remoteControl.shareHostProfile";function wJe(e,t,n){if(!oe(e)||e.remoteControl===void 0)return[];let r=n?.policySource===!0,o=xy.map((f)=>`"${f}"`).join(", "),s=r?'In managed settings this is treated as "off" (the most restrictive): Remote Control environments report nothing about this machine until an administrator fixes it.':"While it is present, Remote Control environments report nothing about this machine.",i=(f)=>({file:t,path:Z6,message:`${f}. ${s}`,severity:"warning",expected:o,...r?{statusOnly:!0}:{preserveOnWrite:!0}}),a=(f)=>typeof f==="string"?`"${ko(f).replace(/^<key>$/,"<value>")}"`:Pn(f),l=e.remoteControl;if(!oe(l)){if(r)e.remoteControl={shareHostProfile:"off"};else delete e.remoteControl;return[i(`"remoteControl" must be an object like { "shareHostProfile": ${o.replace(/, /g," | ")} }; received ${a(l)}`)]}let c=[],d=Object.keys(l).filter((f)=>f!=="shareHostProfile");if(d.length>0){if(r)l.shareHostProfile="off";c.push(i(`"remoteControl" has an unrecognized key ${d.map((f)=>`"${ko(f)}"`).join(", ")} (its only key is "shareHostProfile")`))}let p=l.shareHostProfile;if(p!==void 0&&!(typeof p==="string"&&xy.includes(p))){if(r)l.shareHostProfile="off";else delete l.shareHostProfile;c.push(i(`"${Z6}" must be one of ${o}; received ${a(p)}`))}return c}var vJe=["enabledMcpjsonServers","disabledMcpjsonServers"],xJe=/^[A-Za-z0-9_-]+$/;function kJe(e){if(!oe(e))return;for(let t of vJe){let n=e[t];if(typeof n==="string"&&xJe.test(n))e[t]=[n]}}function gf(e,t,n){let r=[...D9(e,t)];if(fJe(e),!n?.policySource)kJe(e);return r.push(...iJe(e,t,{policySource:n?.policySource,strictParseFollows:n?.mcpServerEntrySalvageOnly}),...lJe(e,t),...yJe(e,t),...SJe(e,t),...EJe(e,t),...CJe(e,t,{policySource:n?.policySource}),...wJe(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:dJe(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly}),...n?.mcpServerEntrySalvageOnly?gJe(e,t):[],...n?.mcpServerEntrySalvageOnly?mJe(e,t,n.marketplacePatternIndexMapOut):[]),r}function ok(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),C6.filter((n)=>t.has(n))}function LJe(){return Mt(Ai(),"managed-settings.json")}function Q6(e){return e.map((t)=>{let{invalidValue:n}=t,r=n!==void 0&&n!==null,o=r?Sb(n):void 0,s=o===void 0?void 0:ln(o);return{...t,path:ln(t.path),message:ln(t.message),...t.expected!==void 0&&{expected:ln(t.expected)},...t.suggestion!==void 0&&{suggestion:ln(t.suggestion)},...r&&(o===void 0||typeof n==="string"||s!==o)&&{invalidValue:s}}})}function sk(e){if(e.diskless)return{settings:null,errors:[],documentHasPolicyContent:!1,loadState:"absent"};let t,n=(E)=>{if(E===E3)return!0;return t??=e.asksOrganization?.()===!0,t&&E()},r=!1,o={},s=new Set,i=t3(e,(E,b,C)=>{if(E.settings===null){if(!n(C))return E;return PS.forEach((A)=>s.add(A)),{...E,errors:Q6(E.errors)}}if(!n(C))return Object.assign(o,Ri(E.settings,xi)),E;return r=!0,{...E,settings:{},errors:Q6(E.errors)}});if(!r)return s.size===0?i:{...i,lostSignInPins:[...s]};let a=[],l=[],c=t3(e,(E,b,C)=>{if(E.settings===null||!n(C))return{...E,settings:E.settings&&{},errors:[]};let A=MJe(E,E.settings,b);for(let R of PS)if(E.settings[R]!==void 0&&A.settings?.[R]===void 0)s.add(R);return a.push([b,Object.keys(A.settings??{})]),l.push(...A.errors.slice(E.errors.length)),A}),d=[...i.errors,...l],p=i.settings??{},f=c.settings??{},m=!ru({...i,settings:p})&&{heldOnly:!0};if(Object.keys(f).length===0)return{...i,errors:d,...m,lostSignInPins:[...s]};let g=Object.keys(p).length===0,_={...g?f:vn(Zy([p,f],"merge",!1,0).admin,"parentSettingsBehavior"),...Ri(p,"parentSettingsBehavior"),...o},y=_,S=p;for(let[E,b]of a)for(let C of b)if(C in S&&Gr(y[C],S[C]))d.push({file:E,path:ln(C),message:`In a cloud session that takes its managed settings from your organization, a managed settings file may only restrict: "${ln(C)}" was ignored in ${ln(E)}, since another managed settings document sets it and this one adds nothing to it.`,severity:"warning",statusOnly:!0,userWritable:!0});return{...g?c:i,settings:_,errors:d,...m,lostSignInPins:[...s],...!cu(p)&&{onlyHeldContent:!0},settingsNotHeld:p,heldOffPlugins:Object.keys(f.enabledPlugins??{}).filter((E)=>p.enabledPlugins?.[E]===void 0),heldAllowLists:fk.filter((E)=>f[E]!==void 0&&p[E]===void 0)}}function MJe(e,t,n){let r=a6(t),o=NJe(t,r).map((s)=>({...s,key:ln(s.key)}));if(o.length===0)return e;if(!e3.has(n))e3.add(n),G(`${ln(n)}: not taken as written: ${o.map(({key:s})=>s).join(", ")}: this session takes its managed settings from its organization, and a managed settings file may only restrict there`,{level:"warn"});return{...e,settings:r,errors:[...e.errors,...o.filter(({key:s})=>!Li(s)).map(({key:s,became:i})=>({file:n,path:s,message:`In a cloud session that takes its managed settings from your organization, a managed settings file may only restrict: "${s}" ${i} in ${ln(n)}.`,severity:"warning",statusOnly:!0,userWritable:!0}))]}}function NJe(e,t){let n=(r,o)=>o==="disableAllHooks"&&e.disableAllHooks===!0&&t.allowManagedHooksOnly===!0?'was taken as "allowManagedHooksOnly"':o==="allowManagedHooksOnly"&&r===!0?'was set by "disableAllHooks"':r===void 0?"was ignored":"was kept in part";return Object.keys(e).flatMap((r)=>{let o=e[r],s=t[r];if(Gr(o,s))return[];if(!oe(o)||!oe(s))return[{key:r,became:n(s,r)}];return Object.keys(o).filter((i)=>!Gr(o[i],s[i])).map((i)=>({key:`${r}.${i}`,became:n(s[i],r)}))})}function S3(e){return st()==="wsl"&&(!e||Lx())}var e3=Le(new Set,(e)=>e.clear());function t3(e,t){let n=e.mdm?.()?.heldDocuments??[];if(S3(e.asksOrganization?.()===!0)){let r=La(lk({...e,file:()=>({settings:null,errors:[]})}));if(e.wslInherits?.()){let o=n.length===0?void 0:r||La(hf(kn,e.store)),s=hf(kn,e.store,t,o?n:[]);if(o??(La(s)||r))return s;let i=hf(Ai(),e.store,t,n);return{...i,errors:[...s.errors,...i.errors],loadState:Po(s.loadState,i.loadState)}}if(r)return hf(null,e.store,t,n)}return hf(Ai(),e.store,t,n)}var E3=()=>!0;function Xx(e,t,n){n.push(...t.errors);let{settings:r}=t;if(!r||Object.keys(r).length===0)return;for(let[o,s]of My){let i=o.split(".");if(pt(r,i)===void 0)continue;let a=t.errors.find((d)=>d.substituted&&d.path===o),l=a!==void 0,c=pt(e.merged,i);if(l&&c!==void 0&&!e.floors.has(o)){let d=i.at(-1);if(s.inert.has(s.read(c))){Kq(r,i),n.push({file:a.file,path:o,message:`That substitute is not applied: "${d}" keeps the value an earlier managed-settings document of this folder wrote.`,severity:"warning",statusOnly:!0});continue}n.push({file:a.file,path:o,message:`That substitute also displaces the wider "${d}" an earlier managed-settings document of this folder wrote, until this document is fixed.`,severity:"warning",statusOnly:!0})}if(l)e.floors.add(o);else e.floors.delete(o)}if(e.merged=mn(e.merged,r,Wr),e.found=!0,cu(r)&&!t.errors.some((o)=>o.onlySubstitutes))e.authored=!0}function ik(e){return e.endsWith(".json")&&!e.startsWith(".")}function UJe(e){return(e.isFile()||e.isSymbolicLink())&&ik(e.name)}function n3(e,t,n,r){let o=e.managedFileProtections,s={file:r,folder:e.managedDocumentLinks.folderIsLink.get(t)===!1?o.folderOwners.get(t):void 0,posix:st()!=="windows"&&!n.startsWith(kn)};return o.note(n,uP({...s,linked:e.managedDocumentLinks.isLinked(n)})),()=>ak(e,n,s.file,s.folder)}function ak(e,t,n,r){let o=process.geteuid?.(),s=process.getuid?.();if(S3(!0)&&(t===Ii||t.startsWith(`${kn}${DJe}`)))return r3;if(o===0||s===0)return!0;if(st()==="windows"||o===void 0)return r3;let a=e.managedDocumentLinks.linkOf(t),l={uids:s===void 0||s===o?[o]:[o,s],groups:()=>[...process.getgroups?.()??[],...process.getegid?[process.getegid()]:[],...process.getgid?[process.getgid()]:[]]};if(Vw(l,n,a===null?r:n)!==!1||a?.kind==="unverified")return!0;let d=e.policy.writableNow??=new Map,p=d.get(t)??Ww(t);if(d.set(t,p),p!=="no")return!0;let f=e.policy.walkedDocuments??=new Map,m=f.get(t)??O2(t,l,e.policy.certainDirectories??=new Map);return f.set(t,m),m}var r3=!1;function o3(e,t,n,r){let o=e.managedDocumentLinks;o.noteWalked(Mt(t,...n),()=>S2(t,n,r,o.folderIsLink,e.managedFileProtections.folderOwners))}function hf(e,t,n=(o)=>o,r=[]){let o=[],s={merged:{},found:!1,authored:!1,floors:new Set},i=!1,a="absent";for(let{path:p,parsed:f}of r)Xx(s,n(f,p,E3),o),i||=ou(f),a=Po(a,Di(f));if(e===null)return s3(s,o,i,a,t);let l=su(Mt(e,"managed-settings.json"),t,void 0,!0),c=()=>!1;if(Di(l)!=="absent")o3(t,e,["managed-settings.json"]),c=n3(t,ut(e),Mt(e,"managed-settings.json"),l.fileOwner);Xx(s,n(l,Mt(e,"managed-settings.json"),c),o),i||=ou(l),a=Po(a,Di(l));let d=Mt(e,"managed-settings.d");try{let p=t.folderListingForPolicyWalk(d),f,m;if(p!==void 0)f=p;else{let g=Oe().readdirSync(d).filter(UJe);f=g.map((_)=>_.name).sort(),m=new Set(g.filter((_)=>!_.isFile()).map((_)=>_.name)),t.noteWalkListing(d,f)}for(let g of f){let _=su(Mt(d,g),t,void 0,!0),y=()=>!1;if(Di(_)!=="absent")o3(t,e,["managed-settings.d",g],m?.has(g)),y=n3(t,d,Mt(d,g),_.fileOwner);Xx(s,n(_,Mt(d,g),y),o),i||=ou(_),a=Po(a,Di(_))}}catch(p){let f=le(p);if(f!=="ENOENT"&&f!=="ENOTDIR")G(`managed-settings.d read failed: ${p}`,{level:"error"}),o.push(Ef(d,p,"directory")),a="didNotLoad",n({settings:null,errors:[]},d,()=>!0)}return s3(s,o,i,a,t)}function s3(e,t,n,r,o){let s=e.found&&lu(e.merged)?e.merged:null;if(s?.forceLoginOrgUUID!==void 0)o.managedFileProtections.setsOrgPin=!0;return{settings:s,errors:t,documentHasPolicyContent:n,loadState:r,...s!==null&&!e.authored&&cu(s)&&{onlySubstitutes:!0}}}function FJe(e,t){if(et(e))VJe(t);else G(ln(`settings file read failed at ${t}: ${e}`),{level:"error"})}function su(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{...s,settings:s.settings?dr(s.settings):null};let i,a=KJe(e,n,r,({ino:l,size:c,mtimeMs:d,ctimeMs:p})=>{i={ino:l,size:c,mtimeMs:d,ctimeMs:p}});if(n===void 0&&a.loadState==="absent")i??=null;if(i!==void 0)t.noteFirstRead(e,i);return t.parsedFiles.set(o,a),{...a,settings:a.settings?dr(a.settings):null}}function lk(e){let t=e.mdm?.();if(!t)return{settings:null,errors:[],documentHasPolicyContent:!1,loadState:"absent"};return{settings:t.settings&&Object.keys(t.settings).length>0?t.settings:null,errors:ZJe(t,()=>ck(e),()=>e.file?.()??sk(e)),documentHasPolicyContent:ou(t),loadState:Di(t),...t.onlySubstitutes&&{onlySubstitutes:t.onlySubstitutes}}}function yf(e,t){let n=a3.get(e),r=n?.get(t);if(r)return i3(r);let o=HJe(e,t);if(n)n.set(t,o);else a3.set(e,new Map([[t,o]]));return i3(o)}function i3(e){return{settings:e.settings&&dr(e.settings),errors:e.errors.map((t)=>({...t})),documentHasPolicyContent:e.documentHasPolicyContent,loadState:e.loadState,removed:e.removed,...e.onlySubstitutes&&{onlySubstitutes:e.onlySubstitutes}}}var a3=new WeakMap;function HJe(e,t){let n=dr(e),r=gf(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=yx(R3(t,o),t,n).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...mf(s.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad",removed:[]};let i=[...D3(r,s.data,o),...o],a=e,l=Object.keys(s.data).length>0?s.data:null;return{settings:l,errors:i,documentHasPolicyContent:M3(e,s.data),loadState:"loaded",removed:Object.keys(a).filter((c)=>b3(c,a[c])&&s.data[c]===void 0&&i.every((d)=>d.statusOnly||d.path!==c&&!d.path.startsWith(`${c}.`))),...l!==null&&o.some((c)=>c.onlySubstitutes)&&{onlySubstitutes:!0}}}function b3(e,t){let n=Ly();return n.includes(e)||eu.some(({alias:r,canonical:o})=>r===e&&n.includes(o))?_x(e,t):Ny(e)&&C3(e,t)}function C3(e,t){return t===null||oe(t)&&Object.keys(t).length>0&&Object.entries(t).every(([n,r])=>{let o=`${e}.${n}`;return _x(o,r)||Ny(o)&&C3(o,r)})}function Li(e){return qw()&&(e==="managedMcpServers"||e.startsWith("managedMcpServers."))}var nS=["managedMcpServers","isolation","attributionProjectPolicy"],$Je=[...nS,"deniedModels","availableModelsMatch"];function A3(e,t){if(!oe(e))return[];let n=[];for(let r of $Je){if(!(r in e))continue;if(delete e[r],!Li(r))n.push({file:t,path:r,message:`"${r}" is only honored from managed settings and was ignored here.`,severity:"warning",preserveOnWrite:!0})}return n}function R3(e,t){return(n)=>{if(Li(n.path))return;if(t.push({file:e,path:n.path,message:n.message,severity:"warning",...n.statusOnly&&{statusOnly:n.statusOnly},...n.startupFatal&&{startupFatal:n.startupFatal},...n.substituted&&{substituted:n.substituted},...n.onlySubstitutes&&{onlySubstitutes:n.onlySubstitutes},...n.removal&&{removal:n.removal}}),n.statusOnly||n.startupFatal)G(ln(`${e}: ${n.path}: ${n.message}`),{level:n.startupFatal?"error":"warn"})}}function ck(e){let t=e?.remote?e.remote():m6((c)=>yf(c,"remote managed settings").settings),n=!e?.remote&&!Li("managedMcpServers")&&u6()?[{file:"remote managed settings",path:"managedMcpServers",message:"The organization's MCP servers in the cached remote settings are withheld until the server confirms them this session; they connect as soon as it does.",severity:"warning",statusOnly:!0}]:[],r=e?.remote?void 0:r6(),o=(r?.state==="stale_cache"||r?.state==="failed")&&r.failure.errorKind==="ruled_empty"?Jx(r.failure.rulings??[]):[];if(!t||Object.keys(t).length===0)return{settings:null,errors:[...n,...o],servedSnapshot:!1,documentHasPolicyContent:!1};let{settings:s,errors:i,documentHasPolicyContent:a,onlySubstitutes:l}=yf(t,"remote managed settings");return{settings:s,errors:[...n,...o,...Jx(i)],servedSnapshot:o6(t),documentHasPolicyContent:a,...l&&{onlySubstitutes:l}}}var l3="parent managed settings";function zJe(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let n=yf(t,l3);for(let r of nS)if(n.settings?.[r]!==void 0&&!Li(r))n.errors.push({file:l3,path:r,message:`"${r}" is only honored from the organization's managed settings sources (server-managed, MDM, managed-settings.json), not from settings a host passes in, and was ignored here.`,severity:"warning",statusOnly:!0});return n}function BJe(e){return null}function O3(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=qw(),r=e.store.inlineFlagParse;if(r?.inline!==t||r.desktopSupplied!==n)r={inline:t,desktopSupplied:n,parsed:jJe(t)},e.store.inlineFlagParse=r;let{settings:o,errors:s}=r.parsed;return{settings:o&&dr(o),errors:s.map((i)=>({...i}))}}function jJe(e){let t=dr(e),n=[...A3(t,"SDK inline settings"),...gf(t,"SDK inline settings")],r=Dy(t).safeParse(t);if(!r.success)return{settings:null,errors:[...n,...mf(r.error,"SDK inline settings")]};if(n.some((o)=>o.severity==="fatal"))return{settings:null,errors:n};return{settings:r.data,errors:n}}var Sf=2097152;function KJe(e,t,n,r){try{let o;if(t!==void 0)o=t;else{let s=n||GJe(e)?tl(Oe(),e):Mu(Oe(),e);if(n){let i={};o=bi(s.resolvedPath,Sf,(l)=>{i.owner={uid:l.uid,gid:l.gid,mode:l.mode},r?.(l)});let a=Xy(o,e,n);return i.owner?{...a,fileOwner:i.owner}:a}o=bi(s.resolvedPath,Sf,r)}return Xy(o,e,n)}catch(o){return YJe(o,e)}}function Xy(e,t,n){if(e.trim()==="")return{settings:{},errors:[],loadState:"loaded"};let r=Sa(e,!1);if(n){if(!oe(r))return{settings:null,errors:[rS(t)],loadState:"didNotLoad"};let a=dr(r),l=gf(a,t,{skipMcpServerEntryFilter:!0,policySource:!0}),c=[],d=yx(R3(t,c),t,a).safeParse(a);if(!d.success)return{settings:null,errors:[...l,...mf(d.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad"};return{settings:d.data,errors:[...D3(l,d.data,c),...c],documentHasPolicyContent:M3(r,d.data),loadState:"loaded"}}let o=dr(r),s=[...A3(o,t),...gf(o,t)],i=Dy(o).safeParse(o);if(!i.success){let a=mf(i.error,t);return{settings:null,errors:[...s,...a]}}if(s.some((a)=>a.severity==="fatal"))return{settings:null,errors:s};return{settings:i.data,errors:s}}function rS(e,{userWritable:t=!1}={}){return t?{file:e,path:"",message:`Managed settings document (${e}) could not be parsed as a JSON object; none of its settings are in effect. Fix or remove it.`,severity:"warning",statusOnly:!0,userWritable:!0}:{file:e,path:"",message:"Managed settings document could not be parsed as a JSON object; none of its settings are in effect. Fix or remove it.",startupFatal:!0}}function GJe(e){let t=Ja();if(t===null)return!1;let n=Ze(tS(ut(e))),r=ut(t);return n===Ze(r)||n===WJe(r)}var Qx;function WJe(e){if(Qx?.lexical!==e){let t=tS(e);Qx={lexical:e,physical:Ze(Mt(Zf(t)??t,IJe(e)))}}return Qx.physical}function VJe(e){G(ln(`Broken symlink or missing file encountered for settings.json at path: ${e}`))}function qJe(){return{settings:null,errors:[],loadState:"absent"}}function YJe(e,t){if(pI(e))throw e;if(FJe(e,t),et(e))return qJe();return{settings:null,errors:[Ef(t,e)],loadState:"didNotLoad"}}function Ef(e,t,n="file"){return{file:e,path:"",message:`${n==="directory"?"Managed settings drop-in directory":"Settings file"} could not be read: ${t instanceof Error?t.message:String(t)}`,severity:"fatal",errorClass:"unreadable",...le(t)!==void 0&&{errno:le(t)}}}function T3(e){return{file:e,path:"wslInheritsWindowsSettings",message:`"wslInheritsWindowsSettings" in ${e} holds a value that cannot be read (it takes true or false) and no Windows administrator policy is deployed beside it (HKLM or ${kn}), so whether WSL inherits Windows policy is unknown: no Windows or managed-file policy is in effect (/etc/claude-code is not read beneath it), and unless server-managed settings supply the policy — they apply regardless — sign-in and policy enforcement fail closed until the flag is fixed.`,severity:"fatal",statusOnly:!0}}function c3(e){return e.path==="wslInheritsWindowsSettings"&&e.severity==="fatal"}function ZJe(e,t,n){let r=e.withheldFlagRecord&&n().heldOnly===!0?[...e.errors,e.withheldFlagRecord]:e.errors;if(!r.some(c3))return r;if(!ru(t()))return r;return r.map((o)=>c3(o)?{...o,severity:"warning"}:o)}function tk(e,t){switch(e){case"userSettings":return ut(Ut());case"policySettings":return ut(qy(t));case"projectSettings":return ut(t.projectConfigDir??qy(t));case"localSettings":{if(t.projectConfigDir!==void 0)return ut(t.projectConfigDir);return uk(qy(t),t.canonicalGitRoot)}case"flagSettings":return t.flagPath?tS(ut(t.flagPath)):ut(qy(t))}}function qy(e){if(e.cwd===null)throw new ku;return e.cwd}function uk(e,t){let n=JJe(e,t);if(n.decided!==void 0)return n.decided;if(!t5e(n.root))return n.cwdResolved;return n.root}function JJe(e,t){let n=t?.(e);if(!n)return{decided:ut(e)};let r=ut(n),o=ut(e);if(r===o)return{decided:r};let s;try{s=n5e()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function XJe(e){return ls().localStoreProbes.canonicalRootOwnerUids(e,QJe)}function QJe(e){let t=Oe(),n=null;try{n=t.lstatSync(Mt(e,".claude")).uid}catch(r){if(!et(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:e5e(e),claudeEntryUid:n}}function e5e(e){let t=Oe();try{return t.lstatSync(Mt(e,".git")).uid}catch(n){throw n}}function t5e(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return G(`localSettings: not canonicalizing the consent store to ${e} — this platform has no uid semantics to verify directory ownership with, so the store stays at the session cwd (canonicalization is POSIX-only)`,{level:"warn"}),!1;let t=typeof process.geteuid==="function"?process.geteuid():process.getuid?.();try{let{rootUid:n,gitEntryUid:r,claudeEntryUid:o}=XJe(e);if(n===t&&r===t&&(o===null||o===t))return!0;return G(`localSettings: not canonicalizing the consent store to ${e} — it (uid ${n}), its .git entry (uid ${r}), or its .claude entry (uid ${o??"absent"}) is not owned by the current user (uid ${t}); the store stays at the session cwd (the pre-canonicalization behavior). If you own this repo, chown it (including .git and .claude) or run from a directory you own.`,{level:"warn"}),!1}catch(n){return G(`localSettings: not canonicalizing the consent store to ${e} — its ownership could not be verified (${n instanceof Error?n.message:String(n)}); the store stays at the session cwd`,{level:"warn"}),!1}}function n5e(){return ls().localStoreProbes.normalizedRealHomeDir(r5e)}function r5e(){let e=Zf(PJe());if(e===null)throw Error("home directory realpath unavailable");return Ze(e)}var u3={default:"settings.json",cowork:"cowork_settings.json"};function o5e(e){if(e.coworkPlugins||Dt.CLAUDE_CODE_USE_COWORK_PLUGINS)return u3.cowork;return u3.default}function iu(e,t){switch(e){case"userSettings":return Mt(tk(e,t),o5e(t));case"projectSettings":case"localSettings":{if(t.diskless||t.cwd===null&&t.projectConfigDir===void 0)return;let n=tk(e,t),r=Mt(n,Qy(e));if(dk(t)&&uf(n)&&jy(n))return;return r}case"policySettings":return LJe();case"flagSettings":return t.flagPath}}function Qy(e){switch(e){case"projectSettings":return Mt(".claude","settings.json");case"localSettings":return Mt(".claude","settings.local.json")}}function w3(e){if(e.diskless)return;if(e.cwd===null||uk(e.cwd,e.canonicalGitRoot)===ut(e.cwd))return;if(e.projectConfigDir!==void 0)return;let t=Mt(ut(e.cwd),Qy("localSettings"));if(dk(e))return;return t}function dk(e){let t=e.projectConfigDir??e.cwd;return t!==null&&uf(ut(t))&&jy(ut(t))}function s5e(e,t){if(e!=="projectSettings"&&e!=="localSettings"||t.diskless||t.cwd===null&&t.projectConfigDir===void 0)return[];if(!dk(t))return[];let n=[],r=tk(e,t),o=Mt(r,Qy(e));if(uf(r)&&jy(r))n.push(o);if(e==="localSettings"&&t.cwd!==null&&t.projectConfigDir===void 0&&uk(t.cwd,t.canonicalGitRoot)!==ut(t.cwd)){let s=Mt(ut(t.cwd),Qy("localSettings"));if(uf(ut(t.cwd)))n.push(s)}return n}var i5e=" is not used: it is in a connector-downloads folder, where Claude Code saves files from claude.ai connectors, so no settings are taken from it. To use it, move or rename the folder named connector-downloads.";function a5e(e){return{file:e,path:"",message:`${ln(e)}${i5e}`,severity:"fatal",statusOnly:!0}}function l5e(e,t){let n=t.repoTierFreeze.tier(e);if(n!==void 0)return n.settings;return t.perSource.get(e)}function v3(e,t){let n=l5e(e,t.store);if(n!==void 0)return n;let r=H5e(e,t),o=r&&_f(e,r,t);return t.store.perSource.set(e,o),o}function x3(e){return(e.parentSettingsBehavior??(Up()?"merge":"first-wins"))==="merge"}function c5e(e,t=!1){return!e||x3(e)||t}var u5e=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function d5e(e){let t={};for(let{path:n,restrictive:r}of xo()){let o=pt(e,n);if(n[0]==="sandbox"&&Ea(r).includes(o))jt(t,n,o)}return t.sandbox??{}}function k3(e){let t=e?.disableAllHooks;return t!==void 0&&t!==null&&t!==!1&&t!=="false"}function nk(e,t,n,r){let o={};if(e.allowManagedHooksOnly===!0||e.disableAllHooks===!0||k3(n))o.allowManagedHooksOnly=!0;if(e.disableSkillShellExecution===!0)o.disableSkillShellExecution=!0;if(t.hooks===void 0&&!Object.values(t.enabledPlugins??{}).some((a)=>a!==!1&&a!==void 0)){if(e.allowedHttpHookUrls?.length===0)o.allowedHttpHookUrls=[];if(e.httpHookAllowedEnvVars?.length===0)o.httpHookAllowedEnvVars=[]}if(e.disableCommandPluginSources===!0)o.disableCommandPluginSources=!0;if(e.disableSideloadFlags===!0)o.disableSideloadFlags=!0;if(e.disableWindowsBashCommandSplit===!0)o.disableWindowsBashCommandSplit=!0;if(e.allowManagedMcpServersOnly===!0)o.allowManagedMcpServersOnly=!0;if(e.disableClaudeAiConnectors===!0)o.disableClaudeAiConnectors=!0;if(e.syncClaudeAiSkills===!1)o.syncClaudeAiSkills=!1;if(e.syncClaudeAiPlugins===!1)o.syncClaudeAiPlugins=!1;if(e.remoteTools?.allowUnattendedServing===!1)o.remoteTools={...o.remoteTools,allowUnattendedServing:!1};if(e.allowManagedPermissionRulesOnly===!0)o.allowManagedPermissionRulesOnly=!0;if(e.disableAutoMode==="disable")o.disableAutoMode="disable";let s=e.remoteControl?.shareHostProfile;if(s==="off"||s==="basic")o.remoteControl={...o.remoteControl,shareHostProfile:s};if(L6(e.attribution,e.includeCoAuthoredBy)==="disabled")o.attribution={...o.attribution,commitTrailers:!1};if(e.attribution?.sessionUrl===!1)o.attribution={...o.attribution,sessionUrl:!1};let i=e.strictPluginOnlyCustomization;if(i===!0||Array.isArray(i)&&i.length>0)o.strictPluginOnlyCustomization=i;if(e.deniedMcpServers)o.deniedMcpServers=e.deniedMcpServers;if(e.blockedMarketplaces?.length)o.blockedMarketplaces=e.blockedMarketplaces;if(e.deniedModels&&e.deniedModels.length>0)o.deniedModels=e.deniedModels;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)o.forceLoginOrgUUID=e.forceLoginOrgUUID;for(let a of nu)if(t[a]===void 0&&e[a])Object.assign(o,{[a]:e[a]});if(e.enforceAvailableModels===!0)o.enforceAvailableModels=!0;if(e.availableModelsMatch==="exact")o.availableModelsMatch="exact";if(e.permissions){let a=Ri(e.permissions,["deny","ask"]);for(let l of["deny","ask"]){let c=a[l];if(c!==void 0)a[l]=c.filter((d)=>{if(!Hp.test(d))return!0;return G(`Ignoring ${l} rule "${d}" from the parent process's managed settings: a rule starting with "!" removes paths from the rules listed before it instead of restricting anything, so it is not merged into the policy rules. Spell the deny without the exception instead.`,{level:"warn"}),!1})}if(e.permissions.disableBypassPermissionsMode==="disable")a.disableBypassPermissionsMode="disable";if(e.permissions.disableAutoMode==="disable")a.disableAutoMode="disable";if(e.permissions.blockReadsOutsideWorkingDirectories===!0)a.blockReadsOutsideWorkingDirectories=!0;if(e.permissions.blockWritesOutsideWorkingDirectories===!0)a.blockWritesOutsideWorkingDirectories=!0;if(e.permissions.denyInsteadOfPrompting===!0)a.denyInsteadOfPrompting=!0;if(t.allowManagedPermissionRulesOnly!==!0){let{allow:l,additionalDirectories:c}=e.permissions;if(l&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)a.allow=l;if(c)a.additionalDirectories=c}if(Object.keys(a).length>0)o.permissions=a}if(e.sandbox){let{network:a,filesystem:l,credentials:c}=e.sandbox,d={},p=a?Ri(a,["deniedDomains"]):{},f=l?Ri(l,["denyRead","denyWrite"]):{};if(a){if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&a.allowedDomains)p.allowedDomains=a.allowedDomains}if(Object.keys(p).length>0)d.network=p;if(l){if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&l.allowRead)f.allowRead=l.allowRead}if(Object.keys(f).length>0)d.filesystem=f;if(c){let m=(c.files??[]).map((y)=>y.mode==="deny"?{path:y.path,mode:"deny"}:{path:y.path,mode:"mask",injectHosts:[]}),g=(c.envVars??[]).filter((y)=>y.mode==="deny").map((y)=>({name:y.name,mode:"deny"})),_={...m.length>0&&{files:m},...g.length>0&&{envVars:g}};if(c.sigv4){let y={};for(let S of["streaming","presigned","sigv4a"])if(c.sigv4[S]==="deny")y[S]="deny";_.sigv4=y}{let y=P3(c.awsPairs??[],[]);if(y.length>0)_.awsPairs=y}if(Object.keys(_).length>0)d.credentials=_}if(mn(d,d5e(e)),Object.keys(d).length>0)o.sandbox=d}return o}function P3(e,t){let n=Oi,r=new Set(t.flatMap(d3));return Nt(e.flatMap(d3)).filter((o)=>n.includes(o)&&!r.has(o)).map((o,s)=>({accessKeyIdVar:o,secretAccessKeyVar:`${dy}${s+1}_`}))}function d3(e){if(!oe(e))return[];return[e.accessKeyIdVar,e.secretAccessKeyVar,e.sessionTokenVar].filter((t)=>typeof t==="string")}var p5e=new Set([...[...xx].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...kx,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE"]);function f5e(e,t){if(!t||!e)return null;let n={};if(e.model!==void 0)n.model=e.model;if(e.availableModels!==void 0)n.availableModels=e.availableModels;if(e.availableModelsMatch==="exact"||e.availableModelsMatch!==void 0&&e.availableModels!==void 0)n.availableModelsMatch=e.availableModelsMatch;if(e.enforceAvailableModels!==void 0)n.enforceAvailableModels=e.enforceAvailableModels;if(e.deniedModels!==void 0&&e.deniedModels.length>0)n.deniedModels=e.deniedModels;if(e.fallbackModel!==void 0)n.fallbackModel=e.fallbackModel;if(e.modelPicker!==void 0)n.modelPicker=e.modelPicker;return Object.keys(n).length>0?n:null}function m5e(e){let t=[];for(let n of e?.deniedModels??[]){let{warning:r}=k6(n);if(r!==void 0)t.push({file:"managed settings",path:"deniedModels",message:r,severity:"warning",statusOnly:!0})}return t}function g5e(e){if(e?.availableModelsMatch!=="exact")return[];let t=e.availableModels??[];return t.flatMap((n)=>{let r=D6(n,t);return r===void 0?[]:[{file:"managed settings",path:"availableModels",message:r,severity:"warning",statusOnly:!0}]})}function p3(e,t){let n=e.deniedModels;if(Object.assign(e,t),n!==void 0&&t.deniedModels!==void 0)e.deniedModels=Nt([...n,...t.deniedModels])}function Yy(e){if(delete e.model,delete e.fallbackModel,delete e.modelPicker,delete e.modelOverrides,e.env){let t={};for(let[n,r]of Object.entries(e.env))if(!p5e.has(n.toUpperCase()))t[n]=r;e.env=t}}function h5e(e){let t=e.store.policy.allTiers;if(t!==void 0)return t;let n=w5e(e);return e.store.policy.allTiers=n,n}function Da(){return st()==="macos"?"plist":"hklm"}function I3(e){let t=bf(e);if(t.composes==="tier")return"helper";let n=au(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return Da();if(n.present.file)return"file";if(n.parentSlice||n.hostModelOverlay)return"parent";let r=e.hkcu?.();return r&&Object.keys(r.settings).length>0?"hkcu":null}function au(e){let t=[],n=ck(e),{settings:r,servedSnapshot:o}=n;t.push(...n.errors);let s=bf(e),i=s.composes==="remoteSlot"?s.helper:Jy(r),a=lk(e),l=a.settings;t.push(...a.errors);let c=Jy(l),d=e.file?.()??sk(e),p=d.settings;t.push(...d.errors);let f=Jy(p),m=ru(a),g=ru(d),_=g&&d.heldOnly===!0,y=e.policyOnlyServerTier?.()==="unconfirmed"&&(m&&e.mdm?.().userWritable!==!0||g),S=y&&i?E5e(i):i,E=!y&&(s.composes==="remoteSlot"?S!==null:ru(n)),b=ek(S,E),C=ek(c,m),A=d.onlyHeldContent?L3:ek(f,g),R=!y&&S!==null&&b>=Math.max(C,A),x=c!==null&&C>=A,L=[[y?null:r,R],[l,x],[p,f!==null]],re=(s.composes==="remoteSlot"?s.helper:L.find(([he,Rt])=>he!==null&&(he===r&&o?Rt:he.managedSourcesBehavior!==void 0||Rt))?.[0])?.managedSourcesBehavior,T=y?S:null,w=S!==null&&!R,I=w?null:S,M=c!==null&&!x&&I===null,z=M?null:c,J=[],Q=[[w,"remote",S],[M,Da(),c]];for(let[he,Rt,Kt]of Q){if(!he||Kt===null)continue;if(J.push([Kt,Rt]),!cu(Kt)||Kt===T)continue;let qr=Rt==="remote"&&m?Da():"file";t.push({file:Ia[Rt],path:Object.keys(Kt).find((Fa)=>!xi.includes(Fa))??"",message:`${Ia[Rt]} holds only values that could not be applied as written, so ${Ia[qr]} supplies the managed settings while that fail-closed reading still binds beside it (the most restrictive value of each such key applies), until it is fixed.`,severity:"warning",statusOnly:!0})}let{settings:W,errors:B}=zJe(e);t.push(...B);let it=BJe(e);t.push(...it?.errors??[]);let Ve=it?.settings??W,ot=I!==null&&o&&s.composes!=="remoteSlot",At=!(I!==null&&E&&!ot)&&!(z!==null&&m),Zt=At&&(!g||_),Ke=Zt&&_,we=Ke&&Ve&&f?vn(f,nu.filter((he)=>Ve[he]!==void 0)):f,ge=(m?z:null)??(g?f:null),sn=Ve!==null&&(ge===null||x3(ge)||Ke),Fe=[b5e(I,o&&s.composes!=="remoteSlot",[z,we&&vn(we,d.heldAllowLists??[]),...sn?[Ri(Ve,nu)]:[]]),z,we,...J.map(([he])=>he)].filter((he)=>he!==null),En=[...I!==null?["remote"]:[],...z!==null?[Da()]:[],...f!==null?["file"]:[],...J.map(([,he])=>he)],ys=(he)=>Fe.some((Rt)=>Rt!==we&&Rt[he]!==void 0),Ni=we!==null&&d.onlyHeldContent===!0&&At&&re!=="merge"&&Fe[0]!==we,Io=I!==null&&e.policyOnlyServerTier?.()!==void 0,{admin:gn,merged:Na}=Zy(Ni?Fe.filter((he)=>he!==we):Fe,re,ot,Ni?Fe.length-2:J.length,Io),Ss=(he)=>Ky({slot:he,adminTiers:Fe})||Ve?.allowManagedMcpServersOnly===!0&&he?.allowManagedMcpServersOnly!==!1,Df=(he,Rt)=>Na?ys(he):Fe[0]!==we&&Fe[0]?.[he]!==void 0||he==="allowedMcpServers"&&ys(he)&&Ss(Rt),Vr=gn&&we&&Ni?Zy([gn,vn(we,fk.filter((he)=>Df(he,gn)))],"merge",!1,0).admin:gn&&T&&!Na?Zy([gn,T],"merge",!1,0).admin:gn;if(Io&&Vr!==null){let{kept:he}=G3(e);for(let Rt of K3){let Kt=pt(he,Rt),qr=pt(Vr,Rt);if(Kt!==void 0)jt(Vr,Rt,D5e.includes(Rt.join("."))&&Array.isArray(Kt)&&Array.isArray(qr)?Nt([...qr,...Kt]):Kt)}}let Ui=Vr===null?[n,a,d].find(ou):void 0,Or=Vr??(Ui?{}:null),_u={remote:I!==null||Ui===n,mdm:z!==null||Ui===a,file:f!==null||Ui===d},yu=[];if(Na){let he=_u.remote?"remote":_u.mdm?Da():"file",Rt=[[z,Da()],[we,"file"]];for(let[Kt,qr]of Rt){if(Kt===null||Kt===Fe[0]||ot&&Kt===Fe[1])continue;let Fa=pk.filter((Ha)=>Object.values(Kt[Ha]??{}).some((Ff)=>Ff!==void 0&&Ff!==null)),[Uf]=Fa;if(Uf===void 0)continue;yu.push(qr),t.push({file:Ia[qr],path:Uf,message:`${Fa.map((Ha)=>`"${Ha}"`).join(" and ")} in ${Ia[qr]} ignored: policy helper configuration is read from the highest managed settings source only (${Ia[he]} here), even with managedSourcesBehavior "merge". Configure the helper in that source instead.`,severity:"warning",statusOnly:!0})}}let Su=(he)=>he!==null&&(he===Fe[0]||Object.keys(vn(he,W3())).length>0),Lf={remote:Su(I),mdm:Su(z),file:Su(we)},Fi={allowManagedPermissionRulesOnly:Fe.some((he)=>he.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:Or?.forceLoginOrgUUID,...Ri(Or??{},nu),hooks:Or?.hooks,enabledPlugins:Or?.enabledPlugins,allowedMcpServers:Ss(Or)?Wx({slot:Or,adminTiers:Fe}):Or?.allowedMcpServers,sandbox:{network:{allowManagedDomainsOnly:Fe.some((he)=>he.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:Fe.some((he)=>he.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},Eu=c5e(Vr,Zt),Ua=Ke&&Ve?f3(Ve,Fi):Ve,Mf=Eu&&Ve&&!Ke?nu.filter((he)=>Ve[he]!==void 0&&d.heldAllowLists?.includes(he)===!0&&Gr(Fi[he],f?.[he])&&!Df(he,Or)):[],Es=(Ua||k3(e.parentManaged))&&Eu?Ke?nk(Ua??{},{...Fi,allowManagedPermissionRulesOnly:!0,sandbox:{network:{allowManagedDomainsOnly:!0},filesystem:{allowManagedReadPathsOnly:!0}}},e.parentManaged,e.parentOrganizationSettings?.own):nk(Ua??{},vn(Fi,Mf),e.parentManaged,e.parentOrganizationSettings?.own):null,bu=Es&&Object.keys(Es).length>0?Es:null,Nf=f5e(Ve===W?Ua:Ke&&W?f3(W,Fi):W,e.hostManagedProvider);return{tiers:Fe,tierSources:En,admin:Or,parentSlice:bu,hostModelOverlay:Nf,errors:t,present:_u,mode:re,merged:Na,composed:Lf,snapshotFirst:ot,parentNeverShutOut:Zt,shadowedHelperSources:yu,parentIncluded:Eu,heldEmpty:Ui!==void 0,fileNotHeld:d.settingsNotHeld,heldInTheHostsPlace:Mf,policyOnlyLeads:Io}}function Zy(e,t,n,r,o=!1){let s=e[0];if(!s)return{admin:null,merged:!1};let{managedSourcesBehavior:i,...a}=s,l=t==="merge"&&e.length>=2;if(!l&&r===0&&!o)return{admin:i===void 0?s:a,merged:!1};let c=e.slice(l||o?1:e.length-r).map((p,f)=>{let m=l&&n&&f===0,g=m?{...p}:vn(p,W3());if(!m){for(let y of u5e)if(pt(g,y)!==void 0)jt(g,y,void 0)}let _=pt(g.sandbox,["enabledPlatforms"]);if(Array.isArray(_)&&_.includes(st()))jt(g,["sandbox","enabledPlatforms"],void 0);else if(_!==void 0)delete g.sandbox;return g});if(!l)return m3(a,[s,...c]),{admin:a,merged:!1};let d={};for(let p of[...c].reverse())mn(d,p,rk);return mn(d,a,n?C5e:rk),m3(d,[s,...c]),_5e(d,[s,...c],n),{admin:d,merged:!0}}var pk=["policyHelper","policyHelpers"],Ia={remote:"server-managed settings",plist:"the managed preferences plist",hklm:"the HKLM policy key",file:"managed-settings.json"};function lu(e){return Object.keys(e).some((t)=>!xi.includes(t))}function cu(e){return Object.entries(e).some(([t,n])=>!xi.includes(t)&&!sf(n))}function Jy(e){return e&&lu(e)?e:null}function ru(e){return e.settings!==null&&cu(e.settings)&&!e.onlySubstitutes}function D3(e,t,n){return ru({settings:t})&&!n.some((r)=>r.onlySubstitutes)?J6(e):e}var L3=0;function ek(e,t){if(e===null)return-1;if(t)return 2;return cu(e)?1:L3}function M3(e,t){return Object.entries(e).some(([n,r])=>r!==null&&!b3(n,r)&&!xi.includes(n))||t!==null&&lu(t)}function ou(e){return e.documentHasPolicyContent??(e.settings!==null&&lu(e.settings))}function Di(e){return e.loadState??(e.settings!==null?"loaded":"absent")}function Po(e,t){if(e==="didNotLoad"||t==="didNotLoad")return"didNotLoad";return e==="loaded"||t==="loaded"?"loaded":"absent"}function La(e){return e.userWritable!==!0&&(ou(e)||e.loadState==="didNotLoad")}function _5e(e,t,n){let r=t.findIndex((s)=>s.availableModels!==void 0),o=t.findIndex((s)=>s.modelOverrides!==void 0);if(o!==-1&&(r===-1||o<=r||n&&r===0))e.modelOverrides={...t[o].modelOverrides};else delete e.modelOverrides}var N3=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders"],y5e=["awsPairs","ripgrep"];function U3(e,t,n){if(t===void 0)return e;if(Array.isArray(t))return n==="awsPairs"&&Array.isArray(e)?[...t,...P3(e,t)]:[...t];if(!oe(t))return t;return K_(t,(r)=>Array.isArray(r)?[...r]:r)}var fk=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders","allowedMarketplaces","allowedHttpHookUrls","httpHookAllowedEnvVars"],nu=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedProviders"],F3=[["allowManagedMcpServersOnly","allowedMcpServers"],["enforceAvailableModels","availableModels"]];function f3(e,t){return vn(e,F3.filter(([,n])=>e[n]===void 0&&t[n]===void 0).map(([n])=>n))}var S5e=[...F3.map(([e])=>e),"allowManagedPermissionRulesOnly","allowManagedHooksOnly","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars","strictPluginOnlyCustomization","sandbox.network.allowManagedDomainsOnly","sandbox.filesystem.allowManagedReadPathsOnly","sandbox.enabled"];function E5e(e){return Jy(nk(vn(e,S5e),{...Object.fromEntries(nu.map((t)=>[t,[]])),forceLoginOrgUUID:[],allowManagedPermissionRulesOnly:!0,sandbox:{network:{allowManagedDomainsOnly:!0},filesystem:{allowManagedReadPathsOnly:!0}}}))}function b5e(e,t,n){if(e===null||!t)return e;let r=fk.filter((o)=>n.some((s)=>s?.[o]!==void 0));return r.length===0?e:vn(e,r)}function rk(e,t,n){if(n!==void 0&&(N3.includes(n)||y5e.includes(n)))return U3(e,t,n);return H3(e,t,n)}function C5e(e,t,n){if(n!==void 0&&N3.includes(n))return U3(e,t,n);return H3(e,t,n)}function H3(e,t,n){if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Nt([...t,...e]);return Wr(e,t,n)}function m3(e,t){let n=t[0],r=e;for(let o of xo()){let{path:s,restrictive:i}=o,a=Ea(i),l=Math.min(...t.map((c)=>a.indexOf(F_(o,c))).filter((c)=>c!==-1));if(Number.isFinite(l))jt(r,s,a[l]);else if(pt(n,s)===void 0&&pt(e,s)!==void 0)jt(r,s,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Nt(t.flatMap((s)=>Array.isArray(s.strictPluginOnlyCustomization)?s.strictPluginOnlyCustomization:[]));if(o.length>0)e.strictPluginOnlyCustomization=o;else if(n?.strictPluginOnlyCustomization===void 0)delete e.strictPluginOnlyCustomization}}function bf(e){let t=e.helper?.()??null;if(!t)return{composes:"none"};let n=e.helperArmedFromRemote?.()===!1?"tier":"remoteSlot";if(e.helperMergesOutput?.()!==!0)return{composes:n,helper:t,mergedOver:null};if(!e.store.policy.mergedHelper){let{base:r,mergedOver:o}=n==="remoteSlot"?{base:ck(e).settings,mergedOver:"remote"}:$3(e);e.store.policy.mergedHelper={helper:T5e(r,t),mergedOver:Object.keys(z3(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function $3(e){let t=lk(e);if(au({...e,helper:void 0}).present.mdm)return{base:t.settings,mergedOver:Da(),errors:t.errors};let n=e.file?.()??sk(e);return{base:n.settings,mergedOver:"file",errors:[...t.errors,...n.errors]}}function z3(e){return vn(e??{},pk)}function A5e(e,t){let n=new Map;for(let[o,s]of Object.entries(t)){let i=o.toUpperCase();if(!n.has(i))n.set(i,s)}let r={};for(let[o,s]of Object.entries(e))r[o]=n.get(o.toUpperCase())??s;return Object.assign(r,t)}var R5e=["forceLoginOrgUUID","gatewayInternalNetworks","allowedHttpHookUrls","httpHookAllowedEnvVars","allowRead"];function O5e(e,t,n){let r=n!==void 0&&t!==void 0&&R5e.includes(n)?t:rk(e,t,n);return r===t&&Array.isArray(r)?[...r]:r}function T5e(e,t){let n=z3(e),r=mn({},n,t,O5e);if(n.env&&t.env)r.env=A5e(n.env,t.env);return r}function w5e(e){let t=bf(e);if(t.composes==="tier")return[t.helper];let{tiers:n,parentSlice:r}=au(e);return r?[...n,r]:n}function v5e(e,t,n){let r={slot:n,adminTiers:e};return e.flatMap((o,s)=>{let i=t[s],a=U6(o,r);return i!==void 0&&a.length>0?[{source:i,keys:a}]:[]})}var B3=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var eS=[...B3,"otelHeadersHelper","proxyAuthHelper"],g3=["disableAllHooks","enabledPlugins","extraKnownMarketplaces","agent","allowedHttpHookUrls","httpHookAllowedEnvVars","autoMemoryDirectory","modelOverrides","allowedMcpServers","skipWebFetchPreflight","autoUploadSessions","xaaIdp","claudeMdExcludes","enableAllProjectMcpServers","enabledMcpjsonServers"];function x5e(e,t,n){if(!g3.some((o)=>t[o]!==void 0)||(n.launchFolderKeysFrom?.(e)??"as_read")==="as_read")return t;let r={...t};for(let o of g3)delete r[o];return h6("keys"),r}function _f(e,t,n){return k5e(e,x5e(e,t,n),n)}function k5e(e,t,n){let r=eS.some((a)=>t[a]!==void 0);if(!r&&e!=="policySettings")return t;let o=n.credentialHelperKeysFrom(e);if(o==="as_read")return t;let s=e==="policySettings"&&o==="machine_admin"?P5e(n):{};if(!r&&Object.keys(s).length===0)return t;let i={...t};for(let a of eS)delete i[a];return Object.assign(i,s)}function P5e(e){let t=mk(e),n={};for(let r of eS){let o=t?.[r];if(o!==void 0)n[r]=o}return n}function mk(e){let t=j3(e),n=bf(t);return n.composes==="tier"?n.helper:au(t).admin}function j3(e){let t=e.helperArmedFromRemote?.()===!1&&e.helperArmedFromUserWritableBase?.()===!1;return{...e,store:new bs,remote:()=>null,helper:t?e.helper:()=>null,...e.mdm?.().userWritable===!0&&{mdm:()=>({settings:{},errors:[]})}}}function I5e(e){return e.helperArmedFromUserWritableBase?.()!==!1||e.helperMergesOutput?.()===!0&&e.mdm?.().userWritable===!0}function h3(e,t){if(t.store.policy.machineLoginPins===void 0){let o=mk(t);t.store.policy.machineLoginPins={value:{forceLoginOrgUUID:o?.forceLoginOrgUUID,forceLoginMethod:o?.forceLoginMethod}}}let{forceLoginOrgUUID:n,forceLoginMethod:r}=t.store.policy.machineLoginPins.value;if(n!==void 0)e.forceLoginOrgUUID=n;if(r==="claudeai"||r==="console")e.forceLoginMethod=r}var K3=[["model"],["fallbackModel"],["advisorModel"],["modelOverrides"],["modelPricing"],["modelPicker"],["processWrapper"],["sandbox","credentials","files"],["sandbox","credentials","envVars"],["sandbox","credentials","awsPairs"],["availableModels"],["requiredMinimumVersion"],["requiredMaximumVersion"],["strictKnownMarketplaces"],["allowedMarketplaces"],["allowedChannelPlugins"],["deniedModels"],["blockedMarketplaces"],...Qc.map((e)=>["autoMode",e]),["hooks"],["allowedHttpHookUrls"],["httpHookAllowedEnvVars"],["managedMcpServers"],["extraKnownMarketplaces"],["additionalMarketplaces"],["enabledPlugins"],["pluginConfigs"],["pluginTrustMessage"],["pluginSuggestionMarketplaces"],["claudeMd"],["cleanupPeriodDays"],["desktopSessionCleanupPeriodDays"]],D5e=["deniedModels","blockedMarketplaces",...Qc.map((e)=>`autoMode.${e}`)];function G3(e){if(e.store.policy.machineBeneathPolicyOnly===void 0){let t=mk(e),n={};for(let r of K3){let o=pt(t,r);if(o!==void 0)jt(n,r,o)}e.store.policy.machineBeneathPolicyOnly={kept:n,env:L5e(e)}}return e.store.policy.machineBeneathPolicyOnly}function L5e(e){return gk({...j3(e),helper:()=>null,hkcu:void 0,parentManaged:null}).settings?.env}var M5e=[...eS,"forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","env","modelPicker",...pk,...xi];function W3(){return M5e}function V3(e){return f9.some((t)=>e.startsWith(t))||Ox.includes(e)}function N5e(e,t,n,r=0){let o=new Map,s=new Map,i=!1;for(let[a,l]of e.entries()){let c=new Set,d=t?.[a]===!0;for(let[p,f]of Object.entries(l??{})){let m=p.toUpperCase(),g=V3(m);if(g&&f.trim()==="")continue;if(g&&i)continue;if(g&&a>r&&t?.[a]===!0)continue;let _=o.get(m);if(_!==void 0){if(c.has(m))s.set(p,f);else if(!s.has(p))s.set(p,_);continue}if(a>r&&n?.[a]?.has(m))continue;if(s.set(p,f),c.add(m),o.set(m,f),g)d=!0}if(d)i=!0}return Object.fromEntries(s)}var U5e="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function _3(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==U5e)t[n]=r;return t}function F5e(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function y3(e,t){if(t===e.store.parentLeftOutReason)return;if(e.store.parentLeftOutReason=t,t!==null)G(`--managed-settings left out of the policy tier: ${t}`,{level:"warn"})}function gk(e){let t=bf(e),n=(e.helperWarnings?.()??[]).filter((A)=>!Li(A.path)),r=Object.keys(e.parentManaged??{}).length>0;if(t.composes==="tier"){y3(e,r?"a policy helper supplies that tier (parentSettingsBehavior does not apply to it)":null);let{helper:A}=t;e.store.lastPolicyEnvComposition=null;let R=I5e(e),x=e.hostManagedProvider||R?{...A}:A;if(e.hostManagedProvider)Yy(x);if(R)h3(x,e);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&A.availableModels!==void 0?A.modelOverrides:void 0},e.store.policy.deniedModelsOverrides={value:e.hostManagedProvider?A.modelOverrides:void 0};let L=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?$3(e).errors.filter((F)=>!F.statusOnly):[],...au(e).errors.filter((F)=>F.statusOnly)];return{settings:x,errors:[...L,...n]}}let{tiers:o,tierSources:s,admin:i,parentSlice:a,hostModelOverlay:l,errors:c,present:d,snapshotFirst:p,parentIncluded:f,heldInTheHostsPlace:m,policyOnlyLeads:g}=au(e),_=null;if(r&&!f)_="an administrator's managed settings apply and do not set parentSettingsBehavior to 'merge'";else if(r&&!a&&!l)_="nothing shuts it out, yet none of its keys was kept (unreadable, no restriction, or already set by an administrator)";if(y3(e,_),c.push(...n),!i&&!a){e.store.lastPolicyEnvComposition=null,e.store.policy.pairedModelOverrides={value:void 0},e.store.policy.deniedModelsOverrides={value:void 0};let A=e.hkcu?.();if(A&&Object.keys(A.settings).length>0){let R=e.hostManagedProvider?{...A.settings}:A.settings;if(e.hostManagedProvider){if(Yy(R),l)p3(R,l)}return{settings:R,errors:[...c,...A.errors]}}if(l)return{settings:{...l},errors:[...c,...A?.errors??[]]};return{settings:null,errors:[...c,...A?.errors??[]]}}let y=mn({},a??{},vn(i??{},m),Wr);if(a?.availableModelsMatch==="exact")y.availableModelsMatch="exact";if(a?.allowManagedHooksOnly===!0)y.allowManagedHooksOnly=!0;if(a?.disableSkillShellExecution===!0)y.disableSkillShellExecution=!0;if(a?.disableWindowsBashCommandSplit===!0)y.disableWindowsBashCommandSplit=!0;if(o.some((A)=>A.forceRemoteSettingsRefresh===!0))y.forceRemoteSettingsRefresh=!0;if(s.includes("remote")||e.mdm?.().userWritable===!0)h3(y,e);let S=Dt.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0&&!g,E=y.env;if(!S){let A=o;if(g){let x=G3(e).env,L=e.heldMdmEnv?.(),F=L===void 0?x:{...x,...L},re=new Map(Object.entries(F??{}).filter(([,W])=>W.trim()!=="").map(([W,B])=>[W.toUpperCase(),B])),T=new Set(re.keys()),w=b6(F,o[0]?.env)||Object.entries(o[0]?.env??{}).some(([W,B])=>B==="1"&&Ca.some((it)=>it===W.toUpperCase())&&T.has(W.toUpperCase())),I=T.has("AWS_REGION")?void 0:re.get("AWS_DEFAULT_REGION"),M=S6(o[0]?.env??{},T),z=Object.entries(o[0]?.env??{}).filter(([W])=>{let B=W.toUpperCase();return w?!E6.includes(B):!(y6.includes(B)&&T.has(B)||M.dropped.includes(B))}).map(([W,B])=>I!==void 0&&W.toUpperCase()==="AWS_REGION"?[W,I]:[W,B]).concat(w?[]:M.cleared.map((W)=>[W,""])),[J,Q]=Bq(z,([W,B])=>Ox.includes(W.toUpperCase())&&Zr(B));A=[{...o[0],env:Object.fromEntries(Q.some(([W])=>V3(W.toUpperCase()))?z:Q)},{env:{...F,...Object.fromEntries(J)}}]}let R=N5e(A.map((x)=>x.env),A.map((x)=>(x.otelHeadersHelper??"").trim()!==""),A.map((x)=>{let L=new Set;for(let F of B3){let re=x[F];if(typeof re==="string"&&re.trim()!=="")for(let T of m9[F])L.add(T)}return L.size>0?L:void 0}),p||g?1:0);if(Object.keys(R).length>0)y.env=R;else delete y.env}if(y.env){let A=_3(y.env);if(A&&Object.keys(A).length>0)y.env=A;else delete y.env}if(e.hostManagedProvider){if(Yy(y),l)p3(y,l)}let b={env:_3(E)};if(e.hostManagedProvider)Yy(b);let C=!S&&!F5e(y.env,b.env);e.store.lastPolicyEnvComposition={unionOptedOut:S,unionChangedEnv:C,remoteTierPresent:d.remote,mdmTierPresent:d.mdm,fileTierPresent:d.file,adminTierCount:o.length,tiersWithEnv:ja(o,(A)=>Object.keys(A.env??{}).length>0)},e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&i?.availableModels!==void 0&&i.modelOverrides!==void 0&&l?.availableModels===void 0?i.modelOverrides:void 0},e.store.policy.deniedModelsOverrides={value:e.hostManagedProvider?i?.modelOverrides:void 0};for(let{source:A,keys:R}of v5e(o,s,y)){let[x]=R;if(x===void 0)continue;let L=Ia[A],F=R.length===1;c.push({file:L,path:x,message:`${R.map((re)=>`"${re}"`).join(" and ")} in ${L} ${F?"is":"are"} not applied: ${L} is not the managed settings source that applies for ${F?"this key":"these keys"} (/status lists the setting sources). Remove ${F?"it":"them"} from ${L}, or set ${F?"it":"them"} in the source that applies.`,severity:"warning",statusOnly:!0})}return{settings:y,errors:c}}function H5e(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return gk(t).settings;let r=iu(e,t),{settings:o}=r?su(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=O3(t);if(s)return mn(o||{},s,Wr)}if(e==="localSettings"&&n){let s=w3(t);if(s){let{settings:i}=su(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),mn(i,o||{},Wr)}}return o}function $5e(e,t){return{...e,...t}}function Wr(e,t,n){if(n==="modelPicker"&&t!==void 0)return q3(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Nt([...e,...t])}if((n==="extraKnownMarketplaces"||n==="managedMcpServers")&&oe(e)&&oe(t))return $5e(e,t);return}function q3(e){if(!oe(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>oe(n)?{...n}:n)}}}function z5e(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();Lp("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=mn(r,n,Wr);let o=[],s=new Set,i=new Set,a=(y)=>{for(let S of y){let E=`${S.file}:${S.path}:${S.message}`;if(!s.has(E))s.add(E),o.push(S)}},l=[],c=[Ai()];if(st()==="wsl"&&e.wslInherits?.())c.push(kn);let d=new Set(c.map((y)=>ut(Mt(y,"managed-settings.json")))),p=new Set(c.map((y)=>ut(Mt(y,"managed-settings.d")))),f=(y)=>{let S=ut(y);return d.has(S)||p.has(tS(S))},m=(y,S,E)=>{if(E?.channelLabel!==!0&&f(y))return;let b=S.sandbox?.filesystem?.allowRead?.length??0,C=S.sandbox?.network?.allowedDomains?.length??0;if(b>0||C>0)l.push({file:y,allowReadCount:b,allowedDomainsCount:C})},g=null;for(let y of ok(e)){if(y==="policySettings"){let{settings:b,errors:C}=gk(e);if(g=b,a(m5e(b)),a(g5e(b)),b)r=mn(r,_f(y,b,e),Wr);a(C);continue}let S=e.store.repoTierFreeze.tier(y);if(S!==void 0){let b=iu(y,e);if(b)i.add(ut(b));if(a([...S.errors]),S.settings)r=mn(r,S.settings,Wr);continue}if(y==="localSettings"){let b=w3(e);if(b&&!i.has(ut(b))){i.add(ut(b));let{settings:C,errors:A}=su(b,e.store);if(a(A),C)e.onLegacyLocalSettingsRead?.("cascade"),m(b,C),r=mn(r,_f(y,C,e),Wr)}}for(let b of s5e(y,e)){let C;try{C=Mu(Oe(),b).absentAt===void 0}catch{C=!0}if(C)a([a5e(b)]),G(`Settings file ${b} is not used: it is in a connector-downloads folder`)}let E=iu(y,e);if(E){let b=ut(E),C=y==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(b)||C){i.add(b);let{settings:A,errors:R}=su(E,e.store,y==="flagSettings"?e.flagExpectedContent:void 0);if(a(R),A){if(y==="flagSettings"&&e.flagInlineJson===!0)m(A6,A,{channelLabel:!0});else m(E,A);r=mn(r,_f(y,A,e),Wr)}}}if(y==="flagSettings"){let{settings:b,errors:C}=O3(e);if(a(C),b)m("SDK inline settings",b,{channelLabel:!0}),r=mn(r,_f(y,b,e),Wr)}}if(g){if(g.availableModels!==void 0)r.availableModels=[...g.availableModels];if(g.enforceAvailableModels!==void 0)r.enforceAvailableModels=g.enforceAvailableModels;if(g.modelPicker!==void 0)r.modelPicker=q3(g.modelPicker)}let _=g?.deniedModels;if(_!==void 0)r.deniedModels=[..._];else delete r.deniedModels;if(l.length>0){let y=h5e(e),S=(E,b,C,A,R)=>({file:E,path:b,severity:"warning",statusOnly:!0,message:`${b} is ignored — managed settings set ${C}, so only ${A} from managed settings are honored. The ${R===1?"entry":`${R} entries`} in ${E} will NOT apply (see https://code.claude.com/docs/en/settings#sandbox-settings).`});if(y.some((E)=>E.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)){for(let E of l)if(E.allowReadCount>0)a([S(E.file,"sandbox.filesystem.allowRead","allowManagedReadPathsOnly","allowRead paths",E.allowReadCount)])}if(y.some((E)=>E.sandbox?.network?.allowManagedDomainsOnly===!0)){for(let E of l)if(E.allowedDomainsCount>0)a([S(E.file,"sandbox.network.allowedDomains","allowManagedDomainsOnly","allowed domains (and WebFetch domain rules)",E.allowedDomainsCount)])}}return Lp("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:i.size,error_count:o.length}),e.store.hookedMerge.computed=r,K6({settings:r,errors:o},e.store.hookedMerge.answers)}finally{e.store.isLoadingFromDisk=!1}}function B5e(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=z5e(e);return e.store.mergedSettings=n,n}function j5e(e){let{settings:t}=B5e(e);return t||{}}function Y3(e){e.store.invalidateAll();let t=[];for(let n of ok(e)){let r=v3(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:j5e(e),sources:t}}function Z3(e,t){let n=ok(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(v3(o,t)?.[e]!==void 0)return o}return null}import{execFile as K5e}from"child_process";import{accessSync as G5e,closeSync as W5e,constants as V5e,openSync as q5e,readSync as Y5e}from"fs";var Z5e=new Set(["EAGAIN","EMFILE","ENFILE","ENOMEM"]);class tJ{promise=null;start(){if(this.promise)return;this.promise=_k()}reset(){this.promise=null}}var J5e=new tJ;function X5e(e){if(!e)return{status:"ok",exitCode:0,errno:null,signal:null};let t=e,n=typeof t.signal==="string"&&t.signal?t.signal:null;if(typeof t.code==="string")return{status:"spawn_error",exitCode:null,errno:t.code,signal:null};if(t.killed===!0)return{status:"timeout",exitCode:null,errno:null,signal:n};if(n)return{status:"killed",exitCode:null,errno:null,signal:n};return{status:"exited",exitCode:typeof t.code==="number"?t.code:null,errno:null,signal:null}}function hk(e,t,n){let r=Date.now();return new Promise((o)=>{try{K5e(e,t,{encoding:"utf-8",timeout:Yx,windowsHide:!0,...n!==void 0&&{maxBuffer:n}},(s,i,a)=>{o({stdout:i??"",stderr:a??"",...X5e(s),durationMs:Date.now()-r})})}catch(s){let i=s.code;o({stdout:"",stderr:"",status:"spawn_error",exitCode:null,errno:typeof i==="string"?i:null,signal:null,durationMs:Date.now()-r})}})}function J3(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs,answered:e.status==="ok"||e.status==="exited"&&e.exitCode===1&&e.stderr.includes(z6)}}function X3(e){return e.status==="ok"||e.status==="exited"&&e.exitCode!==null}function nJ(e){return e.status==="spawn_error"&&e.errno==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}function Q3(e){if(nJ(e))return{unreadReason:"plutil's output exceeded the size limit",unreadCause:"oversize"};switch(e.status){case"timeout":return{unreadReason:`plutil timed out after ${Yx/1000} seconds`,unreadCause:"timeout"};case"killed":return{unreadReason:"plutil was stopped by a signal",unreadCause:"killed"};case"spawn_error":return{unreadReason:"plutil could not be run",unreadCause:e.errno!==null&&Z5e.has(e.errno)?"spawn_busy":"spawn_error"};case"ok":case"exited":return{unreadReason:"plutil did not finish"}}}function Q5e(e){let t;try{return t=q5e(e,"r"),Y5e(t,Buffer.alloc(1),0,1,0),null}catch(n){return{code:n&&typeof n==="object"&&"code"in n?n.code:void 0,message:n instanceof Error?n.message:String(n)}}finally{if(t!==void 0)try{W5e(t)}catch{}}}function _k(){return(async()=>{if(process.platform==="darwin"){let e=B6(),n=(await Promise.all(e.map(async({path:o,...s})=>{try{G5e(o,V5e.R_OK)}catch(c){let d=c&&typeof c==="object"&&"code"in c?c.code:void 0;if(d==="ENOENT"||d==="ENOTDIR")return null;return{stdout:null,unreadReason:c instanceof Error?c.message:String(c),...typeof d==="string"&&{unreadErrno:d},...s}}let i=await hk(qx,[...H6,o],Vy);if(!X3(i))return{stdout:null,...Q3(i),...s};if(i.status==="ok")return{stdout:i.stdout,...s};let a=await hk(qx,[...$6,o]);if(!X3(a)){let{unreadReason:c,unreadCause:d}=Q3(a),f=d==="timeout"||d==="killed"||d==="spawn_busy"?"lint_unfinished":d;return{stdout:null,unreadReason:`plutil rejected the conversion, and in the check that follows ${c}`,unreadCause:f,...s}}if(a.status==="ok")return{stdout:null,unreadReason:"it holds a value plutil cannot convert to JSON (a date or data value)",unreadCause:"unconvertible",...s};let l=Q5e(o);if(l!==null){if(l.code==="ENOENT"||l.code==="ENOTDIR")return null;return{stdout:null,unreadReason:l.message,...typeof l.code==="string"&&{unreadErrno:l.code},...s}}return{stdout:"",...s}}))).filter((o)=>o!==null),r=n.findIndex((o)=>o.stdout!==null);return{plistStdouts:r===-1?n:n.slice(0,r+1),hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}}if(process.platform==="win32"){let t=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`;return eJ(t)}if(pf())return eJ(Ii);return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}async function eJ(e){let t=(o)=>hk(e,["query",o,"/v",df],Vy),[n,r]=await Promise.all([t(Gy),t(Wy)]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,...nJ(n)&&{hklmUnreadReason:`the value exceeds ${Vy/1048576} MiB`},hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:J3(n),hkcu:J3(r)}}}function rJ(){return J5e.promise}var nXe=Object.freeze({settings:{},errors:[],loadState:"absent"}),uu=Object.freeze({settings:{},errors:[]});class aJ{mdm=null;hkcu=null;wslInherits=!1;whereAsked=void 0;readOutcomes=null;unansweredReadsInARow=0;lastAnswered=null;loadPromise=null;reread={failedFor:void 0,failedAt:0,inFlight:void 0,startedAt:0};startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await(rJ()??_k()),{mdm:o,hkcu:s,wslInherits:i,whereAsked:a}=await Sk(r,e);this.replace(o,s,i,a,r.outcomes),this.readOutcomes=r.outcomes;let l=Date.now()-t;G(`MDM settings load completed in ${l}ms`);try{pi("tengu_managed_settings_os_read",pXe(r,l))}catch{}let c=Ck();if(Object.keys(c.settings).length>0){G(`MDM settings found: ${Object.keys(c.settings).join(", ")}`);try{Lp("info","mdm_settings_loaded",{duration_ms:l,key_count:Object.keys(o.settings).length,error_count:o.errors.length})}catch{}}})()}replace(e,t,n,r,o){if(this.mdm=e,this.hkcu=t,this.wslInherits=n,this.whereAsked=r,o===void 0)return;let s={mdm:e,hkcu:t,wslInherits:n,whereAsked:r};if((o.hklm===null||o.hklm.answered)&&!sS(s).mdm.errors.some((a)=>a.errorClass==="unreadable"&&a.errno===void 0&&a.userWritable!==!0))this.unansweredReadsInARow=0,this.lastAnswered=s;else this.unansweredReadsInARow++}reset(){this.mdm=null,this.hkcu=null,this.wslInherits=!1,this.whereAsked=void 0,this.readOutcomes=null,this.unansweredReadsInARow=0,this.lastAnswered=null,this.loadPromise=null,this.reread={failedFor:void 0,failedAt:0,inFlight:void 0,startedAt:0}}}var oJ="@builtin",rXe=["prependPlugins","appendPlugins"];function oXe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var sXe=new Te(()=>new aJ);function Af(){return sXe.of(Gt().host)}function iXe(e){Af().startLoad(e)}async function lJ(){let e=Af();if(!e.loadPromise)iXe();await e.loadPromise}function Ck(){return sS(Af()).mdm??nXe}function sS(e){return e.whereAsked!==void 0&&z_()?e.whereAsked:e}function cJ(){return sS(Af()).hkcu??uu}function uJ(){return sS(Af()).wslInherits}function Cf(e,t,{userWritable:n=!1}={}){let r=Sa(e,!1);if(!oe(r))return{settings:{},errors:[rS(t,{userWritable:n})],documentHasPolicyContent:!1,loadState:"didNotLoad"};let o=[],s=r;for(let f of n?nS:[]){if(!(f in s))continue;if(s=s===r?{...r}:s,delete s[f],!Li(f))o.push({file:t,path:f,message:`"${f}" is only honored from administrator-controlled managed settings and was ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}if(n){for(let m of rXe){if(!(m in s))continue;s=s===r?{...r}:s,delete s[m],o.push({file:t,path:m,message:`"${m}" is only honored from administrator-controlled managed settings and was ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}let f=s.enabledPlugins;if(oXe(f)){if(Object.entries(f).filter(([g,_])=>g.endsWith(oJ)||_!==!1).length>0){s=s===r?{...r}:s;let g=Dc(f,(_,y)=>!y.endsWith(oJ)&&_===!1);if(Object.keys(g).length>0)s.enabledPlugins=g;else delete s.enabledPlugins;o.push({file:t,path:"enabledPlugins",message:`"enabledPlugins" entries that enable a plugin, or name a built-in, are only honored from administrator-controlled managed settings and were ignored in ${t}, which the user account can write.`,severity:"warning",statusOnly:!0})}}}let{settings:i,errors:a,documentHasPolicyContent:l,loadState:c,onlySubstitutes:d}=yf(s,t),p=[...o,...a];return{settings:i??{},errors:n?p.map((f)=>({...f.severity==="warning"&&!f.startupFatal?f:{...aXe(f),severity:"warning",statusOnly:!0},userWritable:!0})):p,documentHasPolicyContent:l,loadState:c,...d&&{onlySubstitutes:d}}}function aXe({startupFatal:e,loadedWithoutGuardHook:t,...n}){return n}function yk(e,t,n,r){return{file:e,path:"",message:`Managed settings document (${e}) could not be read: ${t}; none of its settings are in effect.`,severity:n?"warning":"fatal",statusOnly:!0,errorClass:"unreadable",...r.errno!==void 0&&{errno:r.errno},...r.cause!==void 0&&{unreadCause:r.cause},...n&&{userWritable:!0}}}function oS(e,t="Settings"){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^[ \\t]+${n}[ \\t]+REG_(?:EXPAND_)?SZ[ \\t]+([\\s\\S]*)`,"im"),o=e.match(r)?.[1]?.trimEnd();return o?o:null}var lXe=new Map([["ENOENT",an("ENOENT")],["EACCES",an("EACCES")],["EPERM",an("EPERM")],["ENOEXEC",an("ENOEXEC")],["EAGAIN",an("EAGAIN")],["EMFILE",an("EMFILE")],["ENOMEM",an("ENOMEM")],["ETIMEDOUT",an("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",an("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),cXe=new Map([["SIGTERM",an("SIGTERM")],["SIGKILL",an("SIGKILL")],["SIGINT",an("SIGINT")]]);function uXe(e){if(!e)return;return lXe.get(e)??an("other")}function dXe(e){if(!e)return;return cXe.get(e)??an("other")}function sJ(e,t){if(!t)return{};return{[`${e}_status`]:Cs(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:uXe(t.errno),[`${e}_signal`]:dXe(t.signal),[`${e}_duration_ms`]:t.durationMs}}function pXe(e,t){return{is_wsl:pf(),await_ms:t,...sJ("hklm",e.outcomes.hklm),...sJ("hkcu",e.outcomes.hkcu)}}async function Sk(e,t,n=!1){let r=[],o=!1,s="absent";for(let S of e.plistStdouts??[]){let{label:E,userWritable:b}=S;if(b&&o)continue;let C=S.stdout===null?{settings:{},errors:[yk(E,S.unreadReason,b,{errno:S.unreadErrno,cause:S.unreadCause})],documentHasPolicyContent:!1,loadState:"didNotLoad",...b&&{userWritable:b}}:{...Cf(S.stdout,E,{userWritable:b}),...b&&{userWritable:b}};if(b?lu(C.settings):C.documentHasPolicyContent)return{mdm:{...C,errors:[...r,...C.errors],documentHasPolicyContent:!0},hkcu:uu,wslInherits:!1};if(o||=La(C),r.push(...C.errors),!b)s=Po(s,C.loadState)}let i=`Registry: ${Gy}\\${df}`,a=null,l="disarmed",c=`Registry: ${Wy}\\${df}`;if(!n&&(e.hklmStdout!==null||e.hklmUnreadReason!==void 0||e.hkcuStdout!==null)&&process.platform!=="win32"&&Zx()){let[S,E]=await Promise.all([Ii,tXe(Ii)].map((C)=>eXe(C).then(({uid:A,gid:R,mode:x})=>({uid:A,gid:R,mode:x}),()=>{return}))),b=!0;try{b=ak(new bs,Ii,S,E)}catch(C){G(`registry tool: could not be asked about, held: ${C}`,{level:"error"})}if(b){let C=[];if(e.hklmStdout!==null)C.push([i,Cf(oS(e.hklmStdout)??"",i)]);else if(e.hklmUnreadReason!==void 0)C.push([i,{settings:{},errors:[yk(i,e.hklmUnreadReason,!1,{cause:"oversize"})],documentHasPolicyContent:!1,loadState:"didNotLoad"}]);if(e.hkcuStdout!==null)C.push([c,Cf(oS(e.hkcuStdout)??"",c,{userWritable:!0})]);let A=await Sk(e,t,!0),R=await Sk({...e,hklmStdout:null,hklmUnreadReason:void 0,hkcuStdout:null},t,!0);return{...A,whereAsked:{...R,mdm:{...R.mdm,heldDocuments:C.map(([x,L])=>({path:x,parsed:{...L,settings:L.loadState==="loaded"?L.settings:null}}))}}}}}if(e.hklmStdout!==null){let S=oS(e.hklmStdout)??"";a=Cf(S,i);let E=Sa(S,!1);if(oe(E))l=fx(E)}else if(e.hklmUnreadReason!==void 0)a={settings:{},errors:[yk(i,e.hklmUnreadReason,!1,{cause:"oversize"})],documentHasPolicyContent:!1,loadState:"didNotLoad"};let d=a!==null&&La(a);if(a)r.push(...a.errors),s=Po(s,a.loadState);let p=pf(),f="disarmed",m=i,g=[];if(p){if(f=l,f!=="armed"){let S=await mXe(t);if(g=S.links,S.flag==="armed"||f==="disarmed")f=S.flag,m=S.unreadableFlagPath??kn;if(f==="disarmed")r.push(...S.records),s=Po(s,S.loadState)}}let _=f!=="disarmed",y={settings:{},errors:r,loadState:s};if(p&&!_){let S=new Set(a?.errors.filter((E)=>E.severity==="warning"));return{mdm:{...y,errors:y.errors.map((E)=>S.has(E)?{...E,wslIgnored:!0}:E),...g.length>0&&{managedDocumentLinks:g}},hkcu:uu,wslInherits:!1}}if(a&&d)return{mdm:a,hkcu:uu,wslInherits:_};if(f==="unreadable"){let S=await bk(kn,t),E=T3(m);return{mdm:{...y,errors:S?y.errors:[...y.errors,E],...S&&{withheldFlagRecord:E},documentHasPolicyContent:!0,loadState:Po(y.loadState,"loaded")},hkcu:uu,wslInherits:_}}if(e.hkcuStdout!==null&&!tt()&&!await fXe(_,t)){let S=Cf(oS(e.hkcuStdout)??"",c,{userWritable:!0});if(!p||S.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:E,managedSourcesBehavior:b,...C}=S.settings;return{mdm:y,hkcu:{settings:C,errors:S.errors},wslInherits:_}}if(S.errors.length>0)return{mdm:y,hkcu:{settings:{},errors:S.errors},wslInherits:_}}return{mdm:y,hkcu:uu,wslInherits:_}}async function dJ(e,t){if(be()&&t!==void 0)return(await e2(e,Sf)).content;return bi(e,Sf)}async function fXe(e,t){if(e&&await bk(kn,t))return!0;return bk(Ai(),t)}async function iJ(e,t){let n;try{n=await dJ(e,t)}catch(r){return!et(r)}try{let r=Xy(n,e,!0);return La({...r,loadState:Di(r)})}catch{return!0}}function Ek(e){let t=le(e);return t==="ENOENT"||t==="ENOTDIR"}async function mXe(e){let t=[],n="absent",r=[],o=new Map;async function s(p,f){let m=Ma(kn,...p),g;try{g=await dJ(m,e)}catch(S){if(Ek(S))return"disarmed";t.push(Ef(m,S)),n="didNotLoad"}let _=await E2(kn,p,f,o);if(_!==null)r.push(_);if(g===void 0)return"disarmed";let y=g.trim()===""?{}:Sa(g,!1);if(!oe(y))return t.push(rS(m)),n="didNotLoad","disarmed";return n=Po(n,"loaded"),fx(y)}let i=Ma(kn,"managed-settings.json"),a=await s(["managed-settings.json"]);if(a==="armed")return{flag:a,records:t,loadState:n,links:r};let l=a==="unreadable"?i:void 0,c=Ma(kn,"managed-settings.d"),d;try{d=await Oe().readdir(c)}catch(p){if(!Ek(p))t.push(Ef(c,p,"directory")),n="didNotLoad";return{flag:a,unreadableFlagPath:l,records:t,loadState:n,links:r}}for(let p of d){if(!(p.isFile()||p.isSymbolicLink())||!p.name.endsWith(".json")||p.name.startsWith("."))continue;let f=await s(["managed-settings.d",p.name],p.isSymbolicLink());if(f==="armed")return{flag:f,records:t,loadState:n,links:r};if(f==="unreadable")a=f,l??=Ma(c,p.name)}return{flag:a,unreadableFlagPath:l,records:t,loadState:n,links:r}}async function bk(e,t){if(await iJ(Ma(e,"managed-settings.json"),t))return!0;let n=Ma(e,"managed-settings.d"),r;try{r=await Oe().readdir(n)}catch(o){return!Ek(o)}for(let o of r)if((o.isFile()||o.isSymbolicLink())&&ik(o.name)&&await iJ(Ma(n,o.name),t))return!0;return!1}function pJ(e){if(!Object.hasOwn(e,jx))return{tier:e,organization:null,memberLost:!1};let{[jx]:t,...n}=e;return{tier:n,organization:null,memberLost:!1}}var hXe={user:"userSettings",project:"projectSettings",local:"localSettings"},fJ={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},_Xe=["user","project","local"];async function mJ(e={}){await lJ();let t=e.managedSettings&&pJ(e.managedSettings),n={store:new bs,cwd:gXe(e.cwd??Oe().cwd()),allowedSources:(e.settingSources??_Xe).map((l)=>hXe[l]),diskless:tt(),parentManaged:t?.tier??null,parentOrganizationSettings:t?.organization,flagInline:null,flagPath:void 0,mdm:Ck,hkcu:cJ,wslInherits:uJ,credentialHelperKeysFrom:()=>"as_read",asksOrganization:()=>z_(),...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:r,sources:o}=Y3(n),s=I3(n)??void 0,i=o.map(({source:l,settings:c})=>({source:fJ[l],settings:c,path:l==="policySettings"?void 0:iu(l,n),...l==="policySettings"&&{policyOrigin:s}})),a={};for(let l of Object.keys(r)){let c=Z3(l,n);if(c)a[l]={source:fJ[c],path:c==="policySettings"?void 0:iu(c,n),...c==="policySettings"&&{policyOrigin:s}}}return{effective:r,provenance:a,sources:i}}var yXe=new Set(["bypassPermissions","auto","acceptEdits"]),SXe=new Set(["project"]),EXe=new Set(["project","local"]);function bXe(e){let t=e.effective.permissions?.defaultMode;if(!t||!yXe.has(t))return e.effective;for(let n=e.sources.length-1;n>=0;n--){let r=e.sources[n];if(r.settings.permissions?.defaultMode!==void 0){if((R6.includes(t)?EXe:SXe).has(r.source)){let{defaultMode:s,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}import{execFile as L8e}from"child_process";import{randomUUID as M8e}from"crypto";import{mkdir as gS,mkdtemp as N8e,readFile as U8e,rm as A5,writeFile as R5}from"fs/promises";import{createRequire as F8e}from"module";import{homedir as Pf,tmpdir as H8e}from"os";import{dirname as E5,isAbsolute as jk,join as Ct,posix as O5,resolve as If,sep as $8e,win32 as T5}from"path";import{fileURLToPath as z8e}from"url";import{setMaxListeners as CXe}from"events";var AXe=50;function Rf(e=AXe){let t=new AbortController;return CXe(e,t.signal),t}var a2t=new FinalizationRegistry(({parentSignalRef:e,handler:t})=>{e.deref()?.removeEventListener("abort",t)});var RXe="ask-withdrawn-by-asker",l2t=new DOMException(RXe,"AbortError");var c2t={"user-cancel":new DOMException("user-cancel","AbortError"),"remote-cancel":new DOMException("remote-cancel","AbortError"),shutdown:new DOMException("shutdown","AbortError"),interrupt:new DOMException("interrupt","AbortError"),"turn-abort":new DOMException("turn-abort","AbortError"),background:new DOMException("background","AbortError"),"refusal-fallback-edit":new DOMException("refusal-fallback-edit","AbortError"),"recovery-timeout":new DOMException("recovery-timeout","AbortError"),"permission-stop":new DOMException("permission-stop","AbortError")};var OXe="server-fallback-tombstone";var u2t=new DOMException(OXe,"AbortError");var TXe="subagent-park",d2t=new DOMException(TXe,"AbortError");import{spawn as HXe}from"child_process";import{existsSync as $Xe}from"fs";import{createInterface as zXe}from"readline";import{StringDecoder as BXe}from"string_decoder";var wXe=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var Ak={bearer:[/\bBearer\s+(?=[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]|%[0-9A-Fa-f]{2}){7})[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]+|%[0-9A-Fa-f]{2})*/gi,"Bearer <token>"],basic:[/(:\s*)Basic\s+[A-Za-z0-9+/=]{8,}/gi,"$1Basic <token>"],sk:[/\bsk-[A-Za-z0-9_-]{20,}/g,"<token>"]},vXe=[/\bBearer\s{1,512}(?=[A-Za-z0-9._~+/=-](?:[A-Za-z0-9._~+/=-]|%(?!20)[0-9A-Fa-f]{2}){15})(?:eyJ|(?=(?:[A-Za-z0-9._~+/=-]|%(?!20)[0-9A-Fa-f]{2}){0,64}[0-9=]))/i,/:\s{0,512}Basic\s{1,512}(?=[A-Za-z0-9+/=]{16})(?=[A-Za-z0-9+/=]{0,64}[0-9=])/i,/\bsk-(?=[A-Za-z0-9_-]{20})(?=[A-Za-z0-9_-]{0,64}[0-9])/];var f2t=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${du("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${du("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),gJ=[[Of("sk-ant-","[A-Za-z0-9_-]",8,Rk(8)),"<token>"],[Of("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,Rk(20)),"<token>"]],hJ=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],xXe=`(?:${hJ.join("|")})`,_J=[[new RegExp(`(^|[^A-Za-z0-9+])${xXe}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],yJ=[[Of("gh[opusr]_","[A-Za-z0-9]",20,du("[A-Za-z0-9]")),"<token>"],[/github_pat_[A-Za-z0-9_]{82,}/g,"<token>"],[/sq0(?:atp|csp)-[A-Za-z0-9_-]{22,}/g,"<token>"],[/(^|[^A-Za-z0-9+/])EAAA[A-Za-z0-9+/=%_-]{56,}/g,"$1<token>"],[Of("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,du("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[Of("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",du("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${du("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[wXe,"hooks.slack.com/<redacted>"]];var kXe=[new RegExp("(?<![A-Za-z0-9_-])(?=[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*)((?:[A-Za-z0-9_-]*?-)??)ey[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]{10}[A-Za-z0-9_-]*","g"),"$1<jwt>"],PXe=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,SJ=[[/(^|[^A-Za-z0-9+_-])AIza[A-Za-z0-9_-]{35}(?![A-Za-z0-9+=_-])/g,"$1<token>"],[/(^|[^A-Za-z0-9+_-])GOCSPX-[A-Za-z0-9_-]{28}(?![A-Za-z0-9+=_-])/g,"$1<token>"]],EJ=[[/(^|[^A-Za-z0-9+_-])[sr]k_(?:live|test|prod)_(?=[A-Za-z0-9]{0,64}[0-9])[A-Za-z0-9]{24,}(?![A-Za-z0-9+=_-])/g,"$1<token>"]],IXe=[Ak.bearer,Ak.basic,...gJ,Ak.sk,..._J],DXe=[...yJ,kXe,...SJ,...EJ],m2t=[[new RegExp(`sk-${Rk(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...hJ.map((e)=>[new RegExp(`${e}[A-Z2-7]{16}`,"g"),"<token>"]),[/AIza[\w-]{35}/g,"<token>"],[/GOCSPX-[\w-]{28,}/g,"<token>"],[/[sr]k_(?:live|test|prod)_[A-Za-z0-9]{24,}/g,"<token>"]];function Tf(e){return[...IXe,...DXe].reduce((t,[n,r])=>t.replace(n,r),String(e))}var g2t=[...vXe,...[...gJ,..._J,...yJ,...SJ,...EJ].map(([e])=>new RegExp(e.source,e.flags.replaceAll("g",""))),PXe];function Of(e,t,n,r,o="",s="",i="g"){let a=`${t}{${n},}${o}`;return new RegExp(`(?:\\b${e}${s}${a}|${e}${r}${a})`,i)}function du(e){return`(?=${e}{0,64}[0-9])`}function Rk(e){return`(?=[A-Za-z0-9_-]{0,64}?(?=[A-Za-z0-9]{${e}})(?=[A-Za-z0-9]{0,64}[0-9])(?=[A-Za-z0-9]{0,64}[A-Za-z]))`}function LXe(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")}var MXe=new Set(["filesystem.denyRead","filesystem.denyWrite","network.deniedDomains","credentials.files","credentials.envVars"]),NXe=new Set(["ripgrep","network.tlsTerminate"]),UXe=new Set(["__proto__","constructor","prototype"]),FXe=["httpProxyPort","socksProxyPort"];function bJ(e,t,n=""){let r=Rr(e)?{...e}:{};for(let[o,s]of Object.entries(t)){if(UXe.has(o)||s===void 0)continue;let i=n?`${n}.${o}`:o,a=Object.hasOwn(r,o)?r[o]:void 0;if(MXe.has(i)&&Array.isArray(a)&&Array.isArray(s))r[o]=Nt([...a,...s]);else if(Rr(a)&&Rr(s)&&!NXe.has(i))r[o]=bJ(a,s,i);else r[o]=s}return r}function CJ(e,t){let n={...e};if(!t)return n;let r=n.settings;if(r&&!LXe(r))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let o={};if(r)try{o=je(r)}catch{}let s=bJ(o.sandbox,t),i=t.credentials?.files,a=t.filesystem!==void 0||Array.isArray(i)&&i.some((f)=>Rr(f)&&f.mode==="deny"),l=s.filesystem;if(a&&t.filesystem?.disabled===void 0&&Rr(l)&&l.disabled===!0)delete l.disabled;let c=t.network,d=c?.allowedDomains!==void 0||(c?.deniedDomains?.length??0)>0||c?.strictAllowlist===!0,p=s.network;if(d&&Rr(p)){for(let f of FXe)if(c?.[f]===void 0&&p[f]!==void 0)delete p[f]}if(t.enabled===!0&&s.failIfUnavailable===void 0)s.failIfUnavailable=!0;return n.settings=ce({...o,sandbox:s}),n}function Ye(e,t){return`${e}=${t}`}function iS(e,t){let n=String(t);if(n.length>1&&n.startsWith("-"))return[Ye(e,n)];return[e,n]}function AJ(e,t,n){e.push(...iS(`--${t}`,n))}var jXe=2000,Ok=2048,TJ="sdk-exit-after-stderr-drained",KXe=200;function Tk(e){return e==="exit"?TJ:e}class wJ{#e=new Set;#t=!1;#n=()=>this.killAll();track(e){if(this.#e.add(e),!this.#t)this.#t=!0,process.on("exit",this.#n)}untrack(e){this.#e.delete(e)}isTracking(e){return this.#e.has(e)}get size(){return this.#e.size}killAll(){for(let e of this.#e)if(!e.killed)if(process.platform==="win32")try{e.stdin.end()}catch{}else e.kill("SIGTERM")}reset(){process.off("exit",this.#n),this.#t=!1,this.#e.clear()}}var aS=new wJ,GXe=/[(),\u0000-\u001f\u007f-\u009f]/;function WXe(e){if(typeof e!=="string"||e.trim()==="")throw Error("Skill names must be non-empty strings.");if(!Uu(e))throw new ve(`Invalid skill name ${ce(e)}: the name contains an unpaired surrogate, which cannot survive the UTF-8 encoding of the CLI invocation; no skill discovered from the filesystem can have such a name.`,"skill name with unpaired surrogate rejected");if(e!==e.trim())throw new ve(`Invalid skill name ${ce(e)}: leading or trailing whitespace is not allowed — the Skill tool trims the invoked name, so a padded rule can never match. Remove the padding.`,"skill name with surrounding whitespace rejected");if(GXe.test(e))throw new ve(`Invalid skill name ${ce(e)}: parentheses, commas, and control characters are not allowed in skill names. Skill names match the skill's directory name (or 'plugin:skill' for plugin-qualified skills); rename the skill if its directory name contains these characters.`,"invalid skill name rejected");if(e==="*")throw Error("Invalid skill name '*': use skills: 'all' to enable every skill.");if(e.endsWith(":*")||e.endsWith(" *"))throw new ve(`Invalid skill name ${ce(e)}: wildcard-suffix names are not allowed; list each skill by its exact name.`,"wildcard-suffix skill name rejected");if(e.startsWith("/"))throw new ve(`Invalid skill name ${ce(e)}: skill names may not start with '/'. Skills are invoked as slash commands, but the skills option takes the skill's canonical name — the directory name, or 'plugin:skill'.`,"skill name with leading slash rejected");if(e.includes("\\\\"))throw new ve(`Invalid skill name ${ce(e)}: consecutive backslashes are not allowed — the permission-rule parser collapses escaped backslashes, so the rule would name a different skill. Rename the skill.`,"skill name with consecutive backslashes rejected");if(e.endsWith("\\"))throw new ve(`Invalid skill name ${ce(e)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return e}class vk{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";exitListeners=[];abortHandler;forwardedAbort=Rf();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||Rf(),e.deferSpawn)this.spawnPromise=new Promise((t,n)=>{this.spawnResolve=t,this.spawnReject=n}),this.spawnPromise.catch(()=>{});else this.initialize()}spawn(){try{this.initialize()}catch(t){throw this.spawnAbort(Yn(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 Xa()?"bun":"node"}spawnLocalProcess(e){let{command:t,args:n,cwd:r,env:o,signal:s}=e,i=performance.now(),a=HXe(t,n,{cwd:r,stdio:["pipe","pipe","pipe"],signal:s,env:o,windowsHide:!0}),l=performance.now()-i;if(a.pid!==void 0&&this.options.onProcessSpawned)try{this.options.onProcessSpawned(a.pid,{spawnSyncMs:l})}catch(S){on(`onProcessSpawned threw: ${ft(S)}`)}let c=new BXe("utf8"),d=!1,p=!1,f=!1,m,g=Ae(o.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;a.stderr.on("data",(S)=>{if(f)return;let E=c.write(S);if(this.stderrTail+=E,this.stderrTail.length>2*Ok)this.stderrTail=gm(Tf(this.stderrTail),Ok);if(g)on(E),this.options.stderr?.(E)}),a.stderr.on("error",(S)=>{on(`[ProcessTransport] stderr read failed: ${S.code??S.message}`)});let _=()=>{if(f)return;if(f=!0,m)clearTimeout(m);a.emit(TJ,a.exitCode,a.signalCode);let S=a.stderr;if(ZXe(S))S.unref();else S.destroy()};return a.stderr.once("close",()=>{if(this.stderrTail+=c.end(),d=!0,p)_()}),a.once("exit",()=>{if(p=!0,this.ready=!1,d)_();else m=setTimeout(_,KXe)}),{stdin:a.stdin,stdout:a.stdout,get killed(){return a.killed},get exitCode(){return a.exitCode},get signalCode(){return a.signalCode},kill:a.kill.bind(a),on:(S,E)=>a.on(Tk(S),E),once:(S,E)=>a.once(Tk(S),E),off:(S,E)=>a.off(Tk(S),E)}}initialize(){try{let{additionalDirectories:e=[],projectConfigRoot:t,agent:n,betas:r,cwd:o,executable:s=this.getDefaultExecutable(),executableArgs:i=[],extraArgs:a={},pathToClaudeCodeExecutable:l,env:c={...process.env},thinkingConfig:d,maxTurns:p,maxBudgetUsd:f,taskBudget:m,model:g,fallbackModel:_,jsonSchema:y,permissionMode:S,allowDangerouslySkipPermissions:E,permissionPromptToolName:b,permissionPrompts:C,continueConversation:A,resume:R,settingSources:x,skills:L,disallowedTools:F=[],tools:re,mcpServers:T,strictMcpConfig:w,canUseTool:I,includePartialMessages:M,plugins:z,pluginsViaInitialize:J,sandbox:Q}=this.options,{allowedTools:W=[]}=this.options;if(L!==void 0){let ge=L==="all"?["Skill"]:L.map((Fe)=>`Skill(${WXe(Fe)})`),sn=new Set(W);W=[...W,...ge.filter((Fe)=>!sn.has(Fe))]}let B=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(d){switch(d.type){case"enabled":if(d.budgetTokens===void 0)B.push("--thinking=adaptive");else B.push(Ye("--max-thinking-tokens",d.budgetTokens));break;case"disabled":B.push("--thinking=disabled");break;case"adaptive":B.push("--thinking=adaptive");break}if(d.type!=="disabled"&&d.display)B.push(Ye("--thinking-display",d.display))}if(this.options.effort)B.push(Ye("--effort",this.options.effort));if(p)B.push(Ye("--max-turns",p));if(f!==void 0)B.push(Ye("--max-budget-usd",f));if(m)B.push(Ye("--task-budget",m.total));if(g)B.push(Ye("--model",g));if(n)B.push(Ye("--agent",n));if(r&&r.length>0)B.push(Ye("--betas",r.join(",")));if(y)B.push(Ye("--json-schema",ce(y)));if(this.options.debugFile)B.push(Ye("--debug-file",this.options.debugFile));else if(this.options.debug)B.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let ge=RW();if(ge)B.push(Ye("--debug-file",ge))}if(I){if(b)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");B.push("--permission-prompt-tool=stdio")}else if(b)B.push(Ye("--permission-prompt-tool",b));if(C)B.push(Ye("--permission-prompts",C));if(A)B.push("--continue");if(R)B.push(Ye("--resume",R));if(this.options.channels&&this.options.channels.length>0)for(let ge of this.options.channels)B.push(Ye("--channels",ge));if(W.length>0)B.push(Ye("--allowedTools",W.join(",")));if(F.length>0)B.push(Ye("--disallowedTools",F.join(",")));if(re!==void 0)if(Array.isArray(re))B.push(Ye("--tools",re.join(",")));else B.push("--tools=default");if(T&&Object.keys(T).length>0)B.push(...iS("--mcp-config",ce({mcpServers:T})));if(x!==void 0)B.push(Ye("--setting-sources",x.join(",")));if(w)B.push("--strict-mcp-config");if(S)B.push(Ye("--permission-mode",S));if(E)B.push("--allow-dangerously-skip-permissions");if(_){if(g&&_===g)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");B.push(Ye("--fallback-model",_))}if(this.options.includeHookEvents)B.push("--include-hook-events");if(M)B.push("--include-partial-messages");if(this.options.sessionMirror)B.push("--session-mirror");if(t!==void 0)B.push(Ye("--project-config-root",t));for(let ge of e)B.push(Ye("--add-dir",ge));if(J)B.push("--await-initialize");else if(z&&z.length>0)for(let ge of z)if(ge.type==="local")B.push(ge.skipMcpDiscovery?Ye("--plugin-dir-no-mcp",ge.path):Ye("--plugin-dir",ge.path));else throw Error(`Unsupported plugin type: ${ge.type}`);if(this.options.forkSession)B.push("--fork-session");if(this.options.resumeSessionAt)B.push(Ye("--resume-session-at",this.options.resumeSessionAt));if(this.options.resumeDropsTurn!==void 0)B.push(Ye("--resume-drops-turn",this.options.resumeDropsTurn));if(this.options.sessionId)B.push(Ye("--session-id",this.options.sessionId));if(this.options.persistSession===!1)B.push("--no-session-persistence");if(this.options.managedSettings)B.push(...iS("--managed-settings",this.options.managedSettings));let it={...a??{}};if(this.options.settings)it.settings=this.options.settings;let Ve=CJ(it,Q);for(let[ge,sn]of Object.entries(Ve))if(sn===null)B.push(`--${ge}`);else AJ(B,ge,sn);if(!c.CLAUDE_CODE_ENTRYPOINT)c.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete c.NODE_OPTIONS,Ae(c.DEBUG_CLAUDE_AGENT_SDK))c.DEBUG="1";else delete c.DEBUG;let ot=VXe(l),At=ot?l:s,Zt=ot?[...i,...B]:[...i,l,...B],Ke={command:At,args:Zt,cwd:o,env:c,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)on(`Spawning Claude Code (custom): ${At} ${Zt.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(Ke);else on(`Spawning Claude Code: ${At} ${Zt.join(" ")}`),this.process=this.spawnLocalProcess(Ke);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(ge)=>{on(`[ProcessTransport] stdin write failed (child likely exited): ${ge.code??ge.message}`),this.ready=!1}),aS.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let we=this.process;we.on("error",(ge)=>{this.ready=!1;let sn=ge,Fe=sn.syscall!==void 0?sn.syscall.startsWith("spawn"):mE(ge);if(Fe&&!we.killed)aS.untrack(we);if(this.abortController.signal.aborted)this.exitError=lS(),hn(ge,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(Fe&&mE(ge)){let{message:En,telemetryMessage:ys,errorClass:Ni}=qXe(l,ot),Io={telemetryMessage:`${ys}${wk(ge)}`,errorClass:Ni,code:Ru(ge)};this.exitError=hn(ReferenceError(En),Io),hn(ge,Io),on(this.exitError.message)}else{let En={telemetryMessage:Fe?`Failed to spawn Claude Code process${wk(ge)}`:`Claude Code process error${wk(ge)}`,errorClass:Fe?"spawn_failed":"process_error",code:Ru(ge)};this.exitError=hn(Error(`Failed to spawn Claude Code process: ${Tf(ge.message)}`),En),hn(ge,En),on(this.exitError.message)}}),we.on("exit",(ge,sn)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=lS();else{let Fe=this.getProcessExitError(ge,sn);if(Fe)this.exitError=Fe,on(Fe.message)}}),this.ready=!this.abortController.signal.aborted}catch(e){throw this.ready=!1,e}}getProcessExitError(e,t){if(e!==0&&e!==null){let n=Number.isInteger(e)?e:void 0;return hn(Error(`Claude Code process exited with code ${e}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process exited with code ${n??"unknown"}`,errorClass:"process_exited_nonzero",exitCode:n})}else if(t){let n=/^SIG[A-Z0-9]{1,8}$/.test(t)?t:"unknown";return hn(Error(`Claude Code process terminated by signal ${t}${this.formatStderrTail()}`),{telemetryMessage:`Claude Code process terminated by signal ${n}`,errorClass:"process_killed_by_signal",signal:n})}return}formatStderrTail(){let e=gm(Tf(this.stderrTail),Ok).trim();return e?`. stderr: ${e}`:""}write(e){if(this.abortController.signal.aborted)throw RJ();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){on("[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 hn(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${OP(this.exitError)??"untagged exit error"}`,errorClass:OJ(this.exitError,"errorClass"),code:Ru(this.exitError),exitCode:YXe(this.exitError),signal:OJ(this.exitError,"signal")});on(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{if(!this.processStdin.write(e))on("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${ft(t)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?lS():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;let e=this.process?.exitCode??null,t=this.process?.signalCode??null,n=!this.exitEventDelivered&&(e!==null&&e>=0||t!==null),r;if(n){if(this.exitEventDelivered=!0,r=this.abortController.signal.aborted?lS():this.getProcessExitError(e,t),r&&!this.exitError)this.exitError=r}let o=this.exitListeners;this.exitListeners=[];for(let{callback:a,handler:l}of o)if(this.process?.off("exit",l),n)try{a(r)}catch(c){on(`[ProcessTransport] onExit callback threw during close(): ${ft(c)}`)}let s=()=>{if(this.abortController.signal.aborted)this.forwardedAbort.abort(this.abortController.signal.reason)},i=this.process;if(i&&!i.killed&&i.exitCode===null&&i.signalCode==null)setTimeout((a,l)=>{if(a.exitCode!==null||a.signalCode!=null){l();return}if(process.platform==="win32"){setTimeout((c,d)=>{if(c.exitCode===null)c.kill("SIGKILL");d()},5000,a,l).unref();return}a.kill("SIGTERM"),setTimeout((c)=>{if(c.exitCode===null)c.kill("SIGKILL")},5000,a).unref(),l()},jXe,i,s).unref(),i.once("exit",()=>aS.untrack(i));else if(i)aS.untrack(i),s();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=zXe({input:this.processStdout}),t=this.process?(()=>{let n=this.process,r=()=>e.close();return n.on("error",r),()=>n.off("error",r)})():void 0;if(this.exitError)e.close();try{for await(let n of e)if(n.trim()){let r;try{r=je(n)}catch(o){on(`Non-JSON stdout: ${n}`);continue}yield r}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()}onExit(e){if(!this.process)return()=>{};let t=(n,r)=>{let o=this.getProcessExitError(n,r);e(o)};return this.process.on("exit",t),this.exitListeners.push({callback:e,handler:t}),()=>{if(this.process)this.process.off("exit",t);let n=this.exitListeners.findIndex((r)=>r.handler===t);if(n!==-1)this.exitListeners.splice(n,1)}}async waitForExit(){if(this.exitError)throw this.exitError;if(!this.process||this.process.exitCode===0||this.process.killed&&this.exitEventDelivered)return;return new Promise((e,t)=>{let n=(o,s)=>{if(this.abortController.signal.aborted){t(RJ());return}let i=this.getProcessExitError(o,s);if(i)t(i);else e()};this.process.once("exit",n);let r=(o)=>{this.process.off("exit",n),t(o)};this.process.once("error",r),this.process.once("exit",()=>{this.process.off("error",r)})})}}function VXe(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((n)=>e.endsWith(n))}function qXe(e,t){let n=t?"native binary":"executable",r=Tf(e);if($Xe(e))return{message:t?`Claude Code native binary at ${r} 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 ${r} exists but failed to launch.`,telemetryMessage:`Claude Code ${n} exists at the configured path but failed to launch`,errorClass:"executable_launch_failed"};return{message:t?`Claude Code native binary not found at ${r}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${r}. Is options.pathToClaudeCodeExecutable set?`,telemetryMessage:`Claude Code ${n} not found at the configured path`,errorClass:"executable_not_found"}}function wk(e){let t=Ru(e);return t===void 0?"":` (${t})`}function lS(){return hn(new tr("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function RJ(){return hn(new tr("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function OJ(e,t){let n=Object.hasOwn(e,t)?Reflect.get(e,t):void 0;return typeof n==="string"?n:void 0}function YXe(e){let t=Object.hasOwn(e,"exitCode")?Reflect.get(e,"exitCode"):void 0;return typeof t==="number"?t:void 0}function ZXe(e){return typeof Reflect.get(e,"unref")==="function"}import{existsSync as JXe}from"fs";var pu="@anthropic-ai/claude-agent-sdk";function XXe(){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 vJ(e,t={}){let n=t.platform??process.platform,r=t.arch??process.arch,o=t.exists??JXe,s=t.preferMusl??XXe(),i="claude",a=n==="win32"?".exe":"",c=(n==="android"?[`${pu}-linux-${r}-android`]:n==="linux"?s?[`${pu}-linux-${r}-musl`,`${pu}-linux-${r}`]:[`${pu}-linux-${r}`,`${pu}-linux-${r}-musl`]:[`${pu}-${n}-${r}`]).map((d)=>`${d}/claude${a}`);for(let d of c)try{let p=e(d);if(o(p))return p}catch{}return null}function xJ({supportedDialogKinds:e,onUserDialog:t}){if(e!==void 0&&e.length>0&&!t)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.")}var QXe=["signed_out","identity_changed","transient","refresh_failed"];function kJ(e){return QXe.some((t)=>t===e)}var cS=600000;var PJ=600000,uS=["SessionStart","Setup"];var dS=60000,IJ=PJ,DJ=dS+IJ,e8e="startupHooksOpen",t8e=64;class xk{clock;onRunning;limitMs;countedLeftMs;uncountedLeftMs;uncountedMs=0;counting=!0;armedAtMs=0;cancelTimer;rejectExpired;followed=new Set;unfollowedOpen=0;reportedEvents=new Set;reported=0;constructor(e,t=Ka,n){this.clock=t;this.onRunning=n;this.limitMs=e??dS,this.countedLeftMs=this.limitMs,this.uncountedLeftMs=e==null?IJ:0}race(e){let t=new Promise((n,r)=>{this.rejectExpired=r});return this.arm(),Promise.race([e,t]).finally(()=>this.end())}note(e){if(this.rejectExpired===void 0||e.type!=="system")return;switch(e.subtype){case"hook_started":if(!uS.includes(e.hook_event)||this.followed.has(e.hook_id))return;if(this.followed.size<t8e)this.followed.add(e.hook_id);else this.unfollowedOpen++;if(this.reportedEvents.add(e.hook_event),this.reported++,this.counting&&this.uncountedLeftMs>0)this.countedLeftMs=Math.max(0,this.countedLeftMs-this.armedForMs()),this.counting=!1,this.arm();this.onRunning?.(this.open());return;case"hook_response":if(!this.followed.delete(e.hook_id)){if(this.unfollowedOpen===0||!uS.includes(e.hook_event))return;this.unfollowedOpen--}if(!this.counting)this.countAgain();this.onRunning?.(this.open());return;default:return}}open(){return this.followed.size+this.unfollowedOpen}armedForMs(){return this.clock.monotonicNow()-this.armedAtMs}arm(){if(this.cancelTimer?.(),this.armedAtMs=this.clock.monotonicNow(),!this.counting){this.cancelTimer=this.clock.setTimeout(()=>this.countAgain(),this.uncountedLeftMs);return}let e=Math.min(this.countedLeftMs,Zc);this.cancelTimer=this.clock.setTimeout(()=>{if(this.countedLeftMs-=e,this.countedLeftMs>0)this.arm();else this.expire()},e)}countAgain(){let e=Math.min(Math.max(0,this.armedForMs()),this.uncountedLeftMs);this.uncountedLeftMs-=e,this.uncountedMs+=e,this.counting=this.open()===0||this.uncountedLeftMs<=0,this.arm()}expire(){let e=this.rejectExpired,t=`Subprocess initialization did not complete within ${this.limitMs}ms`,n=uS.join(" or "),r=Math.round(this.uncountedMs/1000),o=this.open(),s=`${this.reported} ${[...this.reportedEvents].join(" and ")} ${Ts(this.reported,"hook")}`,i=[`${t}.`,...r>0?[`Not counted: ${r} ${Ts(r,"second")} in which Claude Code reported a ${n} hook running.`]:[],this.reported===0?`Claude Code did not answer the initialize request and reported no ${n} hook running. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:o===0?`Claude Code reported ${s}, which ${this.reported===1?"":"all "}finished, and then did not answer the initialize request. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:`Claude Code reported ${s}, ${this.reported===1?"which had not finished":o===this.reported?"none of which had finished":`${o} of which had not finished`}, and did not answer the initialize request. A hook that runs in the background counts as not finished until it ends. Check ${this.reported===1?"this hook":"these hooks"} first, then authentication and network connectivity.`],a=Object.assign(hn(Error(i.join(" ")),{telemetryMessage:t,errorClass:"initialize_timeout"}),{[e8e]:o});this.end(),e?.(a)}end(){this.cancelTimer?.(),this.cancelTimer=void 0,this.rejectExpired=void 0}}var LJ="SDK MCP server not found";var MJ="No hook callback found for ID";var kk="startup_mark",NJ="startupMark",UJ="startupMarkAgeMs",FJ=64;function HJ(e){return"method"in e&&"id"in e&&e.id!==null}var $J=Object.freeze({}),zJ=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),tqt=Symbol("swallow");class Pk{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 BJ=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var jJ="2025-11-25";var n8e="notifications/tools/list_changed";function KJ(e){return oe(e)&&!("id"in e)&&e.method===n8e}var GJ=250,r8e=new Set(["interrupt","cancel_async_message"]),pS="sdk-manifest-capture:",fu=Symbol("suppressControlResponse");function WJ(e,t,n){for(let r of n){let o=r==="tools"?fv(t):void 0;G(o?`[Query] MCP server '${e}': ${ZY(o)}`:`[Query] MCP server '${e}': ignoring malformed ${r} in its config`)}}class fS{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;verbatimPrompts;runEndCeilingMs;pendingControlResponses=new Map;unmatchedControlResponses=new Map;static UNMATCHED_CONTROL_RESPONSES_MAX=1024;cleanupPerformed=!1;cleanupCause;sdkMessages;inputStream=new Pp;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;promptHold;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;lastStartupFailureReason;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let n={type:"system",subtype:"mirror_error",error:t,key:e,uuid:za(),session_id:e.sessionId};this.inputStream.enqueue(n)}addCleanupCallback(e){if(this.cleanupPerformed)e();else this.cleanupCallbacks.push(e)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpServers.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||this.workSecretAnswerer!==void 0}remoteControlCallGeneration=0;uiHost;workSecretAnswerer;constructor(e,t,n,r,o,s=new Map,i,a,l,c,d,p,f=!1,m=cS){this.transport=e;this.isSingleUserTurn=t;this.canUseTool=n;this.hooks=r;this.abortController=o;this.jsonSchema=i;this.initConfig=a;this.onElicitation=l;this.getOAuthToken=c;this.getHostAuthToken=d;this.onUserDialog=p;this.verbatimPrompts=f;this.runEndCeilingMs=m;for(let[g,_]of s)this.connectSdkMcpServer(g,_);if(this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((g)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,g()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{}),this.hasHookSetToBlock()){let g=setTimeout(()=>{this.cleanup(Error('Claude Code did not answer initialize, so a hook set to onFailure: "block" could not be confirmed and the prompt was not sent. Check the connection and start a new session.'))},DJ);g.unref?.(),this.promptHold=this.initialization.then(()=>(clearTimeout(g),!0),(_)=>(clearTimeout(g),this.cleanup(_),!1)),this.writeBehindPromptHold(this.promptHold,()=>{})}}writeBehindPromptHold(e,t){let n=e.then(async(o)=>{if(!o||this.abortController?.signal.aborted)return!1;return await t(),!0}),r=n.catch(()=>!0).then((o)=>{if(o&&this.promptHold===r)this.promptHold=void 0;return o});return this.promptHold=r,n}hasHookSetToBlock(){return Object.values(this.hooks??{}).some((e)=>Array.isArray(e)&&e.some((t)=>t?.onFailure!=null&&t.onFailure!=="continue"))}setError(e){this.inputStream.error(e)}setFrameObserver(e){this.frameObserver=e}dropUnreadHookProgress(e){this.inputStream.dropNewestQueued((t)=>t.type==="system"&&t.subtype==="hook_progress"&&t.hook_id===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.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),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 t of this.cancelControllers.values())t.abort();this.cancelControllers.clear(),this.transport.close()}catch(t){G(`[Query.cleanup] transport.close() failed: ${ft(t)}`,{level:"error"})}try{let t=e??Ik();for(let{reject:n}of this.pendingControlResponses.values())n(t);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:n}of this.pendingMcpResponses.values())n(t);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let{transport:n}of this.sdkMcpServers.values())n.close().catch(()=>{});if(this.sdkMcpServers.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(),_n(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>=fS.UNMATCHED_CONTROL_RESPONSES_MAX){let n=this.unmatchedControlResponses.keys().next().value;if(n!==void 0)this.unmatchedControlResponses.delete(n)}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"){if(kk in e){let t=e[kk];if(typeof t==="string"&&t.length<=FJ)this.startupMark={mark:t,atMs:Date.now()}}continue}else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){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((n)=>n.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||void 0,this.lastStartupFailureReason=e.is_error&&"startup_failure_reason"in e&&typeof e.startup_failure_reason==="string"?e.startup_failure_reason:void 0,this.modelLessTurnEnded=e.subtype==="success"&&!e.is_error&&e.num_turns===0&&e.result==="",!this.modelLessTurnEnded)this.errorTextBeforeModelLessTurns=this.lastErrorResultText;if(this.resultReceived=!0,this.sessionState===void 0||this.sessionState==="idle"||!this.hasBidirectionalNeeds())this.endRun();else this.armRunEndCeiling()}else if(e.type==="system"&&e.subtype==="session_state_changed"){if(this.sessionState=e.state,e.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,e.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in e&&e.sdk_host_only===!0)continue}else if(!(e.type==="system"&&e.subtype==="session_writes_lost")){if(this.lastErrorResultText=void 0,this.lastStartupFailureReason=void 0,e.type==="system"&&e.subtype==="init")this.modelLessTurnEnded=!1;else if(e.type!=="system"||e.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((e.type==="assistant"||e.type==="stream_event")&&e.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}try{this.frameObserver?.(e)}catch(t){G(`[Query.readMessages] The frame observer threw: ${ft(t)}`,{level:"error"})}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(t!==void 0&&!(e instanceof tr)&&e?.name!=="SSEHttpError"){let n=hn(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result",startupFailureReason:this.lastStartupFailureReason});G(`[Query.readMessages] Replacing exit error with result text. Original: ${ft(e)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){G(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){G(`[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 n;try{let r=await this.processControlRequest(e,t.signal);if(this.cleanupPerformed)return;if(r===fu)return;let o={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:r}};n=ce(o)+`
|
|
156
156
|
`}catch(r){if(this.cleanupPerformed)return;let o={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:ft(r)}};n=ce(o)+`
|
|
157
|
-
`}try{await Promise.resolve(this.transport.write(n))}catch(r){G(`[Query.handleControlRequest] Response write failed: ${ft(r)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(BJ.some((n)=>n===e.request.subtype))return G(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),fu;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(r===null)return fu;return{...r,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);else if(e.request.subtype==="mcp_message"){let n=e.request,r=this.sdkMcpServers.get(n.server_name)?.transport;if(!r)throw Error(`${LJ}: ${n.server_name}`);if(HJ(n.message))return{mcp_response:await this.handleMcpControlRequest(n.server_name,n,r)};else{if(r.onmessage)r.onmessage(n.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let n=e.request;if(this.onElicitation){let r=await this.onElicitation({serverName:n.mcp_server_name,message:n.message,mode:n.mode,url:n.url,elicitationId:n.elicitation_id,requestedSchema:n.requested_schema,title:n.title,displayName:n.display_name,description:n.description},{signal:t,requestId:e.request_id});if(r===null)return fu;return r}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let n=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:t,requestId:e.request_id});if(n===null)return fu;return n}return G(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),pi("tengu_request_user_dialog_response_ignored",{shape:Cs("auto_cancel")}),fu}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let n,r=await this.getOAuthToken({signal:t,onDecline:(o)=>{if(kJ(o))n=o},...e.request.kind!==void 0&&{kind:e.request.kind}})??null;return r===null&&n!==void 0?{accessToken:r,reason:n}:{accessToken:r}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let n=await this.getHostAuthToken({signal:t})??null;return typeof n==="string"||n===null?{authToken:n}:n}else if(e.request.subtype==="remote_control_work_secret"){let n=this.workSecretAnswerer;if(!n)throw Error("refreshWorkSecret callback is not provided.");if(!VJ(n.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await n.refresh(n.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:n,...r}=e.request;return this.uiHost.copy(r,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:n,...r}=e.request;return this.uiHost.promptRead(r,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:n,...r}=e.request;return this.uiHost.promptFill(r,{signal:t})}if(e.request.subtype==="ui_prompt_paint"&&this.uiHost?.promptPaint){let{subtype:n,...r}=e.request;return this.uiHost.promptPaint(r,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:n,...r}=e.request;return this.uiHost.promptSuggest(r,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:n,...r}=e.request;return this.uiHost.readSelection(r,{signal:t})}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let t,n;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){t=await this.captureSdkMcpServerManifests();for(let i of this.sdkMcpToolsChangedDuringCapture){let a=t!==void 0&&Object.hasOwn(t,i)?t[i]:void 0;if(a?.toolsListResult!==void 0)t[i]={initializeResult:a.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let s=this.buildInitializeRequest(t);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{n=this.request(s)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let o=(await n).response;if(this.hasHookSetToBlock()){let s=o.hook_on_failure_supported!==!0?Error('The process answering initialize does not honor onFailure on hook matchers, so a hook that fails would not block. Update Claude Code if it is old, or remove onFailure: "block" from your hooks.'):e&&o.hooks_applied===!1?Error('This session was already running and did not register your hooks, so a hook set to onFailure: "block" would never run. Start a new session, or remove onFailure: "block" from your hooks.'):void 0;if(s!==void 0)throw this.cleanup(s),s}if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&o.plugins_applied!==!0)G(`[Query.initialize] Claude Code reported plugins_applied=${String(o.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return o}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[s,i]of Object.entries(this.hooks))if(i?.length>0)this.initHooksPayload[s]=i.map((a)=>{let l=[];for(let c of a.hooks){let d=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(d,c),l.push(d)}return{matcher:a.matcher,hookCallbackIds:l,timeout:a.timeout,onFailure:a.onFailure}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([s,{settings:i}])=>Object.keys(i).length>0?[[s,i]]:[]),r=n.length>0?Object.fromEntries(n):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:r,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,r=async(p,f)=>{try{if(await this.sdkMcpServers.get(p)?.connection,n)return;let m=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:pS+"initialize",method:"initialize",params:{protocolVersion:jJ,capabilities:$J,clientInfo:{...zJ,version:"0.3.321"}}}},f);if(n)return;if(!("result"in m)){G(`[Query.captureSdkMcpServerManifests] '${p}' answered initialize with an error; leaving it to the CLI: ${ce(m)}`,{level:"warn"});return}let g=m.result;f.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let _=g.capabilities,y=typeof _==="object"&&_!==null&&"tools"in _&&_.tools!==void 0&&_.tools!==null,S;if(y){let C=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:pS+"tools-list",method:"tools/list"}},f);if(n)return;if(!("result"in C)){G(`[Query.captureSdkMcpServerManifests] '${p}' answered tools/list with an error; leaving it to the CLI: ${ce(C)}`,{level:"warn"});return}if(C.result.nextCursor===void 0)S=C.result}let b=je(ce(S===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:S}));t.set(p,{transport:f,manifest:b})}catch(m){if(!n)G(`[Query.captureSdkMcpServerManifests] '${p}': ${m}; the CLI will handshake it over the control channel`,{level:"warn"})}},o=Array.from(this.sdkMcpServers,([p,{transport:f}])=>r(p,f)),s=Promise.all(o).then(()=>"settled"),i=new Promise((p)=>{this.stopSdkMcpManifestCapture=()=>p("closed")}),a=await Ou(Promise.race([s,i]),GJ);n=!0,this.stopSdkMcpManifestCapture=void 0;let l=Math.round(performance.now()-e),c={servers:o.length,captured:t.size,elapsed_ms:l};if(a==="closed"){pc("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)G(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${GJ} ms; the rest will handshake over the control channel`,{level:"warn"}),pc("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)pc("sdk_mcp_manifest_capture","partial",c);else kp("sdk_mcp_manifest_capture",c);if(t.size===0)return;let d=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([p,f])=>{let m=t.get(p);return m!==void 0&&m.transport===f.transport?[[p,m.manifest]]:[]}));if(Object.keys(d).length===0)return;return G(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(d).join(", ")}] captured in ${l} ms`),d}async interrupt(e){return rn("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let r=t.response?.cancelled;return{still_queued:n.filter((o)=>typeof o==="string"),...Array.isArray(r)&&{cancelled:r.filter((o)=>typeof o==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let r=(s)=>{if(s.subtype==="success"){let{pending_permission_requests:i,pending_user_dialog_requests:a,pending_elicitation_requests:l,...c}=s;t(c)}else n(new ve(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests||s.pending_elicitation_requests)G("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Ik());return}let o=this.unmatchedControlResponses.get(e);if(o){this.unmatchedControlResponses.delete(e),r(o);return}this.pendingControlResponses.set(e,{handler:(s)=>{this.pendingControlResponses.delete(e),r(s)},reject:n})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:t})}async applyFlagSettings(e){return rn("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,t){return rn("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return rn("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,t){await this.request({subtype:"seed_read_state",path:e,mtime:t})}async setCwd(e,t){return rn("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...t?.trustAccepted!==void 0&&{trust_accepted:t.trustAccepted},...t?.trustedDirectory!==void 0&&{trusted_directory:t.trustedDirectory}})).response)}async claimSession(e){let t=rn("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(r)=>{if(r?.initialize===void 0)return n;let o=r.initialize,s=await n.then((c)=>({hooks_applied:c.hooks_applied,plugins_applied:c.plugins_applied,code_running_mcp_tools_applied:c.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied,l=o.code_running_mcp_tools_applied??s.code_running_mcp_tools_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a},...l!==void 0&&{code_running_mcp_tools_applied:l}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let r=++this.remoteControlCallGeneration,o=this.workSecretAnswerer,s=n?.reattachSessionId||(n?.workSecret===void 0?void 0:s8e(n.workSecret)),i=e&&n?.workSecret!==void 0&&n.refreshWorkSecret&&s!==void 0?{sessionId:s,refresh:n.refreshWorkSecret}:void 0;this.workSecretAnswerer=i;let a;try{a=(await this.request({subtype:"remote_control",enabled:e,...t!==void 0&&{name:t},reattach_session_id:n?.reattachSessionId,keep_session_on_exit:n?.keepSessionOnExit,work_secret:n?.workSecret})).response}catch(l){if(r===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw l}if(e&&r===this.remoteControlCallGeneration){let l=a.bridge_session_id,c=[i,o];this.workSecretAnswerer=typeof l==="string"?c.find((d)=>d!==void 0&&VJ(d.sessionId,l)):void 0}return a}async submitFeedback(e,t){return(await this.request({subtype:"submit_feedback",description:e,surface:t?.surface,draft_id:t?.draft_id,type:t?.type,title:t?.title,area:t?.area,attach_transcript:t?.attach_transcript,save_locally:t?.save_locally})).response}async submitSurveyFeedback(e){return(await this.request({subtype:"submit_survey_feedback",...e})).response}async renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return rn("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return rn("sdk_side_question",async()=>{let r=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return r.response===null?null:{response:r.response,synthetic:r.synthetic??!1,...r.refusal_fallback&&{refusalFallback:{originalModel:r.refusal_fallback.original_model,fallbackModel:r.refusal_fallback.fallback_model,content:r.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(Yn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Ik());let r=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(r);let o={request_id:r,type:"control_request",request:e},s=e.subtype==="initialize";return new Promise((i,a)=>{let l,c=!1,d=(g)=>{this.pendingControlResponses.delete(r),l?.(),i(g)},p=(g)=>{this.pendingControlResponses.delete(r),l?.(),a(g)};if(n){let g=()=>{if(p(Yn(n.reason??"Control request aborted")),!c)return;try{Promise.resolve(this.transport.write(ce({type:"control_cancel_request",request_id:r})+`
|
|
157
|
+
`}try{await Promise.resolve(this.transport.write(n))}catch(r){G(`[Query.handleControlRequest] Response write failed: ${ft(r)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(BJ.some((n)=>n===e.request.subtype))return G(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),fu;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(r===null)return fu;return{...r,toolUseID:e.request.tool_use_id}}else if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);else if(e.request.subtype==="mcp_message"){let n=e.request,r=this.sdkMcpServers.get(n.server_name)?.transport;if(!r)throw Error(`${LJ}: ${n.server_name}`);if(HJ(n.message))return{mcp_response:await this.handleMcpControlRequest(n.server_name,n,r)};else{if(r.onmessage)r.onmessage(n.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if(e.request.subtype==="elicitation"){let n=e.request;if(this.onElicitation){let r=await this.onElicitation({serverName:n.mcp_server_name,message:n.message,mode:n.mode,url:n.url,elicitationId:n.elicitation_id,requestedSchema:n.requested_schema,title:n.title,displayName:n.display_name,description:n.description},{signal:t,requestId:e.request_id});if(r===null)return fu;return r}return{action:"decline"}}else if(e.request.subtype==="request_user_dialog"){if(this.onUserDialog){let n=await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:t,requestId:e.request_id});if(n===null)return fu;return n}return G(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),pi("tengu_request_user_dialog_response_ignored",{shape:Cs("auto_cancel")}),fu}else if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");let n,r=await this.getOAuthToken({signal:t,onDecline:(o)=>{if(kJ(o))n=o},...e.request.kind!==void 0&&{kind:e.request.kind}})??null;return r===null&&n!==void 0?{accessToken:r,reason:n}:{accessToken:r}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");let n=await this.getHostAuthToken({signal:t})??null;return typeof n==="string"||n===null?{authToken:n}:n}else if(e.request.subtype==="remote_control_work_secret"){let n=this.workSecretAnswerer;if(!n)throw Error("refreshWorkSecret callback is not provided.");if(!VJ(n.sessionId,e.request.session_id))throw Error("remote_control_work_secret names a session this host did not attach.");return{work_secret:await n.refresh(n.sessionId,{signal:t})||null}}if(e.request.subtype==="ui_copy"&&this.uiHost?.copy){let{subtype:n,...r}=e.request;return this.uiHost.copy(r,{signal:t})}if(e.request.subtype==="ui_prompt_read"&&this.uiHost?.promptRead){let{subtype:n,...r}=e.request;return this.uiHost.promptRead(r,{signal:t})}if(e.request.subtype==="ui_prompt_fill"&&this.uiHost?.promptFill){let{subtype:n,...r}=e.request;return this.uiHost.promptFill(r,{signal:t})}if(e.request.subtype==="ui_prompt_paint"&&this.uiHost?.promptPaint){let{subtype:n,...r}=e.request;return this.uiHost.promptPaint(r,{signal:t})}if(e.request.subtype==="ui_prompt_suggest"&&this.uiHost?.promptSuggest){let{subtype:n,...r}=e.request;return this.uiHost.promptSuggest(r,{signal:t})}if(e.request.subtype==="ui_read_selection"&&this.uiHost?.readSelection){let{subtype:n,...r}=e.request;return this.uiHost.readSelection(r,{signal:t})}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){try{for await(let e of this.inputStream)this.transport.markDelivered?.(e),yield e}finally{await this.cleanup()}}async initialize({first:e}={first:!1}){if(!e&&!this.initializeHasBeenWritten)await this.initializeWritten;let t,n;try{if(e&&this.initConfig?.captureSdkMcpManifests===!0&&this.sdkMcpServers.size>0){t=await this.captureSdkMcpServerManifests();for(let i of this.sdkMcpToolsChangedDuringCapture){let a=t!==void 0&&Object.hasOwn(t,i)?t[i]:void 0;if(a?.toolsListResult!==void 0)t[i]={initializeResult:a.initializeResult}}}this.sdkMcpToolsChangedDuringCapture.clear();let s=this.buildInitializeRequest(t);if(this.cleanupPerformed)throw this.cleanupCause??Error("Query closed before initialize was sent");this.writingFirstInitialize=e;try{n=this.request(s)}finally{this.writingFirstInitialize=!1}}finally{if(e)this.markInitializeWritten()}let o=(await n).response;if(this.hasHookSetToBlock()){let s=o.hook_on_failure_supported!==!0?Error('The process answering initialize does not honor onFailure on hook matchers, so a hook that fails would not block. Update Claude Code if it is old, or remove onFailure: "block" from your hooks.'):e&&o.hooks_applied===!1?Error('This session was already running and did not register your hooks, so a hook set to onFailure: "block" would never run. Start a new session, or remove onFailure: "block" from your hooks.'):void 0;if(s!==void 0)throw this.cleanup(s),s}if(this.initConfig?.plugins!==void 0&&this.initConfig.plugins.length>0&&o.plugins_applied!==!0)G(`[Query.initialize] Claude Code reported plugins_applied=${String(o.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return o}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[s,i]of Object.entries(this.hooks))if(i?.length>0)this.initHooksPayload[s]=i.map((a)=>{let l=[];for(let c of a.hooks){let d=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(d,c),l.push(d)}return{matcher:a.matcher,hookCallbackIds:l,timeout:a.timeout,onFailure:a.onFailure}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([s,{settings:i}])=>Object.keys(i).length>0?[[s,i]]:[]),r=n.length>0?Object.fromEntries(n):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:r,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,r=async(p,f)=>{try{if(await this.sdkMcpServers.get(p)?.connection,n)return;let m=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:pS+"initialize",method:"initialize",params:{protocolVersion:jJ,capabilities:$J,clientInfo:{...zJ,version:"0.3.322"}}}},f);if(n)return;if(!("result"in m)){G(`[Query.captureSdkMcpServerManifests] '${p}' answered initialize with an error; leaving it to the CLI: ${ce(m)}`,{level:"warn"});return}let g=m.result;f.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let _=g.capabilities,y=typeof _==="object"&&_!==null&&"tools"in _&&_.tools!==void 0&&_.tools!==null,S;if(y){let C=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:pS+"tools-list",method:"tools/list"}},f);if(n)return;if(!("result"in C)){G(`[Query.captureSdkMcpServerManifests] '${p}' answered tools/list with an error; leaving it to the CLI: ${ce(C)}`,{level:"warn"});return}if(C.result.nextCursor===void 0)S=C.result}let b=je(ce(S===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:S}));t.set(p,{transport:f,manifest:b})}catch(m){if(!n)G(`[Query.captureSdkMcpServerManifests] '${p}': ${m}; the CLI will handshake it over the control channel`,{level:"warn"})}},o=Array.from(this.sdkMcpServers,([p,{transport:f}])=>r(p,f)),s=Promise.all(o).then(()=>"settled"),i=new Promise((p)=>{this.stopSdkMcpManifestCapture=()=>p("closed")}),a=await Ou(Promise.race([s,i]),GJ);n=!0,this.stopSdkMcpManifestCapture=void 0;let l=Math.round(performance.now()-e),c={servers:o.length,captured:t.size,elapsed_ms:l};if(a==="closed"){pc("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)G(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${GJ} ms; the rest will handshake over the control channel`,{level:"warn"}),pc("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)pc("sdk_mcp_manifest_capture","partial",c);else kp("sdk_mcp_manifest_capture",c);if(t.size===0)return;let d=Object.fromEntries(Array.from(this.sdkMcpServers).flatMap(([p,f])=>{let m=t.get(p);return m!==void 0&&m.transport===f.transport?[[p,m.manifest]]:[]}));if(Object.keys(d).length===0)return;return G(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(d).join(", ")}] captured in ${l} ms`),d}async interrupt(e){return rn("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let r=t.response?.cancelled;return{still_queued:n.filter((o)=>typeof o==="string"),...Array.isArray(r)&&{cancelled:r.filter((o)=>typeof o==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let r=(s)=>{if(s.subtype==="success"){let{pending_permission_requests:i,pending_user_dialog_requests:a,pending_elicitation_requests:l,...c}=s;t(c)}else n(new ve(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests||s.pending_elicitation_requests)G("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Ik());return}let o=this.unmatchedControlResponses.get(e);if(o){this.unmatchedControlResponses.delete(e),r(o);return}this.pendingControlResponses.set(e,{handler:(s)=>{this.pendingControlResponses.delete(e),r(s)},reject:n})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:t})}async applyFlagSettings(e){return rn("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async getHooksListing(){return(await this.request({subtype:"get_hooks_listing"})).response}async getTaskOutput(e){return(await this.request({subtype:"get_task_output",task_id:e})).response}async listPermissionRules(){return(await this.request({subtype:"list_permission_rules"})).response}async updateSettings(e,t){return rn("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return rn("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,t){await this.request({subtype:"seed_read_state",path:e,mtime:t})}async setCwd(e,t){return rn("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...t?.trustAccepted!==void 0&&{trust_accepted:t.trustAccepted},...t?.trustedDirectory!==void 0&&{trusted_directory:t.trustedDirectory}})).response)}async claimSession(e){let t=rn("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(r)=>{if(r?.initialize===void 0)return n;let o=r.initialize,s=await n.then((c)=>({hooks_applied:c.hooks_applied,plugins_applied:c.plugins_applied,code_running_mcp_tools_applied:c.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied,l=o.code_running_mcp_tools_applied??s.code_running_mcp_tools_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a},...l!==void 0&&{code_running_mcp_tools_applied:l}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let r=++this.remoteControlCallGeneration,o=this.workSecretAnswerer,s=n?.reattachSessionId||(n?.workSecret===void 0?void 0:s8e(n.workSecret)),i=e&&n?.workSecret!==void 0&&n.refreshWorkSecret&&s!==void 0?{sessionId:s,refresh:n.refreshWorkSecret}:void 0;this.workSecretAnswerer=i;let a;try{a=(await this.request({subtype:"remote_control",enabled:e,...t!==void 0&&{name:t},reattach_session_id:n?.reattachSessionId,keep_session_on_exit:n?.keepSessionOnExit,work_secret:n?.workSecret})).response}catch(l){if(r===this.remoteControlCallGeneration)this.workSecretAnswerer=void 0;throw l}if(e&&r===this.remoteControlCallGeneration){let l=a.bridge_session_id,c=[i,o];this.workSecretAnswerer=typeof l==="string"?c.find((d)=>d!==void 0&&VJ(d.sessionId,l)):void 0}return a}async submitFeedback(e,t){return(await this.request({subtype:"submit_feedback",description:e,surface:t?.surface,draft_id:t?.draft_id,type:t?.type,title:t?.title,area:t?.area,attach_transcript:t?.attach_transcript,save_locally:t?.save_locally})).response}async submitSurveyFeedback(e){return(await this.request({subtype:"submit_survey_feedback",...e})).response}async renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return rn("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return rn("sdk_side_question",async()=>{let r=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return r.response===null?null:{response:r.response,synthetic:r.synthetic??!1,...r.refusal_fallback&&{refusalFallback:{originalModel:r.refusal_fallback.original_model,fallbackModel:r.refusal_fallback.fallback_model,content:r.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(Yn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Ik());let r=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(r);let o={request_id:r,type:"control_request",request:e},s=e.subtype==="initialize";return new Promise((i,a)=>{let l,c=!1,d=(g)=>{this.pendingControlResponses.delete(r),l?.(),i(g)},p=(g)=>{this.pendingControlResponses.delete(r),l?.(),a(g)};if(n){let g=()=>{if(p(Yn(n.reason??"Control request aborted")),!c)return;try{Promise.resolve(this.transport.write(ce({type:"control_cancel_request",request_id:r})+`
|
|
158
158
|
`)).catch(()=>{})}catch{}};n.addEventListener("abort",g,{once:!0}),l=()=>{n.removeEventListener("abort",g)}}this.pendingControlResponses.set(r,{handler:(g)=>{if(g.subtype==="success")d(g);else p(hn(Error(g.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:typeof g.error_code==="string"&&o8e.test(g.error_code)?g.error_code:void 0}));if(!s&&(g.pending_permission_requests||g.pending_user_dialog_requests||g.pending_elicitation_requests))G(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${e.subtype})`);else{if(g.pending_permission_requests)this.processPendingPermissionRequests(g.pending_permission_requests);if(g.pending_user_dialog_requests)this.processPendingUserDialogRequests(g.pending_user_dialog_requests)}},reject:p});let f=ce(o)+`
|
|
159
159
|
`,m=()=>{if(n?.aborted)return;return c=!0,this.transport.write(f)};try{let g=this.promptHold;(g!==void 0&&r8e.has(e.subtype)?this.writeBehindPromptHold(g,m):this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(m()):this.initializeWritten.then(m)).catch(p)}catch(g){p(g)}})}initializationResult(){return this.initialization}afterInitialize(e){if(this.initializeHasBeenWritten)return Promise.resolve(e());return this.initializeWritten.then(e)}writePrompt(e){if(this.promptHold!==void 0)return this.writeBehindPromptHold(this.promptHold,()=>this.writeStreamMessage(e)).then(()=>{});return this.afterInitialize(()=>this.writeStreamMessage(e))}reinitialize(){return rn("sdk_reinitialize",()=>this.initialize({first:!1}))}async supportedCommands(){let{commands:e}=await this.initialization;return this.latestCommands??e}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,t){return rn("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:e,enabled:t})})}async readMcpResource(e,t){return(await this.request({subtype:"mcp_read_resource",serverName:e,uri:t})).response}async enableChannel(e){return rn("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,t,n){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:t,redirectUriOnly:n?.redirectUriOnly})).response}async mcpClearAuth(e){return(await this.request({subtype:"mcp_clear_auth",serverName:e})).response}async mcpSubmitOAuthCallbackUrl(e,t){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:e,callbackUrl:t})).response}async claudeAuthenticate(e){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e})).response}async claudeOAuthCallback(e,t){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:e,state:t})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(e){return(await this.request({subtype:"get_context_usage",...e})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(e){return(await this.request({subtype:"get_usage",...e?.skipBehaviors&&{skip_behaviors:!0}})).response}async getMemoryDialog(){return(await this.request({subtype:"get_memory_dialog"})).response}async getSkillsDialog(){return(await this.request({subtype:"get_skills_dialog"})).response}async getStatus(){return(await this.request({subtype:"get_status"})).response}async exportConversation(){return(await this.request({subtype:"export_conversation"})).response}async readCloudSessions(e,t){return(await this.request(e,t)).response}async getChromeDialog(){return(await this.request({subtype:"get_chrome_dialog"})).response}async getChromeBrowsers(){return(await this.request({subtype:"get_chrome_browsers"})).response}async selectChromeBrowser(e){return(await this.request({subtype:"select_chrome_browser",device_id:e})).response}async getSandboxDialog(){return(await this.request({subtype:"get_sandbox_dialog"})).response}async readFile(e,t){try{return(await this.request({subtype:"read_file",path:e,max_bytes:t?.maxBytes,encoding:t?.encoding})).response}catch{return null}}async getPlan(){return(await this.request({subtype:"get_plan"})).response}async reloadPlugins(e){return rn("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...e?.holdOnCacheImpact&&{hold_on_cache_impact:!0},...e?.addPlugins&&e.addPlugins.length>0&&{add_plugins:e.addPlugins}})).response)}async reloadSkills(){return rn("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return rn("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return rn("sdk_mcp_set_servers",async()=>{let t={},n={};for(let[a,l]of Object.entries(e))if(l.type==="sdk"&&"instance"in l)t[a]=l;else n[a]=l;let r=new Set(this.sdkMcpServers.keys()),o=new Set(Object.keys(t));for(let a of r)if(!o.has(a))await this.disconnectSdkMcpServer(a);for(let[a,l]of Object.entries(t)){let c=this.sdkMcpServers.get(a);if(!c){this.connectSdkMcpServer(a,l);continue}let{settings:d,ignored:p}=pv(l);if(WJ(a,l,p),d.timeout!==c.settings.timeout||d.disableAutoBackground!==c.settings.disableAutoBackground||d.connectorId!==c.settings.connectorId)G(`[Query.setMcpServers] MCP server '${a}' is already registered, so the different timeout, disableAutoBackground or connectorId passed to setMcpServers is ignored; remove and re-add the server to change it`);if(d.tools!==void 0&&!YY(d.tools,c.settings.tools))G(d.tools.length===0?`[Query.setMcpServers] MCP server '${a}': per-tool policy cleared`:`[Query.setMcpServers] MCP server '${a}': per-tool policy replaced (${d.tools.length} ${d.tools.length===1?"entry":"entries"})`),c.settings={...c.settings,tools:d.tools}}let s={};for(let a of Object.keys(t))s[a]={type:"sdk",name:a,...this.sdkMcpServers.get(a)?.settings};return(await this.request({subtype:"mcp_set_servers",servers:{...n,...s}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){G("[Query.streamInput] Starting to process input stream");try{if(!this.initializeHasBeenWritten)await this.initializeWritten;let t=0,n=[];for await(let r of e){if(t++,G(`[Query.streamInput] Processing message ${t}: ${r.type}`),this.abortController?.signal.aborted||this.promptHold!==void 0&&this.cleanupPerformed)break;let o=ce(this.verbatimPrompts?{...r,client_composed:!0}:r)+`
|
|
160
160
|
`;if(this.promptHold===void 0)await Promise.resolve(this.writeStreamMessage(o));else n.push(this.writeBehindPromptHold(this.promptHold,()=>this.writeStreamMessage(o)))}if(G(`[Query.streamInput] Finished processing ${t} messages from input stream`),this.promptHold!==void 0)n.push(this.promptHold);if((await Promise.all(n)).includes(!1))return;if(t>0&&this.hasBidirectionalNeeds())G("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();G("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(t){if(!(t instanceof tr))throw t}}writeStreamMessage(e){return this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),this.transport.write(e)}endRun(){if(this.runEnded)return;if(this.runEnded=!0,this.clearRunEndCeiling(),this.runEndedResolve?.(),this.isSingleUserTurn)G("[Query.readMessages] Run ended for single-turn query, closing stdin"),this.transport.endInput()}armRunEndCeiling(){if(this.clearRunEndCeiling(),this.runEnded||this.cleanupPerformed||this.runEndCeilingMs<=0)return;this.runEndCeilingTimer=setTimeout(()=>{G(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,Zc)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return G("[Query.waitForRunEnd] Run already ended, returning immediately"),Promise.resolve();return new Promise((e)=>{let t=this.abortController?.signal;if(this.cleanupPerformed||t?.aborted){e();return}let n=()=>e();t?.addEventListener("abort",n,{once:!0}),this.addCleanupCallback(()=>{t?.removeEventListener("abort",n),e()}),this.runEndedResolve=()=>{t?.removeEventListener("abort",n),e()}})}handleHookCallbacks(e,t,n,r){let o=this.hookCallbacks.get(e);if(!o)throw Error(`${MJ}: ${e}`);return o(t,n,{signal:r})}connectSdkMcpServer(e,t){let n=new Pk((i)=>this.sendMcpServerMessageToCli(e,i)),r=t.instance.connect(n).catch((i)=>{if(this.sdkMcpServers.get(e)?.transport===n)this.sdkMcpServers.delete(e);G(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${i}`,{level:"error"})}),{settings:o,ignored:s}=pv(t);WJ(e,t,s),this.sdkMcpServers.set(e,{transport:n,settings:o,connection:r})}async disconnectSdkMcpServer(e){let t=this.sdkMcpServers.get(e);if(t){let n=`${e}:${pS}`;for(let[r,o]of this.pendingMcpResponses)if(r.startsWith(n))this.pendingMcpResponses.delete(r),o.reject(Error("MCP server was removed during the manifest capture"));if(await t.transport.close(),this.sdkMcpServers.get(e)===t)this.sdkMcpServers.delete(e)}}sendMcpServerMessageToCli(e,t){if("id"in t&&t.id!==null&&t.id!==void 0){let r=`${e}:${t.id}`,o=this.pendingMcpResponses.get(r);if(o){o.resolve(t),this.pendingMcpResponses.delete(r);return}if(typeof t.id==="string"&&t.id.startsWith(pS)){G(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let n={type:"control_request",request_id:za(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&KJ(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.afterInitialize(()=>this.transport.write(ce(n)+`
|
|
161
|
-
`)).catch((r)=>{G(`[Query.sendMcpServerMessageToCli] Transport write failed: ${r}`,{level:"error"})})}handleMcpControlRequest(e,t,n){let r="id"in t.message?t.message.id:null,o=`${e}:${r}`;return new Promise((s,i)=>{let a=()=>{this.pendingMcpResponses.delete(o)},l=(d)=>{a(),s(d)},c=(d)=>{a(),i(d)};if(this.pendingMcpResponses.set(o,{resolve:l,reject:c}),n.onmessage)n.onmessage(t.message);else{a(),i(Error("No message handler registered"));return}})}}function Ik(){return Error("Query closed before response received")}var o8e=/^[a-z][a-z0-9_]{0,63}$/;function VJ(e,t){if(e===t)return!0;let n=e.slice(e.lastIndexOf("_")+1),r=t.slice(t.lastIndexOf("_")+1);return n.length>=4&&n===r}function s8e(e){try{let t=je(Buffer.from(e,"base64url").toString("utf8"));if(typeof t!=="object"||t===null||!("session_ingress_token"in t)||typeof t.session_ingress_token!=="string")return;let n=t.session_ingress_token,o=(n.startsWith("sk-ant-si-")?n.slice(10):n).split(".");if(o.length!==3||!o[1])return;let s=je(Buffer.from(o[1],"base64url").toString("utf8"));return typeof s==="object"&&s!==null&&"session_id"in s&&typeof s.session_id==="string"&&s.session_id?s.session_id:void 0}catch{return}}var qJ=typeof globalThis==="object"?globalThis:global;var gs="1.9.0";var YJ=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function i8e(e){var t=new Set([e]),n=new Set,r=e.match(YJ);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function s(a){return n.add(a),!1}function i(a){return t.add(a),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(YJ);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};if(d.prerelease!=null)return s(l);if(o.major!==d.major)return s(l);if(o.major===0){if(o.minor===d.minor&&o.patch<=d.patch)return i(l);return s(l)}if(o.minor<=d.minor)return i(l);return s(l)}}var ZJ=i8e(gs);var a8e=gs.split(".")[0],wf=Symbol.for("opentelemetry.js.api."+a8e),vf=qJ;function mu(e,t,n,r){var o;if(r===void 0)r=!1;var s=vf[wf]=(o=vf[wf])!==null&&o!==void 0?o:{version:gs};if(!r&&s[e]){var i=Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(i.stack||i.message),!1}if(s.version!==gs){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+gs);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+gs+"."),!0}function hs(e){var t,n,r=(t=vf[wf])===null||t===void 0?void 0:t.version;if(!r||!ZJ(r))return;return(n=vf[wf])===null||n===void 0?void 0:n[e]}function gu(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+gs+".");var n=vf[wf];if(n)delete n[e]}var l8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},c8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},JJ=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("verbose",this._namespace,t)},e}();function xf(e,t,n){var r=hs("diag");if(!r)return;return n.unshift(t),r[e].apply(r,c8e([],l8e(n),!1))}var In;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(In||(In={}));function XJ(e,t){if(e<In.NONE)e=In.NONE;else if(e>In.ALL)e=In.ALL;t=t||{};function n(r,o){var s=t[r];if(typeof s==="function"&&e>=o)return s.bind(t);return function(){}}return{error:n("error",In.ERROR),warn:n("warn",In.WARN),info:n("info",In.INFO),debug:n("debug",In.DEBUG),verbose:n("verbose",In.VERBOSE)}}var u8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},d8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},p8e="diag",Mi=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=hs("diag");if(!a)return;return a[o].apply(a,d8e([],u8e(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:In.INFO};if(o===n){var c=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}if(typeof s==="number")s={logLevel:s};var d=hs("diag"),p=XJ((a=s.logLevel)!==null&&a!==void 0?a:In.INFO,o);if(d&&!s.suppressOverrideMessage){var f=(l=Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+f),p.warn("Current logger will overwrite one already registered from "+f)}return mu("diag",p,n,!0)};n.setLogger=r,n.disable=function(){gu(p8e,n)},n.createComponentLogger=function(o){return new JJ(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){if(!this._instance)this._instance=new e;return this._instance},e}();var f8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},m8e=function(e){var t=typeof Symbol==="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==="number")return{next:function(){if(e&&r>=e.length)e=void 0;return{value:e&&e[r++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},QJ=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(!n)return;return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=f8e(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){var t,n,r=[];for(var o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var i=m8e(r),a=i.next();!a.done;a=i.next()){var l=a.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{if(a&&!a.done&&(n=i.return))n.call(i)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();var Xqt=Mi.instance();function e5(e){if(e===void 0)e={};return new QJ(new Map(Object.entries(e)))}function t5(e){return Symbol.for(e)}var g8e=function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e}(),n5=new g8e;var r5={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},o5={set:function(e,t,n){if(e==null)return;e[t]=n}};var h8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},_8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},s5=function(){function e(){}return e.prototype.active=function(){return n5},e.prototype.with=function(t,n,r){var o=[];for(var s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,_8e([r],h8e(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var y8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},S8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},Dk="context",E8e=new s5,mS=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return mu(Dk,t,Mi.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){var o,s=[];for(var i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,S8e([t,n,r],y8e(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return hs(Dk)||E8e},e.prototype.disable=function(){this._getContextManager().disable(),gu(Dk,Mi.instance())},e}();var Lk=mS.getInstance();var i5=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}();var Mk=t5("OpenTelemetry Baggage Key");function Nk(e){return e.getValue(Mk)||void 0}function a5(){return Nk(mS.getInstance().active())}function l5(e,t){return e.setValue(Mk,t)}function c5(e){return e.deleteValue(Mk)}var Uk="propagation",b8e=new i5,u5=function(){function e(){this.createBaggage=e5,this.getBaggage=Nk,this.getActiveBaggage=a5,this.setBaggage=l5,this.deleteBaggage=c5}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return mu(Uk,t,Mi.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=o5;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=r5;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){gu(Uk,Mi.instance())},e.prototype._getGlobalPropagator=function(){return hs(Uk)||b8e},e}();var Fk=u5.getInstance();import{copyFile as C8e,readFile as A8e,rm as p5,writeFile as f5}from"fs/promises";import{homedir as d5}from"os";import{join as Hk}from"path";function m5(e){return{globalConfig:Hk(e||d5(),".claude.json"),userSettings:Hk(e||Hk(d5(),".claude"),"settings.json")}}function $k(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function hu(e,t,n,r){if(r)return R8e(r,e,t,n);try{if(n)await f5(t,n(await A8e(e)),{mode:384});else await C8e(e,t)}catch(o){if(le(o)===void 0)throw o;if(!et(o))await p5(t,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${e} (${le(o)})`)}}async function R8e({backend:e,key:t},n,r,o){let s=await e.read([t]);if(!s.ok){if(s.error.code==="InvalidArgument")throw new ve(`sessionStore resume: invalid v5 key for ${n}: ${s.error.argument}${s.error.reason?` (${s.error.reason})`:""}`,"sessionStore resume: invalid v5 key (InvalidArgument from backend read)");G(`sessionStore resume: skipping ${n} (${s.error.code})`);return}let i=s.value.items[0];if(!i?.found)return;let a=Buffer.from(i.value);try{await f5(r,o?o(a):a,{mode:384})}catch(l){if(le(l)===void 0)throw l;if(!et(l))await p5(r,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${n} (${le(l)})`)}}import{createHash as O8e}from"crypto";import{homedir as LYt,userInfo as T8e}from"os";var g5="-credentials";function h5(e=""){let t=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,n=t!==void 0?!t:!process.env.CLAUDE_CONFIG_DIR,r=t!==void 0?t.normalize("NFC"):Ut(),o=n?"":`-${O8e("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${OL().OAUTH_FILE_SUFFIX}${e}${o}`}var w8e=/^[a-zA-Z0-9._-]+$/;function _5(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||T8e().username}catch{e="claude-code-user"}if(!w8e.test(e))return"claude-code-user";return e}class y5{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var HYt=new Te(()=>new y5);function v8e(e,t){if(e==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let n=t.filter((r)=>r.length>0&&!r.includes("("));if(n.length===0)return;return`canUseTool will not be invoked for: ${n.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function S5(e,t,n){if(!e)return;let r=v8e(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as x8e}from"fs";import{isAbsolute as k8e,relative as P8e,resolve as I8e,sep as D8e}from"path";function zk(e){let t=I8e(e??"."),n;try{n=x8e(t)}catch{n=t}return Ze(n)}function Dn(e,t){let n=zk(e);if(t===void 0)return eo(n);return(t.CLAUDE_CONFIG_DIR?sb(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??rd(n)}function kf(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function Bk(e,t){let n=P8e(t,e),r=n.split(D8e);if(r[0]===".."||k8e(n))return null;if(r.length<2)return null;let o=r[0],s=r[1];if(r.length===2&&s.endsWith(".jsonl"))return{projectKey:o,sessionId:s.replace(/\.jsonl$/,"")};if(r.length>=4){let i=r.slice(2),a=i.length-1;return i[a]=i.at(-1).replace(/\.jsonl$/,""),{projectKey:o,sessionId:s,subpath:i.join("/")}}return null}process.env.NoDefaultCurrentDirectoryInExePath="1";var B8e=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function b5(e){let t;try{t=je(Lc(e.toString("utf8")))}catch{return e}if(!C5(t))return e;let n=!1;for(let o of B8e)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(C5(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?ce(t):e}function C5(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function j8e(e,t){if(!e)return;let n=e;try{let r=je(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=ce(r)}catch{}await R5(t,n,{mode:384})}function K8e(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=h5(g5);return new Promise((t)=>{L8e("security",["find-generic-password","-a",_5(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function w5(e,t,n,r,o=60000,s){if(!qe(t))return;let i=Dn(n,r),a=await wr(e.load({projectKey:i,sessionId:t}),o,`SessionStore.load() timed out after ${o}ms for session ${t}`);if(!a||a.length===0)return;let l=Ct(H8e(),`claude-resume-${M8e()}`);try{let c=Ct(l,"projects",i);await gS(c,{recursive:!0,mode:448});let d=Ct(c,`${t}.jsonl`);await nd(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??Ct(Pf(),".claude"),m;try{m=await U8e(Ct(f,".credentials.json"),"utf-8")}catch(E){if(!et(E))throw E}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await K8e()??m;await j8e(m,Ct(l,".credentials.json"));let g=m5(Os("CLAUDE_CONFIG_DIR")),_=p||Pf(),y=Ct(_,".claude.json");await hu(y,Ct(l,".claude.json"),void 0,$k(s,y,g.globalConfig,Ht.globalConfig())),await hu(Ct(f,".config.json"),Ct(l,".config.json"));for(let E of AL)if(E)await hu(Ct(_,`.claude${E}.json`),Ct(l,`.claude${E}.json`));let S=Ct(f,"settings.json");if(await hu(S,Ct(l,"settings.json"),b5,$k(s,S,g.userSettings,Ht.userSettings())),await hu(Ct(f,"cowork_settings.json"),Ct(l,"cowork_settings.json"),b5),e.listSubkeys)await G8e(e,{projectKey:i,sessionId:t},Ct(c,t),o);return l}catch(c){throw await hS(l),c}}async function G8e(e,t,n,r){let o=await wr(e.listSubkeys({projectKey:t.projectKey,sessionId:t.sessionId}),r,`SessionStore.listSubkeys() timed out after ${r}ms for session ${t.sessionId}`);for(let s of o){let i=If(n,s+".jsonl");if(!s||jk(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+$8e)){G(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await wr(e.load({projectKey:t.projectKey,sessionId:t.sessionId,subpath:s}),r,`SessionStore.load() timed out after ${r}ms for session ${t.sessionId} subpath ${s}`);if(!a||a.length===0)continue;let l=[],c=[];for(let d of a)if(kf(d))l.push(d);else c.push(d);if(c.length>0)await gS(E5(i),{recursive:!0}),await nd(i,c);if(l.length>0){let d=l.at(-1),p=If(n,s+".meta.json");await gS(E5(p),{recursive:!0});let{type:f,...m}=d;await R5(p,ce(m),{mode:384})}}}function v5(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(O5.isAbsolute(e.directory)||T5.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&t===void 0)G("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return t}var W8e=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function Kk(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o,readsStartupMarks:s}=t,{systemPrompt:i,settings:a,managedSettings:l,settingSources:c,sandbox:d,...p}=e??{},f,m,g,_;if(i===void 0)f="";else if(typeof i==="string")f=i;else if(Array.isArray(i))f=i;else if(i.type==="custom")f=i.prompt,_=i.snapshot;else if(i.type==="preset")m=i.append,g=i.excludeDynamicSections,_=i.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.321";let{abortController:y=Rf(),additionalDirectories:S=[],projectConfigRoot:E,agent:b,agents:C,allowedTools:A=[],betas:R,canUseTool:x,continue:L,cwd:F,debug:re,debugFile:T,disallowedTools:w=[],tools:I,env:M,executable:z=Xa()?"bun":"node",executableArgs:J=[],extraArgs:Q={},fallbackModel:W,enableFileCheckpointing:B,toolConfig:it,forkSession:Ve,hooks:ot,includeHookEvents:At,includePartialMessages:Zt,forwardSubagentText:Ke,verbatimPrompts:we=!1,onElicitation:ge,onUserDialog:sn,supportedDialogKinds:Fe,perTaskStopAffordance:En,rapidFollowupPreempt:ys,workspaceTrust:Ni,persistSession:Io,sessionStore:gn,sessionStoreFlush:Na,thinking:Ss,effort:Df,maxThinkingTokens:Vr,maxTurns:Ui,maxBudgetUsd:Or,taskBudget:_u,mcpServers:yu,model:Su,outputFormat:Lf,permissionMode:Fi,allowDangerouslySkipPermissions:Eu=!1,permissionPromptToolName:Ua,permissionPrompts:Mf,plugins:Es,pluginDelivery:bu="argv",getOAuthToken:Nf,getHostAuthToken:he,workload:Rt,resume:Kt,resumeSessionAt:qr,resumeDropsTurn:Fa,sessionId:Uf,skills:Ha,stderr:Ff,strictMcpConfig:W5}=p,qk=Fi;if(gn&&Io===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. To avoid keeping a local copy, pass env: { ...process.env, CLAUDE_CONFIG_DIR: dir }, where dir is a new private directory such as fs.mkdtempSync(path.join(os.tmpdir(), 'claude-')), and delete dir when the query ends.");xJ({supportedDialogKinds:Fe,onUserDialog:sn});let V5=v5(Ni);if(gn&&L&&!Kt&&!gn.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(gn&&B)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(gn&&p.spawnClaudeCodeProcess)G("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(S5(!!x,qk??"default",A),bu!=="argv"&&bu!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let Yk=bu==="initialize"&&Es!==void 0&&Es.length>0,yS=p.pathToClaudeCodeExecutable;if(!yS){let yt=z8e(import.meta.url),Ln=F8e(yt),Yr=vJ(($a)=>Ln.resolve($a));if(!Yr)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.`);yS=Yr}let Zk=Lf?.type==="json_schema"?Lf.schema:void 0,_t=M?{...M}:{...process.env};if(!_t.CLAUDE_CODE_ENTRYPOINT)_t.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!_t.CLAUDE_AGENT_SDK_VERSION)_t.CLAUDE_AGENT_SDK_VERSION="0.3.321";if(B)_t.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(_t).some((yt)=>yt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))_t.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(s&&!Object.keys(_t).some((yt)=>yt.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))_t.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let SS=Pu(_t.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),q5=Number.isFinite(SS)&&SS>=0?SS:cS;if(Nf)_t.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(he)_t.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(it?.askUserQuestion?.previewFormat)_t.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=it.askUserQuestion.previewFormat;for(let[yt,Ln]of[[it?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[it?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(yt)_t[Ln]="1";else if(!M){for(let Yr of Object.keys(_t))if(Yr.toUpperCase()===Ln)delete _t[Yr]}let ES={};if(Fk.inject(Lk.active(),ES),"traceparent"in ES){for(let yt of["TRACEPARENT","TRACESTATE"])if(!(yt in(M??{})))delete _t[yt]}for(let[yt,Ln]of Object.entries(ES)){let Yr=yt.toUpperCase();if(!(Yr in(M??{})))_t[Yr]=Ln}let Jk={},Xk=new Map;if(yu)for(let[yt,Ln]of Object.entries(yu))if(Ln.type==="sdk"&&Ln.instance)Xk.set(yt,Ln);else Jk[yt]=Ln;let Cu;if(Ss)switch(Ss.type){case"adaptive":Cu={type:"adaptive",display:Ss.display};break;case"enabled":Cu={type:"enabled",budgetTokens:Ss.budgetTokens,display:Ss.display};break;case"disabled":Cu={type:"disabled"};break}else if(Vr!==void 0)Cu=Vr===0?{type:"disabled"}:{type:"enabled",budgetTokens:Vr};if(r){if(_t.CLAUDE_CONFIG_DIR=r,process.platform==="win32")_t.CLAUDE_SECURESTORAGE_CONFIG_DIR=M?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??M?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let Y5=Boolean(Kt||L)&&!p.pathToClaudeCodeExecutable&&!p.spawnClaudeCodeProcess&&Q?.["sdk-url"]===void 0&&!Object.keys(Q??{}).some((yt)=>yt.startsWith("sdk-url="))&&!J.some((yt)=>/^--sdk-url(=|$)/.test(yt)),Qk=new vk({abortController:y,additionalDirectories:S,projectConfigRoot:E,agent:b,betas:R,cwd:F,debug:re,debugFile:T,executable:z,executableArgs:J,extraArgs:{...Q,...Rt&&{workload:Rt},...Y5&&{"await-initialize":null}},pathToClaudeCodeExecutable:yS,env:_t,forkSession:Ve,stderr:Ff,thinkingConfig:Cu,effort:Df,maxTurns:Ui,maxBudgetUsd:Or,taskBudget:_u,model:Su,fallbackModel:W,jsonSchema:Zk,permissionMode:qk,allowDangerouslySkipPermissions:Eu,permissionPromptToolName:Ua,permissionPrompts:Mf,continueConversation:gn?void 0:L,resume:Kt,resumeSessionAt:qr,resumeDropsTurn:Fa,sessionId:Uf,settings:typeof a==="object"?ce(a):a,managedSettings:l?ce(l):void 0,settingSources:c,skills:Ha,allowedTools:A,disallowedTools:w,tools:I,mcpServers:Jk,strictMcpConfig:W5,canUseTool:!!x,hooks:!!ot,includeHookEvents:At,includePartialMessages:Zt,persistSession:Io,sessionMirror:!!gn,plugins:Es,pluginsViaInitialize:Yk,sandbox:d,spawnClaudeCodeProcess:p.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),Z5={systemPrompt:f,appendSystemPrompt:m,planModeInstructions:p.planModeInstructions,systemPromptSnapshot:_,appendSubagentSystemPrompt:p.appendSubagentSystemPrompt,toolAliases:p.toolAliases,codeRunningMcpTools:p.codeRunningMcpTools,excludeDynamicSections:g,agents:C,title:p.title,skills:Ha,webSearchIsolationExemptMcpServers:p.webSearchIsolationExemptMcpServers,promptSuggestions:p.promptSuggestions,agentProgressSummaries:p.agentProgressSummaries,forwardSubagentText:Ke,supportedDialogKinds:Fe,perTaskStopAffordance:En,rapidFollowupPreempt:ys,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:V5,plugins:Yk?Es:void 0,captureSdkMcpManifests:!om("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},bS=new fS(Qk,n,x,ot,y,Xk,Zk,Z5,ge,Nf,he,sn,we,q5);if(gn){let yt=()=>Ct(_t.CLAUDE_CONFIG_DIR??Ct(Pf(),".claude"),"projects"),Ln=Na==="eager",Yr=new jb(async($a,CS)=>{let Au=Bk($a,yt());if(Au)await gn.append(Au,CS);else G(`[SessionStore] dropping mirror frame: filePath ${$a} is not under ${yt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:($a,CS)=>{let Au=Bk($a,yt());if(Au)bS.reportMirrorError(Au,CS.message)},maxPendingEntries:Ln?0:qu,maxPendingBytes:Ln?0:Wi});bS.setTranscriptMirrorBatcher(Yr)}return{queryInstance:bS,transport:Qk,abortController:y,processEnv:_t,verbatimPrompts:we}}function Gk(e,t,n,r){if(typeof t==="string")e.writePrompt(ce({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,...r&&{client_composed:!0}})+`
|
|
161
|
+
`)).catch((r)=>{G(`[Query.sendMcpServerMessageToCli] Transport write failed: ${r}`,{level:"error"})})}handleMcpControlRequest(e,t,n){let r="id"in t.message?t.message.id:null,o=`${e}:${r}`;return new Promise((s,i)=>{let a=()=>{this.pendingMcpResponses.delete(o)},l=(d)=>{a(),s(d)},c=(d)=>{a(),i(d)};if(this.pendingMcpResponses.set(o,{resolve:l,reject:c}),n.onmessage)n.onmessage(t.message);else{a(),i(Error("No message handler registered"));return}})}}function Ik(){return Error("Query closed before response received")}var o8e=/^[a-z][a-z0-9_]{0,63}$/;function VJ(e,t){if(e===t)return!0;let n=e.slice(e.lastIndexOf("_")+1),r=t.slice(t.lastIndexOf("_")+1);return n.length>=4&&n===r}function s8e(e){try{let t=je(Buffer.from(e,"base64url").toString("utf8"));if(typeof t!=="object"||t===null||!("session_ingress_token"in t)||typeof t.session_ingress_token!=="string")return;let n=t.session_ingress_token,o=(n.startsWith("sk-ant-si-")?n.slice(10):n).split(".");if(o.length!==3||!o[1])return;let s=je(Buffer.from(o[1],"base64url").toString("utf8"));return typeof s==="object"&&s!==null&&"session_id"in s&&typeof s.session_id==="string"&&s.session_id?s.session_id:void 0}catch{return}}var qJ=typeof globalThis==="object"?globalThis:global;var gs="1.9.0";var YJ=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function i8e(e){var t=new Set([e]),n=new Set,r=e.match(YJ);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function s(a){return n.add(a),!1}function i(a){return t.add(a),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(YJ);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};if(d.prerelease!=null)return s(l);if(o.major!==d.major)return s(l);if(o.major===0){if(o.minor===d.minor&&o.patch<=d.patch)return i(l);return s(l)}if(o.minor<=d.minor)return i(l);return s(l)}}var ZJ=i8e(gs);var a8e=gs.split(".")[0],wf=Symbol.for("opentelemetry.js.api."+a8e),vf=qJ;function mu(e,t,n,r){var o;if(r===void 0)r=!1;var s=vf[wf]=(o=vf[wf])!==null&&o!==void 0?o:{version:gs};if(!r&&s[e]){var i=Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(i.stack||i.message),!1}if(s.version!==gs){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+gs);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+gs+"."),!0}function hs(e){var t,n,r=(t=vf[wf])===null||t===void 0?void 0:t.version;if(!r||!ZJ(r))return;return(n=vf[wf])===null||n===void 0?void 0:n[e]}function gu(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+gs+".");var n=vf[wf];if(n)delete n[e]}var l8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},c8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},JJ=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return xf("verbose",this._namespace,t)},e}();function xf(e,t,n){var r=hs("diag");if(!r)return;return n.unshift(t),r[e].apply(r,c8e([],l8e(n),!1))}var In;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(In||(In={}));function XJ(e,t){if(e<In.NONE)e=In.NONE;else if(e>In.ALL)e=In.ALL;t=t||{};function n(r,o){var s=t[r];if(typeof s==="function"&&e>=o)return s.bind(t);return function(){}}return{error:n("error",In.ERROR),warn:n("warn",In.WARN),info:n("info",In.INFO),debug:n("debug",In.DEBUG),verbose:n("verbose",In.VERBOSE)}}var u8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},d8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},p8e="diag",Mi=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=hs("diag");if(!a)return;return a[o].apply(a,d8e([],u8e(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:In.INFO};if(o===n){var c=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}if(typeof s==="number")s={logLevel:s};var d=hs("diag"),p=XJ((a=s.logLevel)!==null&&a!==void 0?a:In.INFO,o);if(d&&!s.suppressOverrideMessage){var f=(l=Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+f),p.warn("Current logger will overwrite one already registered from "+f)}return mu("diag",p,n,!0)};n.setLogger=r,n.disable=function(){gu(p8e,n)},n.createComponentLogger=function(o){return new JJ(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){if(!this._instance)this._instance=new e;return this._instance},e}();var f8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},m8e=function(e){var t=typeof Symbol==="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==="number")return{next:function(){if(e&&r>=e.length)e=void 0;return{value:e&&e[r++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},QJ=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(!n)return;return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=f8e(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){var t,n,r=[];for(var o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var i=m8e(r),a=i.next();!a.done;a=i.next()){var l=a.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{if(a&&!a.done&&(n=i.return))n.call(i)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();var Xqt=Mi.instance();function e5(e){if(e===void 0)e={};return new QJ(new Map(Object.entries(e)))}function t5(e){return Symbol.for(e)}var g8e=function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e}(),n5=new g8e;var r5={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},o5={set:function(e,t,n){if(e==null)return;e[t]=n}};var h8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},_8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},s5=function(){function e(){}return e.prototype.active=function(){return n5},e.prototype.with=function(t,n,r){var o=[];for(var s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,_8e([r],h8e(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var y8e=function(e,t){var n=typeof Symbol==="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{while((t===void 0||t-- >0)&&!(o=r.next()).done)s.push(o.value)}catch(a){i={error:a}}finally{try{if(o&&!o.done&&(n=r.return))n.call(r)}finally{if(i)throw i.error}}return s},S8e=function(e,t,n){if(n||arguments.length===2){for(var r=0,o=t.length,s;r<o;r++)if(s||!(r in t)){if(!s)s=Array.prototype.slice.call(t,0,r);s[r]=t[r]}}return e.concat(s||Array.prototype.slice.call(t))},Dk="context",E8e=new s5,mS=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return mu(Dk,t,Mi.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){var o,s=[];for(var i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,S8e([t,n,r],y8e(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return hs(Dk)||E8e},e.prototype.disable=function(){this._getContextManager().disable(),gu(Dk,Mi.instance())},e}();var Lk=mS.getInstance();var i5=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}();var Mk=t5("OpenTelemetry Baggage Key");function Nk(e){return e.getValue(Mk)||void 0}function a5(){return Nk(mS.getInstance().active())}function l5(e,t){return e.setValue(Mk,t)}function c5(e){return e.deleteValue(Mk)}var Uk="propagation",b8e=new i5,u5=function(){function e(){this.createBaggage=e5,this.getBaggage=Nk,this.getActiveBaggage=a5,this.setBaggage=l5,this.deleteBaggage=c5}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return mu(Uk,t,Mi.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=o5;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=r5;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){gu(Uk,Mi.instance())},e.prototype._getGlobalPropagator=function(){return hs(Uk)||b8e},e}();var Fk=u5.getInstance();import{copyFile as C8e,readFile as A8e,rm as p5,writeFile as f5}from"fs/promises";import{homedir as d5}from"os";import{join as Hk}from"path";function m5(e){return{globalConfig:Hk(e||d5(),".claude.json"),userSettings:Hk(e||Hk(d5(),".claude"),"settings.json")}}function $k(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function hu(e,t,n,r){if(r)return R8e(r,e,t,n);try{if(n)await f5(t,n(await A8e(e)),{mode:384});else await C8e(e,t)}catch(o){if(le(o)===void 0)throw o;if(!et(o))await p5(t,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${e} (${le(o)})`)}}async function R8e({backend:e,key:t},n,r,o){let s=await e.read([t]);if(!s.ok){if(s.error.code==="InvalidArgument")throw new ve(`sessionStore resume: invalid v5 key for ${n}: ${s.error.argument}${s.error.reason?` (${s.error.reason})`:""}`,"sessionStore resume: invalid v5 key (InvalidArgument from backend read)");G(`sessionStore resume: skipping ${n} (${s.error.code})`);return}let i=s.value.items[0];if(!i?.found)return;let a=Buffer.from(i.value);try{await f5(r,o?o(a):a,{mode:384})}catch(l){if(le(l)===void 0)throw l;if(!et(l))await p5(r,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${n} (${le(l)})`)}}import{createHash as O8e}from"crypto";import{homedir as LYt,userInfo as T8e}from"os";var g5="-credentials";function h5(e=""){let t=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,n=t!==void 0?!t:!process.env.CLAUDE_CONFIG_DIR,r=t!==void 0?t.normalize("NFC"):Ut(),o=n?"":`-${O8e("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${OL().OAUTH_FILE_SUFFIX}${e}${o}`}var w8e=/^[a-zA-Z0-9._-]+$/;function _5(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||T8e().username}catch{e="claude-code-user"}if(!w8e.test(e))return"claude-code-user";return e}class y5{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var HYt=new Te(()=>new y5);function v8e(e,t){if(e==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let n=t.filter((r)=>r.length>0&&!r.includes("("));if(n.length===0)return;return`canUseTool will not be invoked for: ${n.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function S5(e,t,n){if(!e)return;let r=v8e(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as x8e}from"fs";import{isAbsolute as k8e,relative as P8e,resolve as I8e,sep as D8e}from"path";function zk(e){let t=I8e(e??"."),n;try{n=x8e(t)}catch{n=t}return Ze(n)}function Dn(e,t){let n=zk(e);if(t===void 0)return eo(n);return(t.CLAUDE_CONFIG_DIR?sb(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??rd(n)}function kf(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function Bk(e,t){let n=P8e(t,e),r=n.split(D8e);if(r[0]===".."||k8e(n))return null;if(r.length<2)return null;let o=r[0],s=r[1];if(r.length===2&&s.endsWith(".jsonl"))return{projectKey:o,sessionId:s.replace(/\.jsonl$/,"")};if(r.length>=4){let i=r.slice(2),a=i.length-1;return i[a]=i.at(-1).replace(/\.jsonl$/,""),{projectKey:o,sessionId:s,subpath:i.join("/")}}return null}process.env.NoDefaultCurrentDirectoryInExePath="1";var B8e=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function b5(e){let t;try{t=je(Lc(e.toString("utf8")))}catch{return e}if(!C5(t))return e;let n=!1;for(let o of B8e)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(C5(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?ce(t):e}function C5(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function j8e(e,t){if(!e)return;let n=e;try{let r=je(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=ce(r)}catch{}await R5(t,n,{mode:384})}function K8e(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=h5(g5);return new Promise((t)=>{L8e("security",["find-generic-password","-a",_5(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function w5(e,t,n,r,o=60000,s){if(!qe(t))return;let i=Dn(n,r),a=await wr(e.load({projectKey:i,sessionId:t}),o,`SessionStore.load() timed out after ${o}ms for session ${t}`);if(!a||a.length===0)return;let l=Ct(H8e(),`claude-resume-${M8e()}`);try{let c=Ct(l,"projects",i);await gS(c,{recursive:!0,mode:448});let d=Ct(c,`${t}.jsonl`);await nd(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??Ct(Pf(),".claude"),m;try{m=await U8e(Ct(f,".credentials.json"),"utf-8")}catch(E){if(!et(E))throw E}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await K8e()??m;await j8e(m,Ct(l,".credentials.json"));let g=m5(Os("CLAUDE_CONFIG_DIR")),_=p||Pf(),y=Ct(_,".claude.json");await hu(y,Ct(l,".claude.json"),void 0,$k(s,y,g.globalConfig,Ht.globalConfig())),await hu(Ct(f,".config.json"),Ct(l,".config.json"));for(let E of AL)if(E)await hu(Ct(_,`.claude${E}.json`),Ct(l,`.claude${E}.json`));let S=Ct(f,"settings.json");if(await hu(S,Ct(l,"settings.json"),b5,$k(s,S,g.userSettings,Ht.userSettings())),await hu(Ct(f,"cowork_settings.json"),Ct(l,"cowork_settings.json"),b5),e.listSubkeys)await G8e(e,{projectKey:i,sessionId:t},Ct(c,t),o);return l}catch(c){throw await hS(l),c}}async function G8e(e,t,n,r){let o=await wr(e.listSubkeys({projectKey:t.projectKey,sessionId:t.sessionId}),r,`SessionStore.listSubkeys() timed out after ${r}ms for session ${t.sessionId}`);for(let s of o){let i=If(n,s+".jsonl");if(!s||jk(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+$8e)){G(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await wr(e.load({projectKey:t.projectKey,sessionId:t.sessionId,subpath:s}),r,`SessionStore.load() timed out after ${r}ms for session ${t.sessionId} subpath ${s}`);if(!a||a.length===0)continue;let l=[],c=[];for(let d of a)if(kf(d))l.push(d);else c.push(d);if(c.length>0)await gS(E5(i),{recursive:!0}),await nd(i,c);if(l.length>0){let d=l.at(-1),p=If(n,s+".meta.json");await gS(E5(p),{recursive:!0});let{type:f,...m}=d;await R5(p,ce(m),{mode:384})}}}function v5(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(O5.isAbsolute(e.directory)||T5.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&t===void 0)G("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return t}var W8e=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function Kk(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o,readsStartupMarks:s}=t,{systemPrompt:i,settings:a,managedSettings:l,settingSources:c,sandbox:d,...p}=e??{},f,m,g,_;if(i===void 0)f="";else if(typeof i==="string")f=i;else if(Array.isArray(i))f=i;else if(i.type==="custom")f=i.prompt,_=i.snapshot;else if(i.type==="preset")m=i.append,g=i.excludeDynamicSections,_=i.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.322";let{abortController:y=Rf(),additionalDirectories:S=[],projectConfigRoot:E,agent:b,agents:C,allowedTools:A=[],betas:R,canUseTool:x,continue:L,cwd:F,debug:re,debugFile:T,disallowedTools:w=[],tools:I,env:M,executable:z=Xa()?"bun":"node",executableArgs:J=[],extraArgs:Q={},fallbackModel:W,enableFileCheckpointing:B,toolConfig:it,forkSession:Ve,hooks:ot,includeHookEvents:At,includePartialMessages:Zt,forwardSubagentText:Ke,verbatimPrompts:we=!1,onElicitation:ge,onUserDialog:sn,supportedDialogKinds:Fe,perTaskStopAffordance:En,rapidFollowupPreempt:ys,workspaceTrust:Ni,persistSession:Io,sessionStore:gn,sessionStoreFlush:Na,thinking:Ss,effort:Df,maxThinkingTokens:Vr,maxTurns:Ui,maxBudgetUsd:Or,taskBudget:_u,mcpServers:yu,model:Su,outputFormat:Lf,permissionMode:Fi,allowDangerouslySkipPermissions:Eu=!1,permissionPromptToolName:Ua,permissionPrompts:Mf,plugins:Es,pluginDelivery:bu="argv",getOAuthToken:Nf,getHostAuthToken:he,workload:Rt,resume:Kt,resumeSessionAt:qr,resumeDropsTurn:Fa,sessionId:Uf,skills:Ha,stderr:Ff,strictMcpConfig:W5}=p,qk=Fi;if(gn&&Io===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. To avoid keeping a local copy, pass env: { ...process.env, CLAUDE_CONFIG_DIR: dir }, where dir is a new private directory such as fs.mkdtempSync(path.join(os.tmpdir(), 'claude-')), and delete dir when the query ends.");xJ({supportedDialogKinds:Fe,onUserDialog:sn});let V5=v5(Ni);if(gn&&L&&!Kt&&!gn.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(gn&&B)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(gn&&p.spawnClaudeCodeProcess)G("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(S5(!!x,qk??"default",A),bu!=="argv"&&bu!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let Yk=bu==="initialize"&&Es!==void 0&&Es.length>0,yS=p.pathToClaudeCodeExecutable;if(!yS){let yt=z8e(import.meta.url),Ln=F8e(yt),Yr=vJ(($a)=>Ln.resolve($a));if(!Yr)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.`);yS=Yr}let Zk=Lf?.type==="json_schema"?Lf.schema:void 0,_t=M?{...M}:{...process.env};if(!_t.CLAUDE_CODE_ENTRYPOINT)_t.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!_t.CLAUDE_AGENT_SDK_VERSION)_t.CLAUDE_AGENT_SDK_VERSION="0.3.322";if(B)_t.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(_t).some((yt)=>yt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))_t.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(s&&!Object.keys(_t).some((yt)=>yt.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))_t.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let SS=Pu(_t.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),q5=Number.isFinite(SS)&&SS>=0?SS:cS;if(Nf)_t.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(he)_t.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(it?.askUserQuestion?.previewFormat)_t.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=it.askUserQuestion.previewFormat;for(let[yt,Ln]of[[it?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[it?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(yt)_t[Ln]="1";else if(!M){for(let Yr of Object.keys(_t))if(Yr.toUpperCase()===Ln)delete _t[Yr]}let ES={};if(Fk.inject(Lk.active(),ES),"traceparent"in ES){for(let yt of["TRACEPARENT","TRACESTATE"])if(!(yt in(M??{})))delete _t[yt]}for(let[yt,Ln]of Object.entries(ES)){let Yr=yt.toUpperCase();if(!(Yr in(M??{})))_t[Yr]=Ln}let Jk={},Xk=new Map;if(yu)for(let[yt,Ln]of Object.entries(yu))if(Ln.type==="sdk"&&Ln.instance)Xk.set(yt,Ln);else Jk[yt]=Ln;let Cu;if(Ss)switch(Ss.type){case"adaptive":Cu={type:"adaptive",display:Ss.display};break;case"enabled":Cu={type:"enabled",budgetTokens:Ss.budgetTokens,display:Ss.display};break;case"disabled":Cu={type:"disabled"};break}else if(Vr!==void 0)Cu=Vr===0?{type:"disabled"}:{type:"enabled",budgetTokens:Vr};if(r){if(_t.CLAUDE_CONFIG_DIR=r,process.platform==="win32")_t.CLAUDE_SECURESTORAGE_CONFIG_DIR=M?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??M?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let Y5=Boolean(Kt||L)&&!p.pathToClaudeCodeExecutable&&!p.spawnClaudeCodeProcess&&Q?.["sdk-url"]===void 0&&!Object.keys(Q??{}).some((yt)=>yt.startsWith("sdk-url="))&&!J.some((yt)=>/^--sdk-url(=|$)/.test(yt)),Qk=new vk({abortController:y,additionalDirectories:S,projectConfigRoot:E,agent:b,betas:R,cwd:F,debug:re,debugFile:T,executable:z,executableArgs:J,extraArgs:{...Q,...Rt&&{workload:Rt},...Y5&&{"await-initialize":null}},pathToClaudeCodeExecutable:yS,env:_t,forkSession:Ve,stderr:Ff,thinkingConfig:Cu,effort:Df,maxTurns:Ui,maxBudgetUsd:Or,taskBudget:_u,model:Su,fallbackModel:W,jsonSchema:Zk,permissionMode:qk,allowDangerouslySkipPermissions:Eu,permissionPromptToolName:Ua,permissionPrompts:Mf,continueConversation:gn?void 0:L,resume:Kt,resumeSessionAt:qr,resumeDropsTurn:Fa,sessionId:Uf,settings:typeof a==="object"?ce(a):a,managedSettings:l?ce(l):void 0,settingSources:c,skills:Ha,allowedTools:A,disallowedTools:w,tools:I,mcpServers:Jk,strictMcpConfig:W5,canUseTool:!!x,hooks:!!ot,includeHookEvents:At,includePartialMessages:Zt,persistSession:Io,sessionMirror:!!gn,plugins:Es,pluginsViaInitialize:Yk,sandbox:d,spawnClaudeCodeProcess:p.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),Z5={systemPrompt:f,appendSystemPrompt:m,planModeInstructions:p.planModeInstructions,systemPromptSnapshot:_,appendSubagentSystemPrompt:p.appendSubagentSystemPrompt,toolAliases:p.toolAliases,codeRunningMcpTools:p.codeRunningMcpTools,excludeDynamicSections:g,agents:C,title:p.title,skills:Ha,webSearchIsolationExemptMcpServers:p.webSearchIsolationExemptMcpServers,promptSuggestions:p.promptSuggestions,agentProgressSummaries:p.agentProgressSummaries,forwardSubagentText:Ke,supportedDialogKinds:Fe,perTaskStopAffordance:En,rapidFollowupPreempt:ys,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:V5,plugins:Yk?Es:void 0,captureSdkMcpManifests:!om("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},bS=new fS(Qk,n,x,ot,y,Xk,Zk,Z5,ge,Nf,he,sn,we,q5);if(gn){let yt=()=>Ct(_t.CLAUDE_CONFIG_DIR??Ct(Pf(),".claude"),"projects"),Ln=Na==="eager",Yr=new jb(async($a,CS)=>{let Au=Bk($a,yt());if(Au)await gn.append(Au,CS);else G(`[SessionStore] dropping mirror frame: filePath ${$a} is not under ${yt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:($a,CS)=>{let Au=Bk($a,yt());if(Au)bS.reportMirrorError(Au,CS.message)},maxPendingEntries:Ln?0:qu,maxPendingBytes:Ln?0:Wi});bS.setTranscriptMirrorBatcher(Yr)}return{queryInstance:bS,transport:Qk,abortController:y,processEnv:_t,verbatimPrompts:we}}function Gk(e,t,n,r){if(typeof t==="string")e.writePrompt(ce({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,...r&&{client_composed:!0}})+`
|
|
162
162
|
`).catch((o)=>n.abort(o));else e.streamInput(t).catch((o)=>n.abort(o))}var V8e=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function hS(e){for(let t=0;;t++)try{return await A5(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!V8e.has(le(n)??""))return;await _n((t+1)*100)}}function q8e(e,t){e.waitForExit().catch(()=>{}).finally(()=>hS(t))}function Y8e({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return Z8e(e,t);let{queryInstance:n,abortController:r,verbatimPrompts:o}=Kk(t,{isSingleUserTurn:typeof e==="string"});return Gk(n,e,r,o),n}function Z8e(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s,verbatimPrompts:i}=Kk({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),a=If(t.cwd??"."),l=t.sessionStore,c=t.loadTimeoutMs??60000,d=t.resume;return(async()=>{if(!d)d=(await wr(l.listSessions(Dn(a,t.env)),c,`SessionStore.listSessions() timed out after ${c}ms`)).slice().sort((m,g)=>g.mtime-m.mtime)[0]?.sessionId;if(!d)return;return w5(l,d,a,t.env,t.loadTimeoutMs)})().then((f)=>{if(f){r.updateResume(d);let m={CLAUDE_CONFIG_DIR:f};if(process.platform==="win32"){let g=t.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??t.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";m.CLAUDE_SECURESTORAGE_CONFIG_DIR=g,s.CLAUDE_SECURESTORAGE_CONFIG_DIR=g}r.updateEnv(m),s.CLAUDE_CONFIG_DIR=f,n.addCleanupCallback(()=>q8e(r,f))}if(!n.isClosed())r.spawn()}).catch((f)=>{let m=Yn(f);r.spawnAbort(m),n.setError(m)}),Gk(n,e,o,i),n}async function J8e(e={}){return(await x5(e)).warm}async function x5({options:e,initializeTimeoutMs:t}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=If(e.cwd??".");if(!r){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let l=e.loadTimeoutMs??60000;r=(await wr(e.sessionStore.listSessions(Dn(a,e.env)),l,`SessionStore.listSessions() timed out after ${l}ms`)).slice().sort((d,p)=>p.mtime-d.mtime)[0]?.sessionId}if(r)n=await w5(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let _=function(){if(g)return;g=!0,p.close()},a=Kk(n&&r&&r!==e?.resume?{...e,resume:r}:e,{isSingleUserTurn:!1,resumeConfigDir:n,readsStartupMarks:!0});o=a.queryInstance;let{transport:l,abortController:c,verbatimPrompts:d}=a;s=l;let p=a.queryInstance;if(n){let S=n;p.addCleanupCallback(()=>{i=l.waitForExit().catch(()=>{}).then(()=>hS(S))})}let m=new xk(t,Ka,e?.onStartupHooksRunning);p.setFrameObserver((S)=>{if(m.note(S),S.type==="system"&&S.subtype==="hook_progress")p.dropUnreadHookProgress(S.hook_id)});try{await m.race(p.initializationResult())}catch(S){if(S instanceof Error&&"errorClass"in S&&S.errorClass==="initialize_timeout"&&Object.isExtensible(S)){let E=p.startupMarkReached();Object.assign(S,{[NJ]:E?.mark??"none",...E&&{[UJ]:E.ageMs}})}throw S}finally{p.setFrameObserver(void 0)}let g=!1;return{warm:{query(S){if(g)throw Error("WarmQuery.query() can only be called once");g=!0;try{Gk(p,S,c,d)}catch(E){throw p.close(),E}if(typeof S==="string")p.setIsSingleUserTurn(!0);return p},close:_,async[Symbol.asyncDispose](){g=!0,p.close(),await i}},query:p,transport:l}}catch(a){if(o?.close(),n&&!i){let l=s;i=(l?l.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>hS(n))}throw await i,a}}async function X8e({options:e,initializeTimeoutMs:t}={}){if(e?.resume||e?.continue||e?.forkSession)throw Error("prewarm(): resume/continue/forkSession describe a session; a spare has none — pass them to query() instead");let n=e?.cwd===void 0,r;if(e?.cwd!==void 0)r=e.cwd;else{let C=e?.env,A=C?.CLAUDE_CONFIG_DIR?.trim(),R=C?.HOME?.trim(),x=C===void 0?Ut():A||Ct(R||Pf(),".claude"),L=jk(x)?x:Ct(Pf(),".claude");if(!jk(L))throw Error("prewarm(): no absolute config home to park the spare under (neither CLAUDE_CONFIG_DIR nor HOME gives an absolute path); set one of them to an absolute path or pass options.cwd");let F=Ct(L,"spares");await gS(F,{recursive:!0,mode:448}),r=await N8e(Ct(F,"spare-"))}function o(){return n?A5(r,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve()}let{workspaceTrust:s,...i}=e??{};if(s!==void 0)G("prewarm(): workspaceTrust is a per-session attestation — pass it to claim(); not sent to the spare",{level:"warn"});let{warm:a,query:l,transport:c}=await rn("sdk_prewarm",async()=>{try{return await x5({options:{...i,cwd:r,extraArgs:{...i.extraArgs,"await-claim":null}},initializeTimeoutMs:t??dS})}catch(C){throw await o(),C}}),d=Object.entries(e?.mcpServers??{}).filter(([,C])=>C.type==="sdk").map(([C])=>C),p;function f(){return p??=c.waitForExit().catch(()=>{}).then(o),p}let m=!1,g=!1,_=!1,y,S=new Promise((C,A)=>{y={resolve:C,reject:A}});S.catch(()=>{});let E=c.waitForExit().then(()=>{return},()=>{return});E.then(()=>{if(!m)_=!0,y.reject(Error("spare_exited: the spare process exited before it was claimed")),f()});let b={claimed:S,exited:E,claim({prompt:C,options:A}){if(m)throw Error("SpareProcess.claim() can only be called once");if(g||_)throw Error("SpareProcess.claim(): the spare was closed or has exited; start the session with query()");let R=W8e.filter((Ke)=>A.settings?.[Ke]!==void 0);if(R.length>0)throw new ve(`SpareProcess.claim(): hook settings (${R.join(", ")}) cannot be applied at claim; pass them to prewarm() in Options.settings, where they are in force before any hook, as on a cold start. Nothing was sent: this spare can still be claimed without them.`,"SpareProcess.claim(): hook settings cannot be applied at claim");let x=typeof A.cwd==="string"&&A.cwd.trim()!==""&&!O5.isAbsolute(A.cwd)&&!T5.isAbsolute(A.cwd)&&A.cwd!=="~"&&!A.cwd.startsWith("~/")?If(A.cwd):A.cwd;m=!0;let L=v5(A.workspaceTrust),F=A.settings,re=oe(F),{model:T,agent:w,fastMode:I,permissions:M,availableModels:z,disableAutoMode:J,...Q}=re?F:{},W={model:T,agent:w,fastMode:I,permissions:M,availableModels:z,disableAutoMode:J},B=F!==void 0&&(!re||Object.keys(Q).length>0)?l.applyFlagSettings(re?Q:F):void 0,it=l.claimSession({cwd:x,...A.permissionMode!==void 0&&{permission_mode:A.permissionMode},...A.env&&{env:A.env},...A.additionalDirectories&&{additional_directories:A.additionalDirectories},...A.appendSystemPrompt!==void 0&&{append_system_prompt:A.appendSystemPrompt},...A.title!==void 0&&{title:A.title},...A.agents&&{agents:A.agents},...L?.accepted===!0&&{workspace_trust:L},sdk_mcp_servers:d}),Ve=[];if(A.model!==void 0)Ve.push(["model",l.setModel(A.model)]);if(A.maxThinkingTokens!==void 0)Ve.push(["maxThinkingTokens",l.setMaxThinkingTokens(A.maxThinkingTokens)]);let ot=Object.values(W).some((Ke)=>Ke!==void 0)?l.applyFlagSettings(W):void 0,At=F!==void 0?Promise.all([B,ot]):void 0;if(At!==void 0)Ve.push(["settings",At]);for(let[,Ke]of Ve)Ke.catch(()=>{});function Zt(){c.endInput(),f()}if(it.then(async(Ke)=>{o();let we={cwd:Ke.cwd??x,sessionId:Ke.session_id,parkedMs:Ke.parked_ms,sdkMcpSettled:Ke.sdk_mcp_settled},ge=await Promise.allSettled(Ve.map(([,En])=>En)),sn=ge.flatMap((En,ys)=>En.status==="rejected"?[`${String(Ve[ys][0])}: ${ft(En.reason)}`]:[]),Fe=At===void 0?void 0:ge[Ve.findIndex(([En])=>En==="settings")];if(Fe?.status==="rejected")g=!0,l.close(),y.reject(Object.assign(new ve(`settings_not_applied: ${ft(Fe.reason)} — the prompt was not sent and the process was closed; start the session with query()`,"settings_not_applied"),{claim:we}));else if(sn.length>0)y.reject(Object.assign(new ve(`option_not_applied: ${sn.join("; ")} — the prompt was sent and the session runs without these options`,"option_not_applied"),{claim:we}));else y.resolve(we)},(Ke)=>{Zt(),y.reject(Ke)}),At===void 0)return a.query(C);return Promise.all([it,At]).then(()=>{if(g)return;try{a.query(C)}catch{}},()=>{}),l},close(){if(g)return;if(g=!0,m)l.close();else a.close(),y.reject(Error("spare_closed: the spare was closed before it was claimed"));f()},async[Symbol.asyncDispose](){b.close(),await f()}};return b}import{randomUUID as F5}from"crypto";import{constants as k5}from"fs";import{open as Q8e,readdir as I5,rm as e7e,stat as t7e}from"fs/promises";import{join as _s}from"path";var n7e=64;function Vk(e){return be()?e:void 0}async function D5(e,t,n={},r){if(!qe(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let o=ce({type:"custom-title",customTitle:t.trim(),sessionId:e})+`
|
|
163
163
|
`;await U5(e,o,n,Vk(r))}async function L5(e,t,n={},r){if(!qe(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let s=Ki(t).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");t=s}let o=ce({type:"tag",tag:t??"",sessionId:e})+`
|
|
164
164
|
`;await U5(e,o,n,Vk(r))}async function M5(e,t={},n){if(!qe(e))throw Error(`Invalid sessionId: ${e}`);let r=Vk(n);for(let o of await o7e(t,r)){if(be()&&r!==void 0){let a=Xi(o,r.isKeySegment);if(a!==void 0){if(await r7e(a,e,r))return;continue}}let s=_s(o,`${e}.jsonl`),i;try{({size:i}=await t7e(s))}catch(a){let l=le(a);if(l==="ENOENT"||l==="ENOTDIR")continue;throw a}if(i===0)continue;await e7e(s,{force:!0}),await KL(_s(o,e));return}throw Error(t.dir?`Session ${e} not found in project directory for ${t.dir}`:`Session ${e} not found in any project directory`)}async function r7e(e,t,n){let{backend:r,transcriptKey:o}=n,s=o(e,t),i=await r.statMeta(s);if(!i.ok){if(i.error.code==="NotFound")return!1;throw Error("Session delete: transcript unreadable via storage",{cause:i.error})}if((i.value.storedBytes??i.value.size)===0)return!1;for(let l of["transcript","sidecar"]){let c=await r.deleteScope({namespace:l,projectKey:e,sessionId:t});if(!c.ok)throw Error("Session delete: session directory not deletable via storage",{cause:c.error})}let a=await r.delete(s);if(!a.ok)throw Error("Session delete: transcript not deletable via storage",{cause:a.error});return!0}async function o7e(e,t){if(e.dir){let r=await zo(e.dir,Um(t,be())),o=await P5(r,t),s;try{s=await Ho(r)}catch{s=[]}for(let i of s){if(i===r)continue;o.push(...await P5(i,t))}return o}let n=Et();if(be()&&t!==void 0){let r=await N5(t);if(r===void 0)return[];if(r.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return r.names.map((o)=>_s(n,o))}try{return(await I5(n,{withFileTypes:!0})).filter((o)=>o.isDirectory()||o.isSymbolicLink()).map((o)=>_s(n,o.name))}catch{return[]}}async function P5(e,t){let n=dn(t);if(n===void 0||!n.hoverRestOn)return Zn(e);let r=await Zn(e,n),o=hl(e),s=process.platform==="win32",i=[];for(let a of r)if(a===o||await _l(a,e,s,n))i.push(a);return i}async function N5(e){let t=[],n,r=0;try{do{let o=await e.backend.listEntries({namespace:"transcript"},{skipScopeStats:!0,...n!==void 0&&{cursor:n}});if(!o.ok)return r===0?void 0:{names:t,laterPageFailed:!0};for(let s of o.value.items){let i=Hm(s,e.isKeySegment);if(i!==void 0)t.push(i)}n=o.value.cursor}while(n&&++r<n7e);return{names:t,laterPageFailed:Boolean(n)}}catch{return r===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function U5(e,t,n,r){let o=`${e}.jsonl`;if(n.dir){let a=await zo(n.dir,Um(r,be()));for(let c of await Zn(a,dn(r)))if(await _S(_s(c,o),t,Wk(c,e,r)))return;let l;try{l=await Ho(a)}catch{l=[]}for(let c of l){if(c===a)continue;for(let d of await Zn(c,dn(r)))if(await _S(_s(d,o),t,Wk(d,e,r)))return}throw Error(`Session ${e} not found in project directory for ${n.dir}`)}let s=Et();if(be()&&r!==void 0){let a=await N5(r);if(a===void 0)throw new ve(`Session ${e} not found (no projects directory)`,"Session not found (no projects directory)");let{names:l}=a;for(let c of l){let d=_s(s,c);if(await _S(_s(d,o),t,Wk(d,e,r)))return}throw new ve(`Session ${e} not found in any project directory`,"Session not found in any project directory")}let i;try{i=await I5(s)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let a of i)if(await _S(_s(s,a,o),t))return;throw Error(`Session ${e} not found in any project directory`)}async function _S(e,t,n){if(be()&&n!==void 0)return s7e(n,t);let r;try{r=await Q8e(e,k5.O_WRONLY|k5.O_APPEND)}catch(o){let s=le(o);if(s==="ENOENT"||s==="ENOTDIR")return!1;throw o}try{let{size:o}=await r.stat();if(o===0)return!1;let s=process.platform==="win32"?o:void 0,i=Buffer.from(t,"utf8"),a=0;while(a<i.length){let{bytesWritten:l}=await r.write(i,a,i.length-a,s);if(l<=0)throw new ve(`tryAppend: short write to ${e} stalled with ${i.length-a} bytes remaining`,"tryAppend: zero-progress short write");if(a+=l,s!==void 0)s+=l}return!0}finally{await r.close()}}async function s7e({backend:e,key:t},n){let r=await e.append(t,[{data:n}],{precondition:{type:"ifExists",nonEmpty:!0}});if(!r.ok){if(r.error.code==="NotFound")return!1;throw Error("Session append: transcript not writable via storage",{cause:r.error})}return!0}function Wk(e,t,n){if(!be()||n===void 0)return;let r=Xi(e,n.isKeySegment);return r===void 0?void 0:{backend:n.backend,key:n.transcriptKey(r,t)}}async function i7e(e,t,n){if(n?.sessionStore)return c7e(n.sessionStore,e,t,n.dir);return D5(e,t,n)}async function a7e(e,t,n){if(n?.sessionStore)return u7e(n.sessionStore,e,t,n.dir);return L5(e,t,n)}async function l7e(e,t){if(!qe(e))throw new ve(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=Dn(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return M5(e,t)}async function c7e(e,t,n,r){if(!qe(t))throw new ve(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!n.trim())throw Error("title must be non-empty");let o=Dn(r);await e.append({projectKey:o,sessionId:t},[{type:"custom-title",customTitle:n.trim(),sessionId:t,uuid:F5(),timestamp:new Date().toISOString()}])}async function u7e(e,t,n,r){if(!qe(t))throw new ve(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(n!==null){let s=Ki(n).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");n=s}let o=Dn(r);await e.append({projectKey:o,sessionId:t},[{type:"tag",tag:n??"",sessionId:t,uuid:F5(),timestamp:new Date().toISOString()}])}async function hZt(e){return mJ(e)}async function SZt(e,t){if(t?.sessionStore)return b7e(t.sessionStore,e,t);return eH(e,t)}async function EZt(e){if(e?.sessionStore)return y7e(e.sessionStore,e);return gH(e)}async function bZt(e,t){if(t?.sessionStore)return C7e(t.sessionStore,e,t);return hH(e,t)}async function CZt(e,t){if(t?.sessionStore)return A7e(t.sessionStore,e,t);return qH(e,t)}async function AZt(e,t,n,r){if(!qe(e))throw new ve(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=be(),s=o?r:void 0,i=await Is(e,n?.dir,Bn(s),o);if(!i)throw Error(`Session ${e} not found`);let a=Dn(n?.dir),l=n?.batchSize&&n.batchSize>0?n.batchSize:qu,c=s===void 0?void 0:Xi(m7e(i.filePath),en),d=s!==void 0&&c!==void 0?{backend:s,projectKey:c}:void 0;if(d!==void 0)await $O(d.backend,Ht.transcript(d.projectKey,e),{projectKey:a,sessionId:e},t,l);else await H5(i.filePath,{projectKey:a,sessionId:e},t,l);if(n?.includeSubagents===!1)return;if(d!==void 0){let m=await l$(d.backend,d.projectKey,e),g=await c$(d.backend,d.projectKey,e,m);for(let _ of m){let y={projectKey:a,sessionId:e,subpath:Ig(_)};await $O(d.backend,_.kind==="agent"?Ht.transcript(d.projectKey,e,_.agentId,_.agentRelPath):Ht.journal(d.projectKey,e,_.agentRelPath),y,t,l);let S=g.get(y.subpath),E;if(S!==void 0)try{E=je(S)}catch(b){G(`importSessionToStore: skipping unreadable sidecar for ${y.subpath}: ${b}`)}if(E!==void 0)await t.append(y,[{type:"agent_metadata",...E}])}return}let p=i.filePath.replace(/\.jsonl$/,""),f=$5(p,"subagents");for(let m of await _7e(f)){let g=g7e(p,m).split(h7e);g[g.length-1]=g.at(-1).replace(/\.jsonl$/,"");let _={projectKey:a,sessionId:e,subpath:g.join("/")};await H5(m,_,t,l);let y=m.replace(/\.jsonl$/,".meta.json"),S;try{S=je(await f7e(y,"utf8"))}catch(E){if(!et(E))G(`importSessionToStore: skipping unreadable sidecar ${y}: ${E}`)}if(S!==void 0)await t.append(_,[{type:"agent_metadata",...S}])}}async function H5(e,t,n,r){let o=[],s=0,i=await d7e(e,"r");try{for await(let a of yL(i)){if(!a)continue;try{o.push(je(a))}catch(l){G(`importSessionToStore: skipping unparseable line in ${e}: ${l}`);continue}if(s+=a.length,o.length>=r||s>=Wi)await n.append(t,o),o=[],s=0}}finally{await i.close().catch(()=>{})}if(o.length>0)await n.append(t,o)}async function _7e(e){let t=[];async function n(r){let o;try{o=await p7e(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=$5(r,s.name);if(s.isDirectory())await n(i);else if(s.isFile()&&s.name.endsWith(".jsonl"))t.push(i)}}return await n(e),t}async function RZt(e,t){if(t?.sessionStore)return R7e(t.sessionStore,e,t.dir);return o$(e,t)}async function OZt(e,t,n){if(n?.sessionStore)return O7e(n.sessionStore,e,t,n);return s$(e,t,n)}function z5(e){return e.map((t)=>ce(t)).join(`
|