@anthropic-ai/claude-agent-sdk 0.3.305 → 0.3.306

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
3
3
 
4
- // Version: 0.3.305
4
+ // Version: 0.3.306
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 s2e(e){return ld(se(e))}function i2e(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 a2e(e){return yi($Z(e))}function $Z(e){return{shellSettings:e.shellSettings,envVars:e.envVars,sandboxSettings:Object.keys(e.sandboxSettings).length>0?e.sandboxSettings:void 0,...vZ(e),hooks:e.hooks,payloadSlots:gx(e).length>0?Object.fromEntries(gx(e).map(([t,n])=>{let{isolationSettings:r,...o}=n;return[t,{...o,...vZ(n)}]})):void 0}}function vZ(e){return Object.keys(e.isolationSettings).length>0?{isolationSettings:e.isolationSettings}:{}}function yi(e){return se(fp(e))}function zZ(e){return ld(a2e(e))}function HZ(e,t,n){if(zZ(t)===e)return!0;return typeof n==="string"&&n.length>0&&ld(yi({...$Z(t),claudeMd:n}))===e}function kZ(e,t,n){return se([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}var l2e=new Set(["dns","unix","ipv4","ipv6"]),CLt=new Set([...l2e,"http","https","ws","wss","ftp","file","grpc","grpcs","otlp","xds","tcp","udp","tls","h2","h2c","http2"]);function jZ(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function c2e(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of Rc){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var d2e="remote-settings.json",p2e=5000;var VZ="remote-settings-helper-consent";function f2e(){return WZ(It(),VZ)}function m2e(e){let t=PZ(e);return FZ(t)?t:void 0}function g2e(e){let t=sa(e,(n,r)=>r.startsWith("$")&&r!=="$schema");if(Object.keys(t).length!==Object.keys(e).length)qZ.set(t,e);return t}function BZ(e){return qZ.get(e)??e}var qZ=new WeakMap;class ZZ{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;hybridBlockFilter=null;hybridLeftOut=null;lastLoadStatus=void 0;loadCycleEnded=!1;loadCycleBegun=!1;lastLoadStatusChanged=ze();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&&!Yo())return e;if(e!==null){let n=FO(this.coworkCloudHolds,e);return this.coworkCloudHolds=n_(n),n}return t?this.coworkCloudHolds:null}replaceSessionCache(e,t){let n=t?.verified===!0||!Yo();if(!n&&e!==null&&e===this.sessionCache)return;let r=this.heldSoFar(n?b2e(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?FO(this.coworkCloudHolds,e):e;this.sessionCache=t,this.seedConsentBaseline(t)}seedConsentBaseline(e){let t=m2e(e);if(t!==void 0){let n=T2e();if(n===void 0||!HZ(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.hybridBlockFilter=null,this.hybridLeftOut=null,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){K(`Remote settings: load-status listener threw: ${rt(t)}`,{level:"error"})}}}var h2e=new Ie(()=>new ZZ);function _o(){return h2e.of(nn().host)}function YZ(){return _o().lastLoadStatus}function Oc(){return}function _2e(){return _o().evalPolicySnapshotOnly}function _x(){return Je()||_2e()}function JZ(e){let{projectedView:t,projectedParse:n}=_o();return e!==null&&(t?.view===e||n?.view===e||y2e(e))}function y2e(e){return Yo()&&Object.keys(e).length>0&&Gt(n_(e),e)}var S2e=[["allowedHttpHookUrls"],["httpHookAllowedEnvVars"],["isolation","required"]],XZ=[{path:["sandbox","credentials","files"],names:"path"},{path:["sandbox","credentials","envVars"],names:"name"}];function QZ(e){for(let n of S2e)cn(e,n,void 0);for(let{path:n,names:r}of XZ){let o=Tt(e,n),s=(Array.isArray(o)?o:[o]).flatMap((i)=>ie(i)&&typeof i[r]==="string"?[{[r]:i[r],mode:"deny"}]:[]);cn(e,n,s.length>0?s:void 0)}for(let n of[["permissions","deny"],["permissions","ask"]]){let r=Tt(e,n);if(Array.isArray(r)){let o=r.filter((s)=>typeof s!=="string"||!lp.test(s));cn(e,n,o)}}for(let{path:n,restrictive:r}of mo()){let o=Tt(e,n),s=n[0]==="strictPluginOnlyCustomization"?o:Ec(o);if(r===!0&&s===!1)cn(e,n,void 0)}let t=e.strictPluginOnlyCustomization;if(Array.isArray(t)&&!t.some((n)=>Rp.includes(n)))delete e.strictPluginOnlyCustomization;if(e.availableModelsMatch==="prefix")delete e.availableModelsMatch}function eY(e){let t={...WO(e)};if(QZ(t),e.parentSettingsBehavior==="merge")t.parentSettingsBehavior="merge";let n=Object.fromEntries([...eW,dc].flatMap((s)=>Object.entries(e.pluginConfigs?.[s]?.options??{}))),r=UO({pluginConfigs:{[dc]:{options:n}}});if(r!==void 0)t.pluginConfigs=r;let o=Object.entries(e.enabledPlugins??{}).filter(([s,i])=>i===!1&&!(s.includes("@")&&wZ(s.slice(s.lastIndexOf("@")+1))===OZ));return o.length===0?t:{...t,enabledPlugins:Object.fromEntries(o)}}function KZ(e){if(!e||!_x())return e;let t={...WO(e)};if(Je()){if(QZ(t),e===_o().verifiedPayload&&typeof e.claudeMd==="string"&&e.claudeMd!=="")t.claudeMd=e.claudeMd}return{...t,managedSourcesBehavior:"merge"}}function E2e(){return FV(()=>Yo()||rn.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST&&ZG.has(rn.CLAUDE_CODE_ENTRYPOINT??"")||Qh())}function tY(){return Oc()??WZ(It(),d2e)}var nY=8388608;function b2e(e){if(e===null||!Yo())return e;let t=n_(e);return Gt(t,e)?e:t}function C2e(){if(E2e())return null;let e=_o(),t=e.storedCopyRefusal;if(t!==null&&$O()&&Date.now()-t.atMs<p2e)return e.storedCopyTrust={trusted:!1,reason:t.reason},null;e.storedCopyTrust="not_asked";try{let n=O2e();if(n===null)return null;let r=$e(lc(n));if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=g2e(r);return A2e(o)?o:null}catch(n){if(hG(n))K(`Remote settings: Disk cache exceeds ${nY} bytes; ignoring it as if absent`);return null}}function A2e(e){let t=_o();if(!$O()||!t.storedCopyGateCovers||Oc()!==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=IV({kind:"managed-settings",cachePath:tY(),body:BZ(e),bodySha:_V(BZ(e)),account:t.storedAccountReader?.(),pinnedOrgs:r.orgs,nowMs:Date.now(),roots:NV()});if(o.trusted)return t.storedCopyTrust=o,!0;n=o.reason}catch(o){K(`Remote settings: the gate on a stored copy failed: ${rt(o)}`,{level:"error"}),n="error"}return t.storedCopyTrust={trusted:!1,reason:n},t.storedCopyRefusal={atMs:Date.now(),reason:n},t.seedConsentBaseline(e),K(`Remote settings: the stored copy is not trusted at rest (${n}); treating it as absent`),!1}var R2e=4096;function T2e(){let e=yx();if(e!==void 0)return e.attestation;if(Je())return;try{return ci(f2e(),R2e).trim()||void 0}catch{return}}function O2e(){let e=yx();if(e!==void 0)return e.content;if(Je()&&Oc()===void 0)return null;return ci(tY(),nY)}function yx(){let e=_o().backendView;if(!be()||e===void 0||!e.ready||e.stoodDown||Oc()!==void 0)return;if(!XP(e.configHome)){e.standDown("config home changed");return}return e}var _Mt=Lt.state("remote-settings"),yMt=Lt.state(VZ);var w2e=new Set([...o2,"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",...YO,...JO,"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",...tw,...nw,...rw,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...XO,"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 x2e(e){if(!e||!e.env&&!("managedMcpServers"in e))return e;let{managedMcpServers:t,...n}=e;return e.env?{...n,env:sa(e.env,(r,o)=>w2e.has(o.toUpperCase()))}:n}function rY(){let e=sY();if(e===null||_x()||oY(_o(),e))return!1;if(GZ(e))return!0;let t=hx(e);if(t.length===0)return!1;let{chain:n}=SZ();return t.some(([r,o])=>{let s=DZ(r);return(s===void 0||n.includes(s))&&GZ(o)})}function GZ(e){let t=e.managedMcpServers;return ie(t)&&Object.keys(t).length>0}function oY(e,t){return t===e.verifiedPayload||Boolean(Oc())}function sY(){let e=_o();if(!Oc()&&e.eligible!==!0)return e.heldSoFar(null);if(e.sessionCache)return e.sessionCache;let t=yx()!==void 0,n=C2e();if(n){if(e.seedFromDisk(n),t)Jo().invalidatePolicyLayer();else rW();return e.sessionCache}return e.heldSoFar(null)}function iY(e){let t=sY(),n=_o(),r=oY(n,t)?t:v2e(n,t);if(r===null||!_x())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(aY(s,KZ(e(r))??{}),Je())for(let{path:i,names:a}of XZ){let l=[o,s].flatMap((c)=>Tt(c,i)??[]);if(l.length>0)cn(s,i,gV(l,a))}n.projectedParse={raw:r,view:s}}return n.projectedParse.view}function aY(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(o!==r&&ie(o)&&ie(r)){let s={...o};aY(s,r),e[n]=s}else e[n]=r}}function v2e(e,t){if(t===null)return null;if(e.unverifiedView?.raw!==t)e.unverifiedView={raw:t,view:x2e(t)};return e.unverifiedView.view}var k2e=wt(new Set,(e)=>e.clear());function lY(e){k2e.add(e)}var P2e=process.platform==="darwin"?16777216:process.platform==="linux"||process.platform==="android"?524288:0,CMt=process.platform==="darwin"?536870912:0,AMt=process.platform==="linux"||process.platform==="android"?2097152:0;var IMt=wt({noFollowAny:"untried",localVolumes:void 0},(e)=>{e.noFollowAny="untried",e.localVolumes=void 0});var DMt=Symbol("no procfs"),LMt=Symbol("descriptor path unreadable");var MMt=Symbol("boundRead.linkToNothing");var cY=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var I2e=["userSettings","projectSettings","localSettings"],D2e=["projectSettings","localSettings"],WMt=new Set(D2e),L2e={userSettings:"user",projectSettings:"project",localSettings:"local"},VMt=I2e.map((e)=>[L2e[e],e]);var uY="--settings (inline JSON)";var dY=["auto","bypassPermissions"];function pY(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 fY=["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"],mY=["sonnet","opus","haiku","fable","best","sonnet[1m]","opus[1m]","fable[1m]","opusplan"],Si=["sonnet","opus","haiku","fable"];function ey(e){return mY.includes(e)}function Sx(e){return e.replace(/\[1m\]$/i,"")}function gY(e){return e.replace(/\[(1|2)m\]/gi,"")}function fa(e){return Si.includes(e)}function ts(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&&!nL.includes(a))return null;t=l}let o=N2e(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(!M2e(s))i.trailer=s;else{let a=/(?:-v\d+@|[-@])(\d{8})/.exec(s)?.[1];if(a!==void 0)i.date=a}return i}function M2e(e){return/^(?:-fast|-latest)?(?:-v\d{1,3}@\d{8}|[-@]\d{8})?(?:-v\d{1,3}(?::\d{1,3})?)?$/.test(e)}function hY(e,t){return e.major-t.major||(e.minor??0)-(t.minor??0)}function N2e(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 or(e){let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g,"?");return t.length>128?`${t.slice(0,128)}…`:t}function U2e(){let e=[...Si],t=e.pop();return e.length===0?t??"":`${e.join(", ")} or ${t}`}function ty(e){return e.charAt(0).toUpperCase()+e.slice(1)}function _Y(e){let t=e.trim().toLowerCase(),n=gY(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(fa(n))return{entry:{kind:"family",family:n},...r!==""&&{warning:`"${or(e)}" blocks every ${ty(n)} model.${r}`}};if(ey(n)||n==="default")return{entry:null,warning:`"${or(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=ts(n),s=o!==null||n.startsWith("claude-")?n:`claude-${n}`,i=o??(s!==n?ts(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!==""?` "${or(l)}" is ignored.`:"";return{entry:{kind:"model",id:i},...(r!==""||c!=="")&&{warning:`"${or(e)}" blocks ${F2e(i)}.${c}${r}`}}}return{entry:{kind:"literal",value:n},warning:$2e(e,n)}}function F2e(e){let t=ty(e.family);return e.minor===void 0?`every ${t} ${e.major}.x model`:`${t} ${e.major}.${e.minor} in every spelling and snapshot`}function $2e(e,t){let n=`"${or(e)}" blocks only the exact model name "${or(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(ts(s)!==null)return`${n} To block a version, write it with a hyphen: "${or(s)}".`}let o=new RegExp(`^(${Si.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 ${ty(s)} ${i}.x model.`}if(/^[a-z]+$/.test(t)){let s=Si.find((i)=>pY(t,i,1)===1);return s!==void 0?`${n} If you meant the ${ty(s)} family, write "${s}".`:`${n} To block a model family other than ${U2e()}, list its versioned IDs.`}return n}function yY(e){let t=Sx(e.trim().toLowerCase());if(t==="")return{kind:"ignored"};if(fa(t))return{kind:"family",family:t};let n=t.startsWith("claude-")?t.slice(7):"";if(fa(n))return{kind:"family",family:n};if(ey(t)||t==="default")return{kind:"ignored"};let r=ts(t)!==null||t.startsWith("claude-")?t:`claude-${t}`,o=ts(r);return o!==null?{kind:"model",id:o,latest:H2e(r,o),spelling:r}:{kind:"literal",value:t}}function z2e(e,t){let n=e.toLowerCase(),r=n.lastIndexOf(t.base);return r===-1?"":n.slice(r+t.base.length)}function H2e(e,t){return t.trailer===void 0&&z2e(e,t).startsWith("-latest")}function j2e(e,t){for(let n of t){if(fa(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 B2e(e){return e.charAt(0).toUpperCase()+e.slice(1)}function SY(e){let t;for(let n of fY){let r=ts(n);if(r!==null&&r.family===e&&!r.legacyVersionFirst&&(t===void 0||hY(r,t)>0))t=r}return t?.base}function EY(e,t){let n=yY(e);switch(n.kind){case"ignored":{if(e.trim()==="")return"An empty availableModels entry was ignored.";let r=SY("opus");return`"${or(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)=>yY(s).kind!=="ignored").map((s)=>Sx(s.trim().toLowerCase()));if(fa(e.trim().toLowerCase())&&j2e(n.family,r))return;let o=SY(n.family);return`"${or(e)}" in availableModels allows every ${B2e(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 K2e(e,n.value)}}function K2e(e,t){let n=`"${or(e)}" in availableModels allows only a model named exactly "${or(t)}".`,r=t.replace(/(\d)\.(\d)/g,"$1-$2");if(r!==t){let s=r.startsWith("claude-")?r:`claude-${r}`;if(ts(s)!==null)return`${n} To allow a version, write it with a hyphen: "${or(s)}".`}let o=new RegExp(`^(${Si.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 G2e(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function bY(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&G2e(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}var W2e=["allowManagedMcpServersOnly","allowedMcpServers","deniedMcpServers","disabledMcpjsonServers","enabledMcpjsonServers","enableAllProjectMcpServers","disableClaudeAiConnectors","managedMcpServers"];function ny({slot:e,adminTiers:t}){return e?.allowManagedMcpServersOnly===!0||t.some((n)=>n.allowManagedMcpServersOnly===!0)}function Ex({slot:e,adminTiers:t}){return e?.allowedMcpServers??t.find((n)=>n.allowedMcpServers!==void 0)?.allowedMcpServers}function CY(e,t){return W2e.filter((n)=>e[n]!==void 0&&!V2e(n,e,t))}function V2e(e,t,n){let r=n.slot??{};switch(e){case"deniedMcpServers":return!0;case"allowManagedMcpServersOnly":return t.allowManagedMcpServersOnly===ny(n);case"disableClaudeAiConnectors":return t.disableClaudeAiConnectors===(r.disableClaudeAiConnectors===!0||n.adminTiers.some((o)=>o.disableClaudeAiConnectors===!0));case"allowedMcpServers":return Gt(t.allowedMcpServers,ny(n)?Ex(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)&&Gt(o[s],i))}}}import{userInfo as q2e}from"os";var AY="com.anthropic.claudecode",ry="HKLM\\SOFTWARE\\Policies\\ClaudeCode",oy="HKCU\\SOFTWARE\\Policies\\ClaudeCode",xp="Settings",Cx="/usr/bin/plutil",RY=["-convert","json","-o","-","--"],TY=["-lint","-s","--"],OY=5000,sy=2097152,Ei="/mnt/c/Windows/System32/reg.exe",Tn="/mnt/c/Program Files/ClaudeCode",bx=wt({isCoworkCloud:void 0},(e)=>{e.isCoworkCloud=void 0});function Ax(){if(bx.isCoworkCloud===void 0){let e=process.env.CLAUDE_CODE_ENTRYPOINT;bx.isCoworkCloud=Xh.some((t)=>t===e)}return bx.isCoworkCloud}function vp(){if(process.platform!=="linux")return!1;let e=Ax();if(process.env.WSL_DISTRO_NAME&&!e)return!0;try{let t=$J("fs").readFileSync("/proc/version","utf8").toLowerCase();return ol(t)}catch{return!1}}function wY(){let e="";try{e=q2e().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${AY}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${AY}.plist`,label:"device-level managed preferences"}),t}var xY=512;function Rx(e){return e.map(Z2e)}function Z2e(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:E,suggestion:b,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:kp(S),message:kp(y),expected:E===void 0?void 0:kp(E),suggestion:b===void 0?void 0:kp(b),invalidValue:typeof C==="string"?kp(C):void 0}}function kp(e){let t=jZ(e.replace(/\s+/gu," "));return t.length>xY?`${t.slice(0,xY-1)}…`:t}function vY(e,t){if(t===null)return e;let n=[...t.values];return{settings:un(Kn(e.settings,n.filter(([,r])=>r===void 0).map(([r])=>r)),ir(Object.fromEntries(n.filter(([,r])=>r!==void 0))),(r,o)=>o),errors:[...e.errors,...t.errors]}}var ns="https://code.claude.com/docs/en",Y2e=[{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:`${ns}/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:`${ns}/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:`${ns}/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:`${ns}/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:`${ns}/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:`${ns}/iam#working-directories`}}],J2e={permissions:`${ns}/iam#configuring-permissions`,env:`${ns}/settings#environment-variables`,hooks:`${ns}/hooks`};function kY(e){let t=Y2e.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=J2e[bE(e.path,".")];return n}var rUt=k(()=>sx(Cc(),{strictPolicyHelperKeys:!0}).strict());function PY(e){return e.code==="invalid_type"}function IY(e){return e.code==="invalid_value"}function X2e(e){return e.code==="unrecognized_keys"}function DY(e){return e.code==="too_small"}var Q2e='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 NY(e){return e.map((t)=>t.severity!=="warning"&&t.message.includes(es)?{...t,message:t.message.replace(es,()=>Q2e),loadedWithoutGuardHook:!0}:t)}function On(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function LY(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Pp(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(IY(r))a=r.values.map((f)=>String(f)),l=a.join(" | "),c=void 0,d=void 0;else if(PY(r)){l=r.expected;let f=LY(r.message);c=f??On(r.input),d=f??On(r.input)}else if(DY(r))l=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,d=c;let p=kY({path:o,code:r.code,expected:l,received:c,enumValues:a,message:r.message,value:c});if(IY(r))i=a?.map((f)=>`"${f}"`).join(", "),s=`Invalid value. Expected one of: ${i}`;else if(PY(r)){let f=LY(r.message)??On(r.input);if(r.expected==="object"&&f==="null"&&o==="")s="Invalid or malformed JSON";else s=`Expected ${r.expected}, but received ${f}`}else if(X2e(r)){let f=r.keys.join(", ");s=`Unrecognized ${Es(r.keys.length,"field")}: ${f}`}else if(DY(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 eqe(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=Vw(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 cx("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 tqe=new Set(Vo);function nqe(e,t){if(!e||typeof e!=="object")return[];return[...j2(e,B2)?[{file:t,path:"hooks",message:`PreToolUse/PermissionRequest hooks are declared outside "hooks" (at the top level or under another key) — ${es}.`,severity:"fatal",docLink:"https://code.claude.com/docs/en/hooks"}]:[],...rqe(e,t)]}function rqe(e,t){if(!("hooks"in e))return[];if(e.hooks===null||typeof e.hooks!=="object"||Array.isArray(e.hooks)){let o=On(e.hooks);if(Array.isArray(e.hooks)&&(e.hooks.some(ie)||Cw(e.hooks)))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o} — ${es}.`,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(I_(n))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received a single matcher — ${es}.`,docLink:"https://code.claude.com/docs/en/hooks"}];let r=[];for(let o of Object.keys(n)){let s=Yf(o);if(!tqe.has(o)){if(la(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 — ${es}.`,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: ${Vo.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=On(i);if(yp.has(o)&&i!==null||la(i,3,{matchersCount:!1})){r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a} — ${es}.`,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}=G2(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} — ${es}.${l.aboutType?` Valid types: ${[...P_()].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: ${[...P_()].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 oqe=[{key:"allowedMcpServers",schema:W_},{key:"deniedMcpServers",schema:V_}];function sqe(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of oqe){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 ${On(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 iqe=["strictKnownMarketplaces","blockedMarketplaces"];function aqe(e){if(!ie(e))return;for(let t of Y_())if(e[t]===null)delete e[t]}function lqe(e,t,n){if(!ie(e))return[];let r=[];for(let o of iqe){let s=e[o];if(!Array.isArray(s))continue;let i=[],a=[];for(let l=0;l<s.length;l++){let c=Ep().safeParse(s[l]);if(!c.success){i.push(s[l]),a.push(l);continue}let d=lx(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 cqe(e,t){if(!ie(e)||e.managedMcpServers===void 0)return[];let r=[],o=x_(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 uqe(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 dqe(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(jw)}function pqe(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=On(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=Qw().safeParse(s[a]),c,d=!1;if(!l.success){let p=uqe(s[a]);if(p!==void 0&&!Rq.has(p)||dqe(s[a]))continue;c=N_(l.error.issues)}else if(l.data.source.source==="settings"&&l.data.source.name!==a)c=`key "${go(a)}" must match the settings source name "${go(l.data.source.name)}"`;if(c!==void 0)i.push({file:t,path:`${r}.${go(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 fqe(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: ${On(o.options)}`:On(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=On(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=nx().safeParse(i[l]);if(c.success){a.push(i[l]);continue}s.push({file:t,path:`${r}.options.${l}`,message:`${gqe(c.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:On(i[l])})}if(a.length!==i.length)o.options=a;return s}function mqe(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 ${On(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!tx().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 ${On(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let l of Object.keys(a)){let c=ex().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.${go(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 gqe(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function hqe(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||_qe(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[Eqe(o,t,n?.policySource===!0)]}function _qe(e){return typeof e==="string"&&Tp.includes(e)}var yqe="crossSessionInbound";function Sqe(e){let t=Tp.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${go(e).replace(/^<key>$/,"<value>")}"`:On(e);return`must be one of ${t}; received ${n}`}function Eqe(e,t,n=!1){let r=Tp.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:yqe,message:`"crossSessionInbound" ${Sqe(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}var MY="remoteControl.shareHostProfile";function bqe(e,t,n){if(!ie(e)||e.remoteControl===void 0)return[];let r=n?.policySource===!0,o=G_.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:MY,message:`${f}. ${s}`,severity:"warning",expected:o,...r?{statusOnly:!0}:{preserveOnWrite:!0}}),a=(f)=>typeof f==="string"?`"${go(f).replace(/^<key>$/,"<value>")}"`:On(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)=>`"${go(f)}"`).join(", ")} (its only key is "shareHostProfile")`))}let p=l.shareHostProfile;if(p!==void 0&&!(typeof p==="string"&&G_.includes(p))){if(r)l.shareHostProfile="off";else delete l.shareHostProfile;c.push(i(`"${MY}" must be one of ${o}; received ${a(p)}`))}return c}var Cqe=["enabledMcpjsonServers","disabledMcpjsonServers"],Aqe=/^[A-Za-z0-9_-]+$/;function Rqe(e){if(!ie(e))return;for(let t of Cqe){let n=e[t];if(typeof n==="string"&&Aqe.test(n))e[t]=[n]}}function Ip(e,t,n){let r=[...xZ(e,t)];if(aqe(e),!n?.policySource)Rqe(e);return r.push(...eqe(e,t,{policySource:n?.policySource,strictParseFollows:n?.mcpServerEntrySalvageOnly}),...nqe(e,t),...pqe(e,t),...fqe(e,t),...mqe(e,t),...hqe(e,t,{policySource:n?.policySource}),...bqe(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:sqe(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly}),...n?.mcpServerEntrySalvageOnly?cqe(e,t):[],...n?.mcpServerEntrySalvageOnly?lqe(e,t,n.marketplacePatternIndexMapOut):[]),r}function Px(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),cY.filter((n)=>t.has(n))}function xqe(){return Bt(di(),"managed-settings.json")}function UY(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:fn(o);return{...t,path:fn(t.path),message:fn(t.message),...t.expected!==void 0&&{expected:fn(t.expected)},...t.suggestion!==void 0&&{suggestion:fn(t.suggestion)},...r&&(o===void 0||typeof n==="string"||s!==o)&&{invalidValue:s}}})}function Ix(e){if(e.diskless)return{settings:null,errors:[],documentHasPolicyContent:!1,loadState:"absent"};let t,n=(E)=>{if(E===o4)return!0;return t??=e.asksOrganization?.()===!0,t&&E()},r=!1,o={},s=new Set,i=$Y(e,(E,b,C)=>{if(E.settings===null){if(!n(C))return E;return By.forEach((A)=>s.add(A)),{...E,errors:UY(E.errors)}}if(!n(C))return Object.assign(o,pi(E.settings,_i)),E;return r=!0,{...E,settings:{},errors:UY(E.errors)}});if(!r)return s.size===0?i:{...i,lostSignInPins:[...s]};let a=[],l=[],c=$Y(e,(E,b,C)=>{if(E.settings===null||!n(C))return{...E,settings:E.settings&&{},errors:[]};let A=vqe(E,E.settings,b);for(let w of By)if(E.settings[w]!==void 0&&A.settings?.[w]===void 0)s.add(w);return a.push([b,Object.keys(A.settings??{})]),l.push(...A.errors.slice(E.errors.length)),A}),d=[...i.errors,...l],p=i.settings??{},f=c.settings??{},m=!wc({...i,settings:p})&&{heldOnly:!0};if(Object.keys(f).length===0)return{...i,errors:d,...m,lostSignInPins:[...s]};let g=Object.keys(p).length===0,_={...g?f:Kn(vx([p,f],"merge",!1,0).admin,"parentSettingsBehavior"),...pi(p,"parentSettingsBehavior"),...o},S=_,y=p;for(let[E,b]of a)for(let C of b)if(C in y&&Gt(S[C],y[C]))d.push({file:E,path:fn(C),message:`In a cloud session that takes its managed settings from your organization, a managed settings file may only restrict: "${fn(C)}" was ignored in ${fn(E)}, since another managed settings document sets it and this one adds nothing to it.`,severity:"warning",statusOnly:!0,userWritable:!0});return{...g?c:i,settings:_,errors:d,...m,lostSignInPins:[...s],...!Dc(p)&&{onlyHeldContent:!0},settingsNotHeld:p,heldOffPlugins:Object.keys(f.enabledPlugins??{}).filter((E)=>p.enabledPlugins?.[E]===void 0),heldAllowLists:Fx.filter((E)=>f[E]!==void 0&&p[E]===void 0)}}function vqe(e,t,n){let r=eY(t),o=kqe(t,r).map((s)=>({...s,key:fn(s.key)}));if(o.length===0)return e;if(!FY.has(n))FY.add(n),K(`${fn(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})=>!Ci(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 ${fn(n)}.`,severity:"warning",statusOnly:!0,userWritable:!0}))]}}function kqe(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(Gt(o,s))return[];if(!ie(o)||!ie(s))return[{key:r,became:n(s,r)}];return Object.keys(o).filter((i)=>!Gt(o[i],s[i])).map((i)=>({key:`${r}.${i}`,became:n(s[i],r)}))})}function r4(e){return xt()==="wsl"&&(!e||fx())}var FY=wt(new Set,(e)=>e.clear());function $Y(e,t){let n=e.mdm?.()?.heldDocuments??[];if(r4(e.asksOrganization?.()===!0)){let r=ha(Mx({...e,file:()=>({settings:null,errors:[]})}));if(e.wslInherits?.()){let o=n.length===0?void 0:r||ha(Dp(Tn,e.store)),s=Dp(Tn,e.store,t,o?n:[]);if(o??(ha(s)||r))return s;let i=Dp(di(),e.store,t,n);return{...i,errors:[...s.errors,...i.errors],loadState:yo(s.loadState,i.loadState)}}if(r)return Dp(null,e.store,t,n)}return Dp(di(),e.store,t,n)}var o4=()=>!0;function Tx(e,t,n){n.push(...t.errors);let{settings:r}=t;if(!r||Object.keys(r).length===0)return;for(let[o,s]of J_){let i=o.split(".");if(Tt(r,i)===void 0)continue;let a=t.errors.find((d)=>d.substituted&&d.path===o),l=a!==void 0,c=Tt(e.merged,i);if(l&&c!==void 0&&!e.floors.has(o)){let d=i.at(-1);if(s.inert.has(s.read(c))){oV(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=un(e.merged,r,Fr),e.found=!0,Dc(r)&&!t.errors.some((o)=>o.onlySubstitutes))e.authored=!0}function Dx(e){return e.endsWith(".json")&&!e.startsWith(".")}function Pqe(e){return(e.isFile()||e.isSymbolicLink())&&Dx(e.name)}function zY(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:xt()!=="windows"&&!n.startsWith(Tn)};return o.note(n,$k({...s,linked:e.managedDocumentLinks.isLinked(n)})),()=>Lx(e,n,s.file,s.folder)}function Lx(e,t,n,r){let o=process.geteuid?.(),s=process.getuid?.();if(r4(!0)&&(t===Ei||t.startsWith(`${Tn}${wqe}`)))return HY;if(o===0||s===0)return!0;if(xt()==="windows"||o===void 0)return HY;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(LO(l,n,a===null?r:n)!==!1||a?.kind==="unverified")return!0;let d=e.policy.writableNow??=new Map,p=d.get(t)??DO(t);if(d.set(t,p),p!=="no")return!0;let f=e.policy.walkedDocuments??=new Map,m=f.get(t)??GG(t,l,e.policy.certainDirectories??=new Map);return f.set(t,m),m}var HY=!1;function jY(e,t,n,r){let o=e.managedDocumentLinks;o.noteWalked(Bt(t,...n),()=>$G(t,n,r,o.folderIsLink,e.managedFileProtections.folderOwners))}function Dp(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)Tx(s,n(f,p,o4),o),i||=xc(f),a=yo(a,bi(f));if(e===null)return BY(s,o,i,a,t);let l=vc(Bt(e,"managed-settings.json"),t,void 0,!0),c=()=>!1;if(bi(l)!=="absent")jY(t,e,["managed-settings.json"]),c=zY(t,vt(e),Bt(e,"managed-settings.json"),l.fileOwner);Tx(s,n(l,Bt(e,"managed-settings.json"),c),o),i||=xc(l),a=yo(a,bi(l));let d=Bt(e,"managed-settings.d");try{let p=t.folderListingForPolicyWalk(d),f,m;if(p!==void 0)f=p;else{let g=xe().readdirSync(d).filter(Pqe);f=g.map((_)=>_.name).sort(),m=new Set(g.filter((_)=>!_.isFile()).map((_)=>_.name)),t.noteWalkListing(d,f)}for(let g of f){let _=vc(Bt(d,g),t,void 0,!0),S=()=>!1;if(bi(_)!=="absent")jY(t,e,["managed-settings.d",g],m?.has(g)),S=zY(t,d,Bt(d,g),_.fileOwner);Tx(s,n(_,Bt(d,g),S),o),i||=xc(_),a=yo(a,bi(_))}}catch(p){let f=fe(p);if(f!=="ENOENT"&&f!=="ENOTDIR")K(`managed-settings.d read failed: ${p}`,{level:"error"}),o.push(Fp(d,p,"directory")),a="didNotLoad",n({settings:null,errors:[]},d,()=>!0)}return BY(s,o,i,a,t)}function BY(e,t,n,r,o){let s=e.found&&Ic(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&&Dc(s)&&{onlySubstitutes:!0}}}function Iqe(e,t){if(ot(e))zqe(t);else K(fn(`settings file read failed at ${t}: ${e}`),{level:"error"})}function vc(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{...s,settings:s.settings?ir(s.settings):null};let i=Uqe(e,n,r);return t.parsedFiles.set(o,i),{...i,settings:i.settings?ir(i.settings):null}}function Mx(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:Bqe(t,()=>Nx(e),()=>e.file?.()??Ix(e)),documentHasPolicyContent:xc(t),loadState:bi(t),...t.onlySubstitutes&&{onlySubstitutes:t.onlySubstitutes}}}function Np(e,t){let n=GY.get(e),r=n?.get(t);if(r)return KY(r);let o=Dqe(e,t);if(n)n.set(t,o);else GY.set(e,new Map([[t,o]]));return KY(o)}function KY(e){return{settings:e.settings&&ir(e.settings),errors:e.errors.map((t)=>({...t})),documentHasPolicyContent:e.documentHasPolicyContent,loadState:e.loadState,removed:e.removed,...e.onlySubstitutes&&{onlySubstitutes:e.onlySubstitutes}}}var GY=new WeakMap;function Dqe(e,t){let n=ir(e),r=Ip(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=px(l4(t,o),t,n).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...Pp(s.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad",removed:[]};let i=[...y4(r,s.data,o),...o],a=e,l=Object.keys(s.data).length>0?s.data:null;return{settings:l,errors:i,documentHasPolicyContent:E4(e,s.data),loadState:"loaded",removed:Object.keys(a).filter((c)=>s4(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 s4(e,t){let n=Y_();return n.includes(e)||Rc.some(({alias:r,canonical:o})=>r===e&&n.includes(o))?dx(e,t):X_(e)&&i4(e,t)}function i4(e,t){return t===null||ie(t)&&Object.keys(t).length>0&&Object.entries(t).every(([n,r])=>{let o=`${e}.${n}`;return dx(o,r)||X_(o)&&i4(o,r)})}function Ci(e){return MO()&&(e==="managedMcpServers"||e.startsWith("managedMcpServers."))}var dy=["managedMcpServers","isolation","attributionProjectPolicy"],Lqe=[...dy,"deniedModels","availableModelsMatch"];function a4(e,t){if(!ie(e))return[];let n=[];for(let r of Lqe){if(!(r in e))continue;if(delete e[r],!Ci(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 l4(e,t){return(n)=>{if(Ci(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)K(fn(`${e}: ${n.path}: ${n.message}`),{level:n.startupFatal?"error":"warn"})}}function Nx(e){let t=e?.remote?e.remote():iY((c)=>Np(c,"remote managed settings").settings),n=!e?.remote&&!Ci("managedMcpServers")&&rY()?[{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:YZ(),o=(r?.state==="stale_cache"||r?.state==="failed")&&r.failure.errorKind==="ruled_empty"?Rx(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}=Np(t,"remote managed settings");return{settings:s,errors:[...n,...o,...Rx(i)],servedSnapshot:JZ(t),documentHasPolicyContent:a,...l&&{onlySubstitutes:l}}}var WY="parent managed settings";function Mqe(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let n=Np(t,WY);for(let r of dy)if(n.settings?.[r]!==void 0&&!Ci(r))n.errors.push({file:WY,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 c4(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=MO(),r=e.store.inlineFlagParse;if(r?.inline!==t||r.desktopSupplied!==n)r={inline:t,desktopSupplied:n,parsed:Nqe(t)},e.store.inlineFlagParse=r;let{settings:o,errors:s}=r.parsed;return{settings:o&&ir(o),errors:s.map((i)=>({...i}))}}function Nqe(e){let t=ir(e),n=[...a4(t,"SDK inline settings"),...Ip(t,"SDK inline settings")],r=Z_(t).safeParse(t);if(!r.success)return{settings:null,errors:[...n,...Pp(r.error,"SDK inline settings")]};if(n.some((o)=>o.severity==="fatal"))return{settings:null,errors:n};return{settings:r.data,errors:n}}var Up=2097152;function Uqe(e,t,n){try{let r;if(t!==void 0)r=t;else{let o=n||Fqe(e)?Va(xe(),e):dI(xe(),e);if(n){let s={};r=ci(o.resolvedPath,Up,(a)=>{s.owner={uid:a.uid,gid:a.gid,mode:a.mode}});let i=ly(r,e,n);return s.owner?{...i,fileOwner:s.owner}:i}r=ci(o.resolvedPath,Up)}return ly(r,e,n)}catch(r){return jqe(r,e)}}function ly(e,t,n){if(e.trim()==="")return{settings:{},errors:[],loadState:"loaded"};let r=ra(e,!1);if(n){if(!ie(r))return{settings:null,errors:[py(t)],loadState:"didNotLoad"};let a=ir(r),l=Ip(a,t,{skipMcpServerEntryFilter:!0,policySource:!0}),c=[],d=px(l4(t,c),t,a).safeParse(a);if(!d.success)return{settings:null,errors:[...l,...Pp(d.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad"};return{settings:d.data,errors:[...y4(l,d.data,c),...c],documentHasPolicyContent:E4(r,d.data),loadState:"loaded"}}let o=ir(r),s=[...a4(o,t),...Ip(o,t)],i=Z_(o).safeParse(o);if(!i.success){let a=Pp(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 py(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 Fqe(e){let t=Ka();if(t===null)return!1;let n=Ge(uy(vt(e))),r=vt(t);return n===Ge(r)||n===$qe(r)}var Ox;function $qe(e){if(Ox?.lexical!==e){let t=uy(e);Ox={lexical:e,physical:Ge(Bt(vf(t)??t,Oqe(e)))}}return Ox.physical}function zqe(e){K(fn(`Broken symlink or missing file encountered for settings.json at path: ${e}`))}function Hqe(){return{settings:null,errors:[],loadState:"absent"}}function jqe(e,t){if(DP(e))throw e;if(Iqe(e,t),ot(e))return Hqe();return{settings:null,errors:[Fp(t,e)],loadState:"didNotLoad"}}function Fp(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 u4(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 ${Tn}), 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 VY(e){return e.path==="wslInheritsWindowsSettings"&&e.severity==="fatal"}function Bqe(e,t,n){let r=e.withheldFlagRecord&&n().heldOnly===!0?[...e.errors,e.withheldFlagRecord]:e.errors;if(!r.some(VY))return r;if(!wc(t()))return r;return r.map((o)=>VY(o)?{...o,severity:"warning"}:o)}function qY(e,t){switch(e){case"userSettings":return vt(It());case"policySettings":return vt(iy(t));case"projectSettings":return vt(t.projectConfigDir??iy(t));case"localSettings":{if(t.projectConfigDir!==void 0)return vt(t.projectConfigDir);return d4(iy(t),t.canonicalGitRoot)}case"flagSettings":return t.flagPath?uy(vt(t.flagPath)):vt(iy(t))}}function iy(e){if(e.cwd===null)throw new iu;return e.cwd}function d4(e,t){let n=Kqe(e,t);if(n.decided!==void 0)return n.decided;if(!qqe(n.root))return n.cwdResolved;return n.root}function Kqe(e,t){let n=t?.(e);if(!n)return{decided:vt(e)};let r=vt(n),o=vt(e);if(r===o)return{decided:r};let s;try{s=Zqe()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function Gqe(e){return Jo().localStoreProbes.canonicalRootOwnerUids(e,Wqe)}function Wqe(e){let t=xe(),n=null;try{n=t.lstatSync(Bt(e,".claude")).uid}catch(r){if(!ot(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:Vqe(e),claudeEntryUid:n}}function Vqe(e){let t=xe();try{return t.lstatSync(Bt(e,".git")).uid}catch(n){throw n}}function qqe(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return K(`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}=Gqe(e);if(n===t&&r===t&&(o===null||o===t))return!0;return K(`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 K(`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 Zqe(){return Jo().localStoreProbes.normalizedRealHomeDir(Yqe)}function Yqe(){let e=vf(Tqe());if(e===null)throw Error("home directory realpath unavailable");return Ge(e)}var ZY={default:"settings.json",cowork:"cowork_settings.json"};function Jqe(e){if(e.coworkPlugins||rn.CLAUDE_CODE_USE_COWORK_PLUGINS)return ZY.cowork;return ZY.default}function kc(e,t){switch(e){case"userSettings":return Bt(qY(e,t),Jqe(t));case"projectSettings":case"localSettings":{if(t.diskless||t.cwd===null&&t.projectConfigDir===void 0)return;return Bt(qY(e,t),p4(e))}case"policySettings":return xqe();case"flagSettings":return t.flagPath}}function p4(e){switch(e){case"projectSettings":return Bt(".claude","settings.json");case"localSettings":return Bt(".claude","settings.local.json")}}function f4(e){if(e.diskless)return;if(e.cwd===null||d4(e.cwd,e.canonicalGitRoot)===vt(e.cwd))return;if(e.projectConfigDir!==void 0)return;return Bt(vt(e.cwd),p4("localSettings"))}function m4(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=wZe(e,t),s=o&&Mp(e,o,t);return t.store.perSource.set(e,s),s}function g4(e){return(e.parentSettingsBehavior??(Qh()?"merge":"first-wins"))==="merge"}function Xqe(e,t=!1){return!e||g4(e)||t}var Qqe=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function eZe(e){let t={};for(let{path:n,restrictive:r}of mo()){let o=Tt(e,n);if(n[0]==="sandbox"&&oa(r).includes(o))cn(t,n,o)}return t.sandbox??{}}function YY(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(bY(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 Lp)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=pi(e.permissions,["deny","ask"]);for(let i of["deny","ask"]){let a=s[i];if(a!==void 0)s[i]=a.filter((l)=>{if(!lp.test(l))return!0;return K(`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?pi(s,["deniedDomains"]):{},d=i?pi(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=h4(a.awsPairs??[],[]);if(g.length>0)m.awsPairs=g}if(Object.keys(m).length>0)l.credentials=m}if(un(l,eZe(e)),Object.keys(l).length>0)n.sandbox=l}return n}function h4(e,t){let n=fi,r=new Set(t.flatMap(JY));return en(e.flatMap(JY)).filter((o)=>n.includes(o)&&!r.has(o)).map((o,s)=>({accessKeyIdVar:o,secretAccessKeyVar:`${A_}${s+1}_`}))}function JY(e){if(!ie(e))return[];return[e.accessKeyIdVar,e.secretAccessKeyVar,e.sessionTokenVar].filter((t)=>typeof t==="string")}var tZe=new Set([...[...QO].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...ew,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE"]);function nZe(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 rZe(e){let t=[];for(let n of e?.deniedModels??[]){let{warning:r}=_Y(n);if(r!==void 0)t.push({file:"managed settings",path:"deniedModels",message:r,severity:"warning",statusOnly:!0})}return t}function oZe(e){if(e?.availableModelsMatch!=="exact")return[];let t=e.availableModels??[];return t.flatMap((n)=>{let r=EY(n,t);return r===void 0?[]:[{file:"managed settings",path:"availableModels",message:r,severity:"warning",statusOnly:!0}]})}function XY(e,t){let n=e.deniedModels;if(Object.assign(e,t),n!==void 0&&t.deniedModels!==void 0)e.deniedModels=en([...n,...t.deniedModels])}function ay(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(!tZe.has(n.toUpperCase()))t[n]=r;e.env=t}}function sZe(e){let t=e.store.policy.allTiers;if(t!==void 0)return t;let n=gZe(e);return e.store.policy.allTiers=n,n}function ga(){return xt()==="macos"?"plist":"hklm"}function _4(e){let t=$p(e);if(t.composes==="tier")return"helper";let n=Pc(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return ga();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 Pc(e){let t=[],n=Nx(e),{settings:r,servedSnapshot:o}=n;t.push(...n.errors);let s=$p(e),i=s.composes==="remoteSlot"?s.helper:wx(r),a=Mx(e),l=a.settings;t.push(...a.errors);let c=wx(l),d=e.file?.()??Ix(e),p=d.settings;t.push(...d.errors);let f=wx(p),m=s.composes==="remoteSlot"?i!==null:wc(n),g=wc(a),_=wc(d),S=_&&d.heldOnly===!0,y=xx(i,m),E=xx(c,g),b=d.onlyHeldContent?S4:xx(f,_),C=i!==null&&y>=Math.max(E,b),A=c!==null&&E>=b,w=[[r,C],[l,A],[p,f!==null]],U=(s.composes==="remoteSlot"?s.helper:w.find(([me,dn])=>me!==null&&(me===r&&o?dn:me.managedSourcesBehavior!==void 0||dn))?.[0])?.managedSourcesBehavior,F=i!==null&&!C,ce=F?null:i,O=c!==null&&!A&&ce===null,T=O?null:c,v=[],D=[[F,"remote",i],[O,ga(),c]];for(let[me,dn,Er]of D){if(!me||Er===null)continue;if(v.push([Er,dn]),!Dc(Er))continue;let $r=dn==="remote"&&g?ga():"file";t.push({file:ma[dn],path:Object.keys(Er).find((as)=>!_i.includes(as))??"",message:`${ma[dn]} holds only values that could not be applied as written, so ${ma[$r]} 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:z,errors:te}=Mqe(e);t.push(...te);let ue=ce!==null&&o&&s.composes!=="remoteSlot",W=!(ce!==null&&m&&!ue)&&!(T!==null&&g),G=W&&(!_||S),st=G&&S,it=st&&z&&f?Kn(f,Lp.filter((me)=>z[me]!==void 0)):f,dt=(g?T:null)??(_?f:null),hn=z!==null&&(dt===null||g4(dt)||st),Ze=[cZe(ce,o&&s.composes!=="remoteSlot",[T,it&&Kn(it,d.heldAllowLists??[]),...hn?[pi(z,Lp)]:[]]),T,it,...v.map(([me])=>me)].filter((me)=>me!==null),vn=[...ce!==null?["remote"]:[],...T!==null?[ga()]:[],...f!==null?["file"]:[],...v.map(([,me])=>me)],Ye=(me)=>Ze.some((dn)=>dn!==it&&dn[me]!==void 0),_e=it!==null&&d.onlyHeldContent===!0&&W&&U!=="merge"&&Ze[0]!==it,{admin:Xt,merged:kt}=vx(_e?Ze.filter((me)=>me!==it):Ze,U,ue,_e?Ze.length-2:v.length),So=(me)=>ny({slot:me,adminTiers:Ze})||z?.allowManagedMcpServersOnly===!0&&me?.allowManagedMcpServersOnly!==!1,ya=(me,dn)=>kt?Ye(me):Ze[0]!==it&&Ze[0]?.[me]!==void 0||me==="allowedMcpServers"&&Ye(me)&&So(dn),Ri=Xt&&it&&_e?vx([Xt,Kn(it,Fx.filter((me)=>ya(me,Xt)))],"merge",!1,0).admin:Xt,Sr=Ri===null?[n,a,d].find(xc):void 0,Qt=Ri??(Sr?{}:null),Hc={remote:ce!==null||Sr===n,mdm:T!==null||Sr===a,file:f!==null||Sr===d},is=[];if(kt){let me=Hc.remote?"remote":Hc.mdm?ga():"file",dn=[[T,ga()],[it,"file"]];for(let[Er,$r]of dn){if(Er===null||Er===Ze[0]||ue&&Er===Ze[1])continue;let as=Ux.filter((ba)=>Object.values(Er[ba]??{}).some((qc)=>qc!==void 0&&qc!==null)),[Vc]=as;if(Vc===void 0)continue;is.push($r),t.push({file:ma[$r],path:Vc,message:`${as.map((ba)=>`"${ba}"`).join(" and ")} in ${ma[$r]} ignored: policy helper configuration is read from the highest managed settings source only (${ma[me]} here), even with managedSourcesBehavior "merge". Configure the helper in that source instead.`,severity:"warning",statusOnly:!0})}}let jc=(me)=>me!==null&&(me===Ze[0]||Object.keys(Kn(me,x4())).length>0),Bc={remote:jc(ce),mdm:jc(T),file:jc(it)},Sa={allowManagedPermissionRulesOnly:Ze.some((me)=>me.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:Qt?.forceLoginOrgUUID,...pi(Qt??{},Lp),allowedMcpServers:So(Qt)?Ex({slot:Qt,adminTiers:Ze}):Qt?.allowedMcpServers,sandbox:{network:{allowManagedDomainsOnly:Ze.some((me)=>me.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:Ze.some((me)=>me.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},Kc=Xqe(Ri,G),Ea=st&&z?Kn(z,lZe.filter(([,me])=>z[me]===void 0&&Sa[me]===void 0).map(([me])=>me)):z,Gc=Kc&&z&&!st?Lp.filter((me)=>z[me]!==void 0&&d.heldAllowLists?.includes(me)===!0&&Gt(Sa[me],f?.[me])&&!ya(me,Qt)):[],Wc=Ea&&Kc?st?YY(Ea,{...Sa,allowManagedPermissionRulesOnly:!0,sandbox:{network:{allowManagedDomainsOnly:!0},filesystem:{allowManagedReadPathsOnly:!0}}}):YY(Ea,Kn(Sa,Gc)):null,Jp=Wc&&Object.keys(Wc).length>0?Wc:null,Oy=nZe(Ea,e.hostManagedProvider);return{tiers:Ze,tierSources:vn,admin:Qt,parentSlice:Jp,hostModelOverlay:Oy,errors:t,present:Hc,mode:U,merged:kt,composed:Bc,snapshotFirst:ue,parentNeverShutOut:G,shadowedHelperSources:is,parentIncluded:Kc,heldEmpty:Sr!==void 0,fileNotHeld:d.settingsNotHeld,heldInTheHostsPlace:Gc}}function vx(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}:Kn(d,x4());if(!f){for(let _ of Qqe)if(Tt(m,_)!==void 0)cn(m,_,void 0)}let g=Tt(m.sandbox,["enabledPlatforms"]);if(Array.isArray(g)&&g.includes(xt()))cn(m,["sandbox","enabledPlatforms"],void 0);else if(g!==void 0)delete m.sandbox;return m});if(!a)return QY(i,[o,...l]),{admin:i,merged:!1};let c={};for(let d of[...l].reverse())un(c,d,kx);return un(c,i,n?uZe:kx),QY(c,[o,...l]),iZe(c,[o,...l],n),{admin:c,merged:!0}}var Ux=["policyHelper","policyHelpers"],ma={remote:"server-managed settings",plist:"the managed preferences plist",hklm:"the HKLM policy key",file:"managed-settings.json"};function Ic(e){return Object.keys(e).some((t)=>!_i.includes(t))}function Dc(e){return Object.entries(e).some(([t,n])=>!_i.includes(t)&&!Op(n))}function wx(e){return e&&Ic(e)?e:null}function wc(e){return e.settings!==null&&Dc(e.settings)&&!e.onlySubstitutes}function y4(e,t,n){return wc({settings:t})&&!n.some((r)=>r.onlySubstitutes)?NY(e):e}var S4=0;function xx(e,t){if(e===null)return-1;if(t)return 2;return Dc(e)?1:S4}function E4(e,t){return Object.entries(e).some(([n,r])=>r!==null&&!s4(n,r)&&!_i.includes(n))||t!==null&&Ic(t)}function xc(e){return e.documentHasPolicyContent??(e.settings!==null&&Ic(e.settings))}function bi(e){return e.loadState??(e.settings!==null?"loaded":"absent")}function yo(e,t){if(e==="didNotLoad"||t==="didNotLoad")return"didNotLoad";return e==="loaded"||t==="loaded"?"loaded":"absent"}function ha(e){return e.userWritable!==!0&&(xc(e)||e.loadState==="didNotLoad")}function iZe(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 b4=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders"],aZe=["awsPairs","ripgrep"];function C4(e,t,n){if(t===void 0)return e;if(Array.isArray(t))return n==="awsPairs"&&Array.isArray(e)?[...t,...h4(e,t)]:[...t];if(!ie(t))return t;return s_(t,(r)=>Array.isArray(r)?[...r]:r)}var Fx=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders","allowedMarketplaces","allowedHttpHookUrls","httpHookAllowedEnvVars"],Lp=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedProviders"],lZe=[["allowManagedMcpServersOnly","allowedMcpServers"],["enforceAvailableModels","availableModels"]];function cZe(e,t,n){if(e===null||!t)return e;let r=Fx.filter((o)=>n.some((s)=>s?.[o]!==void 0));return r.length===0?e:Kn(e,r)}function kx(e,t,n){if(n!==void 0&&(b4.includes(n)||aZe.includes(n)))return C4(e,t,n);return A4(e,t,n)}function uZe(e,t,n){if(n!==void 0&&b4.includes(n))return C4(e,t,n);return A4(e,t,n)}function A4(e,t,n){if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return en([...t,...e]);return Fr(e,t,n)}function QY(e,t){let n=t[0],r=e;for(let o of mo()){let{path:s,restrictive:i}=o,a=oa(i),l=Math.min(...t.map((c)=>a.indexOf(e_(o,c))).filter((c)=>c!==-1));if(Number.isFinite(l))cn(r,s,a[l]);else if(Tt(n,s)===void 0&&Tt(e,s)!==void 0)cn(r,s,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=en(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 $p(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:Nx(e).settings,mergedOver:"remote"}:R4(e);e.store.policy.mergedHelper={helper:mZe(r,t),mergedOver:Object.keys(T4(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function R4(e){let t=Mx(e);if(Pc({...e,helper:void 0}).present.mdm)return{base:t.settings,mergedOver:ga(),errors:t.errors};let n=e.file?.()??Ix(e);return{base:n.settings,mergedOver:"file",errors:[...t.errors,...n.errors]}}function T4(e){return Kn(e??{},Ux)}function dZe(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 pZe=["forceLoginOrgUUID","gatewayInternalNetworks","allowedHttpHookUrls","httpHookAllowedEnvVars","allowRead"];function fZe(e,t,n){let r=n!==void 0&&t!==void 0&&pZe.includes(n)?t:kx(e,t,n);return r===t&&Array.isArray(r)?[...r]:r}function mZe(e,t){let n=T4(e),r=un({},n,t,fZe);if(n.env&&t.env)r.env=dZe(n.env,t.env);return r}function gZe(e){let t=$p(e);if(t.composes==="tier")return[t.helper];let{tiers:n,parentSlice:r}=Pc(e);return r?[...n,r]:n}function hZe(e,t,n){let r={slot:n,adminTiers:e};return e.flatMap((o,s)=>{let i=t[s],a=CY(o,r);return i!==void 0&&a.length>0?[{source:i,keys:a}]:[]})}var O4=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var cy=[...O4,"otelHeadersHelper","proxyAuthHelper"],e4=["disableAllHooks","enabledPlugins","extraKnownMarketplaces","agent","allowedHttpHookUrls","httpHookAllowedEnvVars","autoMemoryDirectory","modelOverrides","allowedMcpServers","skipWebFetchPreflight","autoUploadSessions","xaaIdp","claudeMdExcludes","enableAllProjectMcpServers","enabledMcpjsonServers"];function _Ze(e,t,n){if(!e4.some((o)=>t[o]!==void 0)||(n.launchFolderKeysFrom?.(e)??"as_read")==="as_read")return t;let r={...t};for(let o of e4)delete r[o];return lY("keys"),r}function Mp(e,t,n){return yZe(e,_Ze(e,t,n),n)}function yZe(e,t,n){let r=cy.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"?SZe(n):{};if(!r&&Object.keys(s).length===0)return t;let i={...t};for(let a of cy)delete i[a];return Object.assign(i,s)}function SZe(e){let t=w4(e),n={};for(let r of cy){let o=t?.[r];if(o!==void 0)n[r]=o}return n}function w4(e){let t=EZe(e),n=$p(t);return n.composes==="tier"?n.helper:Pc(t).admin}function EZe(e){let t=e.helperArmedFromRemote?.()===!1&&e.helperArmedFromUserWritableBase?.()===!1;return{...e,store:new hs,remote:()=>null,helper:t?e.helper:()=>null,...e.mdm?.().userWritable===!0&&{mdm:()=>({settings:{},errors:[]})}}}function bZe(e){return e.helperArmedFromUserWritableBase?.()!==!1||e.helperMergesOutput?.()===!0&&e.mdm?.().userWritable===!0}function t4(e,t){if(t.store.policy.machineLoginPins===void 0){let o=w4(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 CZe=[...cy,"forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","env","modelPicker",...Ux,..._i];function x4(){return CZe}function AZe(e){return t2.some((t)=>e.startsWith(t))||e2.includes(e)}function RZe(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=AZe(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 TZe="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function n4(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==TZe)t[n]=r;return t}function OZe(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function v4(e){let t=$p(e),n=(e.helperWarnings?.()??[]).filter((y)=>!Ci(y.path));if(t.composes==="tier"){let{helper:y}=t;e.store.lastPolicyEnvComposition=null;let E=bZe(e),b=e.hostManagedProvider||E?{...y}:y;if(e.hostManagedProvider)ay(b);if(E)t4(b,e);e.store.policy.pairedModelOverrides={value:e.hostManagedProvider&&y.availableModels!==void 0?y.modelOverrides:void 0},e.store.policy.deniedModelsOverrides={value:e.hostManagedProvider?y.modelOverrides:void 0};let C=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?R4(e).errors.filter((A)=>!A.statusOnly):[],...Pc(e).errors.filter((A)=>A.statusOnly)];return{settings:b,errors:[...C,...n]}}let{tiers:r,tierSources:o,admin:s,parentSlice:i,hostModelOverlay:a,errors:l,present:c,snapshotFirst:d,heldInTheHostsPlace:p}=Pc(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 y=e.hkcu?.();if(y&&Object.keys(y.settings).length>0){let E=e.hostManagedProvider?{...y.settings}:y.settings;if(e.hostManagedProvider){if(ay(E),a)XY(E,a)}return{settings:E,errors:[...l,...y.errors]}}if(a)return{settings:{...a},errors:[...l,...y?.errors??[]]};return{settings:null,errors:[...l,...y?.errors??[]]}}let f=un({},i??{},Kn(s??{},p),Fr);if(i?.availableModelsMatch==="exact")f.availableModelsMatch="exact";if(r.some((y)=>y.forceRemoteSettingsRefresh===!0))f.forceRemoteSettingsRefresh=!0;if(o.includes("remote")||e.mdm?.().userWritable===!0)t4(f,e);let m=rn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,g=f.env;if(!m){let y=RZe(r.map((E)=>E.env),r.map((E)=>(E.otelHeadersHelper??"").trim()!==""),r.map((E)=>{let b=new Set;for(let C of O4){let A=E[C];if(typeof A==="string"&&A.trim()!=="")for(let w of n2[C])b.add(w)}return b.size>0?b:void 0}),d?1:0);if(Object.keys(y).length>0)f.env=y;else delete f.env}if(f.env){let y=n4(f.env);if(y&&Object.keys(y).length>0)f.env=y;else delete f.env}if(e.hostManagedProvider){if(ay(f),a)XY(f,a)}let _={env:n4(g)};if(e.hostManagedProvider)ay(_);let S=!m&&!OZe(f.env,_.env);e.store.lastPolicyEnvComposition={unionOptedOut:m,unionChangedEnv:S,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:Fa(r,(y)=>Object.keys(y.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:y,keys:E}of hZe(r,o,f)){let[b]=E;if(b===void 0)continue;let C=ma[y],A=E.length===1;l.push({file:C,path:b,message:`${E.map((w)=>`"${w}"`).join(" and ")} in ${C} ${A?"is":"are"} not applied: ${C} is not the managed settings source that applies for ${A?"this key":"these keys"} (/status lists the setting sources). Remove ${A?"it":"them"} from ${C}, or set ${A?"it":"them"} in the source that applies.`,severity:"warning",statusOnly:!0})}return{settings:f,errors:l}}function wZe(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return v4(t).settings;let r=kc(e,t),{settings:o}=r?vc(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=c4(t);if(s)return un(o||{},s,Fr)}if(e==="localSettings"&&n){let s=f4(t);if(s){let{settings:i}=vc(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),un(i,o||{},Fr)}}return o}function xZe(e,t){return{...e,...t}}function Fr(e,t,n){if(n==="modelPicker"&&t!==void 0)return k4(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return en([...e,...t])}if((n==="extraKnownMarketplaces"||n==="managedMcpServers")&&ie(e)&&ie(t))return xZe(e,t);return}function k4(e){if(!ie(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>ie(n)?{...n}:n)}}}function vZe(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();sp("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=un(r,n,Fr);let o=[],s=new Set,i=new Set,a=(S)=>{for(let y of S){let E=`${y.file}:${y.path}:${y.message}`;if(!s.has(E))s.add(E),o.push(y)}},l=[],c=[di()];if(xt()==="wsl"&&e.wslInherits?.())c.push(Tn);let d=new Set(c.map((S)=>vt(Bt(S,"managed-settings.json")))),p=new Set(c.map((S)=>vt(Bt(S,"managed-settings.d")))),f=(S)=>{let y=vt(S);return d.has(y)||p.has(uy(y))},m=(S,y,E)=>{if(E?.channelLabel!==!0&&f(S))return;let b=y.sandbox?.filesystem?.allowRead?.length??0,C=y.sandbox?.network?.allowedDomains?.length??0;if(b>0||C>0)l.push({file:S,allowReadCount:b,allowedDomainsCount:C})},g=null;for(let S of Px(e)){if(S==="policySettings"){let{settings:b,errors:C}=v4(e);if(g=b,a(rZe(b)),a(oZe(b)),b)r=un(r,Mp(S,b,e),Fr);a(C);continue}let y=e.store.repoTierFreeze.tier(S);if(y!==void 0){let b=kc(S,e);if(b)i.add(vt(b));if(a([...y.errors]),y.settings)r=un(r,y.settings,Fr);continue}if(S==="localSettings"){let b=f4(e);if(b&&!i.has(vt(b))){i.add(vt(b));let{settings:C,errors:A}=vc(b,e.store);if(a(A),C)e.onLegacyLocalSettingsRead?.("cascade"),m(b,C),r=un(r,Mp(S,C,e),Fr)}}let E=kc(S,e);if(E){let b=vt(E),C=S==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(b)||C){i.add(b);let{settings:A,errors:w}=vc(E,e.store,S==="flagSettings"?e.flagExpectedContent:void 0);if(a(w),A){if(S==="flagSettings"&&e.flagInlineJson===!0)m(uY,A,{channelLabel:!0});else m(E,A);r=un(r,Mp(S,A,e),Fr)}}}if(S==="flagSettings"){let{settings:b,errors:C}=c4(e);if(a(C),b)m("SDK inline settings",b,{channelLabel:!0}),r=un(r,Mp(S,b,e),Fr)}}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=k4(g.modelPicker)}let _=g?.deniedModels;if(_!==void 0)r.deniedModels=[..._];else delete r.deniedModels;if(l.length>0){let S=sZe(e),y=(E,b,C,A,w)=>({file:E,path:b,severity:"warning",statusOnly:!0,message:`${b} is ignored — managed settings set ${C}, so only ${A} from managed settings are honored. The ${w===1?"entry":`${w} entries`} in ${E} will NOT apply (see https://code.claude.com/docs/en/settings#sandbox-settings).`});if(S.some((E)=>E.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)){for(let E of l)if(E.allowReadCount>0)a([y(E.file,"sandbox.filesystem.allowRead","allowManagedReadPathsOnly","allowRead paths",E.allowReadCount)])}if(S.some((E)=>E.sandbox?.network?.allowManagedDomainsOnly===!0)){for(let E of l)if(E.allowedDomainsCount>0)a([y(E.file,"sandbox.network.allowedDomains","allowManagedDomainsOnly","allowed domains (and WebFetch domain rules)",E.allowedDomainsCount)])}}return sp("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:i.size,error_count:o.length}),e.store.hookedMerge.computed=r,vY({settings:r,errors:o},e.store.hookedMerge.answers)}finally{e.store.isLoadingFromDisk=!1}}function kZe(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=vZe(e);return e.store.mergedSettings=n,n}function PZe(e){let{settings:t}=kZe(e);return t||{}}function P4(e){e.store.invalidateAll();let t=[];for(let n of Px(e)){let r=m4(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:PZe(e),sources:t}}function I4(e,t){let n=Px(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(m4(o,t)?.[e]!==void 0)return o}return null}import{execFile as IZe}from"child_process";import{accessSync as DZe,closeSync as LZe,constants as MZe,openSync as NZe,readSync as UZe}from"fs";class N4{promise=null;start(){if(this.promise)return;this.promise=zx()}reset(){this.promise=null}}var FZe=new N4;function $Ze(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 $x(e,t,n){let r=Date.now();return new Promise((o)=>{try{IZe(e,t,{encoding:"utf-8",timeout:OY,windowsHide:!0,...n!==void 0&&{maxBuffer:n}},(s,i)=>{o({stdout:i??"",...$Ze(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 D4(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function L4(e){return e.status==="ok"||e.status==="exited"&&e.exitCode!==null}function zZe(e){return e.status==="spawn_error"&&e.errno==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}function HZe(e){let t;try{return t=NZe(e,"r"),UZe(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{LZe(t)}catch{}}}function zx(){return(async()=>{if(process.platform==="darwin"){let e=wY(),n=(await Promise.all(e.map(async({path:o,...s})=>{try{DZe(o,MZe.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 $x(Cx,[...RY,o],sy);if(!L4(i))return{stdout:null,unreadReason:"plutil did not finish converting it",...s};if(i.status==="ok")return{stdout:i.stdout,...s};let a=await $x(Cx,[...TY,o]);if(!L4(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=HZe(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 M4(t)}if(vp())return M4(Ei);return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}async function M4(e){let t=(o)=>$x(e,["query",o,"/v",xp],sy),[n,r]=await Promise.all([t(ry),t(oy)]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,...zZe(n)&&{hklmUnreadReason:`the value exceeds ${sy/1048576} MiB`},hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:D4(n),hkcu:D4(r)}}}function U4(){return FZe.promise}var KZe=Object.freeze({settings:{},errors:[],loadState:"absent"}),Lc=Object.freeze({settings:{},errors:[]});class H4{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(U4()??zx()),{mdm:o,hkcu:s,wslInherits:i,whereAsked:a}=await jx(r,e);this.replace(o,s,i,a);let l=Date.now()-t;K(`MDM settings load completed in ${l}ms`);try{si("tengu_managed_settings_os_read",eYe(r,l))}catch{}let c=Gx();if(Object.keys(c.settings).length>0){K(`MDM settings found: ${Object.keys(c.settings).join(", ")}`);try{sp("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 F4="@builtin",GZe=["prependPlugins","appendPlugins"];function WZe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var VZe=new Ie(()=>new H4);function Hp(){return VZe.of(nn().host)}function qZe(e){Hp().startLoad(e)}async function j4(){let e=Hp();if(!e.loadPromise)qZe();await e.loadPromise}function Gx(){return Wx(Hp()).mdm??KZe}function Wx(e){return e.whereAsked!==void 0&&r_()?e.whereAsked:e}function B4(){return Wx(Hp()).hkcu??Lc}function K4(){return Wx(Hp()).wslInherits}function zp(e,t,{userWritable:n=!1}={}){let r=ra(e,!1);if(!ie(r))return{settings:{},errors:[py(t,{userWritable:n})],documentHasPolicyContent:!1,loadState:"didNotLoad"};let o=[],s=r;for(let f of n?dy:[]){if(!(f in s))continue;if(s=s===r?{...r}:s,delete s[f],!Ci(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 GZe){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(WZe(f)){if(Object.entries(f).filter(([g,_])=>g.endsWith(F4)||_!==!1).length>0){s=s===r?{...r}:s;let g=Vh(f,(_,S)=>!S.endsWith(F4)&&_===!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}=Np(s,t),p=[...o,...a];return{settings:i??{},errors:n?p.map((f)=>({...f.severity==="warning"&&!f.startupFatal?f:{...ZZe(f),severity:"warning",statusOnly:!0},userWritable:!0})):p,documentHasPolicyContent:l,loadState:c,...d&&{onlySubstitutes:d}}}function ZZe({startupFatal:e,loadedWithoutGuardHook:t,...n}){return n}function Hx(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 fy(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 YZe=new Map([["ENOENT",tn("ENOENT")],["EACCES",tn("EACCES")],["EPERM",tn("EPERM")],["ENOEXEC",tn("ENOEXEC")],["EAGAIN",tn("EAGAIN")],["EMFILE",tn("EMFILE")],["ENOMEM",tn("ENOMEM")],["ETIMEDOUT",tn("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",tn("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),JZe=new Map([["SIGTERM",tn("SIGTERM")],["SIGKILL",tn("SIGKILL")],["SIGINT",tn("SIGINT")]]);function XZe(e){if(!e)return;return YZe.get(e)??tn("other")}function QZe(e){if(!e)return;return JZe.get(e)??tn("other")}function $4(e,t){if(!t)return{};return{[`${e}_status`]:_s(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:XZe(t.errno),[`${e}_signal`]:QZe(t.signal),[`${e}_duration_ms`]:t.durationMs}}function eYe(e,t){return{is_wsl:vp(),await_ms:t,...$4("hklm",e.outcomes.hklm),...$4("hkcu",e.outcomes.hkcu)}}async function jx(e,t,n=!1){let r=[],o=!1,s="absent";for(let y of e.plistStdouts??[]){let{label:E,userWritable:b}=y;if(b&&o)continue;let C=y.stdout===null?{settings:{},errors:[Hx(E,y.unreadReason,b,y.unreadErrno)],documentHasPolicyContent:!1,loadState:"didNotLoad",...b&&{userWritable:b}}:{...zp(y.stdout,E,{userWritable:b}),...b&&{userWritable:b}};if(b?Ic(C.settings):C.documentHasPolicyContent)return{mdm:{...C,errors:[...r,...C.errors],documentHasPolicyContent:!0},hkcu:Lc,wslInherits:!1};if(o||=ha(C),r.push(...C.errors),!b)s=yo(s,C.loadState)}let i=`Registry: ${ry}\\${xp}`,a=null,l="disarmed",c=`Registry: ${oy}\\${xp}`;if(!n&&(e.hklmStdout!==null||e.hklmUnreadReason!==void 0||e.hkcuStdout!==null)&&process.platform!=="win32"&&Ax()){let[y,E]=await Promise.all([Ei,BZe(Ei)].map((C)=>jZe(C).then(({uid:A,gid:w,mode:L})=>({uid:A,gid:w,mode:L}),()=>{return}))),b=!0;try{b=Lx(new hs,Ei,y,E)}catch(C){K(`registry tool: could not be asked about, held: ${C}`,{level:"error"})}if(b){let C=[];if(e.hklmStdout!==null)C.push([i,zp(fy(e.hklmStdout)??"",i)]);else if(e.hklmUnreadReason!==void 0)C.push([i,{settings:{},errors:[Hx(i,e.hklmUnreadReason,!1)],documentHasPolicyContent:!1,loadState:"didNotLoad"}]);if(e.hkcuStdout!==null)C.push([c,zp(fy(e.hkcuStdout)??"",c,{userWritable:!0})]);let A=await jx(e,t,!0),w=await jx({...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=fy(e.hklmStdout)??"";a=zp(y,i);let E=ra(y,!1);if(ie(E))l=ax(E)}else if(e.hklmUnreadReason!==void 0)a={settings:{},errors:[Hx(i,e.hklmUnreadReason,!1)],documentHasPolicyContent:!1,loadState:"didNotLoad"};let d=a!==null&&ha(a);if(a)r.push(...a.errors),s=yo(s,a.loadState);let p=vp(),f="disarmed",m=i,g=[];if(p){if(f=l,f!=="armed"){let y=await nYe(t);if(g=y.links,y.flag==="armed"||f==="disarmed")f=y.flag,m=y.unreadableFlagPath??Tn;if(f==="disarmed")r.push(...y.records),s=yo(s,y.loadState)}}let _=f!=="disarmed",S={settings:{},errors:r,loadState:s};if(p&&!_){let y=new Set(a?.errors.filter((E)=>E.severity==="warning"));return{mdm:{...S,errors:S.errors.map((E)=>y.has(E)?{...E,wslIgnored:!0}:E),...g.length>0&&{managedDocumentLinks:g}},hkcu:Lc,wslInherits:!1}}if(a&&d)return{mdm:a,hkcu:Lc,wslInherits:_};if(f==="unreadable"){let y=await Kx(Tn,t),E=u4(m);return{mdm:{...S,errors:y?S.errors:[...S.errors,E],...y&&{withheldFlagRecord:E},documentHasPolicyContent:!0,loadState:yo(S.loadState,"loaded")},hkcu:Lc,wslInherits:_}}if(e.hkcuStdout!==null&&!Je()&&!await tYe(_,t)){let y=zp(fy(e.hkcuStdout)??"",c,{userWritable:!0});if(!p||y.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:E,managedSourcesBehavior:b,...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:Lc,wslInherits:_}}async function G4(e,t){if(be()&&t!==void 0)return(await EG(e,Up)).content;return ci(e,Up)}async function tYe(e,t){if(e&&await Kx(Tn,t))return!0;return Kx(di(),t)}async function z4(e,t){let n;try{n=await G4(e,t)}catch(r){return!ot(r)}try{let r=ly(n,e,!0);return ha({...r,loadState:bi(r)})}catch{return!0}}function Bx(e){let t=fe(e);return t==="ENOENT"||t==="ENOTDIR"}async function nYe(e){let t=[],n="absent",r=[],o=new Map;async function s(p,f){let m=_a(Tn,...p),g;try{g=await G4(m,e)}catch(y){if(Bx(y))return"disarmed";t.push(Fp(m,y)),n="didNotLoad"}let _=await zG(Tn,p,f,o);if(_!==null)r.push(_);if(g===void 0)return"disarmed";let S=g.trim()===""?{}:ra(g,!1);if(!ie(S))return t.push(py(m)),n="didNotLoad","disarmed";return n=yo(n,"loaded"),ax(S)}let i=_a(Tn,"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=_a(Tn,"managed-settings.d"),d;try{d=await xe().readdir(c)}catch(p){if(!Bx(p))t.push(Fp(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??=_a(c,p.name)}return{flag:a,unreadableFlagPath:l,records:t,loadState:n,links:r}}async function Kx(e,t){if(await z4(_a(e,"managed-settings.json"),t))return!0;let n=_a(e,"managed-settings.d"),r;try{r=await xe().readdir(n)}catch(o){return!Bx(o)}for(let o of r)if((o.isFile()||o.isSymbolicLink())&&Dx(o.name)&&await z4(_a(n,o.name),t))return!0;return!1}var oYe={user:"userSettings",project:"projectSettings",local:"localSettings"},W4={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},sYe=["user","project","local"];async function V4(e={}){await j4();let t={store:new hs,cwd:rYe(e.cwd??xe().cwd()),allowedSources:(e.settingSources??sYe).map((a)=>oYe[a]),diskless:Je(),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:Gx,hkcu:B4,wslInherits:K4,credentialHelperKeysFrom:()=>"as_read",asksOrganization:()=>r_(),...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=P4(t),o=_4(t)??void 0,s=r.map(({source:a,settings:l})=>({source:W4[a],settings:l,path:a==="policySettings"?void 0:kc(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let l=I4(a,t);if(l)i[a]={source:W4[l],path:l==="policySettings"?void 0:kc(l,t),...l==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}var iYe=new Set(["bypassPermissions","auto","acceptEdits"]),aYe=new Set(["project"]),lYe=new Set(["project","local"]);function cYe(e){let t=e.effective.permissions?.defaultMode;if(!t||!iYe.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((dY.includes(t)?lYe:aYe).has(r.source)){let{defaultMode:s,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}import{execFile as b4e}from"child_process";import{randomUUID as C4e}from"crypto";import{mkdir as Ay,mkdtemp as A4e,readFile as R4e,rm as X9,writeFile as Q9}from"fs/promises";import{createRequire as T4e}from"module";import{homedir as Zp,tmpdir as O4e}from"os";import{dirname as Z9,isAbsolute as fv,join as yt,posix as eJ,resolve as Yp,sep as w4e,win32 as tJ}from"path";import{fileURLToPath as x4e}from"url";import{setMaxListeners as uYe}from"events";var dYe=50;function jp(e=dYe){let t=new AbortController;return uYe(e,t.signal),t}var X0t=new FinalizationRegistry(({parentSignalRef:e,handler:t})=>{e.deref()?.removeEventListener("abort",t)});var pYe="ask-withdrawn-by-asker",Q0t=new DOMException(pYe,"AbortError");var eFt={"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 fYe="server-fallback-tombstone";var tFt=new DOMException(fYe,"AbortError");var mYe="subagent-park",nFt=new DOMException(mYe,"AbortError");import{spawn as wYe}from"child_process";import{existsSync as xYe}from"fs";import{createInterface as vYe}from"readline";import{StringDecoder as kYe}from"string_decoder";var gYe=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var Vx={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>"]},hYe=[/\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 oFt=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${Mc("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${Mc("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),q4=[[Bp("sk-ant-","[A-Za-z0-9_-]",8,qx(8)),"<token>"],[Bp("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,qx(20)),"<token>"]],Z4=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],_Ye=`(?:${Z4.join("|")})`,Y4=[[new RegExp(`(^|[^A-Za-z0-9+])${_Ye}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],J4=[[Bp("gh[opusr]_","[A-Za-z0-9]",20,Mc("[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>"],[Bp("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,Mc("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[Bp("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",Mc("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${Mc("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[gYe,"hooks.slack.com/<redacted>"]];var yYe=[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>"],SYe=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,X4=[[/(^|[^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>"]],Q4=[[/(^|[^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>"]],EYe=[Vx.bearer,Vx.basic,...q4,Vx.sk,...Y4],bYe=[...J4,yYe,...X4,...Q4],sFt=[[new RegExp(`sk-${qx(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...Z4.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 Kp(e){return[...EYe,...bYe].reduce((t,[n,r])=>t.replace(n,r),String(e))}var iFt=[...hYe,...[...q4,...Y4,...J4,...X4,...Q4].map(([e])=>new RegExp(e.source,e.flags.replaceAll("g",""))),SYe];function Bp(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 Mc(e){return`(?=${e}{0,64}[0-9])`}function qx(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 CYe(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")}var AYe=new Set(["filesystem.denyRead","filesystem.denyWrite","network.deniedDomains","credentials.files","credentials.envVars"]),RYe=new Set(["ripgrep","network.tlsTerminate"]),TYe=new Set(["__proto__","constructor","prototype"]),OYe=["httpProxyPort","socksProxyPort"];function e9(e,t,n=""){let r=ho(e)?{...e}:{};for(let[o,s]of Object.entries(t)){if(TYe.has(o)||s===void 0)continue;let i=n?`${n}.${o}`:o,a=Object.hasOwn(r,o)?r[o]:void 0;if(AYe.has(i)&&Array.isArray(a)&&Array.isArray(s))r[o]=en([...a,...s]);else if(ho(a)&&ho(s)&&!RYe.has(i))r[o]=e9(a,s,i);else r[o]=s}return r}function t9(e,t){let n={...e};if(!t)return n;let r=n.settings;if(r&&!CYe(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=$e(r)}catch{}let s=e9(o.sandbox,t),i=t.credentials?.files,a=t.filesystem!==void 0||Array.isArray(i)&&i.some((f)=>ho(f)&&f.mode==="deny"),l=s.filesystem;if(a&&t.filesystem?.disabled===void 0&&ho(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&&ho(p)){for(let f of OYe)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 Ke(e,t){return`${e}=${t}`}function my(e,t){let n=String(t);if(n.length>1&&n.startsWith("-"))return[Ke(e,n)];return[e,n]}function n9(e,t,n){e.push(...my(`--${t}`,n))}var PYe=2000,Zx=2048,s9="sdk-exit-after-stderr-drained",IYe=200;function Yx(e){return e==="exit"?s9:e}class i9{#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 gy=new i9,DYe=/[(),\u0000-\u001f\u007f-\u009f]/;function LYe(e){if(typeof e!=="string"||e.trim()==="")throw Error("Skill names must be non-empty strings.");if(!Zf(e))throw new ke(`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 ke(`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(DYe.test(e))throw new ke(`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 ke(`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 ke(`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 ke(`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 ke(`Invalid skill name ${se(e)}: names may not end with an unpaired backslash.`,"skill name with unpaired trailing backslash rejected");return e}class Xx{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitEventDelivered=!1;stderrTail="";exitListeners=[];abortHandler;forwardedAbort=jp();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||jp(),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 tl()?"bun":"node"}spawnLocalProcess(e){let{command:t,args:n,cwd:r,env:o,signal:s}=e,i=wYe(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(_){Jt(`onProcessSpawned threw: ${rt(_)}`)}let a=new kYe("utf8"),l=!1,c=!1,d=!1,p,f=Oe(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*Zx)this.stderrTail=qf(Kp(this.stderrTail),Zx);if(f)Jt(S),this.options.stderr?.(S)}),i.stderr.on("error",(_)=>{Jt(`[ProcessTransport] stderr read failed: ${_.code??_.message}`)});let m=()=>{if(d)return;if(d=!0,p)clearTimeout(p);i.emit(s9,i.exitCode,i.signalCode);let _=i.stderr;if(FYe(_))_.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,IYe)}),{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(Yx(_),S),once:(_,S)=>i.once(Yx(_),S),off:(_,S)=>i.off(Yx(_),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:E,permissionPromptToolName:b,permissionPrompts:C,continueConversation:A,resume:w,settingSources:L,skills:U,disallowedTools:F=[],tools:ce,mcpServers:O,strictMcpConfig:T,canUseTool:v,includePartialMessages:D,plugins:z,pluginsViaInitialize:te,sandbox:ue}=this.options,{allowedTools:W=[]}=this.options;if(U!==void 0){let _e=U==="all"?["Skill"]:U.map((kt)=>`Skill(${LYe(kt)})`),Xt=new Set(W);W=[...W,..._e.filter((kt)=>!Xt.has(kt))]}let G=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(d){switch(d.type){case"enabled":if(d.budgetTokens===void 0)G.push("--thinking=adaptive");else G.push(Ke("--max-thinking-tokens",d.budgetTokens));break;case"disabled":G.push("--thinking=disabled");break;case"adaptive":G.push("--thinking=adaptive");break}if(d.type!=="disabled"&&d.display)G.push(Ke("--thinking-display",d.display))}if(this.options.effort)G.push(Ke("--effort",this.options.effort));if(p)G.push(Ke("--max-turns",p));if(f!==void 0)G.push(Ke("--max-budget-usd",f));if(m)G.push(Ke("--task-budget",m.total));if(g)G.push(Ke("--model",g));if(n)G.push(Ke("--agent",n));if(r&&r.length>0)G.push(Ke("--betas",r.join(",")));if(S)G.push(Ke("--json-schema",se(S)));if(this.options.debugFile)G.push(Ke("--debug-file",this.options.debugFile));else if(this.options.debug)G.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let _e=V1();if(_e)G.push(Ke("--debug-file",_e))}if(v){if(b)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");G.push("--permission-prompt-tool=stdio")}else if(b)G.push(Ke("--permission-prompt-tool",b));if(C)G.push(Ke("--permission-prompts",C));if(A)G.push("--continue");if(w)G.push(Ke("--resume",w));if(this.options.channels&&this.options.channels.length>0)for(let _e of this.options.channels)G.push(Ke("--channels",_e));if(W.length>0)G.push(Ke("--allowedTools",W.join(",")));if(F.length>0)G.push(Ke("--disallowedTools",F.join(",")));if(ce!==void 0)if(Array.isArray(ce))G.push(Ke("--tools",ce.join(",")));else G.push("--tools=default");if(O&&Object.keys(O).length>0)G.push(...my("--mcp-config",se({mcpServers:O})));if(L!==void 0)G.push(Ke("--setting-sources",L.join(",")));if(T)G.push("--strict-mcp-config");if(y)G.push(Ke("--permission-mode",y));if(E)G.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.");G.push(Ke("--fallback-model",_))}if(this.options.includeHookEvents)G.push("--include-hook-events");if(D)G.push("--include-partial-messages");if(this.options.sessionMirror)G.push("--session-mirror");if(t!==void 0)G.push(Ke("--project-config-root",t));for(let _e of e)G.push(Ke("--add-dir",_e));if(te)G.push("--await-initialize");else if(z&&z.length>0)for(let _e of z)if(_e.type==="local")G.push(_e.skipMcpDiscovery?Ke("--plugin-dir-no-mcp",_e.path):Ke("--plugin-dir",_e.path));else throw Error(`Unsupported plugin type: ${_e.type}`);if(this.options.forkSession)G.push("--fork-session");if(this.options.resumeSessionAt)G.push(Ke("--resume-session-at",this.options.resumeSessionAt));if(this.options.resumeDropsTurn!==void 0)G.push(Ke("--resume-drops-turn",this.options.resumeDropsTurn));if(this.options.sessionId)G.push(Ke("--session-id",this.options.sessionId));if(this.options.persistSession===!1)G.push("--no-session-persistence");if(this.options.managedSettings)G.push(...my("--managed-settings",this.options.managedSettings));let st={...a??{}};if(this.options.settings)st.settings=this.options.settings;let it=t9(st,ue);for(let[_e,Xt]of Object.entries(it))if(Xt===null)G.push(`--${_e}`);else n9(G,_e,Xt);if(!c.CLAUDE_CODE_ENTRYPOINT)c.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete c.NODE_OPTIONS,Oe(c.DEBUG_CLAUDE_AGENT_SDK))c.DEBUG="1";else delete c.DEBUG;let dt=MYe(l),hn=dt?l:s,Ze=dt?[...i,...G]:[...i,l,...G],vn={command:hn,args:Ze,cwd:o,env:c,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)Jt(`Spawning Claude Code (custom): ${hn} ${Ze.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(vn);else Jt(`Spawning Claude Code: ${hn} ${Ze.join(" ")}`),this.process=this.spawnLocalProcess(vn);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(_e)=>{Jt(`[ProcessTransport] stdin write failed (child likely exited): ${_e.code??_e.message}`),this.ready=!1}),gy.track(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted)this.close();let Ye=this.process;Ye.on("error",(_e)=>{this.ready=!1;let Xt=_e,kt=Xt.syscall!==void 0?Xt.syscall.startsWith("spawn"):TS(_e);if(kt&&!Ye.killed)gy.untrack(Ye);if(this.abortController.signal.aborted)this.exitError=hy(),pn(_e,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(kt&&TS(_e)){let{message:So,telemetryMessage:ya,errorClass:Ri}=NYe(l,dt),Sr={telemetryMessage:`${ya}${Jx(_e)}`,errorClass:Ri,code:eu(_e)};this.exitError=pn(ReferenceError(So),Sr),pn(_e,Sr),Jt(this.exitError.message)}else{let So={telemetryMessage:kt?`Failed to spawn Claude Code process${Jx(_e)}`:`Claude Code process error${Jx(_e)}`,errorClass:kt?"spawn_failed":"process_error",code:eu(_e)};this.exitError=pn(Error(`Failed to spawn Claude Code process: ${Kp(_e.message)}`),So),pn(_e,So),Jt(this.exitError.message)}}),Ye.on("exit",(_e,Xt)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=hy();else{let kt=this.getProcessExitError(_e,Xt);if(kt)this.exitError=kt,Jt(kt.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 pn(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 pn(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=qf(Kp(this.stderrTail),Zx).trim();return e?`. stderr: ${e}`:""}write(e){if(this.abortController.signal.aborted)throw r9();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){Jt("[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 pn(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${Qk(this.exitError)??"untagged exit error"}`,errorClass:o9(this.exitError,"errorClass"),code:eu(this.exitError),exitCode:UYe(this.exitError),signal:o9(this.exitError,"signal")});Jt(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{if(!this.processStdin.write(e))Jt("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${rt(t)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?hy():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?hy():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){Jt(`[ProcessTransport] onExit callback threw during close(): ${rt(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()},PYe,i,s).unref(),i.once("exit",()=>gy.untrack(i));else if(i)gy.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=vYe({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=$e(n)}catch(o){Jt(`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(r9());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 MYe(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((n)=>e.endsWith(n))}function NYe(e,t){let n=t?"native binary":"executable",r=Kp(e);if(xYe(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 Jx(e){let t=eu(e);return t===void 0?"":` (${t})`}function hy(){return pn(new Qn("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function r9(){return pn(new Qn("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function o9(e,t){let n=Object.hasOwn(e,t)?Reflect.get(e,t):void 0;return typeof n==="string"?n:void 0}function UYe(e){let t=Object.hasOwn(e,"exitCode")?Reflect.get(e,"exitCode"):void 0;return typeof t==="number"?t:void 0}function FYe(e){return typeof Reflect.get(e,"unref")==="function"}import{existsSync as $Ye}from"fs";var Nc="@anthropic-ai/claude-agent-sdk";function zYe(){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 a9(e,t={}){let n=t.platform??process.platform,r=t.arch??process.arch,o=t.exists??$Ye,s=t.preferMusl??zYe(),i="claude",a=n==="win32"?".exe":"",c=(n==="android"?[`${Nc}-linux-${r}-android`]:n==="linux"?s?[`${Nc}-linux-${r}-musl`,`${Nc}-linux-${r}`]:[`${Nc}-linux-${r}`,`${Nc}-linux-${r}-musl`]:[`${Nc}-${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 HYe=["signed_out","identity_changed","transient","refresh_failed"];function l9(e){return HYe.some((t)=>t===e)}var _y=600000;var Qx="startup_mark",c9="startupMark",u9="startupMarkAgeMs",d9=64;function p9(e){return"method"in e&&"id"in e&&e.id!==null}var f9=Object.freeze({}),m9=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),NFt=Symbol("swallow");class ev{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 g9=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var h9="2025-11-25";var jYe="notifications/tools/list_changed";function _9(e){return ie(e)&&!("id"in e)&&e.method===jYe}var y9=250,yy="sdk-manifest-capture:",Uc=Symbol("suppressControlResponse");function S9(e,t,n){for(let r of n){let o=r==="tools"?dw(t):void 0;K(o?`[Query] MCP server '${e}': ${A2(o)}`:`[Query] MCP server '${e}': ignoring malformed ${r} in its config`)}}class Sy{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 op;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;startupMark;runEndCeilingTimer;sessionState;lastErrorResultText;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;frameObserver;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let n={type:"system",subtype:"mirror_error",error:t,key:e,uuid:Aa(),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=_y){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)}setFrameObserver(e){this.frameObserver=e}dropUnreadHookProgress(e){this.inputStream.dropNewestQueued((t)=>t.type==="system"&&t.subtype==="hook_progress"&&t.hook_id===e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let t of this.cleanupCallbacks)try{t()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let t of this.cancelControllers.values())t.abort();this.cancelControllers.clear(),this.transport.close()}catch(t){K(`[Query.cleanup] transport.close() failed: ${rt(t)}`,{level:"error"})}try{let t=e??tv();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>=Sy.UNMATCHED_CONTROL_RESPONSES_MAX){let n=this.unmatchedControlResponses.keys().next().value;if(n!==void 0)this.unmatchedControlResponses.delete(n)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive"){if(Qx in e){let t=e[Qx];if(typeof t==="string"&&t.length<=d9)this.startupMark={mark:t,atMs:Date.now()}}continue}else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=e.is_error?e.subtype==="success"?e.result:e.errors.map((n)=>n.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||void 0,this.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()}try{this.frameObserver?.(e)}catch(t){K(`[Query.readMessages] The frame observer threw: ${rt(t)}`,{level:"error"})}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(t!==void 0&&!(e instanceof Qn)&&e?.name!=="SSEHttpError"){let n=pn(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});K(`[Query.readMessages] Replacing exit error with result text. Original: ${rt(e)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){K(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){K(`[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===Uc)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:rt(r)}};n=se(o)+`
159
- `}try{await Promise.resolve(this.transport.write(n))}catch(r){K(`[Query.handleControlRequest] Response write failed: ${rt(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(g9.some((n)=>n===e.request.subtype))return K(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),Uc;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(r===null)return Uc;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(p9(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 Uc;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 Uc;return n}return K(`[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`),si("tengu_request_user_dialog_response_ignored",{shape:_s("auto_cancel")}),Uc}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(l9(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)K(`[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,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,r=async(p,f)=>{try{if(await this.sdkMcpServers.get(p)?.connection,n)return;let m=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:yy+"initialize",method:"initialize",params:{protocolVersion:h9,capabilities:f9,clientInfo:{...m9,version:"0.3.305"}}}},f);if(n)return;if(!("result"in m)){K(`[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:yy+"tools-list",method:"tools/list"}},f);if(n)return;if(!("result"in C)){K(`[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 b=$e(se(y===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:y}));t.set(p,{transport:f,manifest:b})}catch(m){if(!n)K(`[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 Af(Promise.race([s,i]),y9);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"){tc("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)K(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${y9} ms; the rest will handshake over the control channel`,{level:"warn"}),tc("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)tc("sdk_mcp_manifest_capture","partial",c);else rp("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 K(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(d).join(", ")}] captured in ${l} ms`),d}async interrupt(e){return Yt("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let r=t.response?.cancelled;return{still_queued:n.filter((o)=>typeof o==="string"),...Array.isArray(r)&&{cancelled:r.filter((o)=>typeof o==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let r=(s)=>{if(s.subtype==="success"){let{pending_permission_requests:i,pending_user_dialog_requests:a,...l}=s;t(l)}else n(new ke(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests)K("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(tv());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 Yt("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 Yt("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return Yt("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 Yt("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=Yt("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(r)=>{if(r?.initialize===void 0)return n;let o=r.initialize,s=await n.then((c)=>({hooks_applied:c.hooks_applied,plugins_applied:c.plugins_applied,code_running_mcp_tools_applied:c.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied,l=o.code_running_mcp_tools_applied??s.code_running_mcp_tools_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a},...l!==void 0&&{code_running_mcp_tools_applied:l}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let r=++this.remoteControlCallGeneration,o=this.workSecretAnswerer,s=n?.reattachSessionId||(n?.workSecret===void 0?void 0:KYe(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 Yt("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return Yt("sdk_side_question",async()=>{let r=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return r.response===null?null:{response:r.response,synthetic:r.synthetic??!1,...r.refusal_fallback&&{refusalFallback:{originalModel:r.refusal_fallback.original_model,fallbackModel:r.refusal_fallback.fallback_model,content:r.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(Wn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(tv());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){K(`[Query.handleControlRequest] Response write failed: ${rt(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(g9.some((n)=>n===e.request.subtype))return K(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),Uc;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},...typeof e.request.server_policy_ask_only==="boolean"&&{serverPolicyAskOnly:e.request.server_policy_ask_only},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,...typeof e.request.plugin==="string"&&{plugin:e.request.plugin},requestId:e.request_id,...typeof e.request.requires_user_interaction==="boolean"&&{requiresUserInteraction:e.request.requires_user_interaction},...typeof e.request.server_prompt==="string"&&{serverPrompt:e.request.server_prompt},...typeof n==="object"&&n!==null&&"path"in n&&typeof n.path==="string"&&"computer_name"in n&&typeof n.computer_name==="string"&&{computerFolder:{path:n.path,computer_name:n.computer_name}},...e.request.matched_ask_rule&&{matchedAskRule:{source:e.request.matched_ask_rule.source,toolName:e.request.matched_ask_rule.tool_name,...e.request.matched_ask_rule.rule_content!==void 0&&{ruleContent:e.request.matched_ask_rule.rule_content}}}});if(r===null)return Uc;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(p9(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 Uc;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 Uc;return n}return K(`[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`),si("tengu_request_user_dialog_response_ignored",{shape:_s("auto_cancel")}),Uc}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(l9(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)K(`[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,codeRunningMcpTools:this.initConfig?.codeRunningMcpTools,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,r=async(p,f)=>{try{if(await this.sdkMcpServers.get(p)?.connection,n)return;let m=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:yy+"initialize",method:"initialize",params:{protocolVersion:h9,capabilities:f9,clientInfo:{...m9,version:"0.3.306"}}}},f);if(n)return;if(!("result"in m)){K(`[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:yy+"tools-list",method:"tools/list"}},f);if(n)return;if(!("result"in C)){K(`[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 b=$e(se(y===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:y}));t.set(p,{transport:f,manifest:b})}catch(m){if(!n)K(`[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 Af(Promise.race([s,i]),y9);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"){tc("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)K(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${y9} ms; the rest will handshake over the control channel`,{level:"warn"}),tc("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)tc("sdk_mcp_manifest_capture","partial",c);else rp("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 K(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(d).join(", ")}] captured in ${l} ms`),d}async interrupt(e){return Yt("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let r=t.response?.cancelled;return{still_queued:n.filter((o)=>typeof o==="string"),...Array.isArray(r)&&{cancelled:r.filter((o)=>typeof o==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}startupMarkReached(){let e=this.startupMark;return e&&{mark:e.mark,ageMs:Math.max(0,Math.round(Date.now()-e.atMs))}}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let r=(s)=>{if(s.subtype==="success"){let{pending_permission_requests:i,pending_user_dialog_requests:a,...l}=s;t(l)}else n(new ke(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests)K("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(tv());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 Yt("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 Yt("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return Yt("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 Yt("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=Yt("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(r)=>{if(r?.initialize===void 0)return n;let o=r.initialize,s=await n.then((c)=>({hooks_applied:c.hooks_applied,plugins_applied:c.plugins_applied,code_running_mcp_tools_applied:c.code_running_mcp_tools_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0,code_running_mcp_tools_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied,l=o.code_running_mcp_tools_applied??s.code_running_mcp_tools_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a},...l!==void 0&&{code_running_mcp_tools_applied:l}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let r=++this.remoteControlCallGeneration,o=this.workSecretAnswerer,s=n?.reattachSessionId||(n?.workSecret===void 0?void 0:KYe(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 Yt("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return Yt("sdk_side_question",async()=>{let r=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return r.response===null?null:{response:r.response,synthetic:r.synthetic??!1,...r.refusal_fallback&&{refusalFallback:{originalModel:r.refusal_fallback.original_model,fallbackModel:r.refusal_fallback.fallback_model,content:r.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest({...t,request:{...t.request,server_policy_ask_only:void 0}}).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(Wn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(tv());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(pn(Error(g.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:typeof g.error_code==="string"&&BYe.test(g.error_code)?g.error_code:void 0}));if(!s&&(g.pending_permission_requests||g.pending_user_dialog_requests))K(`[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 Yt("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 Yt("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 Yt("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 Yt("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 Yt("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return Yt("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return Yt("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}=uw(l);if(S9(a,l,p),d.timeout!==c.settings.timeout||d.disableAutoBackground!==c.settings.disableAutoBackground)K(`[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&&!C2(d.tools,c.settings.tools))K(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){K("[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++,K(`[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(K(`[Query.streamInput] Finished processing ${t} messages from input stream`),t>0&&this.hasBidirectionalNeeds())K("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();K("[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)K("[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(()=>{K(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,bc)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return K("[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 ev((i)=>this.sendMcpServerMessageToCli(e,i)),r=t.instance.connect(n).catch((i)=>{if(this.sdkMcpServers.get(e)?.transport===n)this.sdkMcpServers.delete(e);K(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${i}`,{level:"error"})}),{settings:o,ignored:s}=uw(t);S9(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}:${yy}`;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(yy)){K(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let n={type:"control_request",request_id:Aa(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&_9(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.writeAfterInitialize(se(n)+`
163
- `).catch((r)=>{K(`[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 tv(){return Error("Query closed before response received")}var BYe=/^[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 KYe(e){try{let t=$e(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=$e(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 b9=typeof globalThis==="object"?globalThis:global;var rs="1.9.0";var C9=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function GYe(e){var t=new Set([e]),n=new Set,r=e.match(C9);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(C9);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 A9=GYe(rs);var WYe=rs.split(".")[0],Gp=Symbol.for("opentelemetry.js.api."+WYe),Wp=b9;function Fc(e,t,n,r){var o;if(r===void 0)r=!1;var s=Wp[Gp]=(o=Wp[Gp])!==null&&o!==void 0?o:{version:rs};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!==rs){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+rs);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+rs+"."),!0}function os(e){var t,n,r=(t=Wp[Gp])===null||t===void 0?void 0:t.version;if(!r||!A9(r))return;return(n=Wp[Gp])===null||n===void 0?void 0:n[e]}function $c(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+rs+".");var n=Wp[Gp];if(n)delete n[e]}var VYe=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},qYe=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))},R9=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 Vp("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("verbose",this._namespace,t)},e}();function Vp(e,t,n){var r=os("diag");if(!r)return;return n.unshift(t),r[e].apply(r,qYe([],VYe(n),!1))}var wn;(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"})(wn||(wn={}));function T9(e,t){if(e<wn.NONE)e=wn.NONE;else if(e>wn.ALL)e=wn.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",wn.ERROR),warn:n("warn",wn.WARN),info:n("info",wn.INFO),debug:n("debug",wn.DEBUG),verbose:n("verbose",wn.VERBOSE)}}var ZYe=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},YYe=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))},JYe="diag",Ai=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=os("diag");if(!a)return;return a[o].apply(a,YYe([],ZYe(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:wn.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=os("diag"),p=T9((a=s.logLevel)!==null&&a!==void 0?a:wn.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 Fc("diag",p,n,!0)};n.setLogger=r,n.disable=function(){$c(JYe,n)},n.createComponentLogger=function(o){return new R9(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 XYe=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},QYe=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.")},O9=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=XYe(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=QYe(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 k$t=Ai.instance();function w9(e){if(e===void 0)e={};return new O9(new Map(Object.entries(e)))}function x9(e){return Symbol.for(e)}var e4e=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}(),v9=new e4e;var k9={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},P9={set:function(e,t,n){if(e==null)return;e[t]=n}};var t4e=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},n4e=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))},I9=function(){function e(){}return e.prototype.active=function(){return v9},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,n4e([r],t4e(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var r4e=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},o4e=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))},nv="context",s4e=new I9,Ey=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return Fc(nv,t,Ai.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,o4e([t,n,r],r4e(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return os(nv)||s4e},e.prototype.disable=function(){this._getContextManager().disable(),$c(nv,Ai.instance())},e}();var rv=Ey.getInstance();var D9=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 ov=x9("OpenTelemetry Baggage Key");function sv(e){return e.getValue(ov)||void 0}function L9(){return sv(Ey.getInstance().active())}function M9(e,t){return e.setValue(ov,t)}function N9(e){return e.deleteValue(ov)}var iv="propagation",i4e=new D9,U9=function(){function e(){this.createBaggage=w9,this.getBaggage=sv,this.getActiveBaggage=L9,this.setBaggage=M9,this.deleteBaggage=N9}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return Fc(iv,t,Ai.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=P9;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=k9;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){$c(iv,Ai.instance())},e.prototype._getGlobalPropagator=function(){return os(iv)||i4e},e}();var av=U9.getInstance();var F9=600000,by=["SessionStart","Setup"];var Cy=60000,$9=F9,uzt=Cy+$9,a4e="startupHooksOpen",l4e=64;class lv{clock;onRunning;limitMs;countedLeftMs;uncountedLeftMs;uncountedMs=0;counting=!0;armedAtMs=0;cancelTimer;rejectExpired;followed=new Set;unfollowedOpen=0;reportedEvents=new Set;reported=0;constructor(e,t=$a,n){this.clock=t;this.onRunning=n;this.limitMs=e??Cy,this.countedLeftMs=this.limitMs,this.uncountedLeftMs=e==null?$9:0}race(e){let t=new Promise((n,r)=>{this.rejectExpired=r});return this.arm(),Promise.race([e,t]).finally(()=>this.end())}note(e){if(this.rejectExpired===void 0||e.type!=="system")return;switch(e.subtype){case"hook_started":if(!by.includes(e.hook_event)||this.followed.has(e.hook_id))return;if(this.followed.size<l4e)this.followed.add(e.hook_id);else this.unfollowedOpen++;if(this.reportedEvents.add(e.hook_event),this.reported++,this.counting&&this.uncountedLeftMs>0)this.countedLeftMs=Math.max(0,this.countedLeftMs-this.armedForMs()),this.counting=!1,this.arm();this.onRunning?.(this.open());return;case"hook_response":if(!this.followed.delete(e.hook_id)){if(this.unfollowedOpen===0||!by.includes(e.hook_event))return;this.unfollowedOpen--}if(!this.counting)this.countAgain();this.onRunning?.(this.open());return;default:return}}open(){return this.followed.size+this.unfollowedOpen}armedForMs(){return this.clock.monotonicNow()-this.armedAtMs}arm(){if(this.cancelTimer?.(),this.armedAtMs=this.clock.monotonicNow(),!this.counting){this.cancelTimer=this.clock.setTimeout(()=>this.countAgain(),this.uncountedLeftMs);return}let e=Math.min(this.countedLeftMs,bc);this.cancelTimer=this.clock.setTimeout(()=>{if(this.countedLeftMs-=e,this.countedLeftMs>0)this.arm();else this.expire()},e)}countAgain(){let e=Math.min(Math.max(0,this.armedForMs()),this.uncountedLeftMs);this.uncountedLeftMs-=e,this.uncountedMs+=e,this.counting=this.open()===0||this.uncountedLeftMs<=0,this.arm()}expire(){let e=this.rejectExpired,t=`Subprocess initialization did not complete within ${this.limitMs}ms`,n=by.join(" or "),r=Math.round(this.uncountedMs/1000),o=this.open(),s=`${this.reported} ${[...this.reportedEvents].join(" and ")} ${Es(this.reported,"hook")}`,i=[`${t}.`,...r>0?[`Not counted: ${r} ${Es(r,"second")} in which Claude Code reported a ${n} hook running.`]:[],this.reported===0?`Claude Code did not answer the initialize request and reported no ${n} hook running. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:o===0?`Claude Code reported ${s}, which ${this.reported===1?"":"all "}finished, and then did not answer the initialize request. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:`Claude Code reported ${s}, ${this.reported===1?"which had not finished":o===this.reported?"none of which had finished":`${o} of which had not finished`}, and did not answer the initialize request. A hook that runs in the background counts as not finished until it ends. Check ${this.reported===1?"this hook":"these hooks"} first, then authentication and network connectivity.`],a=Object.assign(pn(Error(i.join(" ")),{telemetryMessage:t,errorClass:"initialize_timeout"}),{[a4e]:o});this.end(),e?.(a)}end(){this.cancelTimer?.(),this.cancelTimer=void 0,this.rejectExpired=void 0}}import{copyFile as c4e,readFile as u4e,rm as H9,writeFile as j9}from"fs/promises";import{homedir as z9}from"os";import{join as cv}from"path";function B9(e){return{globalConfig:cv(e||z9(),".claude.json"),userSettings:cv(e||cv(z9(),".claude"),"settings.json")}}function uv(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function zc(e,t,n,r){if(r)return d4e(r,e,t,n);try{if(n)await j9(t,n(await u4e(e)),{mode:384});else await c4e(e,t)}catch(o){if(fe(o)===void 0)throw o;if(!ot(o))await H9(t,{force:!0}).catch(()=>{}),K(`sessionStore resume: skipping ${e} (${fe(o)})`)}}async function d4e({backend:e,key:t},n,r,o){let s=await e.read([t]);if(!s.ok){if(s.error.code==="InvalidArgument")throw new ke(`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)");K(`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 j9(r,o?o(a):a,{mode:384})}catch(l){if(fe(l)===void 0)throw l;if(!ot(l))await H9(r,{force:!0}).catch(()=>{}),K(`sessionStore resume: skipping ${n} (${fe(l)})`)}}import{createHash as p4e}from"crypto";import{homedir as Ezt,userInfo as f4e}from"os";var K9="-credentials";function G9(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"):It(),o=n?"":`-${p4e("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${RD().OAUTH_FILE_SUFFIX}${e}${o}`}var m4e=/^[a-zA-Z0-9._-]+$/;function W9(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||f4e().username}catch{e="claude-code-user"}if(!m4e.test(e))return"claude-code-user";return e}class V9{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var Tzt=new Ie(()=>new V9);function g4e(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 q9(e,t,n){if(!e)return;let r=g4e(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as h4e}from"fs";import{isAbsolute as _4e,relative as y4e,resolve as S4e,sep as E4e}from"path";function dv(e){let t=S4e(e??"."),n;try{n=h4e(t)}catch{n=t}return Ge(n)}function xn(e,t){let n=dv(e);if(t===void 0)return Wr(n);return(t.CLAUDE_CONFIG_DIR?aE(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??vu(n)}function qp(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function pv(e,t){let n=y4e(t,e),r=n.split(E4e);if(r[0]===".."||_4e(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 v4e=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function Y9(e){let t;try{t=$e(lc(e.toString("utf8")))}catch{return e}if(!J9(t))return e;let n=!1;for(let o of v4e)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(J9(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?se(t):e}function J9(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function k4e(e,t){if(!e)return;let n=e;try{let r=$e(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=se(r)}catch{}await Q9(t,n,{mode:384})}function P4e(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=G9(K9);return new Promise((t)=>{b4e("security",["find-generic-password","-a",W9(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function nJ(e,t,n,r,o=60000,s){if(!Be(t))return;let i=xn(n,r),a=await Cr(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=yt(O4e(),`claude-resume-${C4e()}`);try{let c=yt(l,"projects",i);await Ay(c,{recursive:!0,mode:448});let d=yt(c,`${t}.jsonl`);await xu(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??yt(Zp(),".claude"),m;try{m=await R4e(yt(f,".credentials.json"),"utf-8")}catch(E){if(!ot(E))throw E}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await P4e()??m;await k4e(m,yt(l,".credentials.json"));let g=B9(Uf("CLAUDE_CONFIG_DIR")),_=p||Zp(),S=yt(_,".claude.json");await zc(S,yt(l,".claude.json"),void 0,uv(s,S,g.globalConfig,Lt.globalConfig())),await zc(yt(f,".config.json"),yt(l,".config.json"));for(let E of CD)if(E)await zc(yt(_,`.claude${E}.json`),yt(l,`.claude${E}.json`));let y=yt(f,"settings.json");if(await zc(y,yt(l,"settings.json"),Y9,uv(s,y,g.userSettings,Lt.userSettings())),await zc(yt(f,"cowork_settings.json"),yt(l,"cowork_settings.json"),Y9),e.listSubkeys)await I4e(e,{projectKey:i,sessionId:t},yt(c,t),o);return l}catch(c){throw await Ry(l),c}}async function I4e(e,t,n,r){let o=await Cr(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=Yp(n,s+".jsonl");if(!s||fv(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+w4e)){K(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Cr(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(qp(d))l.push(d);else c.push(d);if(c.length>0)await Ay(Z9(i),{recursive:!0}),await xu(i,c);if(l.length>0){let d=l.at(-1),p=Yp(n,s+".meta.json");await Ay(Z9(p),{recursive:!0});let{type:f,...m}=d;await Q9(p,se(m),{mode:384})}}}function rJ(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(eJ.isAbsolute(e.directory)||tJ.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&t===void 0)K("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return t}var D4e=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function mv(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o,readsStartupMarks:s}=t,{systemPrompt:i,settings:a,managedSettings:l,settingSources:c,sandbox:d,...p}=e??{},f,m,g,_;if(i===void 0)f="";else if(typeof i==="string")f=i;else if(Array.isArray(i))f=i;else if(i.type==="custom")f=i.prompt,_=i.snapshot;else if(i.type==="preset")m=i.append,g=i.excludeDynamicSections,_=i.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.305";let{abortController:S=jp(),additionalDirectories:y=[],projectConfigRoot:E,agent:b,agents:C,allowedTools:A=[],betas:w,canUseTool:L,continue:U,cwd:F,debug:ce,debugFile:O,disallowedTools:T=[],tools:v,env:D,executable:z=tl()?"bun":"node",executableArgs:te=[],extraArgs:ue={},fallbackModel:W,enableFileCheckpointing:G,toolConfig:st,forkSession:it,hooks:dt,includeHookEvents:hn,includePartialMessages:Ze,forwardSubagentText:vn,verbatimPrompts:Ye=!1,onElicitation:_e,onUserDialog:Xt,supportedDialogKinds:kt,perTaskStopAffordance:So,rapidFollowupPreempt:ya,workspaceTrust:Ri,persistSession:Sr,sessionStore:Qt,sessionStoreFlush:Hc,thinking:is,effort:jc,maxThinkingTokens:Bc,maxTurns:Sa,maxBudgetUsd:Kc,taskBudget:Ea,mcpServers:Gc,model:Wc,outputFormat:Jp,permissionMode:Oy,allowDangerouslySkipPermissions:me=!1,permissionPromptToolName:dn,permissionPrompts:Er,plugins:$r,pluginDelivery:as="argv",getOAuthToken:Vc,getHostAuthToken:ba,workload:qc,resume:yv,resumeSessionAt:CJ,resumeDropsTurn:AJ,sessionId:RJ,skills:Sv,stderr:TJ,strictMcpConfig:OJ}=p,Ev=Oy;if(Qt&&Sr===!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(kt!==void 0&&kt.length>0&&!Xt)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 wJ=rJ(Ri);if(Qt&&U&&!yv&&!Qt.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(Qt&&G)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(Qt&&p.spawnClaudeCodeProcess)K("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(q9(!!L,Ev??"default",A),as!=="argv"&&as!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let bv=as==="initialize"&&$r!==void 0&&$r.length>0,wy=p.pathToClaudeCodeExecutable;if(!wy){let Nt=x4e(import.meta.url),kn=T4e(Nt),zr=a9((Ca)=>kn.resolve(Ca));if(!zr)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.`);wy=zr}let Cv=Jp?.type==="json_schema"?Jp.schema:void 0,pt=D?{...D}:{...process.env};if(!pt.CLAUDE_CODE_ENTRYPOINT)pt.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!pt.CLAUDE_AGENT_SDK_VERSION)pt.CLAUDE_AGENT_SDK_VERSION="0.3.305";if(G)pt.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(pt).some((Nt)=>Nt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))pt.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(s&&!Object.keys(pt).some((Nt)=>Nt.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))pt.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let xy=lu(pt.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),xJ=Number.isFinite(xy)&&xy>=0?xy:_y;if(Vc)pt.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(ba)pt.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(st?.askUserQuestion?.previewFormat)pt.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=st.askUserQuestion.previewFormat;for(let[Nt,kn]of[[st?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[st?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(Nt)pt[kn]="1";else if(!D){for(let zr of Object.keys(pt))if(zr.toUpperCase()===kn)delete pt[zr]}let vy={};if(av.inject(rv.active(),vy),"traceparent"in vy){for(let Nt of["TRACEPARENT","TRACESTATE"])if(!(Nt in(D??{})))delete pt[Nt]}for(let[Nt,kn]of Object.entries(vy)){let zr=Nt.toUpperCase();if(!(zr in(D??{})))pt[zr]=kn}let Av={},Rv=new Map;if(Gc)for(let[Nt,kn]of Object.entries(Gc))if(kn.type==="sdk"&&kn.instance)Rv.set(Nt,kn);else Av[Nt]=kn;let Zc;if(is)switch(is.type){case"adaptive":Zc={type:"adaptive",display:is.display};break;case"enabled":Zc={type:"enabled",budgetTokens:is.budgetTokens,display:is.display};break;case"disabled":Zc={type:"disabled"};break}else if(Bc!==void 0)Zc=Bc===0?{type:"disabled"}:{type:"enabled",budgetTokens:Bc};if(r){if(pt.CLAUDE_CONFIG_DIR=r,process.platform==="win32")pt.CLAUDE_SECURESTORAGE_CONFIG_DIR=D?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??D?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let Tv=new Xx({abortController:S,additionalDirectories:y,projectConfigRoot:E,agent:b,betas:w,cwd:F,debug:ce,debugFile:O,executable:z,executableArgs:te,extraArgs:qc?{...ue,workload:qc}:ue,pathToClaudeCodeExecutable:wy,env:pt,forkSession:it,stderr:TJ,thinkingConfig:Zc,effort:jc,maxTurns:Sa,maxBudgetUsd:Kc,taskBudget:Ea,model:Wc,fallbackModel:W,jsonSchema:Cv,permissionMode:Ev,allowDangerouslySkipPermissions:me,permissionPromptToolName:dn,permissionPrompts:Er,continueConversation:Qt?void 0:U,resume:yv,resumeSessionAt:CJ,resumeDropsTurn:AJ,sessionId:RJ,settings:typeof a==="object"?se(a):a,managedSettings:l?se(l):void 0,settingSources:c,skills:Sv,allowedTools:A,disallowedTools:T,tools:v,mcpServers:Av,strictMcpConfig:OJ,canUseTool:!!L,hooks:!!dt,includeHookEvents:hn,includePartialMessages:Ze,persistSession:Sr,sessionMirror:!!Qt,plugins:$r,pluginsViaInitialize:bv,sandbox:d,spawnClaudeCodeProcess:p.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),vJ={systemPrompt:f,appendSystemPrompt:m,planModeInstructions:p.planModeInstructions,systemPromptSnapshot:_,appendSubagentSystemPrompt:p.appendSubagentSystemPrompt,toolAliases:p.toolAliases,codeRunningMcpTools:p.codeRunningMcpTools,excludeDynamicSections:g,agents:C,title:p.title,skills:Sv,webSearchIsolationExemptMcpServers:p.webSearchIsolationExemptMcpServers,promptSuggestions:p.promptSuggestions,agentProgressSummaries:p.agentProgressSummaries,forwardSubagentText:vn,supportedDialogKinds:kt,perTaskStopAffordance:So,rapidFollowupPreempt:ya,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:wJ,plugins:bv?$r:void 0,captureSdkMcpManifests:!Ff("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},ky=new Sy(Tv,n,L,dt,S,Rv,Cv,vJ,_e,Vc,ba,Xt,Ye,xJ);if(Qt){let Nt=()=>yt(pt.CLAUDE_CONFIG_DIR??yt(Zp(),".claude"),"projects"),kn=Hc==="eager",zr=new zE(async(Ca,Py)=>{let Yc=pv(Ca,Nt());if(Yc)await Qt.append(Yc,Py);else K(`[SessionStore] dropping mirror frame: filePath ${Ca} is not under ${Nt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Ca,Py)=>{let Yc=pv(Ca,Nt());if(Yc)ky.reportMirrorError(Yc,Py.message)},maxPendingEntries:kn?0:Eu,maxPendingBytes:kn?0:Ii});ky.setTranscriptMirrorBatcher(zr)}return{queryInstance:ky,transport:Tv,abortController:S,processEnv:pt,verbatimPrompts:Ye}}function gv(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)=>{K(`[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 tv(){return Error("Query closed before response received")}var BYe=/^[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 KYe(e){try{let t=$e(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=$e(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 b9=typeof globalThis==="object"?globalThis:global;var rs="1.9.0";var C9=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function GYe(e){var t=new Set([e]),n=new Set,r=e.match(C9);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(C9);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 A9=GYe(rs);var WYe=rs.split(".")[0],Gp=Symbol.for("opentelemetry.js.api."+WYe),Wp=b9;function Fc(e,t,n,r){var o;if(r===void 0)r=!1;var s=Wp[Gp]=(o=Wp[Gp])!==null&&o!==void 0?o:{version:rs};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!==rs){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+rs);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+rs+"."),!0}function os(e){var t,n,r=(t=Wp[Gp])===null||t===void 0?void 0:t.version;if(!r||!A9(r))return;return(n=Wp[Gp])===null||n===void 0?void 0:n[e]}function $c(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+rs+".");var n=Wp[Gp];if(n)delete n[e]}var VYe=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},qYe=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))},R9=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 Vp("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Vp("verbose",this._namespace,t)},e}();function Vp(e,t,n){var r=os("diag");if(!r)return;return n.unshift(t),r[e].apply(r,qYe([],VYe(n),!1))}var wn;(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"})(wn||(wn={}));function T9(e,t){if(e<wn.NONE)e=wn.NONE;else if(e>wn.ALL)e=wn.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",wn.ERROR),warn:n("warn",wn.WARN),info:n("info",wn.INFO),debug:n("debug",wn.DEBUG),verbose:n("verbose",wn.VERBOSE)}}var ZYe=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},YYe=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))},JYe="diag",Ai=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=os("diag");if(!a)return;return a[o].apply(a,YYe([],ZYe(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:wn.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=os("diag"),p=T9((a=s.logLevel)!==null&&a!==void 0?a:wn.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 Fc("diag",p,n,!0)};n.setLogger=r,n.disable=function(){$c(JYe,n)},n.createComponentLogger=function(o){return new R9(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 XYe=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},QYe=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.")},O9=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=XYe(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=QYe(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 k$t=Ai.instance();function w9(e){if(e===void 0)e={};return new O9(new Map(Object.entries(e)))}function x9(e){return Symbol.for(e)}var e4e=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}(),v9=new e4e;var k9={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},P9={set:function(e,t,n){if(e==null)return;e[t]=n}};var t4e=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},n4e=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))},I9=function(){function e(){}return e.prototype.active=function(){return v9},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,n4e([r],t4e(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var r4e=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},o4e=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))},nv="context",s4e=new I9,Ey=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return Fc(nv,t,Ai.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,o4e([t,n,r],r4e(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return os(nv)||s4e},e.prototype.disable=function(){this._getContextManager().disable(),$c(nv,Ai.instance())},e}();var rv=Ey.getInstance();var D9=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 ov=x9("OpenTelemetry Baggage Key");function sv(e){return e.getValue(ov)||void 0}function L9(){return sv(Ey.getInstance().active())}function M9(e,t){return e.setValue(ov,t)}function N9(e){return e.deleteValue(ov)}var iv="propagation",i4e=new D9,U9=function(){function e(){this.createBaggage=w9,this.getBaggage=sv,this.getActiveBaggage=L9,this.setBaggage=M9,this.deleteBaggage=N9}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return Fc(iv,t,Ai.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=P9;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=k9;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){$c(iv,Ai.instance())},e.prototype._getGlobalPropagator=function(){return os(iv)||i4e},e}();var av=U9.getInstance();var F9=600000,by=["SessionStart","Setup"];var Cy=60000,$9=F9,uzt=Cy+$9,a4e="startupHooksOpen",l4e=64;class lv{clock;onRunning;limitMs;countedLeftMs;uncountedLeftMs;uncountedMs=0;counting=!0;armedAtMs=0;cancelTimer;rejectExpired;followed=new Set;unfollowedOpen=0;reportedEvents=new Set;reported=0;constructor(e,t=$a,n){this.clock=t;this.onRunning=n;this.limitMs=e??Cy,this.countedLeftMs=this.limitMs,this.uncountedLeftMs=e==null?$9:0}race(e){let t=new Promise((n,r)=>{this.rejectExpired=r});return this.arm(),Promise.race([e,t]).finally(()=>this.end())}note(e){if(this.rejectExpired===void 0||e.type!=="system")return;switch(e.subtype){case"hook_started":if(!by.includes(e.hook_event)||this.followed.has(e.hook_id))return;if(this.followed.size<l4e)this.followed.add(e.hook_id);else this.unfollowedOpen++;if(this.reportedEvents.add(e.hook_event),this.reported++,this.counting&&this.uncountedLeftMs>0)this.countedLeftMs=Math.max(0,this.countedLeftMs-this.armedForMs()),this.counting=!1,this.arm();this.onRunning?.(this.open());return;case"hook_response":if(!this.followed.delete(e.hook_id)){if(this.unfollowedOpen===0||!by.includes(e.hook_event))return;this.unfollowedOpen--}if(!this.counting)this.countAgain();this.onRunning?.(this.open());return;default:return}}open(){return this.followed.size+this.unfollowedOpen}armedForMs(){return this.clock.monotonicNow()-this.armedAtMs}arm(){if(this.cancelTimer?.(),this.armedAtMs=this.clock.monotonicNow(),!this.counting){this.cancelTimer=this.clock.setTimeout(()=>this.countAgain(),this.uncountedLeftMs);return}let e=Math.min(this.countedLeftMs,bc);this.cancelTimer=this.clock.setTimeout(()=>{if(this.countedLeftMs-=e,this.countedLeftMs>0)this.arm();else this.expire()},e)}countAgain(){let e=Math.min(Math.max(0,this.armedForMs()),this.uncountedLeftMs);this.uncountedLeftMs-=e,this.uncountedMs+=e,this.counting=this.open()===0||this.uncountedLeftMs<=0,this.arm()}expire(){let e=this.rejectExpired,t=`Subprocess initialization did not complete within ${this.limitMs}ms`,n=by.join(" or "),r=Math.round(this.uncountedMs/1000),o=this.open(),s=`${this.reported} ${[...this.reportedEvents].join(" and ")} ${Es(this.reported,"hook")}`,i=[`${t}.`,...r>0?[`Not counted: ${r} ${Es(r,"second")} in which Claude Code reported a ${n} hook running.`]:[],this.reported===0?`Claude Code did not answer the initialize request and reported no ${n} hook running. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:o===0?`Claude Code reported ${s}, which ${this.reported===1?"":"all "}finished, and then did not answer the initialize request. Slow plugins, MCP servers, hooks that Claude Code does not report, disks or network can each cause this.`:`Claude Code reported ${s}, ${this.reported===1?"which had not finished":o===this.reported?"none of which had finished":`${o} of which had not finished`}, and did not answer the initialize request. A hook that runs in the background counts as not finished until it ends. Check ${this.reported===1?"this hook":"these hooks"} first, then authentication and network connectivity.`],a=Object.assign(pn(Error(i.join(" ")),{telemetryMessage:t,errorClass:"initialize_timeout"}),{[a4e]:o});this.end(),e?.(a)}end(){this.cancelTimer?.(),this.cancelTimer=void 0,this.rejectExpired=void 0}}import{copyFile as c4e,readFile as u4e,rm as H9,writeFile as j9}from"fs/promises";import{homedir as z9}from"os";import{join as cv}from"path";function B9(e){return{globalConfig:cv(e||z9(),".claude.json"),userSettings:cv(e||cv(z9(),".claude"),"settings.json")}}function uv(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function zc(e,t,n,r){if(r)return d4e(r,e,t,n);try{if(n)await j9(t,n(await u4e(e)),{mode:384});else await c4e(e,t)}catch(o){if(fe(o)===void 0)throw o;if(!ot(o))await H9(t,{force:!0}).catch(()=>{}),K(`sessionStore resume: skipping ${e} (${fe(o)})`)}}async function d4e({backend:e,key:t},n,r,o){let s=await e.read([t]);if(!s.ok){if(s.error.code==="InvalidArgument")throw new ke(`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)");K(`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 j9(r,o?o(a):a,{mode:384})}catch(l){if(fe(l)===void 0)throw l;if(!ot(l))await H9(r,{force:!0}).catch(()=>{}),K(`sessionStore resume: skipping ${n} (${fe(l)})`)}}import{createHash as p4e}from"crypto";import{homedir as Ezt,userInfo as f4e}from"os";var K9="-credentials";function G9(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"):It(),o=n?"":`-${p4e("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${RD().OAUTH_FILE_SUFFIX}${e}${o}`}var m4e=/^[a-zA-Z0-9._-]+$/;function W9(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||f4e().username}catch{e="claude-code-user"}if(!m4e.test(e))return"claude-code-user";return e}class V9{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var Tzt=new Ie(()=>new V9);function g4e(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 q9(e,t,n){if(!e)return;let r=g4e(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as h4e}from"fs";import{isAbsolute as _4e,relative as y4e,resolve as S4e,sep as E4e}from"path";function dv(e){let t=S4e(e??"."),n;try{n=h4e(t)}catch{n=t}return Ge(n)}function xn(e,t){let n=dv(e);if(t===void 0)return Wr(n);return(t.CLAUDE_CONFIG_DIR?aE(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??vu(n)}function qp(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function pv(e,t){let n=y4e(t,e),r=n.split(E4e);if(r[0]===".."||_4e(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 v4e=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function Y9(e){let t;try{t=$e(lc(e.toString("utf8")))}catch{return e}if(!J9(t))return e;let n=!1;for(let o of v4e)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(J9(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?se(t):e}function J9(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function k4e(e,t){if(!e)return;let n=e;try{let r=$e(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=se(r)}catch{}await Q9(t,n,{mode:384})}function P4e(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=G9(K9);return new Promise((t)=>{b4e("security",["find-generic-password","-a",W9(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function nJ(e,t,n,r,o=60000,s){if(!Be(t))return;let i=xn(n,r),a=await Cr(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=yt(O4e(),`claude-resume-${C4e()}`);try{let c=yt(l,"projects",i);await Ay(c,{recursive:!0,mode:448});let d=yt(c,`${t}.jsonl`);await xu(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??yt(Zp(),".claude"),m;try{m=await R4e(yt(f,".credentials.json"),"utf-8")}catch(E){if(!ot(E))throw E}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await P4e()??m;await k4e(m,yt(l,".credentials.json"));let g=B9(Uf("CLAUDE_CONFIG_DIR")),_=p||Zp(),S=yt(_,".claude.json");await zc(S,yt(l,".claude.json"),void 0,uv(s,S,g.globalConfig,Lt.globalConfig())),await zc(yt(f,".config.json"),yt(l,".config.json"));for(let E of CD)if(E)await zc(yt(_,`.claude${E}.json`),yt(l,`.claude${E}.json`));let y=yt(f,"settings.json");if(await zc(y,yt(l,"settings.json"),Y9,uv(s,y,g.userSettings,Lt.userSettings())),await zc(yt(f,"cowork_settings.json"),yt(l,"cowork_settings.json"),Y9),e.listSubkeys)await I4e(e,{projectKey:i,sessionId:t},yt(c,t),o);return l}catch(c){throw await Ry(l),c}}async function I4e(e,t,n,r){let o=await Cr(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=Yp(n,s+".jsonl");if(!s||fv(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+w4e)){K(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Cr(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(qp(d))l.push(d);else c.push(d);if(c.length>0)await Ay(Z9(i),{recursive:!0}),await xu(i,c);if(l.length>0){let d=l.at(-1),p=Yp(n,s+".meta.json");await Ay(Z9(p),{recursive:!0});let{type:f,...m}=d;await Q9(p,se(m),{mode:384})}}}function rJ(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(eJ.isAbsolute(e.directory)||tJ.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&t===void 0)K("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return t}var D4e=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function mv(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o,readsStartupMarks:s}=t,{systemPrompt:i,settings:a,managedSettings:l,settingSources:c,sandbox:d,...p}=e??{},f,m,g,_;if(i===void 0)f="";else if(typeof i==="string")f=i;else if(Array.isArray(i))f=i;else if(i.type==="custom")f=i.prompt,_=i.snapshot;else if(i.type==="preset")m=i.append,g=i.excludeDynamicSections,_=i.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.306";let{abortController:S=jp(),additionalDirectories:y=[],projectConfigRoot:E,agent:b,agents:C,allowedTools:A=[],betas:w,canUseTool:L,continue:U,cwd:F,debug:ce,debugFile:O,disallowedTools:T=[],tools:v,env:D,executable:z=tl()?"bun":"node",executableArgs:te=[],extraArgs:ue={},fallbackModel:W,enableFileCheckpointing:G,toolConfig:st,forkSession:it,hooks:dt,includeHookEvents:hn,includePartialMessages:Ze,forwardSubagentText:vn,verbatimPrompts:Ye=!1,onElicitation:_e,onUserDialog:Xt,supportedDialogKinds:kt,perTaskStopAffordance:So,rapidFollowupPreempt:ya,workspaceTrust:Ri,persistSession:Sr,sessionStore:Qt,sessionStoreFlush:Hc,thinking:is,effort:jc,maxThinkingTokens:Bc,maxTurns:Sa,maxBudgetUsd:Kc,taskBudget:Ea,mcpServers:Gc,model:Wc,outputFormat:Jp,permissionMode:Oy,allowDangerouslySkipPermissions:me=!1,permissionPromptToolName:dn,permissionPrompts:Er,plugins:$r,pluginDelivery:as="argv",getOAuthToken:Vc,getHostAuthToken:ba,workload:qc,resume:yv,resumeSessionAt:CJ,resumeDropsTurn:AJ,sessionId:RJ,skills:Sv,stderr:TJ,strictMcpConfig:OJ}=p,Ev=Oy;if(Qt&&Sr===!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(kt!==void 0&&kt.length>0&&!Xt)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 wJ=rJ(Ri);if(Qt&&U&&!yv&&!Qt.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(Qt&&G)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(Qt&&p.spawnClaudeCodeProcess)K("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(q9(!!L,Ev??"default",A),as!=="argv"&&as!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let bv=as==="initialize"&&$r!==void 0&&$r.length>0,wy=p.pathToClaudeCodeExecutable;if(!wy){let Nt=x4e(import.meta.url),kn=T4e(Nt),zr=a9((Ca)=>kn.resolve(Ca));if(!zr)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.`);wy=zr}let Cv=Jp?.type==="json_schema"?Jp.schema:void 0,pt=D?{...D}:{...process.env};if(!pt.CLAUDE_CODE_ENTRYPOINT)pt.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!pt.CLAUDE_AGENT_SDK_VERSION)pt.CLAUDE_AGENT_SDK_VERSION="0.3.306";if(G)pt.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(pt).some((Nt)=>Nt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))pt.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";if(s&&!Object.keys(pt).some((Nt)=>Nt.toUpperCase()==="CLAUDE_CODE_SDK_READS_STARTUP_MARKS"))pt.CLAUDE_CODE_SDK_READS_STARTUP_MARKS="1";let xy=lu(pt.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),xJ=Number.isFinite(xy)&&xy>=0?xy:_y;if(Vc)pt.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(ba)pt.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(st?.askUserQuestion?.previewFormat)pt.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=st.askUserQuestion.previewFormat;for(let[Nt,kn]of[[st?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[st?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"],[!1,"CLAUDE_CODE_AGENT_PROGRESS_SUMMARIES"]])if(Nt)pt[kn]="1";else if(!D){for(let zr of Object.keys(pt))if(zr.toUpperCase()===kn)delete pt[zr]}let vy={};if(av.inject(rv.active(),vy),"traceparent"in vy){for(let Nt of["TRACEPARENT","TRACESTATE"])if(!(Nt in(D??{})))delete pt[Nt]}for(let[Nt,kn]of Object.entries(vy)){let zr=Nt.toUpperCase();if(!(zr in(D??{})))pt[zr]=kn}let Av={},Rv=new Map;if(Gc)for(let[Nt,kn]of Object.entries(Gc))if(kn.type==="sdk"&&kn.instance)Rv.set(Nt,kn);else Av[Nt]=kn;let Zc;if(is)switch(is.type){case"adaptive":Zc={type:"adaptive",display:is.display};break;case"enabled":Zc={type:"enabled",budgetTokens:is.budgetTokens,display:is.display};break;case"disabled":Zc={type:"disabled"};break}else if(Bc!==void 0)Zc=Bc===0?{type:"disabled"}:{type:"enabled",budgetTokens:Bc};if(r){if(pt.CLAUDE_CONFIG_DIR=r,process.platform==="win32")pt.CLAUDE_SECURESTORAGE_CONFIG_DIR=D?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??D?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let Tv=new Xx({abortController:S,additionalDirectories:y,projectConfigRoot:E,agent:b,betas:w,cwd:F,debug:ce,debugFile:O,executable:z,executableArgs:te,extraArgs:qc?{...ue,workload:qc}:ue,pathToClaudeCodeExecutable:wy,env:pt,forkSession:it,stderr:TJ,thinkingConfig:Zc,effort:jc,maxTurns:Sa,maxBudgetUsd:Kc,taskBudget:Ea,model:Wc,fallbackModel:W,jsonSchema:Cv,permissionMode:Ev,allowDangerouslySkipPermissions:me,permissionPromptToolName:dn,permissionPrompts:Er,continueConversation:Qt?void 0:U,resume:yv,resumeSessionAt:CJ,resumeDropsTurn:AJ,sessionId:RJ,settings:typeof a==="object"?se(a):a,managedSettings:l?se(l):void 0,settingSources:c,skills:Sv,allowedTools:A,disallowedTools:T,tools:v,mcpServers:Av,strictMcpConfig:OJ,canUseTool:!!L,hooks:!!dt,includeHookEvents:hn,includePartialMessages:Ze,persistSession:Sr,sessionMirror:!!Qt,plugins:$r,pluginsViaInitialize:bv,sandbox:d,spawnClaudeCodeProcess:p.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),vJ={systemPrompt:f,appendSystemPrompt:m,planModeInstructions:p.planModeInstructions,systemPromptSnapshot:_,appendSubagentSystemPrompt:p.appendSubagentSystemPrompt,toolAliases:p.toolAliases,codeRunningMcpTools:p.codeRunningMcpTools,excludeDynamicSections:g,agents:C,title:p.title,skills:Sv,webSearchIsolationExemptMcpServers:p.webSearchIsolationExemptMcpServers,promptSuggestions:p.promptSuggestions,agentProgressSummaries:p.agentProgressSummaries,forwardSubagentText:vn,supportedDialogKinds:kt,perTaskStopAffordance:So,rapidFollowupPreempt:ya,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:wJ,plugins:bv?$r:void 0,captureSdkMcpManifests:!Ff("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},ky=new Sy(Tv,n,L,dt,S,Rv,Cv,vJ,_e,Vc,ba,Xt,Ye,xJ);if(Qt){let Nt=()=>yt(pt.CLAUDE_CONFIG_DIR??yt(Zp(),".claude"),"projects"),kn=Hc==="eager",zr=new zE(async(Ca,Py)=>{let Yc=pv(Ca,Nt());if(Yc)await Qt.append(Yc,Py);else K(`[SessionStore] dropping mirror frame: filePath ${Ca} is not under ${Nt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(Ca,Py)=>{let Yc=pv(Ca,Nt());if(Yc)ky.reportMirrorError(Yc,Py.message)},maxPendingEntries:kn?0:Eu,maxPendingBytes:kn?0:Ii});ky.setTranscriptMirrorBatcher(zr)}return{queryInstance:ky,transport:Tv,abortController:S,processEnv:pt,verbatimPrompts:Ye}}function gv(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 L4e=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function Ry(e){for(let t=0;;t++)try{return await X9(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!L4e.has(fe(n)??""))return;await Vn((t+1)*100)}}function M4e(e,t){e.waitForExit().catch(()=>{}).finally(()=>Ry(t))}function N4e({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return U4e(e,t);let{queryInstance:n,abortController:r,verbatimPrompts:o}=mv(t,{isSingleUserTurn:typeof e==="string"});return gv(n,e,r,o),n}function U4e(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s,verbatimPrompts:i}=mv({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),a=Yp(t.cwd??"."),l=t.sessionStore,c=t.loadTimeoutMs??60000,d=t.resume;return(async()=>{if(!d)d=(await Cr(l.listSessions(xn(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 nJ(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(()=>M4e(r,f))}if(!n.isClosed())r.spawn()}).catch((f)=>{let m=Wn(f);r.spawnAbort(m),n.setError(m)}),gv(n,e,o,i),n}async function F4e(e={}){return(await oJ(e)).warm}async function oJ({options:e,initializeTimeoutMs:t}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=Yp(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 Cr(e.sessionStore.listSessions(xn(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 nJ(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let _=function(){if(g)return;g=!0,p.close()},a=mv(n&&r&&r!==e?.resume?{...e,resume:r}:e,{isSingleUserTurn:!1,resumeConfigDir:n,readsStartupMarks:!0});o=a.queryInstance;let{transport:l,abortController:c,verbatimPrompts:d}=a;s=l;let p=a.queryInstance;if(n){let y=n;p.addCleanupCallback(()=>{i=l.waitForExit().catch(()=>{}).then(()=>Ry(y))})}let m=new lv(t,$a,e?.onStartupHooksRunning);p.setFrameObserver((y)=>{if(m.note(y),y.type==="system"&&y.subtype==="hook_progress")p.dropUnreadHookProgress(y.hook_id)});try{await m.race(p.initializationResult())}catch(y){if(y instanceof Error&&"errorClass"in y&&y.errorClass==="initialize_timeout"&&Object.isExtensible(y)){let E=p.startupMarkReached();Object.assign(y,{[c9]:E?.mark??"none",...E&&{[u9]:E.ageMs}})}throw y}finally{p.setFrameObserver(void 0)}let g=!1;return{warm:{query(y){if(g)throw Error("WarmQuery.query() can only be called once");g=!0;try{gv(p,y,c,d)}catch(E){throw p.close(),E}if(typeof y==="string")p.setIsSingleUserTurn(!0);return p},close:_,async[Symbol.asyncDispose](){g=!0,p.close(),await i}},query:p,transport:l}}catch(a){if(o?.close(),n&&!i){let l=s;i=(l?l.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>Ry(n))}throw await i,a}}async function $4e({options:e,initializeTimeoutMs:t}={}){if(e?.resume||e?.continue||e?.forkSession)throw Error("prewarm(): resume/continue/forkSession describe a session; a spare has none — pass them to query() instead");let n=e?.cwd===void 0,r;if(e?.cwd!==void 0)r=e.cwd;else{let C=e?.env,A=C?.CLAUDE_CONFIG_DIR?.trim(),w=C?.HOME?.trim(),L=C===void 0?It():A||yt(w||Zp(),".claude"),U=fv(L)?L:yt(Zp(),".claude");if(!fv(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=yt(U,"spares");await Ay(F,{recursive:!0,mode:448}),r=await A4e(yt(F,"spare-"))}function o(){return n?X9(r,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve()}let{workspaceTrust:s,...i}=e??{};if(s!==void 0)K("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 Yt("sdk_prewarm",async()=>{try{return await oJ({options:{...i,cwd:r,extraArgs:{...i.extraArgs,"await-claim":null}},initializeTimeoutMs:t??Cy})}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 E=c.waitForExit().then(()=>{return},()=>{return});E.then(()=>{if(!m)_=!0,S.reject(Error("spare_exited: the spare process exited before it was claimed")),f()});let b={claimed:y,exited:E,claim({prompt:C,options:A}){if(m)throw Error("SpareProcess.claim() can only be called once");if(g||_)throw Error("SpareProcess.claim(): the spare was closed or has exited; start the session with query()");let w=D4e.filter((v)=>A.settings?.[v]!==void 0);if(w.length>0)throw new ke(`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()!==""&&!eJ.isAbsolute(A.cwd)&&!tJ.isAbsolute(A.cwd)&&A.cwd!=="~"&&!A.cwd.startsWith("~/")?Yp(A.cwd):A.cwd;m=!0;let U=rJ(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}),ce=[];if(A.model!==void 0)ce.push(["model",l.setModel(A.model)]);if(A.maxThinkingTokens!==void 0)ce.push(["maxThinkingTokens",l.setMaxThinkingTokens(A.maxThinkingTokens)]);let O=A.settings!==void 0?l.applyFlagSettings(A.settings):void 0;if(O!==void 0)ce.push(["settings",O]);for(let[,v]of ce)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},z=await Promise.allSettled(ce.map(([,W])=>W)),te=z.flatMap((W,G)=>W.status==="rejected"?[`${String(ce[G][0])}: ${rt(W.reason)}`]:[]),ue=O===void 0?void 0:z[ce.findIndex(([W])=>W==="settings")];if(ue?.status==="rejected")g=!0,l.close(),S.reject(Object.assign(new ke(`settings_not_applied: ${rt(ue.reason)} — the prompt was not sent and the process was closed; start the session with query()`,"settings_not_applied"),{claim:D}));else if(te.length>0)S.reject(Object.assign(new ke(`option_not_applied: ${te.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](){b.close(),await f()}};return b}import{randomUUID as mJ}from"crypto";import{constants as sJ}from"fs";import{open as z4e,readdir as lJ,rm as iJ,stat as H4e}from"fs/promises";import{join as ss}from"path";var j4e=64;function _v(e){return be()?e:void 0}async function cJ(e,t,n={},r){if(!Be(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 fJ(e,o,n,_v(r))}async function uJ(e,t,n={},r){if(!Be(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let s=ki(t).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");t=s}let o=se({type:"tag",tag:t??"",sessionId:e})+`
166
166
  `;await fJ(e,o,n,_v(r))}async function dJ(e,t={},n){if(!Be(e))throw Error(`Invalid sessionId: ${e}`);let r=_v(n);for(let o of await K4e(t,r)){if(be()&&r!==void 0){let a=Ui(o,r.isKeySegment);if(a!==void 0){if(await B4e(a,e,r))return;continue}}let s=ss(o,`${e}.jsonl`),i;try{({size:i}=await H4e(s))}catch(a){let l=fe(a);if(l==="ENOENT"||l==="ENOTDIR")continue;throw a}if(i===0)continue;await iJ(s,{force:!0}),await iJ(ss(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 B4e(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 K4e(e,t){if(e.dir){let r=await Do(e.dir,fm(t,be())),o=await aJ(r,t),s;try{s=await Po(r)}catch{s=[]}for(let i of s){if(i===r)continue;o.push(...await aJ(i,t))}return o}let n=ht();if(be()&&t!==void 0){let r=await pJ(t);if(r===void 0)return[];if(r.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return r.names.map((o)=>ss(n,o))}try{return(await lJ(n,{withFileTypes:!0})).filter((o)=>o.isDirectory()||o.isSymbolicLink()).map((o)=>ss(n,o.name))}catch{return[]}}async function aJ(e,t){let n=sn(t);if(n===void 0||!n.hoverRestOn)return qn(e);let r=await qn(e,n),o=cl(e),s=process.platform==="win32",i=[];for(let a of r)if(a===o||await ul(a,e,s,n))i.push(a);return i}async function pJ(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=gm(s,e.isKeySegment);if(i!==void 0)t.push(i)}n=o.value.cursor}while(n&&++r<j4e);return{names:t,laterPageFailed:Boolean(n)}}catch{return r===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function fJ(e,t,n,r){let o=`${e}.jsonl`;if(n.dir){let a=await Do(n.dir,fm(r,be()));for(let c of await qn(a,sn(r)))if(await Ty(ss(c,o),t,hv(c,e,r)))return;let l;try{l=await Po(a)}catch{l=[]}for(let c of l){if(c===a)continue;for(let d of await qn(c,sn(r)))if(await Ty(ss(d,o),t,hv(d,e,r)))return}throw Error(`Session ${e} not found in project directory for ${n.dir}`)}let s=ht();if(be()&&r!==void 0){let a=await pJ(r);if(a===void 0)throw new ke(`Session ${e} not found (no projects directory)`,"Session not found (no projects directory)");let{names:l}=a;for(let c of l){let d=ss(s,c);if(await Ty(ss(d,o),t,hv(d,e,r)))return}throw new ke(`Session ${e} not found in any project directory`,"Session not found in any project directory")}let i;try{i=await lJ(s)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let a of i)if(await Ty(ss(s,a,o),t))return;throw Error(`Session ${e} not found in any project directory`)}async function Ty(e,t,n){if(be()&&n!==void 0)return G4e(n,t);let r;try{r=await z4e(e,sJ.O_WRONLY|sJ.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 ke(`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 G4e({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 hv(e,t,n){if(!be()||n===void 0)return;let r=Ui(e,n.isKeySegment);return r===void 0?void 0:{backend:n.backend,key:n.transcriptKey(r,t)}}async function W4e(e,t,n){if(n?.sessionStore)return Z4e(n.sessionStore,e,t,n.dir);return cJ(e,t,n)}async function V4e(e,t,n){if(n?.sessionStore)return Y4e(n.sessionStore,e,t,n.dir);return uJ(e,t,n)}async function q4e(e,t){if(!Be(e))throw new ke(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=xn(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return dJ(e,t)}async function Z4e(e,t,n,r){if(!Be(t))throw new ke(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!n.trim())throw Error("title must be non-empty");let o=xn(r);await e.append({projectKey:o,sessionId:t},[{type:"custom-title",customTitle:n.trim(),sessionId:t,uuid:mJ(),timestamp:new Date().toISOString()}])}async function Y4e(e,t,n,r){if(!Be(t))throw new ke(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(n!==null){let s=ki(n).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");n=s}let o=xn(r);await e.append({projectKey:o,sessionId:t},[{type:"tag",tag:n??"",sessionId:t,uuid:mJ(),timestamp:new Date().toISOString()}])}async function ejt(e){return V4(e)}async function rjt(e,t){if(t?.sessionStore)return a9e(t.sessionStore,e,t);return K0(e,t)}async function ojt(e){if(e?.sessionStore)return o9e(e.sessionStore,e);return sF(e)}async function sjt(e,t){if(t?.sessionStore)return l9e(t.sessionStore,e,t);return iF(e,t)}async function ijt(e,t){if(t?.sessionStore)return c9e(t.sessionStore,e,t);return bF(e,t)}async function ajt(e,t,n,r){if(!Be(e))throw new ke(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=be(),s=o?r:void 0,i=await Os(e,n?.dir,$n(s),o);if(!i)throw Error(`Session ${e} not found`);let a=xn(n?.dir),l=n?.batchSize&&n.batchSize>0?n.batchSize:Eu,c=s===void 0?void 0:Ui(e9e(i.filePath),qt),d=s!==void 0&&c!==void 0?{backend:s,projectKey:c}:void 0;if(d!==void 0)await IR(d.backend,Lt.transcript(d.projectKey,e),{projectKey:a,sessionId:e},t,l);else await gJ(i.filePath,{projectKey:a,sessionId:e},t,l);if(n?.includeSubagents===!1)return;if(d!==void 0){let m=await MF(d.backend,d.projectKey,e),g=await NF(d.backend,d.projectKey,e,m);for(let _ of m){let S={projectKey:a,sessionId:e,subpath:cg(_)};await IR(d.backend,_.kind==="agent"?Lt.transcript(d.projectKey,e,_.agentId,_.agentRelPath):Lt.journal(d.projectKey,e,_.agentRelPath),S,t,l);let y=g.get(S.subpath),E;if(y!==void 0)try{E=$e(y)}catch(b){K(`importSessionToStore: skipping unreadable sidecar for ${S.subpath}: ${b}`)}if(E!==void 0)await t.append(S,[{type:"agent_metadata",...E}])}return}let p=i.filePath.replace(/\.jsonl$/,""),f=hJ(p,"subagents");for(let m of await r9e(f)){let g=t9e(p,m).split(n9e);g[g.length-1]=g.at(-1).replace(/\.jsonl$/,"");let _={projectKey:a,sessionId:e,subpath:g.join("/")};await gJ(m,_,t,l);let S=m.replace(/\.jsonl$/,".meta.json"),y;try{y=$e(await Q4e(S,"utf8"))}catch(E){if(!ot(E))K(`importSessionToStore: skipping unreadable sidecar ${S}: ${E}`)}if(y!==void 0)await t.append(_,[{type:"agent_metadata",...y}])}}async function gJ(e,t,n,r){let o=[],s=0;for await(let i of _D(J4e(e,{encoding:"utf8"}))){if(!i)continue;try{o.push($e(i))}catch(a){K(`importSessionToStore: skipping unparseable line in ${e}: ${a}`);continue}if(s+=i.length,o.length>=r||s>=Ii)await n.append(t,o),o=[],s=0}if(o.length>0)await n.append(t,o)}async function r9e(e){let t=[];async function n(r){let o;try{o=await X4e(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=hJ(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 ljt(e,t){if(t?.sessionStore)return u9e(t.sessionStore,e,t.dir);return PF(e,t)}async function cjt(e,t,n){if(n?.sessionStore)return d9e(n.sessionStore,e,t,n);return IF(e,t,n)}function _J(e){return e.map((t)=>se(t)).join(`