@anthropic-ai/claude-agent-sdk 0.3.302 → 0.3.303
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 +49 -48
- package/browser-sdk.js +2 -2
- package/{core-vf1qkp6x.mjs → core-dmg5st5c.mjs} +2 -2
- package/{core-1t4c883z.mjs → core-gvw0a6et.mjs} +1 -1
- package/core.mjs +5 -5
- package/manifest.json +19 -19
- package/manifest.zst.json +25 -25
- package/package.json +12 -12
- package/sdk.mjs +3 -3
package/sdk.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
|
|
3
3
|
|
|
4
|
-
// Version: 0.3.
|
|
4
|
+
// Version: 0.3.303
|
|
5
5
|
|
|
6
6
|
// Want to see the unminified source? We're hiring!
|
|
7
7
|
// https://job-boards.greenhouse.io/anthropic/jobs/4816199008
|
|
@@ -156,11 +156,11 @@ ${n.join(`
|
|
|
156
156
|
`)+(e.endsWith(`
|
|
157
157
|
`)?0:1)}}function CVe(e){return Yu(se(e))}function AVe(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 se([e.command,...t])}function RVe(e){return fi(TZ(e))}function TZ(e){return{shellSettings:e.shellSettings,envVars:e.envVars,sandboxSettings:Object.keys(e.sandboxSettings).length>0?e.sandboxSettings:void 0,...gZ(e),hooks:e.hooks,payloadSlots:Qw(e).length>0?Object.fromEntries(Qw(e).map(([t,n])=>{let{isolationSettings:r,...o}=n;return[t,{...o,...gZ(n)}]})):void 0}}function gZ(e){return Object.keys(e.isolationSettings).length>0?{isolationSettings:e.isolationSettings}:{}}function fi(e){return se(tp(e))}function OZ(e){return Yu(RVe(e))}function wZ(e,t,n){if(OZ(t)===e)return!0;return typeof n==="string"&&n.length>0&&Yu(fi({...TZ(t),claudeMd:n}))===e}function hZ(e,t,n){return se([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}var TVe=new Set(["dns","unix","ipv4","ipv6"]),xDt=new Set([...TVe,"http","https","ws","wss","ftp","file","grpc","grpcs","otlp","xds","tcp","udp","tls","h2","h2c","http2"]);function xZ(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function OVe(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of Ec){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var xVe="remote-settings.json",vVe=5000;var DZ="remote-settings-helper-consent";function kVe(){return IZ(vt(),DZ)}function PVe(e){let t=_Z(e);return RZ(t)?t:void 0}function IVe(e){let t=ea(e,(n,r)=>r.startsWith("$")&&r!=="$schema");if(Object.keys(t).length!==Object.keys(e).length)LZ.set(t,e);return t}function vZ(e){return LZ.get(e)??e}var LZ=new WeakMap;class MZ{sessionCache=null;storedAccountReader=null;storedCopyGateCovers=!0;storedCopyOrgPin={kind:"unreadable"};storedCopyTrust="not_asked";storedCopyRefusal=null;eligible=void 0;eligibilityMemo=void 0;machinePinsSignInMemo=void 0;ineligibleReason=void 0;evalPolicySnapshotOnly=!1;hybridTokenRenewalDue=!1;hybridOrganizationUuid=null;hybridSignInEnded=!1;lastLoadStatus=void 0;loadCycleEnded=!1;loadCycleBegun=!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&&!Wo())return e;if(e!==null){let n=CO(this.coworkCloudHolds,e);return this.coworkCloudHolds=qh(n),n}return t?this.coworkCloudHolds:null}replaceSessionCache(e,t){let n=t?.verified===!0||!Wo();if(!n&&e!==null&&e===this.sessionCache)return;let r=this.heldSoFar(n?FVe(e):null);if(this.sessionCache=r,t?.verified){if(this.verifiedPayload=r,this.verifiedByGateway=ZP()?.url,this.projectedView=null,this.projectedParse=null,t.consentDeferred)this.deferredPayload=r}}seedFromDisk(e){let t=Object.keys(this.coworkCloudHolds).length>0?CO(this.coworkCloudHolds,e):e;this.sessionCache=t,this.seedConsentBaseline(t)}seedConsentBaseline(e){let t=PVe(e);if(t!==void 0){let n=jVe();if(n===void 0||!wZ(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}reset(){this.sessionCache=null,this.storedCopyTrust="not_asked",this.storedCopyRefusal=null,this.storedAccountReader=null,this.storedCopyGateCovers=!0,this.storedCopyOrgPin={kind:"unreadable"},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.hybridSignInEnded=!1,this.lastLoadStatus=void 0,this.loadCycleEnded=!1,this.loadCycleBegun=!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: ${ot(t)}`,{level:"error"})}}}var DVe=new Le(()=>new MZ);function mo(){return DVe.of(tn().host)}function NZ(){return mo().lastLoadStatus}function ca(){return}function LVe(){return mo().evalPolicySnapshotOnly}function tx(){return nt()||LVe()}function UZ(e){let{projectedView:t,projectedParse:n}=mo();return e!==null&&(t?.view===e||n?.view===e||MVe(e))}function MVe(e){return Wo()&&Object.keys(e).length>0&&Xt(qh(e),e)}var NVe=[["allowedHttpHookUrls"],["httpHookAllowedEnvVars"],["isolation","required"]],FZ=[{path:["sandbox","credentials","files"],names:"path"},{path:["sandbox","credentials","envVars"],names:"name"}];function $Z(e){for(let n of NVe)an(e,n,void 0);for(let{path:n,names:r}of FZ){let o=bt(e,n),s=(Array.isArray(o)?o:[o]).flatMap((i)=>ie(i)&&typeof i[r]==="string"?[{[r]:i[r],mode:"deny"}]:[]);an(e,n,s.length>0?s:void 0)}for(let n of[["permissions","deny"],["permissions","ask"]]){let r=bt(e,n);if(Array.isArray(r)){let o=r.filter((s)=>typeof s!=="string"||!Yd.test(s));an(e,n,o)}}for(let{path:n,restrictive:r}of uo()){let o=bt(e,n),s=n[0]==="strictPluginOnlyCustomization"?o:_c(o);if(r===!0&&s===!1)an(e,n,void 0)}let t=e.strictPluginOnlyCustomization;if(Array.isArray(t)&&!t.some((n)=>pp.includes(n)))delete e.strictPluginOnlyCustomization;if(e.availableModelsMatch==="prefix")delete e.availableModelsMatch}function zZ(e){let t={...kO(e)};if($Z(t),e.parentSettingsBehavior==="merge")t.parentSettingsBehavior="merge";let n=Object.fromEntries([...BG,ac].flatMap((s)=>Object.entries(e.pluginConfigs?.[s]?.options??{}))),r=bO({pluginConfigs:{[ac]:{options:n}}});if(r!==void 0)t.pluginConfigs=r;let o=Object.entries(e.enabledPlugins??{}).filter(([s,i])=>i===!1&&!(s.includes("@")&&fZ(s.slice(s.lastIndexOf("@")+1))===pZ));return o.length===0?t:{...t,enabledPlugins:Object.fromEntries(o)}}function kZ(e){if(!e||!tx())return e;let t={...kO(e)};if(nt()){if($Z(t),e===mo().verifiedPayload&&typeof e.claudeMd==="string"&&e.claudeMd!=="")t.claudeMd=e.claudeMd}return{...t,managedSourcesBehavior:"merge"}}function UVe(){return Wo()||ca()===void 0&&Gh()}function HZ(){return ca()??IZ(vt(),xVe)}var jZ=8388608;function FVe(e){if(e===null||!Wo())return e;let t=qh(e);return Xt(t,e)?e:t}function $Ve(){if(UVe())return null;let e=mo(),t=e.storedCopyRefusal;if(t!==null&&AO()&&Date.now()-t.atMs<vVe)return e.storedCopyTrust={trusted:!1,reason:t.reason},null;e.storedCopyTrust="not_asked";try{let n=BVe();if(n===null)return null;let r=Fe(oc(n));if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=IVe(r);return zVe(o)?o:null}catch(n){if(iG(n))G(`Remote settings: Disk cache exceeds ${jZ} bytes; ignoring it as if absent`);return null}}function zVe(e){let t=mo();if(!AO()||!t.storedCopyGateCovers||ca()!==void 0||t.evalPolicySnapshotOnly)return t.storedCopyTrust="not_asked",!0;let n,r=t.storedCopyOrgPin;if(r.kind==="unreadable")n="org_pin_unknown";else try{let o=SV({kind:"managed-settings",cachePath:HZ(),body:vZ(e),bodySha:oV(vZ(e)),account:t.storedAccountReader?.(),pinnedOrgs:r.orgs,nowMs:Date.now(),roots:AV()});if(o.trusted)return t.storedCopyTrust=o,!0;n=o.reason}catch(o){G(`Remote settings: the gate on a stored copy failed: ${ot(o)}`,{level:"error"}),n="error"}return t.storedCopyTrust={trusted:!1,reason:n},t.storedCopyRefusal={atMs:Date.now(),reason:n},t.seedConsentBaseline(e),G(`Remote settings: the stored copy is not trusted at rest (${n}); treating it as absent`),!1}var HVe=4096;function jVe(){let e=nx();if(e!==void 0)return e.attestation;if(nt())return;try{return ri(kVe(),HVe).trim()||void 0}catch{return}}function BVe(){let e=nx();if(e!==void 0)return e.content;if(nt()&&ca()===void 0)return null;return ri(HZ(),jZ)}function nx(){let e=mo().backendView;if(!Ee()||e===void 0||!e.ready||e.stoodDown||ca()!==void 0)return;if(!lI(e.configHome)){e.standDown("config home changed");return}return e}var ALt=Pt.state("remote-settings"),RLt=Pt.state(DZ);var KVe=new Set([...BV,"CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_OPTIONS",...LO,...MO,"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",...$O,...zO,...HO,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...NO,"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 GVe(e){if(!e||!e.env&&!("managedMcpServers"in e))return e;let{managedMcpServers:t,...n}=e;return e.env?{...n,env:ea(e.env,(r,o)=>KVe.has(o.toUpperCase()))}:n}function BZ(){let e=GZ();if(e===null||tx()||KZ(mo(),e))return!1;if(PZ(e))return!0;let t=ex(e);if(t.length===0)return!1;let{chain:n}=sZ();return t.some(([r,o])=>{let s=SZ(r);return(s===void 0||n.includes(s))&&PZ(o)})}function PZ(e){let t=e.managedMcpServers;return ie(t)&&Object.keys(t).length>0}function KZ(e,t){return t===e.verifiedPayload||Boolean(ca())}function GZ(){let e=mo();if(!ca()&&e.eligible!==!0)return e.heldSoFar(null);if(e.sessionCache)return e.sessionCache;let t=nx()!==void 0,n=$Ve();if(n){if(e.seedFromDisk(n),t)Vo().invalidatePolicyLayer();else WG();return e.sessionCache}return e.heldSoFar(null)}function WZ(e){let t=GZ(),n=mo(),r=KZ(n,t)?t:WVe(n,t);if(r===null||!tx())return r;if(n.projectedView?.raw!==r)n.projectedView={raw:r,view:kZ(r)};let o=n.projectedView.view;if(!e)return o;if(n.projectedParse?.raw!==r){let s={...o};if(VZ(s,kZ(e(r))??{}),nt())for(let{path:i,names:a}of FZ){let l=[o,s].flatMap((c)=>bt(c,i)??[]);if(l.length>0)an(s,i,nV(l,a))}n.projectedParse={raw:r,view:s}}return n.projectedParse.view}function VZ(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(o!==r&&ie(o)&&ie(r)){let s={...o};VZ(s,r),e[n]=s}else e[n]=r}}function WVe(e,t){if(t===null)return null;if(e.unverifiedView?.raw!==t)e.unverifiedView={raw:t,view:GVe(t)};return e.unverifiedView.view}var VVe=jt(new Set,(e)=>e.clear());function qZ(e){VVe.add(e)}var qVe=process.platform==="darwin"?16777216:process.platform==="linux"||process.platform==="android"?524288:0,xLt=process.platform==="darwin"?536870912:0,vLt=process.platform==="linux"||process.platform==="android"?2097152:0;var FLt=jt({noFollowAny:"untried",localVolumes:void 0},(e)=>{e.noFollowAny="untried",e.localVolumes=void 0});var $Lt=Symbol("no procfs"),zLt=Symbol("descriptor path unreadable");var HLt=Symbol("boundRead.linkToNothing");var ZZ=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var ZVe=["userSettings","projectSettings","localSettings"],YVe=["projectSettings","localSettings"],XLt=new Set(YVe),JVe={userSettings:"user",projectSettings:"project",localSettings:"local"},QLt=ZVe.map((e)=>[JVe[e],e]);var YZ=["auto","bypassPermissions"];function JZ(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 XZ=["claude-3-5-haiku","claude-3-5-sonnet","claude-3-7-sonnet","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-mythos-5","claude-mythos-5-1","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"],QZ=["sonnet","opus","haiku","fable","best","sonnet[1m]","opus[1m]","fable[1m]","opusplan"],mi=["sonnet","opus","haiku","fable"];function K_(e){return QZ.includes(e)}function rx(e){return e.replace(/\[1m\]$/i,"")}function eY(e){return e.replace(/\[(1|2)m\]/gi,"")}function ua(e){return mi.includes(e)}function Yo(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&&!uL.includes(a))return null;t=l}let o=QVe(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(!XVe(s))i.trailer=s;else{let a=/(?:-v\d+@|[-@])(\d{8})/.exec(s)?.[1];if(a!==void 0)i.date=a}return i}function XVe(e){return/^(?:-fast|-latest)?(?:-v\d{1,3}@\d{8}|[-@]\d{8})?(?:-v\d{1,3}(?::\d{1,3})?)?$/.test(e)}function tY(e,t){return e.major-t.major||(e.minor??0)-(t.minor??0)}function QVe(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 nr(e){let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g,"?");return t.length>128?`${t.slice(0,128)}…`:t}function e2e(){let e=[...mi],t=e.pop();return e.length===0?t??"":`${e.join(", ")} or ${t}`}function G_(e){return e.charAt(0).toUpperCase()+e.slice(1)}function nY(e){let t=e.trim().toLowerCase(),n=eY(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(ua(n))return{entry:{kind:"family",family:n},...r!==""&&{warning:`"${nr(e)}" blocks every ${G_(n)} model.${r}`}};if(K_(n)||n==="default")return{entry:null,warning:`"${nr(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=Yo(n),s=o!==null||n.startsWith("claude-")?n:`claude-${n}`,i=o??(s!==n?Yo(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!==""?` "${nr(l)}" is ignored.`:"";return{entry:{kind:"model",id:i},...(r!==""||c!=="")&&{warning:`"${nr(e)}" blocks ${t2e(i)}.${c}${r}`}}}return{entry:{kind:"literal",value:n},warning:n2e(e,n)}}function t2e(e){let t=G_(e.family);return e.minor===void 0?`every ${t} ${e.major}.x model`:`${t} ${e.major}.${e.minor} in every spelling and snapshot`}function n2e(e,t){let n=`"${nr(e)}" blocks only the exact model name "${nr(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(Yo(s)!==null)return`${n} To block a version, write it with a hyphen: "${nr(s)}".`}let o=new RegExp(`^(${mi.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 ${G_(s)} ${i}.x model.`}if(/^[a-z]+$/.test(t)){let s=mi.find((i)=>JZ(t,i,1)===1);return s!==void 0?`${n} If you meant the ${G_(s)} family, write "${s}".`:`${n} To block a model family other than ${e2e()}, list its versioned IDs.`}return n}function rY(e){let t=rx(e.trim().toLowerCase());if(t==="")return{kind:"ignored"};if(ua(t))return{kind:"family",family:t};let n=t.startsWith("claude-")?t.slice(7):"";if(ua(n))return{kind:"family",family:n};if(K_(t)||t==="default")return{kind:"ignored"};let r=Yo(t)!==null||t.startsWith("claude-")?t:`claude-${t}`,o=Yo(r);return o!==null?{kind:"model",id:o,latest:o2e(r,o),spelling:r}:{kind:"literal",value:t}}function r2e(e,t){let n=e.toLowerCase(),r=n.lastIndexOf(t.base);return r===-1?"":n.slice(r+t.base.length)}function o2e(e,t){return t.trailer===void 0&&r2e(e,t).startsWith("-latest")}function s2e(e,t){for(let n of t){if(ua(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 i2e(e){return e.charAt(0).toUpperCase()+e.slice(1)}function oY(e){let t;for(let n of XZ){let r=Yo(n);if(r!==null&&r.family===e&&!r.legacyVersionFirst&&(t===void 0||tY(r,t)>0))t=r}return t?.base}function sY(e,t){let n=rY(e);switch(n.kind){case"ignored":{if(e.trim()==="")return"An empty availableModels entry was ignored.";let r=oY("opus");return`"${nr(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)=>rY(s).kind!=="ignored").map((s)=>rx(s.trim().toLowerCase()));if(ua(e.trim().toLowerCase())&&s2e(n.family,r))return;let o=oY(n.family);return`"${nr(e)}" in availableModels allows every ${i2e(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 a2e(e,n.value)}}function a2e(e,t){let n=`"${nr(e)}" in availableModels allows only a model named exactly "${nr(t)}".`,r=t.replace(/(\d)\.(\d)/g,"$1-$2");if(r!==t){let s=r.startsWith("claude-")?r:`claude-${r}`;if(Yo(s)!==null)return`${n} To allow a version, write it with a hyphen: "${nr(s)}".`}let o=new RegExp(`^(${mi.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 l2e(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function iY(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&l2e(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}var c2e=["allowManagedMcpServersOnly","allowedMcpServers","deniedMcpServers","disabledMcpjsonServers","enabledMcpjsonServers","enableAllProjectMcpServers","disableClaudeAiConnectors","managedMcpServers"];function W_({slot:e,adminTiers:t}){return e?.allowManagedMcpServersOnly===!0||t.some((n)=>n.allowManagedMcpServersOnly===!0)}function ox({slot:e,adminTiers:t}){return e?.allowedMcpServers??t.find((n)=>n.allowedMcpServers!==void 0)?.allowedMcpServers}function aY(e,t){return c2e.filter((n)=>e[n]!==void 0&&!u2e(n,e,t))}function u2e(e,t,n){let r=n.slot??{};switch(e){case"deniedMcpServers":return!0;case"allowManagedMcpServersOnly":return t.allowManagedMcpServersOnly===W_(n);case"disableClaudeAiConnectors":return t.disableClaudeAiConnectors===(r.disableClaudeAiConnectors===!0||n.adminTiers.some((o)=>o.disableClaudeAiConnectors===!0));case"allowedMcpServers":return Xt(t.allowedMcpServers,W_(n)?ox(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)&&Xt(o[s],i))}}}import{userInfo as d2e}from"os";var lY="com.anthropic.claudecode",V_="HKLM\\SOFTWARE\\Policies\\ClaudeCode",q_="HKCU\\SOFTWARE\\Policies\\ClaudeCode",hp="Settings",ix="/usr/bin/plutil",cY=["-convert","json","-o","-","--"],uY=["-lint","-s","--"],dY=5000,Z_=2097152,gi="/mnt/c/Windows/System32/reg.exe",An="/mnt/c/Program Files/ClaudeCode",sx=jt({isCoworkCloud:void 0},(e)=>{e.isCoworkCloud=void 0});function ax(){if(sx.isCoworkCloud===void 0){let e=process.env.CLAUDE_CODE_ENTRYPOINT;sx.isCoworkCloud=Kh.some((t)=>t===e)}return sx.isCoworkCloud}function _p(){if(process.platform!=="linux")return!1;let e=ax();if(process.env.WSL_DISTRO_NAME&&!e)return!0;try{let t=bJ("fs").readFileSync("/proc/version","utf8").toLowerCase();return sl(t)}catch{return!1}}function pY(){let e="";try{e=d2e().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${lY}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${lY}.plist`,label:"device-level managed preferences"}),t}var fY=512;function lx(e){return e.map(p2e)}function p2e(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,loadedWithoutGuardHook:i,errorClass:a,errno:l,preserveOnWrite:c,mcpErrorMetadata:d,userWritable:p,wslIgnored:f,substituted:m,onlySubstitutes:g,removal:_,path:S,message:y,expected:b,suggestion:E,invalidValue:C,...A}=e,w=A;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,loadedWithoutGuardHook:i,errorClass:a,errno:l,preserveOnWrite:c,mcpErrorMetadata:d,userWritable:p,wslIgnored:f,substituted:m,onlySubstitutes:g,removal:_,path:yp(S),message:yp(y),expected:b===void 0?void 0:yp(b),suggestion:E===void 0?void 0:yp(E),invalidValue:typeof C==="string"?yp(C):void 0}}function yp(e){let t=xZ(e.replace(/\s+/gu," "));return t.length>fY?`${t.slice(0,fY-1)}…`:t}var Jo="https://code.claude.com/docs/en",f2e=[{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:`${Jo}/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:`${Jo}/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:`${Jo}/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:`${Jo}/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:`${Jo}/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:`${Jo}/iam#working-directories`}}],m2e={permissions:`${Jo}/iam#configuring-permissions`,env:`${Jo}/settings#environment-variables`,hooks:`${Jo}/hooks`};function mY(e){let t=f2e.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=m2e[sE(e.path,".")];return n}var sNt=k(()=>Bw(yc(),{strictPolicyHelperKeys:!0}).strict());function gY(e){return e.code==="invalid_type"}function hY(e){return e.code==="invalid_value"}function g2e(e){return e.code==="unrecognized_keys"}function _Y(e){return e.code==="too_small"}var h2e='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 EY(e){return e.map((t)=>t.severity!=="warning"&&t.message.includes(Zo)?{...t,message:t.message.replace(Zo,()=>h2e),loadedWithoutGuardHook:!0}:t)}function Rn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function yY(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Sp(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(hY(r))a=r.values.map((f)=>String(f)),l=a.join(" | "),c=void 0,d=void 0;else if(gY(r)){l=r.expected;let f=yY(r.message);c=f??Rn(r.input),d=f??Rn(r.input)}else if(_Y(r))l=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,d=c;let p=mY({path:o,code:r.code,expected:l,received:c,enumValues:a,message:r.message,value:c});if(hY(r))i=a?.map((f)=>`"${f}"`).join(", "),s=`Invalid value. Expected one of: ${i}`;else if(gY(r)){let f=yY(r.message)??Rn(r.input);if(r.expected==="object"&&f==="null"&&o==="")s="Invalid or malformed JSON";else s=`Expected ${r.expected}, but received ${f}`}else if(g2e(r)){let f=r.keys.join(", ");s=`Unrecognized ${Qc(r.keys.length,"field")}: ${f}`}else if(_Y(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 _2e(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=Pw(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 Vw("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 y2e=new Set(Bo);function S2e(e,t){if(!e||typeof e!=="object")return[];return[...x2(e,v2)?[{file:t,path:"hooks",message:`PreToolUse/PermissionRequest hooks are declared outside "hooks" (at the top level or under another key) — ${Zo}.`,severity:"fatal",docLink:"https://code.claude.com/docs/en/hooks"}]:[],...E2e(e,t)]}function E2e(e,t){if(!("hooks"in e))return[];if(e.hooks===null||typeof e.hooks!=="object"||Array.isArray(e.hooks)){let o=Rn(e.hooks);if(Array.isArray(e.hooks)&&(e.hooks.some(ie)||iw(e.hooks)))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o} — ${Zo}.`,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(b_(n))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received a single matcher — ${Zo}.`,docLink:"https://code.claude.com/docs/en/hooks"}];let r=[];for(let o of Object.keys(n)){let s=Gf(o);if(!y2e.has(o)){if(oa(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 — ${Zo}.`,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: ${Bo.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=Rn(i);if(ip.has(o)&&i!==null||oa(i,3,{matchersCount:!1})){r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a} — ${Zo}.`,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}=P2(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} — ${Zo}.${l.aboutType?` Valid types: ${[...E_()].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: ${[...E_()].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 b2e=[{key:"allowedMcpServers",schema:N_},{key:"deniedMcpServers",schema:U_}];function C2e(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of b2e){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 ${Rn(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 A2e=["strictKnownMarketplaces","blockedMarketplaces"];function R2e(e){if(!ie(e))return;for(let t of z_())if(e[t]===null)delete e[t]}function T2e(e,t,n){if(!ie(e))return[];let r=[];for(let o of A2e){let s=e[o];if(!Array.isArray(s))continue;let i=[],a=[];for(let l=0;l<s.length;l++){let c=lp().safeParse(s[l]);if(!c.success){i.push(s[l]),a.push(l);continue}let d=Ww(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 O2e(e,t){if(!ie(e)||e.managedMcpServers===void 0)return[];let r=[],o=__(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 w2e(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 x2e(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(Ow)}function v2e(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=Rn(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=Uw().safeParse(s[a]),c,d=!1;if(!l.success){let p=w2e(s[a]);if(p!==void 0&&!uq.has(p)||x2e(s[a]))continue;c=T_(l.error.issues)}else if(l.data.source.source==="settings"&&l.data.source.name!==a)c=`key "${po(a)}" must match the settings source name "${po(l.data.source.name)}"`;if(c!==void 0)i.push({file:t,path:`${r}.${po(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 k2e(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!ie(o)||!Array.isArray(o.options)){let l=ie(o)?`options: ${Rn(o.options)}`:Rn(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=Rn(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=zw().safeParse(i[l]);if(c.success){a.push(i[l]);continue}s.push({file:t,path:`${r}.options.${l}`,message:`${I2e(c.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:Rn(i[l])})}if(a.length!==i.length)o.options=a;return s}function P2e(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 ${Rn(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!$w().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 ${Rn(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let l of Object.keys(a)){let c=Fw().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.${po(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 I2e(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function D2e(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||L2e(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[U2e(o,t,n?.policySource===!0)]}function L2e(e){return typeof e==="string"&&fp.includes(e)}var M2e="crossSessionInbound";function N2e(e){let t=fp.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${po(e).replace(/^<key>$/,"<value>")}"`:Rn(e);return`must be one of ${t}; received ${n}`}function U2e(e,t,n=!1){let r=fp.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:M2e,message:`"crossSessionInbound" ${N2e(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}var SY="remoteControl.shareHostProfile";function F2e(e,t,n){if(!ie(e)||e.remoteControl===void 0)return[];let r=n?.policySource===!0,o=M_.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:SY,message:`${f}. ${s}`,severity:"warning",expected:o,...r?{statusOnly:!0}:{preserveOnWrite:!0}}),a=(f)=>typeof f==="string"?`"${po(f).replace(/^<key>$/,"<value>")}"`:Rn(f),l=e.remoteControl;if(!ie(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)=>`"${po(f)}"`).join(", ")} (its only key is "shareHostProfile")`))}let p=l.shareHostProfile;if(p!==void 0&&!(typeof p==="string"&&M_.includes(p))){if(r)l.shareHostProfile="off";else delete l.shareHostProfile;c.push(i(`"${SY}" must be one of ${o}; received ${a(p)}`))}return c}var $2e=["enabledMcpjsonServers","disabledMcpjsonServers"],z2e=/^[A-Za-z0-9_-]+$/;function H2e(e){if(!ie(e))return;for(let t of $2e){let n=e[t];if(typeof n==="string"&&z2e.test(n))e[t]=[n]}}function Ep(e,t,n){let r=[...mZ(e,t)];if(R2e(e),!n?.policySource)H2e(e);return r.push(..._2e(e,t,{policySource:n?.policySource,strictParseFollows:n?.mcpServerEntrySalvageOnly}),...S2e(e,t),...v2e(e,t),...k2e(e,t),...P2e(e,t),...D2e(e,t,{policySource:n?.policySource}),...F2e(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:C2e(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly}),...n?.mcpServerEntrySalvageOnly?O2e(e,t):[],...n?.mcpServerEntrySalvageOnly?T2e(e,t,n.marketplacePatternIndexMapOut):[]),r}function gx(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),ZZ.filter((n)=>t.has(n))}function G2e(){return zt(si(),"managed-settings.json")}function bY(e){return e.map((t)=>{let{invalidValue:n}=t,r=n!==void 0&&n!==null,o=r?aE(n):void 0,s=o===void 0?void 0:dn(o);return{...t,path:dn(t.path),message:dn(t.message),...t.expected!==void 0&&{expected:dn(t.expected)},...t.suggestion!==void 0&&{suggestion:dn(t.suggestion)},...r&&(o===void 0||typeof n==="string"||s!==o)&&{invalidValue:s}}})}function hx(e){if(e.diskless)return{settings:null,errors:[],documentHasPolicyContent:!1,loadState:"absent"};let t,n=(y)=>{if(y===HY)return!0;return t??=e.asksOrganization?.()===!0,t&&y()},r=!1,o={},s=AY(e,(y,b,E)=>{if(y.settings===null)return n(E)?{...y,errors:bY(y.errors)}:y;if(!n(E))return Object.assign(o,ii(y.settings,pi)),y;return r=!0,{...y,settings:{},errors:bY(y.errors)}});if(!r)return s;let i=[],a=[],l=AY(e,(y,b,E)=>{if(y.settings===null||!n(E))return{...y,settings:y.settings&&{},errors:[]};let C=W2e(y,y.settings,b);return i.push([b,Object.keys(C.settings??{})]),a.push(...C.errors.slice(y.errors.length)),C}),c=[...s.errors,...a],d=s.settings??{},p=l.settings??{},f=!Cc({...s,settings:d})&&{heldOnly:!0};if(Object.keys(p).length===0)return{...s,errors:c,...f};let m=Object.keys(d).length===0,g={...m?p:cc(t4([d,p],"merge",!1,0).admin,"parentSettingsBehavior"),...ii(d,"parentSettingsBehavior"),...o},_=g,S=d;for(let[y,b]of i)for(let E of b)if(E in S&&Xt(_[E],S[E]))c.push({file:y,path:dn(E),message:`In a cloud session that takes its managed settings from your organization, a managed settings file may only restrict: "${dn(E)}" was ignored in ${dn(y)}, since another managed settings document sets it and this one adds nothing to it.`,severity:"warning",statusOnly:!0,userWritable:!0});return{...m?l:s,settings:g,errors:c,...f,heldOffPlugins:Object.keys(p.enabledPlugins??{}).filter((y)=>d.enabledPlugins?.[y]===void 0),...p.strictKnownMarketplaces!==void 0&&d.strictKnownMarketplaces===void 0&&{heldAllowLists:["strictKnownMarketplaces"]}}}function W2e(e,t,n){let r=zZ(t),o=V2e(t,r).map((s)=>({...s,key:dn(s.key)}));if(o.length===0)return e;if(!CY.has(n))CY.add(n),G(`${dn(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})=>!_i(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 ${dn(n)}.`,severity:"warning",statusOnly:!0,userWritable:!0}))]}}function V2e(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(Xt(o,s))return[];if(!ie(o)||!ie(s))return[{key:r,became:n(s,r)}];return Object.keys(o).filter((i)=>!Xt(o[i],s[i])).map((i)=>({key:`${r}.${i}`,became:n(s[i],r)}))})}function zY(e){return Rt()==="wsl"&&(!e||Jw())}var CY=jt(new Set,(e)=>e.clear());function AY(e,t){let n=e.mdm?.()?.heldDocuments??[];if(zY(e.asksOrganization?.()===!0)){let r=fa(Sx({...e,file:()=>({settings:null,errors:[]})}));if(e.wslInherits?.()){let o=n.length===0?void 0:r||fa(bp(An,e.store)),s=bp(An,e.store,t,o?n:[]);if(o??(fa(s)||r))return s;let i=bp(si(),e.store,t,n);return{...i,errors:[...s.errors,...i.errors],loadState:go(s.loadState,i.loadState)}}if(r)return bp(null,e.store,t,n)}return bp(si(),e.store,t,n)}var HY=()=>!0;function cx(e,t,n){n.push(...t.errors);let{settings:r}=t;if(!r||Object.keys(r).length===0)return;for(let[o,s]of H_){let i=o.split(".");if(bt(r,i)===void 0)continue;let a=t.errors.find((d)=>d.substituted&&d.path===o),l=a!==void 0,c=bt(e.merged,i);if(l&&c!==void 0&&!e.floors.has(o)){let d=i.at(-1);if(s.inert.has(s.read(c))){GW(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=En(e.merged,r,Lr),e.found=!0,Op(r)&&!t.errors.some((o)=>o.onlySubstitutes))e.authored=!0}function _x(e){return e.endsWith(".json")&&!e.startsWith(".")}function q2e(e){return(e.isFile()||e.isSymbolicLink())&&_x(e.name)}function RY(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:Rt()!=="windows"&&!n.startsWith(An)};return o.note(n,Rk({...s,linked:e.managedDocumentLinks.isLinked(n)})),()=>yx(e,n,s.file,s.folder)}function yx(e,t,n,r){let o=process.geteuid?.(),s=process.getuid?.();if(zY(!0)&&(t===gi||t.startsWith(`${An}${K2e}`)))return TY;if(o===0||s===0)return!0;if(Rt()==="windows"||o===void 0)return TY;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(yO(l,n,a===null?r:n)!==!1||a?.kind==="unverified")return!0;let d=e.policy.writableNow??=new Map,p=d.get(t)??_O(t);if(d.set(t,p),p!=="no")return!0;let f=e.policy.walkedDocuments??=new Map,m=f.get(t)??MG(t,l,e.policy.certainDirectories??=new Map);return f.set(t,m),m}var TY=!1;function OY(e,t,n,r){let o=e.managedDocumentLinks;o.noteWalked(zt(t,...n),()=>vG(t,n,r,o.folderIsLink,e.managedFileProtections.folderOwners))}function bp(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)cx(s,n(f,p,HY),o),i||=Ac(f),a=go(a,hi(f));if(e===null)return wY(s,o,i,a,t);let l=Rc(zt(e,"managed-settings.json"),t,void 0,!0),c=()=>!1;if(hi(l)!=="absent")OY(t,e,["managed-settings.json"]),c=RY(t,Tt(e),zt(e,"managed-settings.json"),l.fileOwner);cx(s,n(l,zt(e,"managed-settings.json"),c),o),i||=Ac(l),a=go(a,hi(l));let d=zt(e,"managed-settings.d");try{let p=t.folderListingForPolicyWalk(d),f,m;if(p!==void 0)f=p;else{let g=we().readdirSync(d).filter(q2e);f=g.map((_)=>_.name).sort(),m=new Set(g.filter((_)=>!_.isFile()).map((_)=>_.name)),t.noteWalkListing(d,f)}for(let g of f){let _=Rc(zt(d,g),t,void 0,!0),S=()=>!1;if(hi(_)!=="absent")OY(t,e,["managed-settings.d",g],m?.has(g)),S=RY(t,d,zt(d,g),_.fileOwner);cx(s,n(_,zt(d,g),S),o),i||=Ac(_),a=go(a,hi(_))}}catch(p){let f=fe(p);if(f!=="ENOENT"&&f!=="ENOTDIR")G(`managed-settings.d read failed: ${p}`,{level:"error"}),o.push(Tp(d,p,"directory")),a="didNotLoad"}return wY(s,o,i,a,t)}function wY(e,t,n,r,o){let s=e.found&&wc(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&&Op(s)&&{onlySubstitutes:!0}}}function Z2e(e,t){if(tt(e))rqe(t);else G(dn(`settings file read failed at ${t}: ${e}`),{level:"error"})}function Rc(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{...s,settings:s.settings?jr(s.settings):null};let i=eqe(e,n,r);return t.parsedFiles.set(o,i),{...i,settings:i.settings?jr(i.settings):null}}function Sx(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:iqe(t,()=>Ex(e),()=>e.file?.()??hx(e)),documentHasPolicyContent:Ac(t),loadState:hi(t),...t.onlySubstitutes&&{onlySubstitutes:t.onlySubstitutes}}}function Ap(e,t){let n=vY.get(e),r=n?.get(t);if(r)return xY(r);let o=Y2e(e,t);if(n)n.set(t,o);else vY.set(e,new Map([[t,o]]));return xY(o)}function xY(e){return{settings:e.settings&&jr(e.settings),errors:e.errors.map((t)=>({...t})),documentHasPolicyContent:e.documentHasPolicyContent,loadState:e.loadState,removed:e.removed,...e.onlySubstitutes&&{onlySubstitutes:e.onlySubstitutes}}}var vY=new WeakMap;function Y2e(e,t){let n=jr(e),r=Ep(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=Yw(GY(t,o),t,n).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...Sp(s.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad",removed:[]};let i=[...n4(r,s.data,o),...o],a=e,l=Object.keys(s.data).length>0?s.data:null;return{settings:l,errors:i,documentHasPolicyContent:r4(e,s.data),loadState:"loaded",removed:Object.keys(a).filter((c)=>jY(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 jY(e,t){let n=z_();return n.includes(e)||Ec.some(({alias:r,canonical:o})=>r===e&&n.includes(o))?Zw(e,t):j_(e)&&BY(e,t)}function BY(e,t){return t===null||ie(t)&&Object.keys(t).length>0&&Object.entries(t).every(([n,r])=>{let o=`${e}.${n}`;return Zw(o,r)||j_(o)&&BY(o,r)})}function _i(e){return SO()&&(e==="managedMcpServers"||e.startsWith("managedMcpServers."))}var ty=["managedMcpServers","isolation"],J2e=[...ty,"deniedModels","availableModelsMatch"];function KY(e,t){if(!ie(e))return[];let n=[];for(let r of J2e){if(!(r in e))continue;if(delete e[r],!_i(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 GY(e,t){return(n)=>{if(_i(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(dn(`${e}: ${n.path}: ${n.message}`),{level:n.startupFatal?"error":"warn"})}}function Ex(e){let t=e?.remote?e.remote():WZ((c)=>Ap(c,"remote managed settings").settings),n=!e?.remote&&!_i("managedMcpServers")&&BZ()?[{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:NZ(),o=(r?.state==="stale_cache"||r?.state==="failed")&&r.failure.errorKind==="ruled_empty"?lx(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}=Ap(t,"remote managed settings");return{settings:s,errors:[...n,...o,...lx(i)],servedSnapshot:UZ(t),documentHasPolicyContent:a,...l&&{onlySubstitutes:l}}}var kY="parent managed settings";function X2e(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let n=Ap(t,kY);for(let r of ty)if(n.settings?.[r]!==void 0&&!_i(r))n.errors.push({file:kY,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 WY(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=SO(),r=e.store.inlineFlagParse;if(r?.inline!==t||r.desktopSupplied!==n)r={inline:t,desktopSupplied:n,parsed:Q2e(t)},e.store.inlineFlagParse=r;let{settings:o,errors:s}=r.parsed;return{settings:o&&jr(o),errors:s.map((i)=>({...i}))}}function Q2e(e){let t=jr(e),n=[...KY(t,"SDK inline settings"),...Ep(t,"SDK inline settings")],r=$_(t).safeParse(t);if(!r.success)return{settings:null,errors:[...n,...Sp(r.error,"SDK inline settings")]};if(n.some((o)=>o.severity==="fatal"))return{settings:null,errors:n};return{settings:r.data,errors:n}}var Rp=2097152;function eqe(e,t,n){try{let r;if(t!==void 0)r=t;else{let o=n||tqe(e)?qa(we(),e):bI(we(),e);if(n){let s={};r=ri(o.resolvedPath,Rp,(a)=>{s.owner={uid:a.uid,gid:a.gid,mode:a.mode}});let i=X_(r,e,n);return s.owner?{...i,fileOwner:s.owner}:i}r=ri(o.resolvedPath,Rp)}return X_(r,e,n)}catch(r){return sqe(r,e)}}function X_(e,t,n){if(e.trim()==="")return{settings:{},errors:[],loadState:"loaded"};let r=Xi(e,!1);if(n){if(!ie(r))return{settings:null,errors:[ny(t)],loadState:"didNotLoad"};let a=jr(r),l=Ep(a,t,{skipMcpServerEntryFilter:!0,policySource:!0}),c=[],d=Yw(GY(t,c),t,a).safeParse(a);if(!d.success)return{settings:null,errors:[...l,...Sp(d.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad"};return{settings:d.data,errors:[...n4(l,d.data,c),...c],documentHasPolicyContent:r4(r,d.data),loadState:"loaded"}}let o=jr(r),s=[...KY(o,t),...Ep(o,t)],i=$_(o).safeParse(o);if(!i.success){let a=Sp(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 ny(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 tqe(e){let t=Ga();if(t===null)return!1;let n=Ke(ey(Tt(e))),r=Tt(t);return n===Ke(r)||n===nqe(r)}var ux;function nqe(e){if(ux?.lexical!==e){let t=ey(e);ux={lexical:e,physical:Ke(zt(Af(t)??t,B2e(e)))}}return ux.physical}function rqe(e){G(dn(`Broken symlink or missing file encountered for settings.json at path: ${e}`))}function oqe(){return{settings:null,errors:[],loadState:"absent"}}function sqe(e,t){if(HP(e))throw e;if(Z2e(e,t),tt(e))return oqe();return{settings:null,errors:[Tp(t,e)],loadState:"didNotLoad"}}function Tp(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",...fe(t)!==void 0&&{errno:fe(t)}}}function VY(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 ${An}), 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 PY(e){return e.path==="wslInheritsWindowsSettings"&&e.severity==="fatal"}function iqe(e,t,n){let r=e.withheldFlagRecord&&n().heldOnly===!0?[...e.errors,e.withheldFlagRecord]:e.errors;if(!r.some(PY))return r;if(!Cc(t()))return r;return r.map((o)=>PY(o)?{...o,severity:"warning"}:o)}function IY(e,t){switch(e){case"userSettings":return Tt(vt());case"policySettings":return Tt(Y_(t));case"projectSettings":return Tt(t.projectConfigDir??Y_(t));case"localSettings":{if(t.projectConfigDir!==void 0)return Tt(t.projectConfigDir);return qY(Y_(t),t.canonicalGitRoot)}case"flagSettings":return t.flagPath?ey(Tt(t.flagPath)):Tt(Y_(t))}}function Y_(e){if(e.cwd===null)throw new Vc;return e.cwd}function qY(e,t){let n=aqe(e,t);if(n.decided!==void 0)return n.decided;if(!dqe(n.root))return n.cwdResolved;return n.root}function aqe(e,t){let n=t?.(e);if(!n)return{decided:Tt(e)};let r=Tt(n),o=Tt(e);if(r===o)return{decided:r};let s;try{s=pqe()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function lqe(e){return Vo().localStoreProbes.canonicalRootOwnerUids(e,cqe)}function cqe(e){let t=we(),n=null;try{n=t.lstatSync(zt(e,".claude")).uid}catch(r){if(!tt(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:uqe(e),claudeEntryUid:n}}function uqe(e){let t=we();try{return t.lstatSync(zt(e,".git")).uid}catch(n){throw n}}function dqe(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}=lqe(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 pqe(){return Vo().localStoreProbes.normalizedRealHomeDir(fqe)}function fqe(){let e=Af(j2e());if(e===null)throw Error("home directory realpath unavailable");return Ke(e)}var DY={default:"settings.json",cowork:"cowork_settings.json"};function mqe(e){if(e.coworkPlugins||Pn.CLAUDE_CODE_USE_COWORK_PLUGINS)return DY.cowork;return DY.default}function Tc(e,t){switch(e){case"userSettings":return zt(IY(e,t),mqe(t));case"projectSettings":case"localSettings":{if(t.cwd===null&&t.projectConfigDir===void 0)return;return zt(IY(e,t),ZY(e))}case"policySettings":return G2e();case"flagSettings":return t.flagPath}}function ZY(e){switch(e){case"projectSettings":return zt(".claude","settings.json");case"localSettings":return zt(".claude","settings.local.json")}}function YY(e){if(e.cwd===null||qY(e.cwd,e.canonicalGitRoot)===Tt(e.cwd))return;if(e.projectConfigDir!==void 0)return;return zt(Tt(e.cwd),ZY("localSettings"))}function JY(e,t){let n=t.store.repoTierFreeze.tier(e);if(n!==void 0)return n.settings;let r=t.store.perSource.get(e);if(r!==void 0)return r;let o=Gqe(e,t),s=o&&Cp(e,o,t);return t.store.perSource.set(e,s),s}function XY(e){return(e.parentSettingsBehavior??(Gh()?"merge":"first-wins"))==="merge"}function gqe(e,t=!1){return!e||XY(e)||t}var hqe=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function _qe(e){let t={};for(let{path:n,restrictive:r}of uo()){let o=bt(e,n);if(n[0]==="sandbox"&&Qi(r).includes(o))an(t,n,o)}return t.sandbox??{}}function yqe(e,t){let n={};if(e.allowManagedHooksOnly===!0)n.allowManagedHooksOnly=!0;if(e.disableCommandPluginSources===!0)n.disableCommandPluginSources=!0;if(e.disableSideloadFlags===!0)n.disableSideloadFlags=!0;if(e.allowManagedMcpServersOnly===!0)n.allowManagedMcpServersOnly=!0;if(e.disableClaudeAiConnectors===!0)n.disableClaudeAiConnectors=!0;if(e.syncClaudeAiSkills===!1)n.syncClaudeAiSkills=!1;if(e.syncClaudeAiPlugins===!1)n.syncClaudeAiPlugins=!1;if(e.remoteTools?.allowUnattendedServing===!1)n.remoteTools={...n.remoteTools,allowUnattendedServing:!1};if(e.allowManagedPermissionRulesOnly===!0)n.allowManagedPermissionRulesOnly=!0;if(e.disableAutoMode==="disable")n.disableAutoMode="disable";let r=e.remoteControl?.shareHostProfile;if(r==="off"||r==="basic")n.remoteControl={...n.remoteControl,shareHostProfile:r};if(iY(e.attribution,e.includeCoAuthoredBy)==="disabled")n.attribution={...n.attribution,commitTrailers:!1};if(e.attribution?.sessionUrl===!1)n.attribution={...n.attribution,sessionUrl:!1};let o=e.strictPluginOnlyCustomization;if(o===!0||Array.isArray(o)&&o.length>0)n.strictPluginOnlyCustomization=o;if(e.deniedMcpServers)n.deniedMcpServers=e.deniedMcpServers;if(e.blockedMarketplaces?.length)n.blockedMarketplaces=e.blockedMarketplaces;if(e.deniedModels&&e.deniedModels.length>0)n.deniedModels=e.deniedModels;if(t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID)n.forceLoginOrgUUID=e.forceLoginOrgUUID;for(let s of fx)if(t[s]===void 0&&e[s])Object.assign(n,{[s]:e[s]});if(e.enforceAvailableModels===!0)n.enforceAvailableModels=!0;if(e.availableModelsMatch==="exact")n.availableModelsMatch="exact";if(e.permissions){let s=ii(e.permissions,["deny","ask"]);for(let i of["deny","ask"]){let a=s[i];if(a!==void 0)s[i]=a.filter((l)=>{if(!Yd.test(l))return!0;return G(`Ignoring ${i} rule "${l}" 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")s.disableBypassPermissionsMode="disable";if(e.permissions.disableAutoMode==="disable")s.disableAutoMode="disable";if(e.permissions.blockReadsOutsideWorkingDirectories===!0)s.blockReadsOutsideWorkingDirectories=!0;if(t.allowManagedPermissionRulesOnly!==!0){let{allow:i,additionalDirectories:a}=e.permissions;if(i&&t.sandbox?.network?.allowManagedDomainsOnly!==!0)s.allow=i;if(a)s.additionalDirectories=a}if(Object.keys(s).length>0)n.permissions=s}if(e.sandbox){let{network:s,filesystem:i,credentials:a}=e.sandbox,l={},c=s?ii(s,["deniedDomains"]):{},d=i?ii(i,["denyRead","denyWrite"]):{};if(s){if(t.sandbox?.network?.allowManagedDomainsOnly!==!0&&s.allowedDomains)c.allowedDomains=s.allowedDomains}if(Object.keys(c).length>0)l.network=c;if(i){if(t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&i.allowRead)d.allowRead=i.allowRead}if(Object.keys(d).length>0)l.filesystem=d;if(a){let p=(a.files??[]).map((g)=>g.mode==="deny"?{path:g.path,mode:"deny"}:{path:g.path,mode:"mask",injectHosts:[]}),f=(a.envVars??[]).filter((g)=>g.mode==="deny").map((g)=>({name:g.name,mode:"deny"})),m={...p.length>0&&{files:p},...f.length>0&&{envVars:f}};if(a.sigv4){let g={};for(let _ of["streaming","presigned","sigv4a"])if(a.sigv4[_]==="deny")g[_]="deny";m.sigv4=g}{let g=QY(a.awsPairs??[],[]);if(g.length>0)m.awsPairs=g}if(Object.keys(m).length>0)l.credentials=m}if(En(l,_qe(e)),Object.keys(l).length>0)n.sandbox=l}return n}function QY(e,t){let n=li,r=new Set(t.flatMap(LY));return Qt(e.flatMap(LY)).filter((o)=>n.includes(o)&&!r.has(o)).map((o,s)=>({accessKeyIdVar:o,secretAccessKeyVar:`${p_}${s+1}_`}))}function LY(e){if(!ie(e))return[];return[e.accessKeyIdVar,e.secretAccessKeyVar,e.sessionTokenVar].filter((t)=>typeof t==="string")}var Sqe=new Set([...[...UO].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...FO,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE"]);function Eqe(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 bqe(e){let t=[];for(let n of e?.deniedModels??[]){let{warning:r}=nY(n);if(r!==void 0)t.push({file:"managed settings",path:"deniedModels",message:r,severity:"warning",statusOnly:!0})}return t}function Cqe(e){if(e?.availableModelsMatch!=="exact")return[];let t=e.availableModels??[];return t.flatMap((n)=>{let r=sY(n,t);return r===void 0?[]:[{file:"managed settings",path:"availableModels",message:r,severity:"warning",statusOnly:!0}]})}function MY(e,t){let n=e.deniedModels;if(Object.assign(e,t),n!==void 0&&t.deniedModels!==void 0)e.deniedModels=Qt([...n,...t.deniedModels])}function J_(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(!Sqe.has(n.toUpperCase()))t[n]=r;e.env=t}}function Aqe(e){let t=e.store.policy.allTiers;if(t!==void 0)return t;let n=Dqe(e);return e.store.policy.allTiers=n,n}function pa(){return Rt()==="macos"?"plist":"hklm"}function e4(e){let t=wp(e);if(t.composes==="tier")return"helper";let n=Oc(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return pa();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 Oc(e){let t=[],n=Ex(e),{settings:r,servedSnapshot:o}=n;t.push(...n.errors);let s=wp(e),i=s.composes==="remoteSlot"?s.helper:dx(r),a=Sx(e),l=a.settings;t.push(...a.errors);let c=dx(l),d=e.file?.()??hx(e),p=d.settings;t.push(...d.errors);let f=dx(p),m=s.composes==="remoteSlot"?i!==null:Cc(n),g=Cc(a),_=Cc(d),S=px(i,m),y=px(c,g),b=px(f,_),E=i!==null&&S>=Math.max(y,b),C=c!==null&&y>=b,A=[[r,E],[l,C],[p,f!==null]],L=(s.composes==="remoteSlot"?s.helper:A.find(([qe,_r])=>qe!==null&&(qe===r&&o?_r:qe.managedSourcesBehavior!==void 0||_r))?.[0])?.managedSourcesBehavior,U=i!==null&&!E,F=U?null:i,ue=c!==null&&!C&&F===null,O=ue?null:c,T=[],v=[[U,"remote",i],[ue,pa(),c]];for(let[qe,_r,Bn]of v){if(!qe||Bn===null)continue;if(T.push([Bn,_r]),!Op(Bn))continue;let Si=_r==="remote"&&g?pa():"file";t.push({file:da[_r],path:Object.keys(Bn).find((ha)=>!pi.includes(ha))??"",message:`${da[_r]} holds only values that could not be applied as written, so ${da[Si]} 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:D,errors:K}=X2e(e);t.push(...K);let X=(g?O:null)??(_?f:null),pe=D!==null&&(X===null||XY(X)),H=[wqe(F,o&&s.composes!=="remoteSlot",[O,f,...pe?[ii(D,fx)]:[]]),O,f,...T.map(([qe])=>qe)].filter((qe)=>qe!==null),W=[...F!==null?["remote"]:[],...O!==null?[pa()]:[],...f!==null?["file"]:[],...T.map(([,qe])=>qe)],Ot=F!==null&&o&&s.composes!=="remoteSlot",{admin:ln,merged:mt}=t4(H,L,Ot,T.length),Dt=ln===null?[n,a,d].find(Ac):void 0,wt=ln??(Dt?{}:null),Zt={remote:F!==null||Dt===n,mdm:O!==null||Dt===a,file:f!==null||Dt===d},Je=!(F!==null&&m&&!Ot)&&!(O!==null&&g)&&!_,he=[];if(mt){let qe=Zt.remote?"remote":Zt.mdm?pa():"file",_r=[[O,pa()],[f,"file"]];for(let[Bn,Si]of _r){if(Bn===null||Bn===H[0]||Ot&&Bn===H[1])continue;let ha=bx.filter((_a)=>Object.values(Bn[_a]??{}).some((zp)=>zp!==void 0&&zp!==null)),[$p]=ha;if($p===void 0)continue;he.push(Si),t.push({file:da[Si],path:$p,message:`${ha.map((_a)=>`"${_a}"`).join(" and ")} in ${da[Si]} ignored: policy helper configuration is read from the highest managed settings source only (${da[qe]} here), even with managedSourcesBehavior "merge". Configure the helper in that source instead.`,severity:"warning",statusOnly:!0})}}let Yt=(qe)=>qe!==null&&(qe===H[0]||Object.keys(cc(qe,d4())).length>0),cn={remote:Yt(F),mdm:Yt(O),file:Yt(f)},ts={allowManagedPermissionRulesOnly:H.some((qe)=>qe.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:wt?.forceLoginOrgUUID,...ii(wt??{},fx),allowedMcpServers:W_({slot:wt,adminTiers:H})||D?.allowManagedMcpServersOnly===!0&&wt?.allowManagedMcpServersOnly!==!1?ox({slot:wt,adminTiers:H}):wt?.allowedMcpServers,sandbox:{network:{allowManagedDomainsOnly:H.some((qe)=>qe.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:H.some((qe)=>qe.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},ga=gqe(ln,Je),ns=D&&ga?yqe(D,ts):null,wn=ns&&Object.keys(ns).length>0?ns:null,my=Eqe(D,e.hostManagedProvider);return{tiers:H,tierSources:W,admin:wt,parentSlice:wn,hostModelOverlay:my,errors:t,present:Zt,mode:L,merged:mt,composed:cn,snapshotFirst:Ot,parentNeverShutOut:Je,shadowedHelperSources:he,parentIncluded:ga,heldEmpty:Dt!==void 0}}function t4(e,t,n,r){let o=e[0];if(!o)return{admin:null,merged:!1};let{managedSourcesBehavior:s,...i}=o,a=t==="merge"&&e.length>=2;if(!a&&r===0)return{admin:s===void 0?o:i,merged:!1};let l=e.slice(a?1:e.length-r).map((d,p)=>{let f=a&&n&&p===0,m=f?{...d}:cc(d,d4());if(!f){for(let _ of hqe)if(bt(m,_)!==void 0)an(m,_,void 0)}let g=bt(m.sandbox,["enabledPlatforms"]);if(Array.isArray(g)&&g.includes(Rt()))an(m,["sandbox","enabledPlatforms"],void 0);else if(g!==void 0)delete m.sandbox;return m});if(!a)return NY(i,[o,...l]),{admin:i,merged:!1};let c={};for(let d of[...l].reverse())En(c,d,mx);return En(c,i,n?xqe:mx),NY(c,[o,...l]),Rqe(c,[o,...l],n),{admin:c,merged:!0}}var bx=["policyHelper","policyHelpers"],da={remote:"server-managed settings",plist:"the managed preferences plist",hklm:"the HKLM policy key",file:"managed-settings.json"};function wc(e){return Object.keys(e).some((t)=>!pi.includes(t))}function Op(e){return Object.entries(e).some(([t,n])=>!pi.includes(t)&&!mp(n))}function dx(e){return e&&wc(e)?e:null}function Cc(e){return e.settings!==null&&Op(e.settings)&&!e.onlySubstitutes}function n4(e,t,n){return Cc({settings:t})&&!n.some((r)=>r.onlySubstitutes)?EY(e):e}function px(e,t){if(e===null)return-1;if(t)return 2;return Op(e)?1:0}function r4(e,t){return Object.entries(e).some(([n,r])=>r!==null&&!jY(n,r)&&!pi.includes(n))||t!==null&&wc(t)}function Ac(e){return e.documentHasPolicyContent??(e.settings!==null&&wc(e.settings))}function hi(e){return e.loadState??(e.settings!==null?"loaded":"absent")}function go(e,t){if(e==="didNotLoad"||t==="didNotLoad")return"didNotLoad";return e==="loaded"||t==="loaded"?"loaded":"absent"}function fa(e){return e.userWritable!==!0&&(Ac(e)||e.loadState==="didNotLoad")}function Rqe(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 o4=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders"],Tqe=["awsPairs","ripgrep"];function s4(e,t,n){if(t===void 0)return e;if(Array.isArray(t))return n==="awsPairs"&&Array.isArray(e)?[...t,...QY(e,t)]:[...t];if(!ie(t))return t;return Eo(t,(r)=>Array.isArray(r)?[...r]:r)}var Oqe=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders","allowedMarketplaces","allowedHttpHookUrls","httpHookAllowedEnvVars"],fx=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedProviders"];function wqe(e,t,n){if(e===null||!t)return e;let r=Oqe.filter((o)=>n.some((s)=>s?.[o]!==void 0));return r.length===0?e:cc(e,r)}function mx(e,t,n){if(n!==void 0&&(o4.includes(n)||Tqe.includes(n)))return s4(e,t,n);return i4(e,t,n)}function xqe(e,t,n){if(n!==void 0&&o4.includes(n))return s4(e,t,n);return i4(e,t,n)}function i4(e,t,n){if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Qt([...t,...e]);return Lr(e,t,n)}function NY(e,t){let n=t[0],r=e;for(let o of uo()){let{path:s,restrictive:i}=o,a=Qi(i),l=Math.min(...t.map((c)=>a.indexOf(Wh(o,c))).filter((c)=>c!==-1));if(Number.isFinite(l))an(r,s,a[l]);else if(bt(n,s)===void 0&&bt(e,s)!==void 0)an(r,s,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Qt(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 wp(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:Ex(e).settings,mergedOver:"remote"}:a4(e);e.store.policy.mergedHelper={helper:Iqe(r,t),mergedOver:Object.keys(l4(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function a4(e){let t=Sx(e);if(Oc({...e,helper:void 0}).present.mdm)return{base:t.settings,mergedOver:pa(),errors:t.errors};let n=e.file?.()??hx(e);return{base:n.settings,mergedOver:"file",errors:[...t.errors,...n.errors]}}function l4(e){return cc(e??{},bx)}function vqe(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 kqe=["forceLoginOrgUUID","gatewayInternalNetworks","allowedHttpHookUrls","httpHookAllowedEnvVars","allowRead"];function Pqe(e,t,n){let r=n!==void 0&&t!==void 0&&kqe.includes(n)?t:mx(e,t,n);return r===t&&Array.isArray(r)?[...r]:r}function Iqe(e,t){let n=l4(e),r=En({},n,t,Pqe);if(n.env&&t.env)r.env=vqe(n.env,t.env);return r}function Dqe(e){let t=wp(e);if(t.composes==="tier")return[t.helper];let{tiers:n,parentSlice:r}=Oc(e);return r?[...n,r]:n}function Lqe(e,t,n){let r={slot:n,adminTiers:e};return e.flatMap((o,s)=>{let i=t[s],a=aY(o,r);return i!==void 0&&a.length>0?[{source:i,keys:a}]:[]})}var c4=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var Q_=[...c4,"otelHeadersHelper","proxyAuthHelper"],UY=["disableAllHooks","enabledPlugins","extraKnownMarketplaces","agent","allowedHttpHookUrls","httpHookAllowedEnvVars","autoMemoryDirectory","modelOverrides","allowedMcpServers","skipWebFetchPreflight","autoUploadSessions","xaaIdp","claudeMdExcludes","enableAllProjectMcpServers","enabledMcpjsonServers"];function Mqe(e,t,n){if(!UY.some((o)=>t[o]!==void 0)||(n.launchFolderKeysFrom?.(e)??"as_read")==="as_read")return t;let r={...t};for(let o of UY)delete r[o];return qZ("keys"),r}function Cp(e,t,n){return Nqe(e,Mqe(e,t,n),n)}function Nqe(e,t,n){let r=Q_.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"?Uqe(n):{};if(!r&&Object.keys(s).length===0)return t;let i={...t};for(let a of Q_)delete i[a];return Object.assign(i,s)}function Uqe(e){let t=u4(e),n={};for(let r of Q_){let o=t?.[r];if(o!==void 0)n[r]=o}return n}function u4(e){let t=Fqe(e),n=wp(t);return n.composes==="tier"?n.helper:Oc(t).admin}function Fqe(e){let t=e.helperArmedFromRemote?.()===!1&&e.helperArmedFromUserWritableBase?.()===!1;return{...e,store:new ds,remote:()=>null,helper:t?e.helper:()=>null,...e.mdm?.().userWritable===!0&&{mdm:()=>({settings:{},errors:[]})}}}function $qe(e){return e.helperArmedFromUserWritableBase?.()!==!1||e.helperMergesOutput?.()===!0&&e.mdm?.().userWritable===!0}function FY(e,t){if(t.store.policy.machineLoginPins===void 0){let o=u4(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 zqe=[...Q_,"forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","env","modelPicker",...bx,...pi];function d4(){return zqe}function Hqe(e){return zV.some((t)=>e.startsWith(t))||$V.includes(e)}function jqe(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=Hqe(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 Bqe="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function $Y(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==Bqe)t[n]=r;return t}function Kqe(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function p4(e){let t=wp(e),n=(e.helperWarnings?.()??[]).filter((S)=>!_i(S.path));if(t.composes==="tier"){let{helper:S}=t;e.store.lastPolicyEnvComposition=null;let y=$qe(e),b=e.hostManagedProvider||y?{...S}:S;if(e.hostManagedProvider)J_(b);if(y)FY(b,e);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&S.availableModels!==void 0?S.modelOverrides:void 0},e.store.policy.deniedModelsOverrides={value:e.hostManagedProvider?S.modelOverrides:void 0};let E=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?a4(e).errors.filter((C)=>!C.statusOnly):[],...Oc(e).errors.filter((C)=>C.statusOnly)];return{settings:b,errors:[...E,...n]}}let{tiers:r,tierSources:o,admin:s,parentSlice:i,hostModelOverlay:a,errors:l,present:c,snapshotFirst:d}=Oc(e);if(l.push(...n),!s&&!i){e.store.lastPolicyEnvComposition=null,e.store.policy.pairedModelOverrides={value:void 0},e.store.policy.deniedModelsOverrides={value:void 0};let S=e.hkcu?.();if(S&&Object.keys(S.settings).length>0){let y=e.hostManagedProvider?{...S.settings}:S.settings;if(e.hostManagedProvider){if(J_(y),a)MY(y,a)}return{settings:y,errors:[...l,...S.errors]}}if(a)return{settings:{...a},errors:[...l,...S?.errors??[]]};return{settings:null,errors:[...l,...S?.errors??[]]}}let p=En({},i??{},s??{},Lr);if(i?.availableModelsMatch==="exact")p.availableModelsMatch="exact";if(r.some((S)=>S.forceRemoteSettingsRefresh===!0))p.forceRemoteSettingsRefresh=!0;if(o.includes("remote")||e.mdm?.().userWritable===!0)FY(p,e);let f=Pn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,m=p.env;if(!f){let S=jqe(r.map((y)=>y.env),r.map((y)=>(y.otelHeadersHelper??"").trim()!==""),r.map((y)=>{let b=new Set;for(let E of c4){let C=y[E];if(typeof C==="string"&&C.trim()!=="")for(let A of HV[E])b.add(A)}return b.size>0?b:void 0}),d?1:0);if(Object.keys(S).length>0)p.env=S;else delete p.env}if(p.env){let S=$Y(p.env);if(S&&Object.keys(S).length>0)p.env=S;else delete p.env}if(e.hostManagedProvider){if(J_(p),a)MY(p,a)}let g={env:$Y(m)};if(e.hostManagedProvider)J_(g);let _=!f&&!Kqe(p.env,g.env);e.store.lastPolicyEnvComposition={unionOptedOut:f,unionChangedEnv:_,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:za(r,(S)=>Object.keys(S.env??{}).length>0)},e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&s?.availableModels!==void 0&&s.modelOverrides!==void 0&&a?.availableModels===void 0?s.modelOverrides:void 0},e.store.policy.deniedModelsOverrides={value:e.hostManagedProvider?s?.modelOverrides:void 0};for(let{source:S,keys:y}of Lqe(r,o,p)){let[b]=y;if(b===void 0)continue;let E=da[S],C=y.length===1;l.push({file:E,path:b,message:`${y.map((A)=>`"${A}"`).join(" and ")} in ${E} ${C?"is":"are"} not applied: ${E} is not the managed settings source that applies for ${C?"this key":"these keys"} (/status lists the setting sources). Remove ${C?"it":"them"} from ${E}, or set ${C?"it":"them"} in the source that applies.`,severity:"warning",statusOnly:!0})}return{settings:p,errors:l}}function Gqe(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return p4(t).settings;let r=Tc(e,t),{settings:o}=r?Rc(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=WY(t);if(s)return En(o||{},s,Lr)}if(e==="localSettings"&&n){let s=YY(t);if(s){let{settings:i}=Rc(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),En(i,o||{},Lr)}}return o}function Wqe(e,t){return{...e,...t}}function Lr(e,t,n){if(n==="modelPicker"&&t!==void 0)return f4(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Qt([...e,...t])}if((n==="extraKnownMarketplaces"||n==="managedMcpServers")&&ie(e)&&ie(t))return Wqe(e,t);return}function f4(e){if(!ie(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>ie(n)?{...n}:n)}}}function Vqe(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();Vd("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=En(r,n,Lr);let o=[],s=new Set,i=new Set,a=(S)=>{for(let y of S){let b=`${y.file}:${y.path}:${y.message}`;if(!s.has(b))s.add(b),o.push(y)}},l=[],c=[si()];if(Rt()==="wsl"&&e.wslInherits?.())c.push(An);let d=new Set(c.map((S)=>Tt(zt(S,"managed-settings.json")))),p=new Set(c.map((S)=>Tt(zt(S,"managed-settings.d")))),f=(S)=>{let y=Tt(S);return d.has(y)||p.has(ey(y))},m=(S,y,b)=>{if(b?.channelLabel!==!0&&f(S))return;let E=y.sandbox?.filesystem?.allowRead?.length??0,C=y.sandbox?.network?.allowedDomains?.length??0;if(E>0||C>0)l.push({file:S,allowReadCount:E,allowedDomainsCount:C})},g=null;for(let S of gx(e)){if(S==="policySettings"){let{settings:E,errors:C}=p4(e);if(g=E,a(bqe(E)),a(Cqe(E)),E)r=En(r,Cp(S,E,e),Lr);a(C);continue}let y=e.store.repoTierFreeze.tier(S);if(y!==void 0){let E=Tc(S,e);if(E)i.add(Tt(E));if(a([...y.errors]),y.settings)r=En(r,y.settings,Lr);continue}if(S==="localSettings"){let E=YY(e);if(E&&!i.has(Tt(E))){i.add(Tt(E));let{settings:C,errors:A}=Rc(E,e.store);if(a(A),C)e.onLegacyLocalSettingsRead?.("cascade"),m(E,C),r=En(r,Cp(S,C,e),Lr)}}let b=Tc(S,e);if(b){let E=Tt(b),C=S==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(E)||C){i.add(E);let{settings:A,errors:w}=Rc(b,e.store,S==="flagSettings"?e.flagExpectedContent:void 0);if(a(w),A){if(S==="flagSettings"&&e.flagInlineJson===!0)m("--settings (inline JSON)",A,{channelLabel:!0});else m(b,A);r=En(r,Cp(S,A,e),Lr)}}}if(S==="flagSettings"){let{settings:E,errors:C}=WY(e);if(a(C),E)m("SDK inline settings",E,{channelLabel:!0}),r=En(r,Cp(S,E,e),Lr)}}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=f4(g.modelPicker)}let _=g?.deniedModels;if(_!==void 0)r.deniedModels=[..._];else delete r.deniedModels;if(l.length>0){let S=Aqe(e),y=(b,E,C,A,w)=>({file:b,path:E,severity:"warning",statusOnly:!0,message:`${E} is ignored — managed settings set ${C}, so only ${A} from managed settings are honored. The ${w===1?"entry":`${w} entries`} in ${b} will NOT apply (see https://code.claude.com/docs/en/settings#sandbox-settings).`});if(S.some((b)=>b.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)){for(let b of l)if(b.allowReadCount>0)a([y(b.file,"sandbox.filesystem.allowRead","allowManagedReadPathsOnly","allowRead paths",b.allowReadCount)])}if(S.some((b)=>b.sandbox?.network?.allowManagedDomainsOnly===!0)){for(let b of l)if(b.allowedDomainsCount>0)a([y(b.file,"sandbox.network.allowedDomains","allowManagedDomainsOnly","allowed domains (and WebFetch domain rules)",b.allowedDomainsCount)])}}return Vd("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:i.size,error_count:o.length}),{settings:r,errors:o}}finally{e.store.isLoadingFromDisk=!1}}function qqe(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=Vqe(e);return e.store.mergedSettings=n,n}function Zqe(e){let{settings:t}=qqe(e);return t||{}}function m4(e){e.store.invalidateAll();let t=[];for(let n of gx(e)){let r=JY(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:Zqe(e),sources:t}}function g4(e,t){let n=gx(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(JY(o,t)?.[e]!==void 0)return o}return null}import{execFile as Yqe}from"child_process";import{accessSync as Jqe,closeSync as Xqe,constants as Qqe,openSync as eZe,readSync as tZe}from"fs";class S4{promise=null;start(){if(this.promise)return;this.promise=Ax()}reset(){this.promise=null}}var nZe=new S4;function rZe(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 Cx(e,t,n){let r=Date.now();return new Promise((o)=>{try{Yqe(e,t,{encoding:"utf-8",timeout:dY,windowsHide:!0,...n!==void 0&&{maxBuffer:n}},(s,i)=>{o({stdout:i??"",...rZe(s),durationMs:Date.now()-r})})}catch(s){let i=s.code;o({stdout:"",status:"spawn_error",exitCode:null,errno:typeof i==="string"?i:null,signal:null,durationMs:Date.now()-r})}})}function h4(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function _4(e){return e.status==="ok"||e.status==="exited"&&e.exitCode!==null}function oZe(e){return e.status==="spawn_error"&&e.errno==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}function sZe(e){let t;try{return t=eZe(e,"r"),tZe(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{Xqe(t)}catch{}}}function Ax(){return(async()=>{if(process.platform==="darwin"){let e=pY(),n=(await Promise.all(e.map(async({path:o,...s})=>{try{Jqe(o,Qqe.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 Cx(ix,[...cY,o],Z_);if(!_4(i))return{stdout:null,unreadReason:"plutil did not finish converting it",...s};if(i.status==="ok")return{stdout:i.stdout,...s};let a=await Cx(ix,[...uY,o]);if(!_4(a))return{stdout:null,unreadReason:"plutil did not finish checking it",...s};if(a.status==="ok")return{stdout:null,unreadReason:"it holds a value plutil cannot convert to JSON (a date or data value)",...s};let l=sZe(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 y4(t)}if(_p())return y4(gi);return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}async function y4(e){let t=(o)=>Cx(e,["query",o,"/v",hp],Z_),[n,r]=await Promise.all([t(V_),t(q_)]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,...oZe(n)&&{hklmUnreadReason:`the value exceeds ${Z_/1048576} MiB`},hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:h4(n),hkcu:h4(r)}}}function E4(){return nZe.promise}var lZe=Object.freeze({settings:{},errors:[],loadState:"absent"}),xc=Object.freeze({settings:{},errors:[]});class R4{mdm=null;hkcu=null;wslInherits=!1;whereAsked=void 0;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await(E4()??Ax()),{mdm:o,hkcu:s,wslInherits:i,whereAsked:a}=await Tx(r,e);this.replace(o,s,i,a);let l=Date.now()-t;G(`MDM settings load completed in ${l}ms`);try{ni("tengu_managed_settings_os_read",yZe(r,l))}catch{}let c=xx();if(Object.keys(c.settings).length>0){G(`MDM settings found: ${Object.keys(c.settings).join(", ")}`);try{Vd("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){this.mdm=e,this.hkcu=t,this.wslInherits=n,this.whereAsked=r}reset(){this.mdm=null,this.hkcu=null,this.wslInherits=!1,this.whereAsked=void 0,this.loadPromise=null}}var b4="@builtin",cZe=["prependPlugins","appendPlugins"];function uZe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var dZe=new Le(()=>new R4);function vp(){return dZe.of(tn().host)}function pZe(e){vp().startLoad(e)}async function T4(){let e=vp();if(!e.loadPromise)pZe();await e.loadPromise}function xx(){return vx(vp()).mdm??lZe}function vx(e){return e.whereAsked!==void 0&&Zh()?e.whereAsked:e}function O4(){return vx(vp()).hkcu??xc}function w4(){return vx(vp()).wslInherits}function xp(e,t,{userWritable:n=!1}={}){let r=Xi(e,!1);if(!ie(r))return{settings:{},errors:[ny(t,{userWritable:n})],documentHasPolicyContent:!1,loadState:"didNotLoad"};let o=[],s=r;for(let f of n?ty:[]){if(!(f in s))continue;if(s=s===r?{...r}:s,delete s[f],!_i(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 cZe){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(uZe(f)){if(Object.entries(f).filter(([g,_])=>g.endsWith(b4)||_!==!1).length>0){s=s===r?{...r}:s;let g=$h(f,(_,S)=>!S.endsWith(b4)&&_===!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}=Ap(s,t),p=[...o,...a];return{settings:i??{},errors:n?p.map((f)=>({...f.severity==="warning"&&!f.startupFatal?f:{...fZe(f),severity:"warning",statusOnly:!0},userWritable:!0})):p,documentHasPolicyContent:l,loadState:c,...d&&{onlySubstitutes:d}}}function fZe({startupFatal:e,loadedWithoutGuardHook:t,...n}){return n}function Rx(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!==void 0&&{errno:r},...n&&{userWritable:!0}}}function ry(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 mZe=new Map([["ENOENT",en("ENOENT")],["EACCES",en("EACCES")],["EPERM",en("EPERM")],["ENOEXEC",en("ENOEXEC")],["EAGAIN",en("EAGAIN")],["EMFILE",en("EMFILE")],["ENOMEM",en("ENOMEM")],["ETIMEDOUT",en("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",en("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),gZe=new Map([["SIGTERM",en("SIGTERM")],["SIGKILL",en("SIGKILL")],["SIGINT",en("SIGINT")]]);function hZe(e){if(!e)return;return mZe.get(e)??en("other")}function _Ze(e){if(!e)return;return gZe.get(e)??en("other")}function C4(e,t){if(!t)return{};return{[`${e}_status`]:ms(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:hZe(t.errno),[`${e}_signal`]:_Ze(t.signal),[`${e}_duration_ms`]:t.durationMs}}function yZe(e,t){return{is_wsl:_p(),await_ms:t,...C4("hklm",e.outcomes.hklm),...C4("hkcu",e.outcomes.hkcu)}}async function Tx(e,t,n=!1){let r=[],o=!1,s="absent";for(let y of e.plistStdouts??[]){let{label:b,userWritable:E}=y;if(E&&o)continue;let C=y.stdout===null?{settings:{},errors:[Rx(b,y.unreadReason,E,y.unreadErrno)],documentHasPolicyContent:!1,loadState:"didNotLoad",...E&&{userWritable:E}}:{...xp(y.stdout,b,{userWritable:E}),...E&&{userWritable:E}};if(E?wc(C.settings):C.documentHasPolicyContent)return{mdm:{...C,errors:[...r,...C.errors],documentHasPolicyContent:!0},hkcu:xc,wslInherits:!1};if(o||=fa(C),r.push(...C.errors),!E)s=go(s,C.loadState)}let i=`Registry: ${V_}\\${hp}`,a=null,l="disarmed",c=`Registry: ${q_}\\${hp}`;if(!n&&(e.hklmStdout!==null||e.hklmUnreadReason!==void 0||e.hkcuStdout!==null)&&process.platform!=="win32"&&ax()){let[y,b]=await Promise.all([gi,aZe(gi)].map((C)=>iZe(C).then(({uid:A,gid:w,mode:L})=>({uid:A,gid:w,mode:L}),()=>{return}))),E=!0;try{E=yx(new ds,gi,y,b)}catch(C){G(`registry tool: could not be asked about, held: ${C}`,{level:"error"})}if(E){let C=[];if(e.hklmStdout!==null)C.push([i,xp(ry(e.hklmStdout)??"",i)]);else if(e.hklmUnreadReason!==void 0)C.push([i,{settings:{},errors:[Rx(i,e.hklmUnreadReason,!1)],documentHasPolicyContent:!1,loadState:"didNotLoad"}]);if(e.hkcuStdout!==null)C.push([c,xp(ry(e.hkcuStdout)??"",c,{userWritable:!0})]);let A=await Tx(e,t,!0),w=await Tx({...e,hklmStdout:null,hklmUnreadReason:void 0,hkcuStdout:null},t,!0);return{...A,whereAsked:{...w,mdm:{...w.mdm,heldDocuments:C.map(([L,U])=>({path:L,parsed:{...U,settings:U.loadState==="loaded"?U.settings:null}}))}}}}}if(e.hklmStdout!==null){let y=ry(e.hklmStdout)??"";a=xp(y,i);let b=Xi(y,!1);if(ie(b))l=Gw(b)}else if(e.hklmUnreadReason!==void 0)a={settings:{},errors:[Rx(i,e.hklmUnreadReason,!1)],documentHasPolicyContent:!1,loadState:"didNotLoad"};let d=a!==null&&fa(a);if(a)r.push(...a.errors),s=go(s,a.loadState);let p=_p(),f="disarmed",m=i,g=[];if(p){if(f=l,f!=="armed"){let y=await EZe(t);if(g=y.links,y.flag==="armed"||f==="disarmed")f=y.flag,m=y.unreadableFlagPath??An;if(f==="disarmed")r.push(...y.records),s=go(s,y.loadState)}}let _=f!=="disarmed",S={settings:{},errors:r,loadState:s};if(p&&!_){let y=new Set(a?.errors.filter((b)=>b.severity==="warning"));return{mdm:{...S,errors:S.errors.map((b)=>y.has(b)?{...b,wslIgnored:!0}:b),...g.length>0&&{managedDocumentLinks:g}},hkcu:xc,wslInherits:!1}}if(a&&d)return{mdm:a,hkcu:xc,wslInherits:_};if(f==="unreadable"){let y=await wx(An,t),b=VY(m);return{mdm:{...S,errors:y?S.errors:[...S.errors,b],...y&&{withheldFlagRecord:b},documentHasPolicyContent:!0,loadState:go(S.loadState,"loaded")},hkcu:xc,wslInherits:_}}if(e.hkcuStdout!==null&&!nt()&&!await SZe(_,t)){let y=xp(ry(e.hkcuStdout)??"",c,{userWritable:!0});if(!p||y.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:b,managedSourcesBehavior:E,...C}=y.settings;return{mdm:S,hkcu:{settings:C,errors:y.errors},wslInherits:_}}if(y.errors.length>0)return{mdm:S,hkcu:{settings:{},errors:y.errors},wslInherits:_}}return{mdm:S,hkcu:xc,wslInherits:_}}async function x4(e,t){if(Ee()&&t!==void 0)return(await uG(e,Rp)).content;return ri(e,Rp)}async function SZe(e,t){if(e&&await wx(An,t))return!0;return wx(si(),t)}async function A4(e,t){let n;try{n=await x4(e,t)}catch(r){return!tt(r)}try{let r=X_(n,e,!0);return fa({...r,loadState:hi(r)})}catch{return!0}}function Ox(e){let t=fe(e);return t==="ENOENT"||t==="ENOTDIR"}async function EZe(e){let t=[],n="absent",r=[],o=new Map;async function s(p,f){let m=ma(An,...p),g;try{g=await x4(m,e)}catch(y){if(Ox(y))return"disarmed";t.push(Tp(m,y)),n="didNotLoad"}let _=await kG(An,p,f,o);if(_!==null)r.push(_);if(g===void 0)return"disarmed";let S=g.trim()===""?{}:Xi(g,!1);if(!ie(S))return t.push(ny(m)),n="didNotLoad","disarmed";return n=go(n,"loaded"),Gw(S)}let i=ma(An,"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(An,"managed-settings.d"),d;try{d=await we().readdir(c)}catch(p){if(!Ox(p))t.push(Tp(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 wx(e,t){if(await A4(ma(e,"managed-settings.json"),t))return!0;let n=ma(e,"managed-settings.d"),r;try{r=await we().readdir(n)}catch(o){return!Ox(o)}for(let o of r)if((o.isFile()||o.isSymbolicLink())&&_x(o.name)&&await A4(ma(n,o.name),t))return!0;return!1}var CZe={user:"userSettings",project:"projectSettings",local:"localSettings"},v4={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},AZe=["user","project","local"];async function k4(e={}){await T4();let t={store:new ds,cwd:bZe(e.cwd??we().cwd()),allowedSources:(e.settingSources??AZe).map((a)=>CZe[a]),diskless:nt(),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:xx,hkcu:O4,wslInherits:w4,credentialHelperKeysFrom:()=>"as_read",asksOrganization:()=>Zh(),...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=m4(t),o=e4(t)??void 0,s=r.map(({source:a,settings:l})=>({source:v4[a],settings:l,path:a==="policySettings"?void 0:Tc(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let l=g4(a,t);if(l)i[a]={source:v4[l],path:l==="policySettings"?void 0:Tc(l,t),...l==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}var RZe=new Set(["bypassPermissions","auto","acceptEdits"]),TZe=new Set(["project"]),OZe=new Set(["project","local"]);function wZe(e){let t=e.effective.permissions?.defaultMode;if(!t||!RZe.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((YZ.includes(t)?OZe:TZe).has(r.source)){let{defaultMode:s,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}import{execFile as UYe}from"child_process";import{randomUUID as FYe}from"crypto";import{mkdir as dy,mkdtemp as $Ye,readFile as zYe,rm as k9,writeFile as P9}from"fs/promises";import{createRequire as HYe}from"module";import{homedir as Up,tmpdir as jYe}from"os";import{dirname as w9,isAbsolute as qx,join as ft,posix as I9,resolve as Fp,sep as BYe,win32 as D9}from"path";import{fileURLToPath as KYe}from"url";import{setMaxListeners as xZe}from"events";var vZe=50;function kp(e=vZe){let t=new AbortController;return xZe(e,t.signal),t}var QUt=new FinalizationRegistry(({parentSignalRef:e,handler:t})=>{e.deref()?.removeEventListener("abort",t)});var kZe="ask-withdrawn-by-asker",e0t=new DOMException(kZe,"AbortError");var t0t={"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 PZe="server-fallback-tombstone";var n0t=new DOMException(PZe,"AbortError");var IZe="subagent-park",r0t=new DOMException(IZe,"AbortError");import{spawn as GZe}from"child_process";import{existsSync as WZe}from"fs";import{createInterface as VZe}from"readline";import{StringDecoder as qZe}from"string_decoder";var DZe=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var kx={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>"]},LZe=[/\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 s0t=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${vc("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${vc("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),P4=[[Pp("sk-ant-","[A-Za-z0-9_-]",8,Px(8)),"<token>"],[Pp("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,Px(20)),"<token>"]],I4=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],MZe=`(?:${I4.join("|")})`,D4=[[new RegExp(`(^|[^A-Za-z0-9+])${MZe}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],L4=[[Pp("gh[opusr]_","[A-Za-z0-9]",20,vc("[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>"],[Pp("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,vc("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[Pp("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",vc("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${vc("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[DZe,"hooks.slack.com/<redacted>"]];var NZe=[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>"],UZe=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,M4=[[/(^|[^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>"]],N4=[[/(^|[^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>"]],FZe=[kx.bearer,kx.basic,...P4,kx.sk,...D4],$Ze=[...L4,NZe,...M4,...N4],i0t=[[new RegExp(`sk-${Px(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...I4.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 Ip(e){return[...FZe,...$Ze].reduce((t,[n,r])=>t.replace(n,r),String(e))}var a0t=[...LZe,...[...P4,...D4,...L4,...M4,...N4].map(([e])=>new RegExp(e.source,e.flags.replaceAll("g",""))),UZe];function Pp(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 vc(e){return`(?=${e}{0,64}[0-9])`}function Px(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 zZe(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")}var HZe=new Set(["filesystem.denyRead","filesystem.denyWrite","network.deniedDomains","credentials.files","credentials.envVars"]),jZe=new Set(["ripgrep","network.tlsTerminate"]),BZe=new Set(["__proto__","constructor","prototype"]),KZe=["httpProxyPort","socksProxyPort"];function U4(e,t,n=""){let r=fo(e)?{...e}:{};for(let[o,s]of Object.entries(t)){if(BZe.has(o)||s===void 0)continue;let i=n?`${n}.${o}`:o,a=Object.hasOwn(r,o)?r[o]:void 0;if(HZe.has(i)&&Array.isArray(a)&&Array.isArray(s))r[o]=Qt([...a,...s]);else if(fo(a)&&fo(s)&&!jZe.has(i))r[o]=U4(a,s,i);else r[o]=s}return r}function F4(e,t){let n={...e};if(!t)return n;let r=n.settings;if(r&&!zZe(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=Fe(r)}catch{}let s=U4(o.sandbox,t),i=t.credentials?.files,a=t.filesystem!==void 0||Array.isArray(i)&&i.some((f)=>fo(f)&&f.mode==="deny"),l=s.filesystem;if(a&&t.filesystem?.disabled===void 0&&fo(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&&fo(p)){for(let f of KZe)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=se({...o,sandbox:s}),n}function Be(e,t){return`${e}=${t}`}function oy(e,t){let n=String(t);if(n.length>1&&n.startsWith("-"))return[Be(e,n)];return[e,n]}function $4(e,t,n){e.push(...oy(`--${t}`,n))}var ZZe=2000,Ix=2048,j4="sdk-exit-after-stderr-drained",YZe=200;function Dx(e){return e==="exit"?j4:e}class B4{#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 sy=new B4,JZe=/[(),\u0000-\u001f\u007f-\u009f]/;function XZe(e){if(typeof e!=="string"||e.trim()==="")throw Error("Skill names must be non-empty strings.");if(!Kf(e))throw new ve(`Invalid skill name ${se(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 ${se(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(JZe.test(e))throw new ve(`Invalid skill name ${se(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 ${se(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 ${se(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 ${se(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 ${se(e)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return e}class Mx{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";exitListeners=[];abortHandler;forwardedAbort=kp();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||kp(),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(Wn(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 nl()?"bun":"node"}spawnLocalProcess(e){let{command:t,args:n,cwd:r,env:o,signal:s}=e,i=GZe(t,n,{cwd:r,stdio:["pipe","pipe","pipe"],signal:s,env:o,windowsHide:!0});if(i.pid!==void 0&&this.options.onProcessSpawned)try{this.options.onProcessSpawned(i.pid)}catch(_){qt(`onProcessSpawned threw: ${ot(_)}`)}let a=new qZe("utf8"),l=!1,c=!1,d=!1,p,f=Te(o.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;i.stderr.on("data",(_)=>{if(d)return;let S=a.write(_);if(this.stderrTail+=S,this.stderrTail.length>2*Ix)this.stderrTail=Bf(Ip(this.stderrTail),Ix);if(f)qt(S),this.options.stderr?.(S)}),i.stderr.on("error",(_)=>{qt(`[ProcessTransport] stderr read failed: ${_.code??_.message}`)});let m=()=>{if(d)return;if(d=!0,p)clearTimeout(p);i.emit(j4,i.exitCode,i.signalCode);let _=i.stderr;if(nYe(_))_.unref();else _.destroy()};return i.stderr.once("close",()=>{if(this.stderrTail+=a.end(),l=!0,c)m()}),i.once("exit",()=>{if(c=!0,this.ready=!1,l)m();else p=setTimeout(m,YZe)}),{stdin:i.stdin,stdout:i.stdout,get killed(){return i.killed},get exitCode(){return i.exitCode},get signalCode(){return i.signalCode},kill:i.kill.bind(i),on:(_,S)=>i.on(Dx(_),S),once:(_,S)=>i.once(Dx(_),S),off:(_,S)=>i.off(Dx(_),S)}}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:S,permissionMode:y,allowDangerouslySkipPermissions:b,permissionPromptToolName:E,permissionPrompts:C,continueConversation:A,resume:w,settingSources:L,skills:U,disallowedTools:F=[],tools:ue,mcpServers:O,strictMcpConfig:T,canUseTool:v,includePartialMessages:D,plugins:K,pluginsViaInitialize:X,sandbox:pe}=this.options,{allowedTools:H=[]}=this.options;if(U!==void 0){let he=U==="all"?["Skill"]:U.map((cn)=>`Skill(${XZe(cn)})`),Yt=new Set(H);H=[...H,...he.filter((cn)=>!Yt.has(cn))]}let W=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(d){switch(d.type){case"enabled":if(d.budgetTokens===void 0)W.push("--thinking=adaptive");else W.push(Be("--max-thinking-tokens",d.budgetTokens));break;case"disabled":W.push("--thinking=disabled");break;case"adaptive":W.push("--thinking=adaptive");break}if(d.type!=="disabled"&&d.display)W.push(Be("--thinking-display",d.display))}if(this.options.effort)W.push(Be("--effort",this.options.effort));if(p)W.push(Be("--max-turns",p));if(f!==void 0)W.push(Be("--max-budget-usd",f));if(m)W.push(Be("--task-budget",m.total));if(g)W.push(Be("--model",g));if(n)W.push(Be("--agent",n));if(r&&r.length>0)W.push(Be("--betas",r.join(",")));if(S)W.push(Be("--json-schema",se(S)));if(this.options.debugFile)W.push(Be("--debug-file",this.options.debugFile));else if(this.options.debug)W.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let he=Y1();if(he)W.push(Be("--debug-file",he))}if(v){if(E)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");W.push("--permission-prompt-tool=stdio")}else if(E)W.push(Be("--permission-prompt-tool",E));if(C)W.push(Be("--permission-prompts",C));if(A)W.push("--continue");if(w)W.push(Be("--resume",w));if(this.options.channels&&this.options.channels.length>0)for(let he of this.options.channels)W.push(Be("--channels",he));if(H.length>0)W.push(Be("--allowedTools",H.join(",")));if(F.length>0)W.push(Be("--disallowedTools",F.join(",")));if(ue!==void 0)if(Array.isArray(ue))W.push(Be("--tools",ue.join(",")));else W.push("--tools=default");if(O&&Object.keys(O).length>0)W.push(...oy("--mcp-config",se({mcpServers:O})));if(L!==void 0)W.push(Be("--setting-sources",L.join(",")));if(T)W.push("--strict-mcp-config");if(y)W.push(Be("--permission-mode",y));if(b)W.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.");W.push(Be("--fallback-model",_))}if(this.options.includeHookEvents)W.push("--include-hook-events");if(D)W.push("--include-partial-messages");if(this.options.sessionMirror)W.push("--session-mirror");if(t!==void 0)W.push(Be("--project-config-root",t));for(let he of e)W.push(Be("--add-dir",he));if(X)W.push("--await-initialize");else if(K&&K.length>0)for(let he of K)if(he.type==="local")W.push(he.skipMcpDiscovery?Be("--plugin-dir-no-mcp",he.path):Be("--plugin-dir",he.path));else throw Error(`Unsupported plugin type: ${he.type}`);if(this.options.forkSession)W.push("--fork-session");if(this.options.resumeSessionAt)W.push(Be("--resume-session-at",this.options.resumeSessionAt));if(this.options.resumeDropsTurn!==void 0)W.push(Be("--resume-drops-turn",this.options.resumeDropsTurn));if(this.options.sessionId)W.push(Be("--session-id",this.options.sessionId));if(this.options.persistSession===!1)W.push("--no-session-persistence");if(this.options.managedSettings)W.push(...oy("--managed-settings",this.options.managedSettings));let Ot={...a??{}};if(this.options.settings)Ot.settings=this.options.settings;let ln=F4(Ot,pe);for(let[he,Yt]of Object.entries(ln))if(Yt===null)W.push(`--${he}`);else $4(W,he,Yt);if(!c.CLAUDE_CODE_ENTRYPOINT)c.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete c.NODE_OPTIONS,Te(c.DEBUG_CLAUDE_AGENT_SDK))c.DEBUG="1";else delete c.DEBUG;let mt=QZe(l),Dt=mt?l:s,wt=mt?[...i,...W]:[...i,l,...W],Zt={command:Dt,args:wt,cwd:o,env:c,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)qt(`Spawning Claude Code (custom): ${Dt} ${wt.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(Zt);else qt(`Spawning Claude Code: ${Dt} ${wt.join(" ")}`),this.process=this.spawnLocalProcess(Zt);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(he)=>{qt(`[ProcessTransport] stdin write failed (child likely exited): ${he.code??he.message}`),this.ready=!1}),sy.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let Je=this.process;Je.on("error",(he)=>{this.ready=!1;let Yt=he,cn=Yt.syscall!==void 0?Yt.syscall.startsWith("spawn"):pS(he);if(cn&&!Je.killed)sy.untrack(Je);if(this.abortController.signal.aborted)this.exitError=iy(),un(he,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(cn&&pS(he)){let{message:ts,telemetryMessage:ga,errorClass:ns}=eYe(l,mt),wn={telemetryMessage:`${ga}${Lx(he)}`,errorClass:ns,code:Hc(he)};this.exitError=un(ReferenceError(ts),wn),un(he,wn),qt(this.exitError.message)}else{let ts={telemetryMessage:cn?`Failed to spawn Claude Code process${Lx(he)}`:`Claude Code process error${Lx(he)}`,errorClass:cn?"spawn_failed":"process_error",code:Hc(he)};this.exitError=un(Error(`Failed to spawn Claude Code process: ${Ip(he.message)}`),ts),un(he,ts),qt(this.exitError.message)}}),Je.on("exit",(he,Yt)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=iy();else{let cn=this.getProcessExitError(he,Yt);if(cn)this.exitError=cn,qt(cn.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 un(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 un(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=Bf(Ip(this.stderrTail),Ix).trim();return e?`. stderr: ${e}`:""}write(e){if(this.abortController.signal.aborted)throw z4();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){qt("[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 un(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:H4(this.exitError,"errorClass"),code:Hc(this.exitError),exitCode:tYe(this.exitError),signal:H4(this.exitError,"signal")});qt(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{if(!this.processStdin.write(e))qt("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${ot(t)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?iy():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?iy():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){qt(`[ProcessTransport] onExit callback threw during close(): ${ot(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()},ZZe,i,s).unref(),i.once("exit",()=>sy.untrack(i));else if(i)sy.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=VZe({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=Fe(n)}catch(o){qt(`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(z4());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 QZe(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((n)=>e.endsWith(n))}function eYe(e,t){let n=t?"native binary":"executable",r=Ip(e);if(WZe(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 Lx(e){let t=Hc(e);return t===void 0?"":` (${t})`}function iy(){return un(new Qn("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function z4(){return un(new Qn("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function H4(e,t){let n=Object.hasOwn(e,t)?Reflect.get(e,t):void 0;return typeof n==="string"?n:void 0}function tYe(e){let t=Object.hasOwn(e,"exitCode")?Reflect.get(e,"exitCode"):void 0;return typeof t==="number"?t:void 0}function nYe(e){return typeof Reflect.get(e,"unref")==="function"}import{existsSync as rYe}from"fs";var kc="@anthropic-ai/claude-agent-sdk";function oYe(){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 K4(e,t={}){let n=t.platform??process.platform,r=t.arch??process.arch,o=t.exists??rYe,s=t.preferMusl??oYe(),i="claude",a=n==="win32"?".exe":"",c=(n==="android"?[`${kc}-linux-${r}-android`]:n==="linux"?s?[`${kc}-linux-${r}-musl`,`${kc}-linux-${r}`]:[`${kc}-linux-${r}`,`${kc}-linux-${r}-musl`]:[`${kc}-${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}var sYe=["signed_out","identity_changed","transient","refresh_failed"];function G4(e){return sYe.some((t)=>t===e)}var ay=600000;function W4(e){return"method"in e&&"id"in e&&e.id!==null}var V4=Object.freeze({}),q4=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),N0t=Symbol("swallow");class Nx{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 Z4=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var Y4="2025-11-25";var iYe="notifications/tools/list_changed";function J4(e){return ie(e)&&!("id"in e)&&e.method===iYe}var X4=250,ly="sdk-manifest-capture:",Pc=Symbol("suppressControlResponse");function Q4(e,t,n){for(let r of n){let o=r==="tools"?ZO(t):void 0;G(o?`[Query] MCP server '${e}': ${c2(o)}`:`[Query] MCP server '${e}': ignoring malformed ${r} in its config`)}}class cy{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 Wd;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;runEndCeilingTimer;sessionState;lastErrorResultText;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;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:Sa(),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=ay){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,_);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(()=>{})}setError(e){this.inputStream.error(e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.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: ${ot(t)}`,{level:"error"})}try{let t=e??Ux();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(),Vn(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>=cy.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")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.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(this.lastErrorResultText=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()}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 Qn)&&e?.name!=="SSEHttpError"){let n=un(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});G(`[Query.readMessages] Replacing exit error with result text. Original: ${ot(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===Pc)return;let o={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:r}};n=se(o)+`
|
|
158
158
|
`}catch(r){if(this.cleanupPerformed)return;let o={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:ot(r)}};n=se(o)+`
|
|
159
|
-
`}try{await Promise.resolve(this.transport.write(n))}catch(r){G(`[Query.handleControlRequest] Response write failed: ${ot(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(Z4.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`),Pc;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},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 Pc;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(`SDK MCP server not found: ${n.server_name}`);if(W4(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 Pc;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 Pc;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`),ni("tengu_request_user_dialog_response_ignored",{shape:ms("auto_cancel")}),Pc}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(G4(o))n=o}})??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(!e9(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_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.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}})}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,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:ly+"initialize",method:"initialize",params:{protocolVersion:Y4,capabilities:V4,clientInfo:{...q4,version:"0.3.302"}}}},f);if(n)return;if(!("result"in m)){G(`[Query.captureSdkMcpServerManifests] '${p}' answered initialize with an error; leaving it to the CLI: ${se(m)}`,{level:"warn"});return}let g=m.result;f.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let _=g.capabilities,S=typeof _==="object"&&_!==null&&"tools"in _&&_.tools!==void 0&&_.tools!==null,y;if(S){let C=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:ly+"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: ${se(C)}`,{level:"warn"});return}if(C.result.nextCursor===void 0)y=C.result}let E=Fe(se(y===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:y}));t.set(p,{transport:f,manifest:E})}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 _f(Promise.race([s,i]),X4);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"){ec("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)G(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${X4} ms; the rest will handshake over the control channel`,{level:"warn"}),ec("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)ec("sdk_mcp_manifest_capture","partial",c);else Gd("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 Vt("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})}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,...l}=s;t(l)}else n(new ve(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests)G("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Ux());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 Vt("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 Vt("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return Vt("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 Vt("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=Vt("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((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a}}},()=>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:lYe(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&&e9(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 renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return Vt("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return Vt("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).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(Wn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Ux());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(Wn(n.reason??"Control request aborted")),!c)return;try{Promise.resolve(this.transport.write(se({type:"control_cancel_request",request_id:r})+`
|
|
159
|
+
`}try{await Promise.resolve(this.transport.write(n))}catch(r){G(`[Query.handleControlRequest] Response write failed: ${ot(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(Z4.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`),Pc;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},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 Pc;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(`SDK MCP server not found: ${n.server_name}`);if(W4(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 Pc;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 Pc;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`),ni("tengu_request_user_dialog_response_ignored",{shape:ms("auto_cancel")}),Pc}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(G4(o))n=o}})??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(!e9(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_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.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}})}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,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:ly+"initialize",method:"initialize",params:{protocolVersion:Y4,capabilities:V4,clientInfo:{...q4,version:"0.3.303"}}}},f);if(n)return;if(!("result"in m)){G(`[Query.captureSdkMcpServerManifests] '${p}' answered initialize with an error; leaving it to the CLI: ${se(m)}`,{level:"warn"});return}let g=m.result;f.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let _=g.capabilities,S=typeof _==="object"&&_!==null&&"tools"in _&&_.tools!==void 0&&_.tools!==null,y;if(S){let C=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:ly+"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: ${se(C)}`,{level:"warn"});return}if(C.result.nextCursor===void 0)y=C.result}let E=Fe(se(y===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:y}));t.set(p,{transport:f,manifest:E})}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 _f(Promise.race([s,i]),X4);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"){ec("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)G(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${X4} ms; the rest will handshake over the control channel`,{level:"warn"}),ec("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)ec("sdk_mcp_manifest_capture","partial",c);else Gd("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 Vt("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})}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,...l}=s;t(l)}else n(new ve(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests)G("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(Ux());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 Vt("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 Vt("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return Vt("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 Vt("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=Vt("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((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a}}},()=>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:lYe(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&&e9(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 renameSession(e,t){await this.request({subtype:"rename_session",title:e,source:"host",session_id:t})}async generateSessionTitle(e,t){return Vt("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return Vt("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).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(Wn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(Ux());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(Wn(n.reason??"Control request aborted")),!c)return;try{Promise.resolve(this.transport.write(se({type:"control_cancel_request",request_id:r})+`
|
|
160
160
|
`)).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(un(Error(g.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:typeof g.error_code==="string"&&aYe.test(g.error_code)?g.error_code:void 0}));if(!s&&(g.pending_permission_requests||g.pending_user_dialog_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=se(o)+`
|
|
161
161
|
`,m=()=>{if(n?.aborted)return;return c=!0,this.transport.write(f)};try{(this.initializeHasBeenWritten||this.writingFirstInitialize?Promise.resolve(m()):this.initializeWritten.then(m)).catch(p)}catch(g){p(g)}})}initializationResult(){return this.initialization}writeAfterInitialize(e){if(this.initializeHasBeenWritten)return Promise.resolve(this.transport.write(e));return this.initializeWritten.then(()=>this.transport.write(e))}reinitialize(){return Vt("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 Vt("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 Vt("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,t){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:t})).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 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 Vt("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 Vt("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return Vt("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return Vt("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}=qO(l);if(Q4(a,l,p),d.timeout!==c.settings.timeout||d.disableAutoBackground!==c.settings.disableAutoBackground)G(`[Query.setMcpServers] MCP server '${a}' is already registered, so the different timeout or disableAutoBackground passed to setMcpServers is ignored; remove and re-add the server to change it`);if(d.tools!==void 0&&!l2(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;for await(let n of e){if(t++,G(`[Query.streamInput] Processing message ${t}: ${n.type}`),this.abortController?.signal.aborted)break;this.runEnded=!1,this.resultReceived=!1,this.clearRunEndCeiling(),await Promise.resolve(this.transport.write(se(this.verbatimPrompts?{...n,client_composed:!0}:n)+`
|
|
162
162
|
`))}if(G(`[Query.streamInput] Finished processing ${t} messages from input stream`),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 Qn))throw t}}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,w_)),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(`No hook callback found for ID: ${e}`);return o(t,n,{signal:r})}connectSdkMcpServer(e,t){let n=new Nx((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}=qO(t);Q4(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}:${ly}`;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(ly)){G(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let n={type:"control_request",request_id:Sa(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&J4(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.writeAfterInitialize(se(n)+`
|
|
163
|
-
`).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 Ux(){return Error("Query closed before response received")}var aYe=/^[a-z][a-z0-9_]{0,63}$/;function e9(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 lYe(e){try{let t=Fe(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=Fe(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 t9=typeof globalThis==="object"?globalThis:global;var Xo="1.9.0";var n9=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function cYe(e){var t=new Set([e]),n=new Set,r=e.match(n9);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(n9);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 r9=cYe(Xo);var uYe=Xo.split(".")[0],Dp=Symbol.for("opentelemetry.js.api."+uYe),Lp=t9;function Ic(e,t,n,r){var o;if(r===void 0)r=!1;var s=Lp[Dp]=(o=Lp[Dp])!==null&&o!==void 0?o:{version:Xo};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!==Xo){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Xo);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Xo+"."),!0}function Qo(e){var t,n,r=(t=Lp[Dp])===null||t===void 0?void 0:t.version;if(!r||!r9(r))return;return(n=Lp[Dp])===null||n===void 0?void 0:n[e]}function Dc(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Xo+".");var n=Lp[Dp];if(n)delete n[e]}var dYe=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},pYe=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))},o9=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 Mp("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("verbose",this._namespace,t)},e}();function Mp(e,t,n){var r=Qo("diag");if(!r)return;return n.unshift(t),r[e].apply(r,pYe([],dYe(n),!1))}var Tn;(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"})(Tn||(Tn={}));function s9(e,t){if(e<Tn.NONE)e=Tn.NONE;else if(e>Tn.ALL)e=Tn.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",Tn.ERROR),warn:n("warn",Tn.WARN),info:n("info",Tn.INFO),debug:n("debug",Tn.DEBUG),verbose:n("verbose",Tn.VERBOSE)}}var fYe=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},mYe=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))},gYe="diag",yi=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Qo("diag");if(!a)return;return a[o].apply(a,mYe([],fYe(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:Tn.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=Qo("diag"),p=s9((a=s.logLevel)!==null&&a!==void 0?a:Tn.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 Ic("diag",p,n,!0)};n.setLogger=r,n.disable=function(){Dc(gYe,n)},n.createComponentLogger=function(o){return new o9(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 hYe=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},_Ye=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.")},i9=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=hYe(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=_Ye(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 vFt=yi.instance();function a9(e){if(e===void 0)e={};return new i9(new Map(Object.entries(e)))}function l9(e){return Symbol.for(e)}var yYe=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}(),c9=new yYe;var u9={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},d9={set:function(e,t,n){if(e==null)return;e[t]=n}};var SYe=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},EYe=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))},p9=function(){function e(){}return e.prototype.active=function(){return c9},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,EYe([r],SYe(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var bYe=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},CYe=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))},Fx="context",AYe=new p9,uy=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return Ic(Fx,t,yi.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,CYe([t,n,r],bYe(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Qo(Fx)||AYe},e.prototype.disable=function(){this._getContextManager().disable(),Dc(Fx,yi.instance())},e}();var $x=uy.getInstance();var f9=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 zx=l9("OpenTelemetry Baggage Key");function Hx(e){return e.getValue(zx)||void 0}function m9(){return Hx(uy.getInstance().active())}function g9(e,t){return e.setValue(zx,t)}function h9(e){return e.deleteValue(zx)}var jx="propagation",RYe=new f9,_9=function(){function e(){this.createBaggage=a9,this.getBaggage=Hx,this.getActiveBaggage=m9,this.setBaggage=g9,this.deleteBaggage=h9}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return Ic(jx,t,yi.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=d9;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=u9;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Dc(jx,yi.instance())},e.prototype._getGlobalPropagator=function(){return Qo(jx)||RYe},e}();var Bx=_9.getInstance();import{copyFile as TYe,readFile as OYe,rm as S9,writeFile as E9}from"fs/promises";import{homedir as y9}from"os";import{join as Kx}from"path";function b9(e){return{globalConfig:Kx(e||y9(),".claude.json"),userSettings:Kx(e||Kx(y9(),".claude"),"settings.json")}}function Gx(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function Lc(e,t,n,r){if(r)return wYe(r,e,t,n);try{if(n)await E9(t,n(await OYe(e)),{mode:384});else await TYe(e,t)}catch(o){if(fe(o)===void 0)throw o;if(!tt(o))await S9(t,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${e} (${fe(o)})`)}}async function wYe({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 E9(r,o?o(a):a,{mode:384})}catch(l){if(fe(l)===void 0)throw l;if(!tt(l))await S9(r,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${n} (${fe(l)})`)}}import{createHash as xYe}from"crypto";import{homedir as d$t,userInfo as vYe}from"os";var C9="-credentials";function A9(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"):vt(),o=n?"":`-${xYe("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${LD().OAUTH_FILE_SUFFIX}${e}${o}`}var kYe=/^[a-zA-Z0-9._-]+$/;function R9(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||vYe().username}catch{e="claude-code-user"}if(!kYe.test(e))return"claude-code-user";return e}class T9{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var h$t=new Le(()=>new T9);function PYe(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 O9(e,t,n){if(!e)return;let r=PYe(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as IYe}from"fs";import{isAbsolute as DYe,relative as LYe,resolve as MYe,sep as NYe}from"path";function Wx(e){let t=MYe(e??"."),n;try{n=IYe(t)}catch{n=t}return Ke(n)}function On(e,t){let n=Wx(e);if(t===void 0)return Br(n);return(t.CLAUDE_CONFIG_DIR?GS(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??_u(n)}function Np(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function Vx(e,t){let n=LYe(t,e),r=n.split(NYe);if(r[0]===".."||DYe(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 GYe=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function x9(e){let t;try{t=Fe(oc(e.toString("utf8")))}catch{return e}if(!v9(t))return e;let n=!1;for(let o of GYe)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(v9(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?se(t):e}function v9(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function WYe(e,t){if(!e)return;let n=e;try{let r=Fe(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=se(r)}catch{}await P9(t,n,{mode:384})}function VYe(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=A9(C9);return new Promise((t)=>{UYe("security",["find-generic-password","-a",R9(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function L9(e,t,n,r,o=60000,s){if(!je(t))return;let i=On(n,r),a=await or(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=ft(jYe(),`claude-resume-${FYe()}`);try{let c=ft(l,"projects",i);await dy(c,{recursive:!0,mode:448});let d=ft(c,`${t}.jsonl`);await hu(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??ft(Up(),".claude"),m;try{m=await zYe(ft(f,".credentials.json"),"utf-8")}catch(b){if(!tt(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await VYe()??m;await WYe(m,ft(l,".credentials.json"));let g=b9(If("CLAUDE_CONFIG_DIR")),_=p||Up(),S=ft(_,".claude.json");await Lc(S,ft(l,".claude.json"),void 0,Gx(s,S,g.globalConfig,Pt.globalConfig())),await Lc(ft(f,".config.json"),ft(l,".config.json"));for(let b of ID)if(b)await Lc(ft(_,`.claude${b}.json`),ft(l,`.claude${b}.json`));let y=ft(f,"settings.json");if(await Lc(y,ft(l,"settings.json"),x9,Gx(s,y,g.userSettings,Pt.userSettings())),await Lc(ft(f,"cowork_settings.json"),ft(l,"cowork_settings.json"),x9),e.listSubkeys)await qYe(e,{projectKey:i,sessionId:t},ft(c,t),o);return l}catch(c){throw await py(l),c}}async function qYe(e,t,n,r){let o=await or(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=Fp(n,s+".jsonl");if(!s||qx(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+BYe)){G(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await or(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(Np(d))l.push(d);else c.push(d);if(c.length>0)await dy(w9(i),{recursive:!0}),await hu(i,c);if(l.length>0){let d=l.at(-1),p=Fp(n,s+".meta.json");await dy(w9(p),{recursive:!0});let{type:f,...m}=d;await P9(p,se(m),{mode:384})}}}function M9(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(I9.isAbsolute(e.directory)||D9.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 ZYe=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function Zx(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o}=t,{systemPrompt:s,settings:i,managedSettings:a,settingSources:l,sandbox:c,...d}=e??{},p,f,m,g;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="custom")p=s.prompt,g=s.snapshot;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections,g=s.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.302";let{abortController:_=kp(),additionalDirectories:S=[],projectConfigRoot:y,agent:b,agents:E,allowedTools:C=[],betas:A,canUseTool:w,continue:L,cwd:U,debug:F,debugFile:ue,disallowedTools:O=[],tools:T,env:v,executable:D=nl()?"bun":"node",executableArgs:K=[],extraArgs:X={},fallbackModel:pe,enableFileCheckpointing:H,toolConfig:W,forkSession:Ot,hooks:ln,includeHookEvents:mt,includePartialMessages:Dt,forwardSubagentText:wt,verbatimPrompts:Zt=!1,onElicitation:Je,onUserDialog:he,supportedDialogKinds:Yt,perTaskStopAffordance:cn,rapidFollowupPreempt:ts,workspaceTrust:ga,persistSession:ns,sessionStore:wn,sessionStoreFlush:my,thinking:qe,effort:_r,maxThinkingTokens:Bn,maxTurns:Si,maxBudgetUsd:ha,taskBudget:$p,mcpServers:_a,model:zp,outputFormat:Qx,permissionMode:eJ,allowDangerouslySkipPermissions:tJ=!1,permissionPromptToolName:nJ,permissionPrompts:rJ,plugins:Hp,pluginDelivery:gy="argv",getOAuthToken:ev,getHostAuthToken:tv,workload:nv,resume:rv,resumeSessionAt:oJ,resumeDropsTurn:sJ,sessionId:iJ,skills:ov,stderr:aJ,strictMcpConfig:lJ}=d,sv=eJ;if(wn&&ns===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");if(Yt!==void 0&&Yt.length>0&&!he)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let cJ=M9(ga);if(wn&&L&&!rv&&!wn.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(wn&&H)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(wn&&d.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(O9(!!w,sv??"default",C),gy!=="argv"&&gy!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let iv=gy==="initialize"&&Hp!==void 0&&Hp.length>0,hy=d.pathToClaudeCodeExecutable;if(!hy){let Jt=KYe(import.meta.url),xn=HYe(Jt),Mr=K4((ya)=>xn.resolve(ya));if(!Mr)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.`);hy=Mr}let av=Qx?.type==="json_schema"?Qx.schema:void 0,Ct=v?{...v}:{...process.env};if(!Ct.CLAUDE_CODE_ENTRYPOINT)Ct.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!Ct.CLAUDE_AGENT_SDK_VERSION)Ct.CLAUDE_AGENT_SDK_VERSION="0.3.302";if(H)Ct.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(Ct).some((Jt)=>Jt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))Ct.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";let _y=Zc(Ct.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),uJ=Number.isFinite(_y)&&_y>=0?_y:ay;if(ev)Ct.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(tv)Ct.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(W?.askUserQuestion?.previewFormat)Ct.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=W.askUserQuestion.previewFormat;for(let[Jt,xn]of[[W?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[W?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(Jt)Ct[xn]="1";else if(!v){for(let Mr of Object.keys(Ct))if(Mr.toUpperCase()===xn)delete Ct[Mr]}let yy={};if(Bx.inject($x.active(),yy),"traceparent"in yy){for(let Jt of["TRACEPARENT","TRACESTATE"])if(!(Jt in(v??{})))delete Ct[Jt]}for(let[Jt,xn]of Object.entries(yy)){let Mr=Jt.toUpperCase();if(!(Mr in(v??{})))Ct[Mr]=xn}let lv={},cv=new Map;if(_a)for(let[Jt,xn]of Object.entries(_a))if(xn.type==="sdk"&&xn.instance)cv.set(Jt,xn);else lv[Jt]=xn;let Mc;if(qe)switch(qe.type){case"adaptive":Mc={type:"adaptive",display:qe.display};break;case"enabled":Mc={type:"enabled",budgetTokens:qe.budgetTokens,display:qe.display};break;case"disabled":Mc={type:"disabled"};break}else if(Bn!==void 0)Mc=Bn===0?{type:"disabled"}:{type:"enabled",budgetTokens:Bn};if(r){if(Ct.CLAUDE_CONFIG_DIR=r,process.platform==="win32")Ct.CLAUDE_SECURESTORAGE_CONFIG_DIR=v?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??v?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let uv=new Mx({abortController:_,additionalDirectories:S,projectConfigRoot:y,agent:b,betas:A,cwd:U,debug:F,debugFile:ue,executable:D,executableArgs:K,extraArgs:nv?{...X,workload:nv}:X,pathToClaudeCodeExecutable:hy,env:Ct,forkSession:Ot,stderr:aJ,thinkingConfig:Mc,effort:_r,maxTurns:Si,maxBudgetUsd:ha,taskBudget:$p,model:zp,fallbackModel:pe,jsonSchema:av,permissionMode:sv,allowDangerouslySkipPermissions:tJ,permissionPromptToolName:nJ,permissionPrompts:rJ,continueConversation:wn?void 0:L,resume:rv,resumeSessionAt:oJ,resumeDropsTurn:sJ,sessionId:iJ,settings:typeof i==="object"?se(i):i,managedSettings:a?se(a):void 0,settingSources:l,skills:ov,allowedTools:C,disallowedTools:O,tools:T,mcpServers:lv,strictMcpConfig:lJ,canUseTool:!!w,hooks:!!ln,includeHookEvents:mt,includePartialMessages:Dt,persistSession:ns,sessionMirror:!!wn,plugins:Hp,pluginsViaInitialize:iv,sandbox:c,spawnClaudeCodeProcess:d.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),dJ={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:d.planModeInstructions,systemPromptSnapshot:g,appendSubagentSystemPrompt:d.appendSubagentSystemPrompt,toolAliases:d.toolAliases,excludeDynamicSections:m,agents:E,title:d.title,skills:ov,webSearchIsolationExemptMcpServers:d.webSearchIsolationExemptMcpServers,promptSuggestions:d.promptSuggestions,agentProgressSummaries:d.agentProgressSummaries,forwardSubagentText:wt,supportedDialogKinds:Yt,perTaskStopAffordance:cn,rapidFollowupPreempt:ts,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:cJ,plugins:iv?Hp:void 0,captureSdkMcpManifests:!Df("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},Sy=new cy(uv,n,w,ln,_,cv,av,dJ,Je,ev,tv,he,Zt,uJ);if(wn){let Jt=()=>ft(Ct.CLAUDE_CONFIG_DIR??ft(Up(),".claude"),"projects"),xn=my==="eager",Mr=new RE(async(ya,Ey)=>{let Nc=Vx(ya,Jt());if(Nc)await wn.append(Nc,Ey);else G(`[SessionStore] dropping mirror frame: filePath ${ya} is not under ${Jt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(ya,Ey)=>{let Nc=Vx(ya,Jt());if(Nc)Sy.reportMirrorError(Nc,Ey.message)},maxPendingEntries:xn?0:lu,maxPendingBytes:xn?0:wi});Sy.setTranscriptMirrorBatcher(Mr)}return{queryInstance:Sy,transport:uv,abortController:_,processEnv:Ct,verbatimPrompts:Zt}}function Yx(e,t,n,r){if(typeof t==="string")e.writeAfterInitialize(se({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,...r&&{client_composed:!0}})+`
|
|
163
|
+
`).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 Ux(){return Error("Query closed before response received")}var aYe=/^[a-z][a-z0-9_]{0,63}$/;function e9(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 lYe(e){try{let t=Fe(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=Fe(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 t9=typeof globalThis==="object"?globalThis:global;var Xo="1.9.0";var n9=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function cYe(e){var t=new Set([e]),n=new Set,r=e.match(n9);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(n9);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 r9=cYe(Xo);var uYe=Xo.split(".")[0],Dp=Symbol.for("opentelemetry.js.api."+uYe),Lp=t9;function Ic(e,t,n,r){var o;if(r===void 0)r=!1;var s=Lp[Dp]=(o=Lp[Dp])!==null&&o!==void 0?o:{version:Xo};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!==Xo){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Xo);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Xo+"."),!0}function Qo(e){var t,n,r=(t=Lp[Dp])===null||t===void 0?void 0:t.version;if(!r||!r9(r))return;return(n=Lp[Dp])===null||n===void 0?void 0:n[e]}function Dc(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Xo+".");var n=Lp[Dp];if(n)delete n[e]}var dYe=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},pYe=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))},o9=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 Mp("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Mp("verbose",this._namespace,t)},e}();function Mp(e,t,n){var r=Qo("diag");if(!r)return;return n.unshift(t),r[e].apply(r,pYe([],dYe(n),!1))}var Tn;(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"})(Tn||(Tn={}));function s9(e,t){if(e<Tn.NONE)e=Tn.NONE;else if(e>Tn.ALL)e=Tn.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",Tn.ERROR),warn:n("warn",Tn.WARN),info:n("info",Tn.INFO),debug:n("debug",Tn.DEBUG),verbose:n("verbose",Tn.VERBOSE)}}var fYe=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},mYe=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))},gYe="diag",yi=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Qo("diag");if(!a)return;return a[o].apply(a,mYe([],fYe(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:Tn.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=Qo("diag"),p=s9((a=s.logLevel)!==null&&a!==void 0?a:Tn.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 Ic("diag",p,n,!0)};n.setLogger=r,n.disable=function(){Dc(gYe,n)},n.createComponentLogger=function(o){return new o9(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 hYe=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},_Ye=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.")},i9=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=hYe(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=_Ye(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 vFt=yi.instance();function a9(e){if(e===void 0)e={};return new i9(new Map(Object.entries(e)))}function l9(e){return Symbol.for(e)}var yYe=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}(),c9=new yYe;var u9={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},d9={set:function(e,t,n){if(e==null)return;e[t]=n}};var SYe=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},EYe=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))},p9=function(){function e(){}return e.prototype.active=function(){return c9},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,EYe([r],SYe(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var bYe=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},CYe=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))},Fx="context",AYe=new p9,uy=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return Ic(Fx,t,yi.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,CYe([t,n,r],bYe(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Qo(Fx)||AYe},e.prototype.disable=function(){this._getContextManager().disable(),Dc(Fx,yi.instance())},e}();var $x=uy.getInstance();var f9=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 zx=l9("OpenTelemetry Baggage Key");function Hx(e){return e.getValue(zx)||void 0}function m9(){return Hx(uy.getInstance().active())}function g9(e,t){return e.setValue(zx,t)}function h9(e){return e.deleteValue(zx)}var jx="propagation",RYe=new f9,_9=function(){function e(){this.createBaggage=a9,this.getBaggage=Hx,this.getActiveBaggage=m9,this.setBaggage=g9,this.deleteBaggage=h9}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return Ic(jx,t,yi.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=d9;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=u9;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Dc(jx,yi.instance())},e.prototype._getGlobalPropagator=function(){return Qo(jx)||RYe},e}();var Bx=_9.getInstance();import{copyFile as TYe,readFile as OYe,rm as S9,writeFile as E9}from"fs/promises";import{homedir as y9}from"os";import{join as Kx}from"path";function b9(e){return{globalConfig:Kx(e||y9(),".claude.json"),userSettings:Kx(e||Kx(y9(),".claude"),"settings.json")}}function Gx(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function Lc(e,t,n,r){if(r)return wYe(r,e,t,n);try{if(n)await E9(t,n(await OYe(e)),{mode:384});else await TYe(e,t)}catch(o){if(fe(o)===void 0)throw o;if(!tt(o))await S9(t,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${e} (${fe(o)})`)}}async function wYe({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 E9(r,o?o(a):a,{mode:384})}catch(l){if(fe(l)===void 0)throw l;if(!tt(l))await S9(r,{force:!0}).catch(()=>{}),G(`sessionStore resume: skipping ${n} (${fe(l)})`)}}import{createHash as xYe}from"crypto";import{homedir as d$t,userInfo as vYe}from"os";var C9="-credentials";function A9(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"):vt(),o=n?"":`-${xYe("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${LD().OAUTH_FILE_SUFFIX}${e}${o}`}var kYe=/^[a-zA-Z0-9._-]+$/;function R9(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||vYe().username}catch{e="claude-code-user"}if(!kYe.test(e))return"claude-code-user";return e}class T9{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var h$t=new Le(()=>new T9);function PYe(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 O9(e,t,n){if(!e)return;let r=PYe(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as IYe}from"fs";import{isAbsolute as DYe,relative as LYe,resolve as MYe,sep as NYe}from"path";function Wx(e){let t=MYe(e??"."),n;try{n=IYe(t)}catch{n=t}return Ke(n)}function On(e,t){let n=Wx(e);if(t===void 0)return Br(n);return(t.CLAUDE_CONFIG_DIR?GS(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??_u(n)}function Np(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function Vx(e,t){let n=LYe(t,e),r=n.split(NYe);if(r[0]===".."||DYe(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 GYe=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function x9(e){let t;try{t=Fe(oc(e.toString("utf8")))}catch{return e}if(!v9(t))return e;let n=!1;for(let o of GYe)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(v9(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?se(t):e}function v9(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function WYe(e,t){if(!e)return;let n=e;try{let r=Fe(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=se(r)}catch{}await P9(t,n,{mode:384})}function VYe(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=A9(C9);return new Promise((t)=>{UYe("security",["find-generic-password","-a",R9(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function L9(e,t,n,r,o=60000,s){if(!je(t))return;let i=On(n,r),a=await or(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=ft(jYe(),`claude-resume-${FYe()}`);try{let c=ft(l,"projects",i);await dy(c,{recursive:!0,mode:448});let d=ft(c,`${t}.jsonl`);await hu(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??ft(Up(),".claude"),m;try{m=await zYe(ft(f,".credentials.json"),"utf-8")}catch(b){if(!tt(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await VYe()??m;await WYe(m,ft(l,".credentials.json"));let g=b9(If("CLAUDE_CONFIG_DIR")),_=p||Up(),S=ft(_,".claude.json");await Lc(S,ft(l,".claude.json"),void 0,Gx(s,S,g.globalConfig,Pt.globalConfig())),await Lc(ft(f,".config.json"),ft(l,".config.json"));for(let b of ID)if(b)await Lc(ft(_,`.claude${b}.json`),ft(l,`.claude${b}.json`));let y=ft(f,"settings.json");if(await Lc(y,ft(l,"settings.json"),x9,Gx(s,y,g.userSettings,Pt.userSettings())),await Lc(ft(f,"cowork_settings.json"),ft(l,"cowork_settings.json"),x9),e.listSubkeys)await qYe(e,{projectKey:i,sessionId:t},ft(c,t),o);return l}catch(c){throw await py(l),c}}async function qYe(e,t,n,r){let o=await or(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=Fp(n,s+".jsonl");if(!s||qx(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+BYe)){G(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await or(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(Np(d))l.push(d);else c.push(d);if(c.length>0)await dy(w9(i),{recursive:!0}),await hu(i,c);if(l.length>0){let d=l.at(-1),p=Fp(n,s+".meta.json");await dy(w9(p),{recursive:!0});let{type:f,...m}=d;await P9(p,se(m),{mode:384})}}}function M9(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(I9.isAbsolute(e.directory)||D9.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 ZYe=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function Zx(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o}=t,{systemPrompt:s,settings:i,managedSettings:a,settingSources:l,sandbox:c,...d}=e??{},p,f,m,g;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="custom")p=s.prompt,g=s.snapshot;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections,g=s.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.303";let{abortController:_=kp(),additionalDirectories:S=[],projectConfigRoot:y,agent:b,agents:E,allowedTools:C=[],betas:A,canUseTool:w,continue:L,cwd:U,debug:F,debugFile:ue,disallowedTools:O=[],tools:T,env:v,executable:D=nl()?"bun":"node",executableArgs:K=[],extraArgs:X={},fallbackModel:pe,enableFileCheckpointing:H,toolConfig:W,forkSession:Ot,hooks:ln,includeHookEvents:mt,includePartialMessages:Dt,forwardSubagentText:wt,verbatimPrompts:Zt=!1,onElicitation:Je,onUserDialog:he,supportedDialogKinds:Yt,perTaskStopAffordance:cn,rapidFollowupPreempt:ts,workspaceTrust:ga,persistSession:ns,sessionStore:wn,sessionStoreFlush:my,thinking:qe,effort:_r,maxThinkingTokens:Bn,maxTurns:Si,maxBudgetUsd:ha,taskBudget:$p,mcpServers:_a,model:zp,outputFormat:Qx,permissionMode:eJ,allowDangerouslySkipPermissions:tJ=!1,permissionPromptToolName:nJ,permissionPrompts:rJ,plugins:Hp,pluginDelivery:gy="argv",getOAuthToken:ev,getHostAuthToken:tv,workload:nv,resume:rv,resumeSessionAt:oJ,resumeDropsTurn:sJ,sessionId:iJ,skills:ov,stderr:aJ,strictMcpConfig:lJ}=d,sv=eJ;if(wn&&ns===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");if(Yt!==void 0&&Yt.length>0&&!he)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let cJ=M9(ga);if(wn&&L&&!rv&&!wn.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(wn&&H)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(wn&&d.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(O9(!!w,sv??"default",C),gy!=="argv"&&gy!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let iv=gy==="initialize"&&Hp!==void 0&&Hp.length>0,hy=d.pathToClaudeCodeExecutable;if(!hy){let Jt=KYe(import.meta.url),xn=HYe(Jt),Mr=K4((ya)=>xn.resolve(ya));if(!Mr)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.`);hy=Mr}let av=Qx?.type==="json_schema"?Qx.schema:void 0,Ct=v?{...v}:{...process.env};if(!Ct.CLAUDE_CODE_ENTRYPOINT)Ct.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!Ct.CLAUDE_AGENT_SDK_VERSION)Ct.CLAUDE_AGENT_SDK_VERSION="0.3.303";if(H)Ct.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(Ct).some((Jt)=>Jt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))Ct.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";let _y=Zc(Ct.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),uJ=Number.isFinite(_y)&&_y>=0?_y:ay;if(ev)Ct.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(tv)Ct.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(W?.askUserQuestion?.previewFormat)Ct.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=W.askUserQuestion.previewFormat;for(let[Jt,xn]of[[W?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[W?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(Jt)Ct[xn]="1";else if(!v){for(let Mr of Object.keys(Ct))if(Mr.toUpperCase()===xn)delete Ct[Mr]}let yy={};if(Bx.inject($x.active(),yy),"traceparent"in yy){for(let Jt of["TRACEPARENT","TRACESTATE"])if(!(Jt in(v??{})))delete Ct[Jt]}for(let[Jt,xn]of Object.entries(yy)){let Mr=Jt.toUpperCase();if(!(Mr in(v??{})))Ct[Mr]=xn}let lv={},cv=new Map;if(_a)for(let[Jt,xn]of Object.entries(_a))if(xn.type==="sdk"&&xn.instance)cv.set(Jt,xn);else lv[Jt]=xn;let Mc;if(qe)switch(qe.type){case"adaptive":Mc={type:"adaptive",display:qe.display};break;case"enabled":Mc={type:"enabled",budgetTokens:qe.budgetTokens,display:qe.display};break;case"disabled":Mc={type:"disabled"};break}else if(Bn!==void 0)Mc=Bn===0?{type:"disabled"}:{type:"enabled",budgetTokens:Bn};if(r){if(Ct.CLAUDE_CONFIG_DIR=r,process.platform==="win32")Ct.CLAUDE_SECURESTORAGE_CONFIG_DIR=v?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??v?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let uv=new Mx({abortController:_,additionalDirectories:S,projectConfigRoot:y,agent:b,betas:A,cwd:U,debug:F,debugFile:ue,executable:D,executableArgs:K,extraArgs:nv?{...X,workload:nv}:X,pathToClaudeCodeExecutable:hy,env:Ct,forkSession:Ot,stderr:aJ,thinkingConfig:Mc,effort:_r,maxTurns:Si,maxBudgetUsd:ha,taskBudget:$p,model:zp,fallbackModel:pe,jsonSchema:av,permissionMode:sv,allowDangerouslySkipPermissions:tJ,permissionPromptToolName:nJ,permissionPrompts:rJ,continueConversation:wn?void 0:L,resume:rv,resumeSessionAt:oJ,resumeDropsTurn:sJ,sessionId:iJ,settings:typeof i==="object"?se(i):i,managedSettings:a?se(a):void 0,settingSources:l,skills:ov,allowedTools:C,disallowedTools:O,tools:T,mcpServers:lv,strictMcpConfig:lJ,canUseTool:!!w,hooks:!!ln,includeHookEvents:mt,includePartialMessages:Dt,persistSession:ns,sessionMirror:!!wn,plugins:Hp,pluginsViaInitialize:iv,sandbox:c,spawnClaudeCodeProcess:d.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),dJ={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:d.planModeInstructions,systemPromptSnapshot:g,appendSubagentSystemPrompt:d.appendSubagentSystemPrompt,toolAliases:d.toolAliases,excludeDynamicSections:m,agents:E,title:d.title,skills:ov,webSearchIsolationExemptMcpServers:d.webSearchIsolationExemptMcpServers,promptSuggestions:d.promptSuggestions,agentProgressSummaries:d.agentProgressSummaries,forwardSubagentText:wt,supportedDialogKinds:Yt,perTaskStopAffordance:cn,rapidFollowupPreempt:ts,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:cJ,plugins:iv?Hp:void 0,captureSdkMcpManifests:!Df("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},Sy=new cy(uv,n,w,ln,_,cv,av,dJ,Je,ev,tv,he,Zt,uJ);if(wn){let Jt=()=>ft(Ct.CLAUDE_CONFIG_DIR??ft(Up(),".claude"),"projects"),xn=my==="eager",Mr=new RE(async(ya,Ey)=>{let Nc=Vx(ya,Jt());if(Nc)await wn.append(Nc,Ey);else G(`[SessionStore] dropping mirror frame: filePath ${ya} is not under ${Jt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(ya,Ey)=>{let Nc=Vx(ya,Jt());if(Nc)Sy.reportMirrorError(Nc,Ey.message)},maxPendingEntries:xn?0:lu,maxPendingBytes:xn?0:wi});Sy.setTranscriptMirrorBatcher(Mr)}return{queryInstance:Sy,transport:uv,abortController:_,processEnv:Ct,verbatimPrompts:Zt}}function Yx(e,t,n,r){if(typeof t==="string")e.writeAfterInitialize(se({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,...r&&{client_composed:!0}})+`
|
|
164
164
|
`).catch((o)=>n.abort(o));else e.streamInput(t).catch((o)=>n.abort(o))}var YYe=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function py(e){for(let t=0;;t++)try{return await k9(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!YYe.has(fe(n)??""))return;await Vn((t+1)*100)}}function JYe(e,t){e.waitForExit().catch(()=>{}).finally(()=>py(t))}function XYe({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return QYe(e,t);let{queryInstance:n,abortController:r,verbatimPrompts:o}=Zx(t,{isSingleUserTurn:typeof e==="string"});return Yx(n,e,r,o),n}function QYe(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s,verbatimPrompts:i}=Zx({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),a=Fp(t.cwd??"."),l=t.sessionStore,c=t.loadTimeoutMs??60000,d=t.resume;return(async()=>{if(!d)d=(await or(l.listSessions(On(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 L9(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(()=>JYe(r,f))}if(!n.isClosed())r.spawn()}).catch((f)=>{let m=Wn(f);r.spawnAbort(m),n.setError(m)}),Yx(n,e,o,i),n}async function e4e(e={}){return(await N9(e)).warm}async function N9({options:e,initializeTimeoutMs:t=60000}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=Fp(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 or(e.sessionStore.listSessions(On(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 L9(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let g=function(){if(m)return;m=!0,p.close()},a=Zx(n&&r&&r!==e?.resume?{...e,resume:r}:e,{isSingleUserTurn:!1,resumeConfigDir:n});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(()=>py(S))})}let f=`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`;await or(p.initializationResult(),t,f).catch((S)=>{throw sP(S,f)?un(S,{telemetryMessage:`Subprocess initialization did not complete within ${t}ms`,errorClass:"initialize_timeout"}):S});let m=!1;return{warm:{query(S){if(m)throw Error("WarmQuery.query() can only be called once");m=!0;try{Yx(p,S,c,d)}catch(y){throw p.close(),y}if(typeof S==="string")p.setIsSingleUserTurn(!0);return p},close:g,async[Symbol.asyncDispose](){m=!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(()=>py(n))}throw await i,a}}async function t4e({options:e,initializeTimeoutMs:t=60000}={}){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(),w=C?.HOME?.trim(),L=C===void 0?vt():A||ft(w||Up(),".claude"),U=qx(L)?L:ft(Up(),".claude");if(!qx(U))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=ft(U,"spares");await dy(F,{recursive:!0,mode:448}),r=await $Ye(ft(F,"spare-"))}function o(){return n?k9(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 Vt("sdk_prewarm",async()=>{try{return await N9({options:{...i,cwd:r,extraArgs:{...i.extraArgs,"await-claim":null}},initializeTimeoutMs:t})}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,S,y=new Promise((C,A)=>{S={resolve:C,reject:A}});y.catch(()=>{});let b=c.waitForExit().then(()=>{return},()=>{return});b.then(()=>{if(!m)_=!0,S.reject(Error("spare_exited: the spare process exited before it was claimed")),f()});let E={claimed:y,exited:b,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 w=ZYe.filter((v)=>A.settings?.[v]!==void 0);if(w.length>0)throw new ve(`SpareProcess.claim(): hook settings (${w.join(", ")}) cannot be applied at claim, because the claimed folder's SessionStart hooks start with the 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 L=typeof A.cwd==="string"&&A.cwd.trim()!==""&&!I9.isAbsolute(A.cwd)&&!D9.isAbsolute(A.cwd)&&A.cwd!=="~"&&!A.cwd.startsWith("~/")?Fp(A.cwd):A.cwd;m=!0;let U=M9(A.workspaceTrust),F=l.claimSession({cwd:L,...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},...U?.accepted===!0&&{workspace_trust:U},sdk_mcp_servers:d}),ue=[];if(A.model!==void 0)ue.push(["model",l.setModel(A.model)]);if(A.maxThinkingTokens!==void 0)ue.push(["maxThinkingTokens",l.setMaxThinkingTokens(A.maxThinkingTokens)]);let O=A.settings!==void 0?l.applyFlagSettings(A.settings):void 0;if(O!==void 0)ue.push(["settings",O]);for(let[,v]of ue)v.catch(()=>{});function T(){c.endInput(),f()}if(F.then(async(v)=>{o();let D={cwd:v.cwd??L,sessionId:v.session_id,parkedMs:v.parked_ms,sdkMcpSettled:v.sdk_mcp_settled},K=await Promise.allSettled(ue.map(([,H])=>H)),X=K.flatMap((H,W)=>H.status==="rejected"?[`${String(ue[W][0])}: ${ot(H.reason)}`]:[]),pe=O===void 0?void 0:K[ue.findIndex(([H])=>H==="settings")];if(pe?.status==="rejected")g=!0,l.close(),S.reject(Object.assign(new ve(`settings_not_applied: ${ot(pe.reason)} — the prompt was not sent and the process was closed; start the session with query()`,"settings_not_applied"),{claim:D}));else if(X.length>0)S.reject(Object.assign(new ve(`option_not_applied: ${X.join("; ")} — the prompt was sent and the session runs without these options`,"option_not_applied"),{claim:D}));else S.resolve(D)},(v)=>{T(),S.reject(v)}),O===void 0)return a.query(C);return Promise.all([F,O]).then(()=>{if(g)return;try{a.query(C)}catch{}},()=>{}),l},close(){if(g)return;if(g=!0,m)l.close();else a.close(),S.reject(Error("spare_closed: the spare was closed before it was claimed"));f()},async[Symbol.asyncDispose](){E.close(),await f()}};return E}import{randomUUID as W9}from"crypto";import{constants as U9}from"fs";import{open as n4e,readdir as z9,rm as F9,stat as r4e}from"fs/promises";import{join as es}from"path";var o4e=64;function Xx(e){return Ee()?e:void 0}async function H9(e,t,n={},r){if(!je(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let o=se({type:"custom-title",customTitle:t.trim(),sessionId:e})+`
|
|
165
165
|
`;await G9(e,o,n,Xx(r))}async function j9(e,t,n={},r){if(!je(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let s=Ti(t).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");t=s}let o=se({type:"tag",tag:t??"",sessionId:e})+`
|
|
166
166
|
`;await G9(e,o,n,Xx(r))}async function B9(e,t={},n){if(!je(e))throw Error(`Invalid sessionId: ${e}`);let r=Xx(n);for(let o of await i4e(t,r)){if(Ee()&&r!==void 0){let a=Ii(o,r.isKeySegment);if(a!==void 0){if(await s4e(a,e,r))return;continue}}let s=es(o,`${e}.jsonl`),i;try{({size:i}=await r4e(s))}catch(a){let l=fe(a);if(l==="ENOENT"||l==="ENOTDIR")continue;throw a}if(i===0)continue;await F9(s,{force:!0}),await F9(es(o,e),{recursive:!0,force:!0});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 s4e(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 i4e(e,t){if(e.dir){let r=await vo(e.dir,lm(t,Ee())),o=await $9(r,t),s;try{s=await wo(r)}catch{s=[]}for(let i of s){if(i===r)continue;o.push(...await $9(i,t))}return o}let n=dt();if(Ee()&&t!==void 0){let r=await K9(t);if(r===void 0)return[];if(r.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return r.names.map((o)=>es(n,o))}try{return(await z9(n,{withFileTypes:!0})).filter((o)=>o.isDirectory()||o.isSymbolicLink()).map((o)=>es(n,o.name))}catch{return[]}}async function $9(e,t){let n=rn(t);if(n===void 0||!n.hoverRestOn)return qn(e);let r=await qn(e,n),o=ul(e),s=process.platform==="win32",i=[];for(let a of r)if(a===o||await dl(a,e,s,n))i.push(a);return i}async function K9(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=um(s,e.isKeySegment);if(i!==void 0)t.push(i)}n=o.value.cursor}while(n&&++r<o4e);return{names:t,laterPageFailed:Boolean(n)}}catch{return r===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function G9(e,t,n,r){let o=`${e}.jsonl`;if(n.dir){let a=await vo(n.dir,lm(r,Ee()));for(let c of await qn(a,rn(r)))if(await fy(es(c,o),t,Jx(c,e,r)))return;let l;try{l=await wo(a)}catch{l=[]}for(let c of l){if(c===a)continue;for(let d of await qn(c,rn(r)))if(await fy(es(d,o),t,Jx(d,e,r)))return}throw Error(`Session ${e} not found in project directory for ${n.dir}`)}let s=dt();if(Ee()&&r!==void 0){let a=await K9(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=es(s,c);if(await fy(es(d,o),t,Jx(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 z9(s)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let a of i)if(await fy(es(s,a,o),t))return;throw Error(`Session ${e} not found in any project directory`)}async function fy(e,t,n){if(Ee()&&n!==void 0)return a4e(n,t);let r;try{r=await n4e(e,U9.O_WRONLY|U9.O_APPEND)}catch(o){let s=fe(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 a4e({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 Jx(e,t,n){if(!Ee()||n===void 0)return;let r=Ii(e,n.isKeySegment);return r===void 0?void 0:{backend:n.backend,key:n.transcriptKey(r,t)}}async function l4e(e,t,n){if(n?.sessionStore)return d4e(n.sessionStore,e,t,n.dir);return H9(e,t,n)}async function c4e(e,t,n){if(n?.sessionStore)return p4e(n.sessionStore,e,t,n.dir);return j9(e,t,n)}async function u4e(e,t){if(!je(e))throw new ve(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=On(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return B9(e,t)}async function d4e(e,t,n,r){if(!je(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=On(r);await e.append({projectKey:o,sessionId:t},[{type:"custom-title",customTitle:n.trim(),sessionId:t,uuid:W9(),timestamp:new Date().toISOString()}])}async function p4e(e,t,n,r){if(!je(t))throw new ve(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(n!==null){let s=Ti(n).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");n=s}let o=On(r);await e.append({projectKey:o,sessionId:t},[{type:"tag",tag:n??"",sessionId:t,uuid:W9(),timestamp:new Date().toISOString()}])}async function jzt(e){return k4(e)}async function Gzt(e,t){if(t?.sessionStore)return A4e(t.sessionStore,e,t);return X0(e,t)}async function Wzt(e){if(e?.sessionStore)return E4e(e.sessionStore,e);return fF(e)}async function Vzt(e,t){if(t?.sessionStore)return R4e(t.sessionStore,e,t);return mF(e,t)}async function qzt(e,t){if(t?.sessionStore)return T4e(t.sessionStore,e,t);return vF(e,t)}async function Zzt(e,t,n,r){if(!je(e))throw new ve(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=Ee(),s=o?r:void 0,i=await As(e,n?.dir,Fn(s),o);if(!i)throw Error(`Session ${e} not found`);let a=On(n?.dir),l=n?.batchSize&&n.batchSize>0?n.batchSize:lu,c=s===void 0?void 0:Ii(h4e(i.filePath),Gt),d=s!==void 0&&c!==void 0?{backend:s,projectKey:c}:void 0;if(d!==void 0)await hR(d.backend,Pt.transcript(d.projectKey,e),{projectKey:a,sessionId:e},t,l);else await V9(i.filePath,{projectKey:a,sessionId:e},t,l);if(n?.includeSubagents===!1)return;if(d!==void 0){let m=await BF(d.backend,d.projectKey,e),g=await KF(d.backend,d.projectKey,e,m);for(let _ of m){let S={projectKey:a,sessionId:e,subpath:og(_)};await hR(d.backend,_.kind==="agent"?Pt.transcript(d.projectKey,e,_.agentId,_.agentRelPath):Pt.journal(d.projectKey,e,_.agentRelPath),S,t,l);let y=g.get(S.subpath),b;if(y!==void 0)try{b=Fe(y)}catch(E){G(`importSessionToStore: skipping unreadable sidecar for ${S.subpath}: ${E}`)}if(b!==void 0)await t.append(S,[{type:"agent_metadata",...b}])}return}let p=i.filePath.replace(/\.jsonl$/,""),f=q9(p,"subagents");for(let m of await S4e(f)){let g=_4e(p,m).split(y4e);g[g.length-1]=g.at(-1).replace(/\.jsonl$/,"");let _={projectKey:a,sessionId:e,subpath:g.join("/")};await V9(m,_,t,l);let S=m.replace(/\.jsonl$/,".meta.json"),y;try{y=Fe(await g4e(S,"utf8"))}catch(b){if(!tt(b))G(`importSessionToStore: skipping unreadable sidecar ${S}: ${b}`)}if(y!==void 0)await t.append(_,[{type:"agent_metadata",...y}])}}async function V9(e,t,n,r){let o=[],s=0;for await(let i of wD(f4e(e,{encoding:"utf8"}))){if(!i)continue;try{o.push(Fe(i))}catch(a){G(`importSessionToStore: skipping unparseable line in ${e}: ${a}`);continue}if(s+=i.length,o.length>=r||s>=wi)await n.append(t,o),o=[],s=0}if(o.length>0)await n.append(t,o)}async function S4e(e){let t=[];async function n(r){let o;try{o=await m4e(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=q9(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 Yzt(e,t){if(t?.sessionStore)return O4e(t.sessionStore,e,t.dir);return $F(e,t)}async function Jzt(e,t,n){if(n?.sessionStore)return w4e(n.sessionStore,e,t,n);return zF(e,t,n)}function Z9(e){return e.map((t)=>se(t)).join(`
|