@anthropic-ai/claude-agent-sdk 0.3.293 → 0.3.294

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.293
4
+ // Version: 0.3.294
5
5
 
6
6
  // Want to see the unminified source? We're hiring!
7
7
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
@@ -135,11 +135,11 @@ ${n.join(`
135
135
  `)+(e.endsWith(`
136
136
  `)?0:1)}}function JHe(e){return _u(ie(e))}function XHe(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 ie([e.command,...t])}function QHe(e){return Ys(iV(e))}function iV(e){return{shellSettings:e.shellSettings,envVars:e.envVars,sandboxSettings:Object.keys(e.sandboxSettings).length>0?e.sandboxSettings:void 0,...YW(e),hooks:e.hooks,payloadSlots:bx(e).length>0?Object.fromEntries(bx(e).map(([t,n])=>{let{isolationSettings:r,...o}=n;return[t,{...o,...YW(n)}]})):void 0}}function YW(e){return Object.keys(e.isolationSettings).length>0?{isolationSettings:e.isolationSettings}:{}}function Ys(e){return ie(Wh(e))}function aV(e){return _u(QHe(e))}function lV(e,t,n){if(aV(t)===e)return!0;return typeof n==="string"&&n.length>0&&_u(Ys({...iV(t),claudeMd:n}))===e}function JW(e,t,n){return ie([e,typeof t==="string"?t:null,typeof n==="string"?n:null])}var eje=new Set(["dns","unix","ipv4","ipv6"]),dvt=new Set([...eje,"http","https","ws","wss","ftp","file","grpc","grpcs","otlp","xds","tcp","udp","tls","h2","h2c","http2"]);function cV(e){return e.replace(/[^\x20-\x7e]/gu,"?")}function tje(e){let t=e.extraKnownMarketplaces;if(t!==void 0&&t!==null)return t;let n=e;for(let{alias:r,canonical:o}of Wl){if(o!=="extraKnownMarketplaces")continue;let s=n[r];if(s!==void 0&&s!==null&&typeof s==="object")return s}return}var rje="remote-settings.json";var fV="remote-settings-helper-consent";function oje(){return pV(it(),fV)}function sje(e){let t=XW(e);return sV(t)?t:void 0}function ije(e){return Di(e,(t,n)=>n.startsWith("$")&&n!=="$schema")}class mV{sessionCache=null;eligible=void 0;eligibilityMemo=void 0;ineligibleReason=void 0;evalPolicySnapshotOnly=!1;lastLoadStatus=void 0;lastLoadStatusChanged=ze();policySettingsNotified=!1;verifiedPayload=null;unverifiedView=null;projectedView=null;projectedParse=null;consentedPayload=null;deferredPayload=null;resetEpoch=0;backendView=void 0;replaceSessionCache(e,t){if(this.sessionCache=e,t?.verified){if(this.verifiedPayload=e,t.consentDeferred)this.deferredPayload=e}}seedFromDisk(e){this.sessionCache=e;let t=sje(e);if(t!==void 0){let n=gje();if(n===void 0||!lV(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.eligible=void 0,this.eligibilityMemo=void 0,this.ineligibleReason=void 0,this.evalPolicySnapshotOnly=!1,this.lastLoadStatus=void 0,this.policySettingsNotified=!1,this.verifiedPayload=null,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){q(`Remote settings: load-status listener threw: ${Ot(t)}`,{level:"error"})}}}var aje=new Fe(()=>new mV);function Gi(){return aje.of(tn().host)}function gV(){return Gi().lastLoadStatus}function ql(){return}function lje(){return Gi().evalPolicySnapshotOnly}function vx(){return ns()||lje()}function hV(e){let{projectedView:t,projectedParse:n}=Gi();return e!==null&&(t?.view===e||n?.view===e)}var cje=[["allowedHttpHookUrls"],["httpHookAllowedEnvVars"],["isolation","required"]],_V=[{path:["sandbox","credentials","files"],names:"path"},{path:["sandbox","credentials","envVars"],names:"name"}];function uje(e){for(let n of cje)un(e,n,void 0);for(let{path:n,names:r}of _V){let o=rn(e,n),s=(Array.isArray(o)?o:[o]).flatMap((i)=>ce(i)&&typeof i[r]==="string"?[{[r]:i[r],mode:"deny"}]:[]);un(e,n,s.length>0?s:void 0)}for(let n of[["permissions","deny"],["permissions","ask"]]){let r=rn(e,n);if(Array.isArray(r)){let o=r.filter((s)=>typeof s!=="string"||!_d.test(s));un(e,n,o)}}for(let{path:n,restrictive:r}of to()){let o=rn(e,n),s=n[0]==="strictPluginOnlyCustomization"?o:Bl(o);if(r===!0&&s===!1)un(e,n,void 0)}let t=e.strictPluginOnlyCustomization;if(Array.isArray(t)&&!t.some((n)=>Pd.includes(n)))delete e.strictPluginOnlyCustomization;if(e.availableModelsMatch==="prefix")delete e.availableModelsMatch}function uV(e){if(!e||!vx())return e;let t={...T1(e)};if(ns())uje(t);return{...t,managedSourcesBehavior:"merge"}}function dje(){return ql()===void 0&&ph()}function pje(){return ql()??pV(it(),rje)}var yV=8388608;function fje(){if(dje())return null;try{let e=hje();if(e===null)return null;let t=We(Ll(e));if(!t||typeof t!=="object"||Array.isArray(t))return null;return ije(t)}catch(e){if(LB(e))q(`Remote settings: Disk cache exceeds ${yV} bytes; ignoring it as if absent`);return null}}var mje=4096;function gje(){let e=Ax();if(e!==void 0)return e.attestation;try{return ki(oje(),mje).trim()||void 0}catch{return}}function hje(){let e=Ax();if(e!==void 0)return e.content;if(ns()&&ql()===void 0)return null;return ki(pje(),yV)}function Ax(){let e=Gi().backendView;if(!Ee()||e===void 0||!e.ready||e.stoodDown||ql()!==void 0)return;if(!mk(e.configHome)){e.standDown("config home changed");return}return e}var Hvt=At.state("remote-settings"),jvt=At.state(fV);var _je=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",...uR,...dR,"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",...gR,...hR,..._R,"CLOUDSDK_CONFIG","GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES","GCLOUD_PROJECT","CLAUDE_CODE_CUSTOM_OAUTH_URL",...pR,"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 yje(e){if(!e||!e.env&&!("managedMcpServers"in e))return e;let{managedMcpServers:t,...n}=e;return e.env?{...n,env:Di(e.env,(r,o)=>_je.has(o.toUpperCase()))}:n}function SV(){let e=bV();if(e===null||vx()||EV(Gi(),e))return!1;if(dV(e))return!0;let t=Cx(e);if(t.length===0)return!1;let{chain:n}=qW();return t.some(([r,o])=>{let s=eV(r);return(s===void 0||n.includes(s))&&dV(o)})}function dV(e){let t=e.managedMcpServers;return ce(t)&&Object.keys(t).length>0}function EV(e,t){return t===e.verifiedPayload||Boolean(ql())}function bV(){let e=Gi();if(!ql()&&e.eligible!==!0)return null;if(e.sessionCache)return e.sessionCache;let t=Ax()!==void 0,n=fje();if(n){if(e.seedFromDisk(n),t)Li().invalidatePolicyLayer();else z1();return n}return null}function CV(e){let t=bV(),n=Gi(),r=EV(n,t)?t:Sje(n,t);if(r===null||!vx())return r;if(n.projectedView?.raw!==r)n.projectedView={raw:r,view:uV(r)};let o=n.projectedView.view;if(!e)return o;if(n.projectedParse?.raw!==r){let s={...o};if(vV(s,uV(e(r))??{}),ns())for(let{path:i,names:a}of _V){let l=[o,s].flatMap((c)=>rn(c,i)??[]);if(l.length>0)un(s,i,h1(l,a))}n.projectedParse={raw:r,view:s}}return n.projectedParse.view}function vV(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(o!==r&&ce(o)&&ce(r)){let s={...o};vV(s,r),e[n]=s}else e[n]=r}}function Sje(e,t){if(t===null)return null;if(e.unverifiedView?.raw!==t)e.unverifiedView={raw:t,view:yje(t)};return e.unverifiedView.view}var Eje=va(new Set,(e)=>e.clear());function AV(e){Eje.add(e)}var bje=process.platform==="darwin"?16777216:process.platform==="linux"||process.platform==="android"?524288:0,Wvt=process.platform==="darwin"?536870912:0,Vvt=process.platform==="linux"||process.platform==="android"?2097152:0;var nAt=va({noFollowAny:"untried",localVolumes:void 0},(e)=>{e.noFollowAny="untried",e.localVolumes=void 0});var rAt=Symbol("no procfs"),oAt=Symbol("descriptor path unreadable");var sAt=Symbol("boundRead.linkToNothing");var RV=["userSettings","projectSettings","localSettings","flagSettings","policySettings"];var Cje=["userSettings","projectSettings","localSettings"],vje=["projectSettings","localSettings"],hAt=new Set(vje),Aje={userSettings:"user",projectSettings:"project",localSettings:"local"},_At=Cje.map((e)=>[Aje[e],e]);var xV=["auto","bypassPermissions"];function TV(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 wV=["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"],OV=["sonnet","opus","haiku","fable","best","sonnet[1m]","opus[1m]","fable[1m]","opusplan"],Js=["sonnet","opus","haiku","fable"];function Vh(e){return OV.includes(e)}function Rx(e){return e.replace(/\[1m\]$/i,"")}function kV(e){return e.replace(/\[(1|2)m\]/gi,"")}function Wi(e){return Js.includes(e)}function Lo(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&&!rI.includes(a))return null;t=l}let o=xje(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(!Rje(s))i.trailer=s;else{let a=/(?:-v\d+@|[-@])(\d{8})/.exec(s)?.[1];if(a!==void 0)i.date=a}return i}function Rje(e){return/^(?:-fast|-latest)?(?:-v\d{1,3}@\d{8}|[-@]\d{8})?(?:-v\d{1,3}(?::\d{1,3})?)?$/.test(e)}function PV(e,t){return e.major-t.major||(e.minor??0)-(t.minor??0)}function xje(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 Wn(e){let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g,"?");return t.length>128?`${t.slice(0,128)}…`:t}function Tje(){let e=[...Js],t=e.pop();return e.length===0?t??"":`${e.join(", ")} or ${t}`}function qh(e){return e.charAt(0).toUpperCase()+e.slice(1)}function IV(e){let t=e.trim().toLowerCase(),n=kV(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(Wi(n))return{entry:{kind:"family",family:n},...r!==""&&{warning:`"${Wn(e)}" blocks every ${qh(n)} model.${r}`}};if(Vh(n)||n==="default")return{entry:null,warning:`"${Wn(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=Lo(n),s=o!==null||n.startsWith("claude-")?n:`claude-${n}`,i=o??(s!==n?Lo(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!==""?` "${Wn(l)}" is ignored.`:"";return{entry:{kind:"model",id:i},...(r!==""||c!=="")&&{warning:`"${Wn(e)}" blocks ${wje(i)}.${c}${r}`}}}return{entry:{kind:"literal",value:n},warning:Oje(e,n)}}function wje(e){let t=qh(e.family);return e.minor===void 0?`every ${t} ${e.major}.x model`:`${t} ${e.major}.${e.minor} in every spelling and snapshot`}function Oje(e,t){let n=`"${Wn(e)}" blocks only the exact model name "${Wn(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(Lo(s)!==null)return`${n} To block a version, write it with a hyphen: "${Wn(s)}".`}let o=new RegExp(`^(${Js.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 ${qh(s)} ${i}.x model.`}if(/^[a-z]+$/.test(t)){let s=Js.find((i)=>TV(t,i,1)===1);return s!==void 0?`${n} If you meant the ${qh(s)} family, write "${s}".`:`${n} To block a model family other than ${Tje()}, list its versioned IDs.`}return n}function DV(e){let t=Rx(e.trim().toLowerCase());if(t==="")return{kind:"ignored"};if(Wi(t))return{kind:"family",family:t};let n=t.startsWith("claude-")?t.slice(7):"";if(Wi(n))return{kind:"family",family:n};if(Vh(t)||t==="default")return{kind:"ignored"};let r=Lo(t)!==null||t.startsWith("claude-")?t:`claude-${t}`,o=Lo(r);return o!==null?{kind:"model",id:o,latest:Pje(r,o),spelling:r}:{kind:"literal",value:t}}function kje(e,t){let n=e.toLowerCase(),r=n.lastIndexOf(t.base);return r===-1?"":n.slice(r+t.base.length)}function Pje(e,t){return t.trailer===void 0&&kje(e,t).startsWith("-latest")}function Ije(e,t){for(let n of t){if(Wi(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 Dje(e){return e.charAt(0).toUpperCase()+e.slice(1)}function LV(e){let t;for(let n of wV){let r=Lo(n);if(r!==null&&r.family===e&&!r.legacyVersionFirst&&(t===void 0||PV(r,t)>0))t=r}return t?.base}function MV(e,t){let n=DV(e);switch(n.kind){case"ignored":{if(e.trim()==="")return"An empty availableModels entry was ignored.";let r=LV("opus");return`"${Wn(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)=>DV(s).kind!=="ignored").map((s)=>Rx(s.trim().toLowerCase()));if(Wi(e.trim().toLowerCase())&&Ije(n.family,r))return;let o=LV(n.family);return`"${Wn(e)}" in availableModels allows every ${Dje(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 Lje(e,n.value)}}function Lje(e,t){let n=`"${Wn(e)}" in availableModels allows only a model named exactly "${Wn(t)}".`,r=t.replace(/(\d)\.(\d)/g,"$1-$2");if(r!==t){let s=r.startsWith("claude-")?r:`claude-${r}`;if(Lo(s)!==null)return`${n} To allow a version, write it with a hyphen: "${Wn(s)}".`}let o=new RegExp(`^(${Js.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 Mje(e){return e!==void 0&&(e.commit!==void 0||e.pr!==void 0)}function NV(e,t){let n=e?.commitTrailers;if(typeof n==="boolean")return n?"explicit-enabled":"disabled";if(e!==void 0&&Mje(e))return e.commit===""?"disabled":"implicit-enabled";if(t!==void 0)return t?"implicit-enabled":"disabled";return}var Nje=["allowManagedMcpServersOnly","allowedMcpServers","deniedMcpServers","disabledMcpjsonServers","enabledMcpjsonServers","enableAllProjectMcpServers","disableClaudeAiConnectors","managedMcpServers"];function Zh({slot:e,adminTiers:t}){return e?.allowManagedMcpServersOnly===!0||t.some((n)=>n.allowManagedMcpServersOnly===!0)}function xx({slot:e,adminTiers:t}){return e?.allowedMcpServers??t.find((n)=>n.allowedMcpServers!==void 0)?.allowedMcpServers}function UV(e,t){return Nje.filter((n)=>e[n]!==void 0&&!Uje(n,e,t))}function Uje(e,t,n){let r=n.slot??{};switch(e){case"deniedMcpServers":return!0;case"allowManagedMcpServersOnly":return t.allowManagedMcpServersOnly===Zh(n);case"disableClaudeAiConnectors":return t.disableClaudeAiConnectors===(r.disableClaudeAiConnectors===!0||n.adminTiers.some((o)=>o.disableClaudeAiConnectors===!0));case"allowedMcpServers":return pr(t.allowedMcpServers,Zh(n)?xx(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)&&pr(o[s],i))}}}import{userInfo as Fje}from"os";var FV="com.anthropic.claudecode",Yh="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Jh="HKCU\\SOFTWARE\\Policies\\ClaudeCode",Md="Settings",Tx="/usr/bin/plutil",zV=["-convert","json","-o","-","--"],$V=["-lint","-s","--"],HV=5000,Xh=2097152,jV="/mnt/c/Windows/System32/reg.exe",cr="/mnt/c/Program Files/ClaudeCode";function Nd(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=HZ("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function BV(){let e="";try{e=Fje().username}catch{}let t=[];if(e)t.push({path:`/Library/Managed Preferences/${e}/${FV}.plist`,label:"per-user managed preferences"});return t.push({path:`/Library/Managed Preferences/${FV}.plist`,label:"device-level managed preferences"}),t}var KV=512;function wx(e){return e.map(zje)}function zje(e){let{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,errorClass:i,errno:a,preserveOnWrite:l,mcpErrorMetadata:c,userWritable:d,wslIgnored:p,substituted:f,onlySubstitutes:m,removal:g,path:_,message:y,expected:S,suggestion:b,invalidValue:E,...C}=e,v=C;return{file:t,severity:n,docLink:r,statusOnly:o,startupFatal:s,errorClass:i,errno:a,preserveOnWrite:l,mcpErrorMetadata:c,userWritable:d,wslIgnored:p,substituted:f,onlySubstitutes:m,removal:g,path:Ud(_),message:Ud(y),expected:S===void 0?void 0:Ud(S),suggestion:b===void 0?void 0:Ud(b),invalidValue:typeof E==="string"?Ud(E):void 0}}function Ud(e){let t=cV(e.replace(/\s+/gu," "));return t.length>KV?`${t.slice(0,KV-1)}…`:t}var Mo="https://code.claude.com/docs/en",$je=[{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:`${Mo}/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:`${Mo}/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:`${Mo}/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:`${Mo}/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:`${Mo}/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:`${Mo}/iam#working-directories`}}],Hje={permissions:`${Mo}/iam#configuring-permissions`,env:`${Mo}/settings#environment-variables`,hooks:`${Mo}/hooks`};function GV(e){let t=$je.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=Hje[sS(e.path,".")];return n}var ERt=P(()=>px(Kl(),{strictPolicyHelperKeys:!0}).strict());function WV(e){return e.code==="invalid_type"}function VV(e){return e.code==="invalid_value"}function jje(e){return e.code==="unrecognized_keys"}function qV(e){return e.code==="too_small"}function fn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";return typeof e}function ZV(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Fd(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(VV(r))a=r.values.map((f)=>String(f)),l=a.join(" | "),c=void 0,d=void 0;else if(WV(r)){l=r.expected;let f=ZV(r.message);c=f??fn(r.input),d=f??fn(r.input)}else if(qV(r))l=String(r.minimum);else if(r.code==="custom"&&"params"in r)c=r.params.received,d=c;let p=GV({path:o,code:r.code,expected:l,received:c,enumValues:a,message:r.message,value:c});if(VV(r))i=a?.map((f)=>`"${f}"`).join(", "),s=`Invalid value. Expected one of: ${i}`;else if(WV(r)){let f=ZV(r.message)??fn(r.input);if(r.expected==="object"&&f==="null"&&o==="")s="Invalid or malformed JSON";else s=`Expected ${r.expected}, but received ${f}`}else if(jje(r)){let f=r.keys.join(", ");s=`Unrecognized ${xc(r.keys.length,"field")}: ${f}`}else if(qV(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 Bje(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=ex(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 hx("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 Kje=new Set(Po);function Gje(e,t){if(!e||typeof e!=="object")return[];return[..._G(e,yG)?[{file:t,path:"hooks",message:`PreToolUse/PermissionRequest hooks are declared outside "hooks" (at the top level or under another key) — ${$i}.`,severity:"fatal",docLink:"https://code.claude.com/docs/en/hooks"}]:[],...Wje(e,t)]}function Wje(e,t){if(!("hooks"in e))return[];if(e.hooks===null||typeof e.hooks!=="object"||Array.isArray(e.hooks)){let o=fn(e.hooks);if(Array.isArray(e.hooks)&&(e.hooks.some(ce)||PR(e.hooks)))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o} — ${$i}.`,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(Rh(n))return[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received a single matcher — ${$i}.`,docLink:"https://code.claude.com/docs/en/hooks"}];let r=[];for(let o of Object.keys(n)){let s=rf(o);if(!Kje.has(o)){if(Fi(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 — ${$i}.`,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: ${Po.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=fn(i);if(Ad.has(o)&&i!==null||Fi(i,3,{matchersCount:!1})){r.push({file:t,path:`hooks.${s}`,message:`Hook event "${s}" must be an array of matchers; received ${a} — ${$i}.`,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}=EG(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} — ${$i}.${l.aboutType?` Valid types: ${[...Ah()].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: ${[...Ah()].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 Vje=[{key:"allowedMcpServers",schema:zh},{key:"deniedMcpServers",schema:$h}];function qje(e,t,n){if(!e||typeof e!=="object")return[];let r=e,o=[];for(let{key:s,schema:i}of Vje){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 ${fn(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 Zje=["strictKnownMarketplaces","blockedMarketplaces"];function Yje(e){if(!ce(e))return;for(let t of Bh())if(e[t]===null)delete e[t]}function Jje(e,t,n){if(!ce(e))return[];let r=[];for(let o of Zje){let s=e[o];if(!Array.isArray(s))continue;let i=[],a=[];for(let l=0;l<s.length;l++){let c=xd().safeParse(s[l]);if(!c.success){i.push(s[l]),a.push(l);continue}let d=gx(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 Xje(e,t){if(!ce(e)||e.managedMcpServers===void 0)return[];let r=[],o=Sh(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 Qje(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 eBe(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(ZR)}function tBe(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=fn(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=ix().safeParse(s[a]),c,d=!1;if(!l.success){let p=Qje(s[a]);if(p!==void 0&&!eW.has(p)||eBe(s[a]))continue;c=wh(l.error.issues)}else if(l.data.source.source==="settings"&&l.data.source.name!==a)c=`key "${no(a)}" must match the settings source name "${no(l.data.source.name)}"`;if(c!==void 0)i.push({file:t,path:`${r}.${no(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 nBe(e,t){if(!e||typeof e!=="object")return[];let n=e,r="modelPicker";if(!(r in n))return[];let o=n[r];if(!ce(o)||!Array.isArray(o.options)){let l=ce(o)?`options: ${fn(o.options)}`:fn(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=fn(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=cx().safeParse(i[l]);if(c.success){a.push(i[l]);continue}s.push({file:t,path:`${r}.options.${l}`,message:`${oBe(c.error.issues[0])}. This row was ignored; the other rows still apply.`,severity:"warning",invalidValue:fn(i[l])})}if(a.length!==i.length)o.options=a;return s}function rBe(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 ${fn(r)}. It was ignored.`,severity:"warning"}];let o=r,s=[];if(o.multiplier!==void 0&&!lx().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 ${fn(i)}. It was ignored.`,severity:"warning"}),delete o.overrides;else{let a=i;for(let l of Object.keys(a)){let c=ax().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.${no(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 oBe(e){if(!e)return"Invalid modelPicker row";return`modelPicker row ${e.path.length>0?`"${e.path.join(".")}" `:""}${e.message}`.trim()}function sBe(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=e,o=r.crossSessionInbound;if(o===void 0||iBe(o))return[];if(n?.policySource)r.crossSessionInbound="refuse";else delete r.crossSessionInbound;return[cBe(o,t,n?.policySource===!0)]}function iBe(e){return typeof e==="string"&&Id.includes(e)}var aBe="crossSessionInbound";function lBe(e){let t=Id.map((r)=>`"${r}"`).join(", "),n=typeof e==="string"?`"${no(e).replace(/^<key>$/,"<value>")}"`:fn(e);return`must be one of ${t}; received ${n}`}function cBe(e,t,n=!1){let r=Id.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:aBe,message:`"crossSessionInbound" ${lBe(e)}. ${o}`,severity:"warning",expected:r,...n&&{statusOnly:!0}}}var YV="remoteControl.shareHostProfile";function uBe(e,t,n){if(!ce(e)||e.remoteControl===void 0)return[];let r=n?.policySource===!0,o=Fh.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:YV,message:`${f}. ${s}`,severity:"warning",expected:o,...r?{statusOnly:!0}:{preserveOnWrite:!0}}),a=(f)=>typeof f==="string"?`"${no(f).replace(/^<key>$/,"<value>")}"`:fn(f),l=e.remoteControl;if(!ce(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)=>`"${no(f)}"`).join(", ")} (its only key is "shareHostProfile")`))}let p=l.shareHostProfile;if(p!==void 0&&!(typeof p==="string"&&Fh.includes(p))){if(r)l.shareHostProfile="off";else delete l.shareHostProfile;c.push(i(`"${YV}" must be one of ${o}; received ${a(p)}`))}return c}function zd(e,t,n){let r=[...ZW(e,t)];return Yje(e),r.push(...Bje(e,t,{policySource:n?.policySource,strictParseFollows:n?.mcpServerEntrySalvageOnly}),...Gje(e,t),...tBe(e,t),...nBe(e,t),...rBe(e,t),...sBe(e,t,{policySource:n?.policySource}),...uBe(e,t,{policySource:n?.policySource}),...n?.skipMcpServerEntryFilter?[]:qje(e,t,{keepWholeFieldInvalid:n?.mcpServerEntrySalvageOnly}),...n?.mcpServerEntrySalvageOnly?Xje(e,t):[],...n?.mcpServerEntrySalvageOnly?Jje(e,t,n.marketplacePatternIndexMapOut):[]),r}function Mx(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),RV.filter((n)=>t.has(n))}function fBe(){return mn(Ks(),"managed-settings.json")}function u2(e){if(Pt()==="wsl"){let t=Xl(Ux(e));if(e.wslInherits?.()){let n=Ox(cr,e.store);if(Xl(n)||t)return n;let r=Ox(Ks(),e.store);return{...r,errors:[...n.errors,...r.errors],loadState:No(n.loadState,r.loadState)}}if(t)return{settings:null,errors:[],documentHasPolicyContent:!1,loadState:"absent"}}return Ox(Ks(),e.store)}function JV(e,t,n){n.push(...t.errors);let{settings:r}=t;if(!r||Object.keys(r).length===0)return;for(let[o,s]of Kh){let i=o.split(".");if(rn(r,i)===void 0)continue;let a=t.errors.find((d)=>d.substituted&&d.path===o),l=a!==void 0,c=rn(e.merged,i);if(l&&c!==void 0&&!e.floors.has(o)){let d=i.at(-1);if(s.inert.has(s.read(c))){s1(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=dn(e.merged,r,xr),e.found=!0,Kd(r)&&!t.errors.some((o)=>o.onlySubstitutes))e.authored=!0}function Nx(e){return e.endsWith(".json")&&!e.startsWith(".")}function mBe(e){return(e.isFile()||e.isSymbolicLink())&&Nx(e.name)}function XV(e,t,n,r){let o=e.managedDocumentLinks;o.noteWalked(mn(t,...n),()=>tK(t,n,r,o.folderIsLink))}function Ox(e,t){let n=[],r={merged:{},found:!1,authored:!1,floors:new Set},o=!1,s="absent",i=Zl(mn(e,"managed-settings.json"),t,void 0,!0);if(JV(r,i,n),o||=jd(i),s=No(s,Zi(i)),Zi(i)!=="absent")XV(t,e,["managed-settings.json"]);let a=mn(e,"managed-settings.d");try{let c=t.folderListingForPolicyWalk(a),d,p;if(c!==void 0)d=c;else{let f=ke().readdirSync(a).filter(mBe);d=f.map((m)=>m.name).sort(),p=new Set(f.filter((m)=>!m.isFile()).map((m)=>m.name)),t.noteWalkListing(a,d)}for(let f of d){let m=Zl(mn(a,f),t,void 0,!0);if(JV(r,m,n),o||=jd(m),s=No(s,Zi(m)),Zi(m)!=="absent")XV(t,e,["managed-settings.d",f],p?.has(f))}}catch(c){let d=pe(c);if(d!=="ENOENT"&&d!=="ENOTDIR")q(`managed-settings.d read failed: ${c}`,{level:"error"}),n.push(Bd(a,c,"directory")),s="didNotLoad"}let l=r.found&&Ql(r.merged)?r.merged:null;return{settings:l,errors:n,documentHasPolicyContent:o,loadState:s,...l!==null&&!r.authored&&Kd(l)&&{onlySubstitutes:!0}}}function gBe(e,t){if(pt(e))vBe(t);else q(`settings file read failed at ${t}: ${e}`,{level:"error"})}function Zl(e,t,n,r){let o=n!==void 0?`${e}\x00pinned`:e,s=t.parsedFiles.get(o);if(s)return{...s,settings:s.settings?Lr(s.settings):null};let i=EBe(e,n,r);return t.parsedFiles.set(o,i),{...i,settings:i.settings?Lr(i.settings):null}}function Ux(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:xBe(t.errors,()=>Fx(e)),documentHasPolicyContent:jd(t),loadState:Zi(t),...t.onlySubstitutes&&{onlySubstitutes:t.onlySubstitutes}}}function Hd(e,t){let n=e2.get(e),r=n?.get(t);if(r)return QV(r);let o=hBe(e,t);if(n)n.set(t,o);else e2.set(e,new Map([[t,o]]));return QV(o)}function QV(e){return{settings:e.settings&&Lr(e.settings),errors:e.errors.map((t)=>({...t})),documentHasPolicyContent:e.documentHasPolicyContent,loadState:e.loadState,removed:e.removed,...e.onlySubstitutes&&{onlySubstitutes:e.onlySubstitutes}}}var e2=new WeakMap;function hBe(e,t){let n=Lr(e),r=zd(n,t,{skipMcpServerEntryFilter:!0,policySource:!0}),o=[],s=Sx(m2(t,o),t,n).safeParse(n);if(!s.success)return{settings:null,errors:[...r,...Fd(s.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad",removed:[]};let i=[...r,...o],a=e,l=Object.keys(s.data).length>0?s.data:null;return{settings:l,errors:i,documentHasPolicyContent:A2(e,s.data),loadState:"loaded",removed:Object.keys(a).filter((c)=>d2(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 d2(e,t){let n=Bh();return n.includes(e)||Wl.some(({alias:r,canonical:o})=>r===e&&n.includes(o))?yx(e,t):Gh(e)&&p2(e,t)}function p2(e,t){return t===null||ce(t)&&Object.keys(t).length>0&&Object.entries(t).every(([n,r])=>{let o=`${e}.${n}`;return yx(o,r)||Gh(o)&&p2(o,r)})}function Yi(e){return sR()&&(e==="managedMcpServers"||e.startsWith("managedMcpServers."))}var o_=["managedMcpServers","isolation"],_Be=[...o_,"deniedModels","availableModelsMatch"];function f2(e,t){if(!ce(e))return[];let n=[];for(let r of _Be){if(!(r in e))continue;if(delete e[r],!Yi(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 m2(e,t){return(n)=>{if(Yi(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)q(`${e}: ${n.path}: ${n.message}`,{level:n.startupFatal?"error":"warn"})}}function Fx(e){let t=e?.remote?e.remote():CV((c)=>Hd(c,"remote managed settings").settings),n=!e?.remote&&!Yi("managedMcpServers")&&SV()?[{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:gV(),o=(r?.state==="stale_cache"||r?.state==="failed")&&r.failure.errorKind==="ruled_empty"?wx(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}=Hd(t,"remote managed settings");return{settings:s,errors:[...n,...o,...wx(i)],servedSnapshot:hV(t),documentHasPolicyContent:a,...l&&{onlySubstitutes:l}}}var t2="parent managed settings";function yBe(e){let t=e.parentManaged;if(!t||Object.keys(t).length===0)return{settings:null,errors:[]};let n=Hd(t,t2);for(let r of o_)if(n.settings?.[r]!==void 0&&!Yi(r))n.errors.push({file:t2,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 g2(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=sR(),r=e.store.inlineFlagParse;if(r?.inline!==t||r.desktopSupplied!==n)r={inline:t,desktopSupplied:n,parsed:SBe(t)},e.store.inlineFlagParse=r;let{settings:o,errors:s}=r.parsed;return{settings:o&&Lr(o),errors:s.map((i)=>({...i}))}}function SBe(e){let t=Lr(e),n=[...f2(t,"SDK inline settings"),...zd(t,"SDK inline settings")],r=jh(t).safeParse(t);if(!r.success)return{settings:null,errors:[...n,...Fd(r.error,"SDK inline settings")]};if(n.some((o)=>o.severity==="fatal"))return{settings:null,errors:n};return{settings:r.data,errors:n}}var s_=2097152;function EBe(e,t,n){try{let r;if(t!==void 0)r=t;else{let o=n||bBe(e)?Oa(ke(),e):Tk(ke(),e);r=ki(o.resolvedPath,s_)}return zx(r,e,n)}catch(r){return RBe(r,e)}}function zx(e,t,n){if(e.trim()==="")return{settings:{},errors:[],loadState:"loaded"};let r=Pi(e,!1);if(n){if(!ce(r))return{settings:null,errors:[i_(t)],loadState:"didNotLoad"};let a=Lr(r),l=zd(a,t,{skipMcpServerEntryFilter:!0,policySource:!0}),c=[],d=Sx(m2(t,c),t,a).safeParse(a);if(!d.success)return{settings:null,errors:[...l,...Fd(d.error,t)],documentHasPolicyContent:!1,loadState:"didNotLoad"};return{settings:d.data,errors:[...l,...c],documentHasPolicyContent:A2(r,d.data),loadState:"loaded"}}let o=Lr(r),s=[...f2(o,t),...zd(o,t)],i=jh(o).safeParse(o);if(!i.success){let a=Fd(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 i_(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 bBe(e){let t=je(r_(xt(e))),n=xt(it());return t===je(n)||t===CBe(n)}var kx;function CBe(e){if(kx?.lexical!==e){let t=r_(e);kx={lexical:e,physical:je(mn(Up(t)??t,pBe(e)))}}return kx.physical}function vBe(e){q(`Broken symlink or missing file encountered for settings.json at path: ${e}`)}function ABe(){return{settings:null,errors:[],loadState:"absent"}}function RBe(e,t){if(gBe(e,t),pt(e))return ABe();return{settings:null,errors:[Bd(t,e)],loadState:"didNotLoad"}}function Bd(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",...pe(t)!==void 0&&{errno:pe(t)}}}function h2(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 ${cr}), 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 n2(e){return e.path==="wslInheritsWindowsSettings"&&e.severity==="fatal"}function xBe(e,t){if(!e.some(n2))return e;if(!t_(t()))return e;return e.map((n)=>n2(n)?{...n,severity:"warning"}:n)}function r2(e,t){switch(e){case"userSettings":return xt(it());case"policySettings":return xt(Qh(t));case"projectSettings":return xt(t.projectConfigDir??Qh(t));case"localSettings":{if(t.projectConfigDir!==void 0)return xt(t.projectConfigDir);return _2(Qh(t),t.canonicalGitRoot)}case"flagSettings":return t.flagPath?r_(xt(t.flagPath)):xt(Qh(t))}}function Qh(e){if(e.cwd===null)throw new bc;return e.cwd}function _2(e,t){let n=TBe(e,t);if(n.decided!==void 0)return n.decided;if(!PBe(n.root))return n.cwdResolved;return n.root}function TBe(e,t){let n=t?.(e);if(!n)return{decided:xt(e)};let r=xt(n),o=xt(e);if(r===o)return{decided:r};let s;try{s=IBe()}catch{return{decided:o}}if(r===s)return{decided:o};return{decided:void 0,root:r,cwdResolved:o}}function wBe(e){return Li().localStoreProbes.canonicalRootOwnerUids(e,OBe)}function OBe(e){let t=ke(),n=null;try{n=t.lstatSync(mn(e,".claude")).uid}catch(r){if(!pt(r))throw r}return{rootUid:t.statSync(e).uid,gitEntryUid:kBe(e),claudeEntryUid:n}}function kBe(e){let t=ke();try{return t.lstatSync(mn(e,".git")).uid}catch(n){throw n}}function PBe(e){if(typeof process.getuid!=="function"&&typeof process.geteuid!=="function")return q(`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}=wBe(e);if(n===t&&r===t&&(o===null||o===t))return!0;return q(`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 q(`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 IBe(){return Li().localStoreProbes.normalizedRealHomeDir(DBe)}function DBe(){let e=Up(dBe());if(e===null)throw Error("home directory realpath unavailable");return je(e)}var o2={default:"settings.json",cowork:"cowork_settings.json"};function LBe(e){if(e.coworkPlugins||Xn.CLAUDE_CODE_USE_COWORK_PLUGINS)return o2.cowork;return o2.default}function Yl(e,t){switch(e){case"userSettings":return mn(r2(e,t),LBe(t));case"projectSettings":case"localSettings":{if(t.cwd===null&&t.projectConfigDir===void 0)return;return mn(r2(e,t),y2(e))}case"policySettings":return fBe();case"flagSettings":return t.flagPath}}function y2(e){switch(e){case"projectSettings":return mn(".claude","settings.json");case"localSettings":return mn(".claude","settings.local.json")}}function S2(e){if(e.cwd===null||_2(e.cwd,e.canonicalGitRoot)===xt(e.cwd))return;if(e.projectConfigDir!==void 0)return;return mn(xt(e.cwd),y2("localSettings"))}function E2(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=pKe(e,t),s=o&&$d(e,o,t);return t.store.perSource.set(e,s),s}function b2(e){return(e.parentSettingsBehavior??(ph()?"merge":"first-wins"))==="merge"}function MBe(e,t=!1){return!e||b2(e)||t}var NBe=[["permissions","defaultMode"],["modelPicker","replaceBuiltInOptions"]];function UBe(e){let t={};for(let{path:n,restrictive:r}of to()){let o=rn(e,n);if(n[0]==="sandbox"&&Ii(r).includes(o))un(t,n,o)}return t.sandbox??{}}function FBe(e,t){let n={};if(e.allowManagedHooksOnly===!0)n.allowManagedHooksOnly=!0;if(e.disableCommandPluginSources===!0)n.disableCommandPluginSources=!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(NV(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 Dx)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=Fl(e.permissions,["deny","ask"]);for(let i of["deny","ask"]){let a=s[i];if(a!==void 0)s[i]=a.filter((l)=>{if(!_d.test(l))return!0;return q(`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?Fl(s,["deniedDomains"]):{},d=i?Fl(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=C2(a.awsPairs??[],[]);if(g.length>0)m.awsPairs=g}if(Object.keys(m).length>0)l.credentials=m}if(dn(l,UBe(e)),Object.keys(l).length>0)n.sandbox=l}return n}function C2(e,t){let n=Ws,r=new Set(t.flatMap(s2));return Nn(e.flatMap(s2)).filter((o)=>n.includes(o)&&!r.has(o)).map((o,s)=>({accessKeyIdVar:o,secretAccessKeyVar:`${hh}${s+1}_`}))}function s2(e){if(!ce(e))return[];return[e.accessKeyIdVar,e.secretAccessKeyVar,e.sessionTokenVar].filter((t)=>typeof t==="string")}var zBe=new Set([...[...fR].filter((e)=>e!=="ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION"),...mR,"CLAUDE_CODE_AUTO_MODE_MODEL","CLAUDE_CODE_BG_CLASSIFIER_MODEL","CLAUDE_CODE_SUBAGENT_MODEL_FORCE"]);function $Be(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 HBe(e){let t=[];for(let n of e?.deniedModels??[]){let{warning:r}=IV(n);if(r!==void 0)t.push({file:"managed settings",path:"deniedModels",message:r,severity:"warning",statusOnly:!0})}return t}function jBe(e){if(e?.availableModelsMatch!=="exact")return[];let t=e.availableModels??[];return t.flatMap((n)=>{let r=MV(n,t);return r===void 0?[]:[{file:"managed settings",path:"availableModels",message:r,severity:"warning",statusOnly:!0}]})}function i2(e,t){let n=e.deniedModels;if(Object.assign(e,t),n!==void 0&&t.deniedModels!==void 0)e.deniedModels=Nn([...n,...t.deniedModels])}function e_(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(!zBe.has(n.toUpperCase()))t[n]=r;e.env=t}}function BBe(e){let t=e.store.policy.allTiers;if(t!==void 0)return t;let n=eKe(e);return e.store.policy.allTiers=n,n}function qi(){return Pt()==="macos"?"plist":"hklm"}function v2(e){let t=Gd(e);if(t.composes==="tier")return"helper";let n=Jl(e);if(t.composes==="remoteSlot"||n.present.remote)return"remote";if(n.present.mdm)return qi();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 Jl(e){let t=[],n=Fx(e),{settings:r,servedSnapshot:o}=n;t.push(...n.errors);let s=Gd(e),i=s.composes==="remoteSlot"?s.helper:Px(r),a=Ux(e),l=a.settings;t.push(...a.errors);let c=Px(l),d=e.file?.()??u2(e),p=d.settings;t.push(...d.errors);let f=Px(p),m=s.composes==="remoteSlot"?i!==null:t_(n),g=t_(a),_=t_(d),y=Ix(i,m),S=Ix(c,g),b=Ix(f,_),E=i!==null&&y>=Math.max(S,b),C=c!==null&&S>=b,v=[[r,E],[l,C],[p,f!==null]],L=(s.composes==="remoteSlot"?s.helper:v.find(([Ge,ur])=>Ge!==null&&(Ge===r&&o?ur:Ge.managedSourcesBehavior!==void 0||ur))?.[0])?.managedSourcesBehavior,z=i!==null&&!E,U=z?null:i,de=c!==null&&!C&&U===null,x=de?null:c,R=[],O=[[z,"remote",i],[de,qi(),c]];for(let[Ge,ur,In]of O){if(!Ge||In===null)continue;if(R.push([In,ur]),!Kd(In))continue;let Qs=ur==="remote"&&g?qi():"file";t.push({file:Vi[ur],path:Object.keys(In).find((Qi)=>!Ki.includes(Qi))??"",message:`${Vi[ur]} holds only values that could not be applied as written, so ${Vi[Qs]} supplies the managed settings while that fail-closed reading still binds beside it (the most restrictive value of each such key applies), until it is fixed.`,severity:"warning",statusOnly:!0})}let{settings:D,errors:B}=yBe(e);t.push(...B);let oe=(g?x:null)??(_?f:null),me=D!==null&&(oe===null||b2(oe)),J=[qBe(U,o&&s.composes!=="remoteSlot",[x,f,...me?[Fl(D,Dx)]:[]]),x,f,...R.map(([Ge])=>Ge)].filter((Ge)=>Ge!==null),K=[...U!==null?["remote"]:[],...x!==null?[qi()]:[],...f!==null?["file"]:[],...R.map(([,Ge])=>Ge)],bt=U!==null&&o&&s.composes!=="remoteSlot",{admin:Xt,merged:dt}=KBe(J,L,bt,R.length),Tt=Xt===null?[n,a,d].find(jd):void 0,Ct=Xt??(Tt?{}:null),Gt={remote:U!==null||Tt===n,mdm:x!==null||Tt===a,file:f!==null||Tt===d},Ye=!(U!==null&&m&&!bt)&&!(x!==null&&g)&&!_,ye=[];if(dt){let Ge=Gt.remote?"remote":Gt.mdm?qi():"file",ur=[[x,qi()],[f,"file"]];for(let[In,Qs]of ur){if(In===null||In===J[0]||bt&&In===J[1])continue;let Qi=$x.filter((ea)=>Object.values(In[ea]??{}).some((rp)=>rp!==void 0&&rp!==null)),[np]=Qi;if(np===void 0)continue;ye.push(Qs),t.push({file:Vi[Qs],path:np,message:`${Qi.map((ea)=>`"${ea}"`).join(" and ")} in ${Vi[Qs]} ignored: policy helper configuration is read from the highest managed settings source only (${Vi[Ge]} here), even with managedSourcesBehavior "merge". Configure the helper in that source instead.`,severity:"warning",statusOnly:!0})}}let Wt=(Ge)=>Ge!==null&&(Ge===J[0]||Object.keys(bd(Ge,P2())).length>0),Qt={remote:Wt(U),mdm:Wt(x),file:Wt(f)},$o={allowManagedPermissionRulesOnly:J.some((Ge)=>Ge.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:Ct?.forceLoginOrgUUID,...Fl(Ct??{},Dx),allowedMcpServers:Zh({slot:Ct,adminTiers:J})||D?.allowManagedMcpServersOnly===!0&&Ct?.allowManagedMcpServersOnly!==!1?xx({slot:Ct,adminTiers:J}):Ct?.allowedMcpServers,sandbox:{network:{allowManagedDomainsOnly:J.some((Ge)=>Ge.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:J.some((Ge)=>Ge.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},Xi=MBe(Xt,Ye),Ho=D&&Xi?FBe(D,$o):null,_n=Ho&&Object.keys(Ho).length>0?Ho:null,h_=$Be(D,e.hostManagedProvider);return{tiers:J,tierSources:K,admin:Ct,parentSlice:_n,hostModelOverlay:h_,errors:t,present:Gt,mode:L,merged:dt,composed:Qt,snapshotFirst:bt,parentNeverShutOut:Ye,shadowedHelperSources:ye,parentIncluded:Xi,heldEmpty:Tt!==void 0}}function KBe(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}:bd(d,P2());if(!f){for(let _ of NBe)if(rn(m,_)!==void 0)un(m,_,void 0)}let g=rn(m.sandbox,["enabledPlatforms"]);if(Array.isArray(g)&&g.includes(Pt()))un(m,["sandbox","enabledPlatforms"],void 0);else if(g!==void 0)delete m.sandbox;return m});if(!a)return a2(i,[o,...l]),{admin:i,merged:!1};let c={};for(let d of[...l].reverse())dn(c,d,Lx);return dn(c,i,n?ZBe:Lx),a2(c,[o,...l]),GBe(c,[o,...l],n),{admin:c,merged:!0}}var $x=["policyHelper","policyHelpers"],Vi={remote:"server-managed settings",plist:"the managed preferences plist",hklm:"the HKLM policy key",file:"managed-settings.json"};function Ql(e){return Object.keys(e).some((t)=>!Ki.includes(t))}function Kd(e){return Object.entries(e).some(([t,n])=>!Ki.includes(t)&&!Dd(n))}function Px(e){return e&&Ql(e)?e:null}function t_(e){return e.settings!==null&&Kd(e.settings)&&!e.onlySubstitutes}function Ix(e,t){if(e===null)return-1;if(t)return 2;return Kd(e)?1:0}function A2(e,t){return Object.entries(e).some(([n,r])=>r!==null&&!d2(n,r)&&!Ki.includes(n))||t!==null&&Ql(t)}function jd(e){return e.documentHasPolicyContent??(e.settings!==null&&Ql(e.settings))}function Zi(e){return e.loadState??(e.settings!==null?"loaded":"absent")}function No(e,t){if(e==="didNotLoad"||t==="didNotLoad")return"didNotLoad";return e==="loaded"||t==="loaded"?"loaded":"absent"}function Xl(e){return e.userWritable!==!0&&(jd(e)||e.loadState==="didNotLoad")}function GBe(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 R2=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders"],WBe=["awsPairs","ripgrep"];function x2(e,t,n){if(t===void 0)return e;if(Array.isArray(t))return n==="awsPairs"&&Array.isArray(e)?[...t,...C2(e,t)]:[...t];if(!ce(t))return t;return ao(t,(r)=>Array.isArray(r)?[...r]:r)}var VBe=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedChannelPlugins","allowedProviders","allowedMarketplaces","allowedHttpHookUrls","httpHookAllowedEnvVars"],Dx=["allowedMcpServers","availableModels","strictKnownMarketplaces","allowedProviders"];function qBe(e,t,n){if(e===null||!t)return e;let r=VBe.filter((o)=>n.some((s)=>s?.[o]!==void 0));return r.length===0?e:bd(e,r)}function Lx(e,t,n){if(n!==void 0&&(R2.includes(n)||WBe.includes(n)))return x2(e,t,n);return T2(e,t,n)}function ZBe(e,t,n){if(n!==void 0&&R2.includes(n))return x2(e,t,n);return T2(e,t,n)}function T2(e,t,n){if(Array.isArray(e)&&Array.isArray(t)&&n!=="fallbackModel")return Nn([...t,...e]);return xr(e,t,n)}function a2(e,t){let n=t[0],r=e;for(let o of to()){let{path:s,restrictive:i}=o,a=Ii(i),l=Math.min(...t.map((c)=>a.indexOf(eh(o,c))).filter((c)=>c!==-1));if(Number.isFinite(l))un(r,s,a[l]);else if(rn(n,s)===void 0&&rn(e,s)!==void 0)un(r,s,void 0)}if(e.strictPluginOnlyCustomization!==!0){let o=Nn(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 Gd(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:Fx(e).settings,mergedOver:"remote"}:w2(e);e.store.policy.mergedHelper={helper:QBe(r,t),mergedOver:Object.keys(O2(r)).length>0?o:null}}return{composes:n,...e.store.policy.mergedHelper}}function w2(e){let t=Ux(e);if(Jl({...e,helper:void 0}).present.mdm)return{base:t.settings,mergedOver:qi(),errors:t.errors};let n=e.file?.()??u2(e);return{base:n.settings,mergedOver:"file",errors:[...t.errors,...n.errors]}}function O2(e){return bd(e??{},$x)}function YBe(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 JBe=["forceLoginOrgUUID","gatewayInternalNetworks","allowedHttpHookUrls","httpHookAllowedEnvVars","allowRead"];function XBe(e,t,n){let r=n!==void 0&&t!==void 0&&JBe.includes(n)?t:Lx(e,t,n);return r===t&&Array.isArray(r)?[...r]:r}function QBe(e,t){let n=O2(e),r=dn({},n,t,XBe);if(n.env&&t.env)r.env=YBe(n.env,t.env);return r}function eKe(e){let t=Gd(e);if(t.composes==="tier")return[t.helper];let{tiers:n,parentSlice:r}=Jl(e);return r?[...n,r]:n}function tKe(e,t,n){let r={slot:n,adminTiers:e};return e.flatMap((o,s)=>{let i=t[s],a=UV(o,r);return i!==void 0&&a.length>0?[{source:i,keys:a}]:[]})}var k2=["apiKeyHelper","awsAuthRefresh","awsCredentialExport","gcpAuthRefresh"];var n_=[...k2,"otelHeadersHelper","proxyAuthHelper"],l2=["disableAllHooks","enabledPlugins","extraKnownMarketplaces","agent","allowedHttpHookUrls","httpHookAllowedEnvVars","autoMemoryDirectory","modelOverrides","allowedMcpServers","skipWebFetchPreflight","autoUploadSessions","xaaIdp","claudeMdExcludes","enableAllProjectMcpServers","enabledMcpjsonServers"];function nKe(e,t,n){if(!l2.some((o)=>t[o]!==void 0)||(n.launchFolderKeysFrom?.(e)??"as_read")==="as_read")return t;let r={...t};for(let o of l2)delete r[o];return AV("keys"),r}function $d(e,t,n){return rKe(e,nKe(e,t,n),n)}function rKe(e,t,n){let r=n_.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"?oKe(n):{};if(!r&&Object.keys(s).length===0)return t;let i={...t};for(let a of n_)delete i[a];return Object.assign(i,s)}function oKe(e){let t=sKe(e),n={};for(let r of n_){let o=t?.[r];if(o!==void 0)n[r]=o}return n}function sKe(e){let t=iKe(e),n=Gd(t);return n.composes==="tier"?n.helper:Jl(t).admin}function iKe(e){let t=e.helperArmedFromRemote?.()===!1&&e.helperArmedFromUserWritableBase?.()===!1;return{...e,store:new ha,remote:()=>null,helper:t?e.helper:()=>null,...e.mdm?.().userWritable===!0&&{mdm:()=>({settings:{},errors:[]})}}}var aKe=[...n_,"forceLoginOrgUUID","forceLoginMethod","forceLoginGatewayUrl","gatewayInternalNetworks","parentSettingsBehavior","env","modelPicker",...$x,...Ki];function P2(){return aKe}function lKe(e){return D1.some((t)=>e.startsWith(t))||I1.includes(e)}function cKe(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=lKe(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 uKe="CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION";function c2(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))if(n.toUpperCase()!==uKe)t[n]=r;return t}function dKe(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([o,s])=>r[o]===s)}function I2(e){let t=Gd(e),n=(e.helperWarnings?.()??[]).filter((y)=>!Yi(y.path));if(t.composes==="tier"){let{helper:y}=t;e.store.lastPolicyEnvComposition=null;let S=e.hostManagedProvider?{...y}:y;if(e.hostManagedProvider)e_(S);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 b=e.store.policy.helperBaseStatusNotices??=[...e.helperMergesOutput?.()===!0?w2(e).errors.filter((E)=>!E.statusOnly):[],...Jl(e).errors.filter((E)=>E.statusOnly)];return{settings:S,errors:[...b,...n]}}let{tiers:r,tierSources:o,admin:s,parentSlice:i,hostModelOverlay:a,errors:l,present:c,snapshotFirst:d}=Jl(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 S=e.hostManagedProvider?{...y.settings}:y.settings;if(e.hostManagedProvider){if(e_(S),a)i2(S,a)}return{settings:S,errors:[...l,...y.errors]}}if(a)return{settings:{...a},errors:[...l,...y?.errors??[]]};return{settings:null,errors:[...l,...y?.errors??[]]}}let p=dn({},i??{},s??{},xr);if(i?.availableModelsMatch==="exact")p.availableModelsMatch="exact";if(r.some((y)=>y.forceRemoteSettingsRefresh===!0))p.forceRemoteSettingsRefresh=!0;let f=Xn.CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION===!0,m=p.env;if(!f){let y=cKe(r.map((S)=>S.env),r.map((S)=>(S.otelHeadersHelper??"").trim()!==""),r.map((S)=>{let b=new Set;for(let E of k2){let C=S[E];if(typeof C==="string"&&C.trim()!=="")for(let v of L1[E])b.add(v)}return b.size>0?b:void 0}),d?1:0);if(Object.keys(y).length>0)p.env=y;else delete p.env}if(p.env){let y=c2(p.env);if(y&&Object.keys(y).length>0)p.env=y;else delete p.env}if(e.hostManagedProvider){if(e_(p),a)i2(p,a)}let g={env:c2(m)};if(e.hostManagedProvider)e_(g);let _=!f&&!dKe(p.env,g.env);e.store.lastPolicyEnvComposition={unionOptedOut:f,unionChangedEnv:_,remoteTierPresent:c.remote,mdmTierPresent:c.mdm,fileTierPresent:c.file,adminTierCount:r.length,tiersWithEnv:Mc(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:S}of tKe(r,o,p)){let[b]=S;if(b===void 0)continue;let E=Vi[y],C=S.length===1;l.push({file:E,path:b,message:`${S.map((v)=>`"${v}"`).join(" and ")} in ${E} ${C?"is":"are"} not applied: ${E} is not the managed settings source that applies for ${C?"this key":"these keys"} (/status lists the setting sources). Remove ${C?"it":"them"} from ${E}, or set ${C?"it":"them"} in the source that applies.`,severity:"warning",statusOnly:!0})}return{settings:p,errors:l}}function pKe(e,t,{includeLegacyLocalSettings:n=!0}={}){if(e==="policySettings")return I2(t).settings;let r=Yl(e,t),{settings:o}=r?Zl(r,t.store,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:s}=g2(t);if(s)return dn(o||{},s,xr)}if(e==="localSettings"&&n){let s=S2(t);if(s){let{settings:i}=Zl(s,t.store);if(i)return t.onLegacyLocalSettingsRead?.("per_source"),dn(i,o||{},xr)}}return o}function fKe(e,t){return{...e,...t}}function xr(e,t,n){if(n==="modelPicker"&&t!==void 0)return D2(t);if(Array.isArray(e)&&Array.isArray(t)){if(n==="fallbackModel")return t;return Nn([...e,...t])}if((n==="extraKnownMarketplaces"||n==="managedMcpServers")&&ce(e)&&ce(t))return fKe(e,t);return}function D2(e){if(!ce(e))return e;let t=e.options;return{...e,...Array.isArray(t)&&{options:t.map((n)=>ce(n)?{...n}:n)}}}function mKe(e){if(e.store.isLoadingFromDisk)return{settings:{},errors:[]};let t=Date.now();md("info","settings_load_started"),e.store.isLoadingFromDisk=!0;try{let n=e.store.pluginBase,r={};if(n)r=dn(r,n,xr);let o=[],s=new Set,i=new Set,a=(y)=>{for(let S of y){let b=`${S.file}:${S.path}:${S.message}`;if(!s.has(b))s.add(b),o.push(S)}},l=[],c=[Ks()];if(Pt()==="wsl"&&e.wslInherits?.())c.push(cr);let d=new Set(c.map((y)=>xt(mn(y,"managed-settings.json")))),p=new Set(c.map((y)=>xt(mn(y,"managed-settings.d")))),f=(y)=>{let S=xt(y);return d.has(S)||p.has(r_(S))},m=(y,S,b)=>{if(b?.channelLabel!==!0&&f(y))return;let E=S.sandbox?.filesystem?.allowRead?.length??0,C=S.sandbox?.network?.allowedDomains?.length??0;if(E>0||C>0)l.push({file:y,allowReadCount:E,allowedDomainsCount:C})},g=null;for(let y of Mx(e)){if(y==="policySettings"){let{settings:E,errors:C}=I2(e);if(g=E,a(HBe(E)),a(jBe(E)),E)r=dn(r,$d(y,E,e),xr);a(C);continue}let S=e.store.repoTierFreeze.tier(y);if(S!==void 0){let E=Yl(y,e);if(E)i.add(xt(E));if(a([...S.errors]),S.settings)r=dn(r,S.settings,xr);continue}if(y==="localSettings"){let E=S2(e);if(E&&!i.has(xt(E))){i.add(xt(E));let{settings:C,errors:v}=Zl(E,e.store);if(a(v),C)e.onLegacyLocalSettingsRead?.("cascade"),m(E,C),r=dn(r,$d(y,C,e),xr)}}let b=Yl(y,e);if(b){let E=xt(b),C=y==="flagSettings"&&e.flagExpectedContent!==void 0;if(!i.has(E)||C){i.add(E);let{settings:v,errors:w}=Zl(b,e.store,y==="flagSettings"?e.flagExpectedContent:void 0);if(a(w),v){if(y==="flagSettings"&&e.flagInlineJson===!0)m("--settings (inline JSON)",v,{channelLabel:!0});else m(b,v);r=dn(r,$d(y,v,e),xr)}}}if(y==="flagSettings"){let{settings:E,errors:C}=g2(e);if(a(C),E)m("SDK inline settings",E,{channelLabel:!0}),r=dn(r,$d(y,E,e),xr)}}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=D2(g.modelPicker)}let _=g?.deniedModels;if(_!==void 0)r.deniedModels=[..._];else delete r.deniedModels;if(l.length>0){let y=BBe(e),S=(b,E,C,v,w)=>({file:b,path:E,severity:"warning",statusOnly:!0,message:`${E} is ignored — managed settings set ${C}, so only ${v} from managed settings are honored. The ${w===1?"entry":`${w} entries`} in ${b} will NOT apply (see https://code.claude.com/docs/en/settings#sandbox-settings).`});if(y.some((b)=>b.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)){for(let b of l)if(b.allowReadCount>0)a([S(b.file,"sandbox.filesystem.allowRead","allowManagedReadPathsOnly","allowRead paths",b.allowReadCount)])}if(y.some((b)=>b.sandbox?.network?.allowManagedDomainsOnly===!0)){for(let b of l)if(b.allowedDomainsCount>0)a([S(b.file,"sandbox.network.allowedDomains","allowManagedDomainsOnly","allowed domains (and WebFetch domain rules)",b.allowedDomainsCount)])}}return md("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:i.size,error_count:o.length}),{settings:r,errors:o}}finally{e.store.isLoadingFromDisk=!1}}function gKe(e){let t=e.store.mergedSettings;if(t!==null)return t;let n=mKe(e);return e.store.mergedSettings=n,n}function hKe(e){let{settings:t}=gKe(e);return t||{}}function L2(e){e.store.invalidateAll();let t=[];for(let n of Mx(e)){let r=E2(n,e);if(r&&Object.keys(r).length>0)t.push({source:n,settings:r})}return{effective:hKe(e),sources:t}}function M2(e,t){let n=Mx(t);for(let r=n.length-1;r>=0;r--){let o=n[r];if(E2(o,t)?.[e]!==void 0)return o}return null}import{execFile as _Ke}from"child_process";import{accessSync as yKe,closeSync as SKe,constants as EKe,openSync as bKe,readSync as CKe}from"fs";class z2{promise=null;start(){if(this.promise)return;this.promise=jx()}reset(){this.promise=null}}var vKe=new z2;function AKe(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 Hx(e,t,n){let r=Date.now();return new Promise((o)=>{try{_Ke(e,t,{encoding:"utf-8",timeout:HV,windowsHide:!0,...n!==void 0&&{maxBuffer:n}},(s,i)=>{o({stdout:i??"",...AKe(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 N2(e){return{status:e.status,exitCode:e.exitCode,errno:e.errno,signal:e.signal,durationMs:e.durationMs}}function U2(e){return e.status==="ok"||e.status==="exited"&&e.exitCode!==null}function RKe(e){return e.status==="spawn_error"&&e.errno==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}function xKe(e){let t;try{return t=bKe(e,"r"),CKe(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{SKe(t)}catch{}}}function jx(){return(async()=>{if(process.platform==="darwin"){let e=BV(),n=(await Promise.all(e.map(async({path:o,...s})=>{try{yKe(o,EKe.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 Hx(Tx,[...zV,o],Xh);if(!U2(i))return{stdout:null,unreadReason:"plutil did not finish converting it",...s};if(i.status==="ok")return{stdout:i.stdout,...s};let a=await Hx(Tx,[...$V,o]);if(!U2(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=xKe(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 F2(t)}if(Nd())return F2(jV);return{plistStdouts:null,hklmStdout:null,hkcuStdout:null,outcomes:{hklm:null,hkcu:null}}})()}async function F2(e){let t=(o)=>Hx(e,["query",o,"/v",Md],Xh),[n,r]=await Promise.all([t(Yh),t(Jh)]);return{plistStdouts:null,hklmStdout:n.status==="ok"?n.stdout:null,...RKe(n)&&{hklmUnreadReason:`the value exceeds ${Xh/1048576} MiB`},hkcuStdout:r.status==="ok"?r.stdout:null,outcomes:{hklm:N2(n),hkcu:N2(r)}}}function $2(){return vKe.promise}var TKe=Object.freeze({settings:{},errors:[],loadState:"absent"}),ec=Object.freeze({settings:{},errors:[]});class W2{mdm=null;hkcu=null;wslInherits=!1;loadPromise=null;startLoad(e){if(this.loadPromise)return;this.loadPromise=(async()=>{let t=Date.now(),r=await($2()??jx()),{mdm:o,hkcu:s,wslInherits:i}=await FKe(r,e);this.replace(o,s,i);let a=Date.now()-t;q(`MDM settings load completed in ${a}ms`);try{js("tengu_managed_settings_os_read",UKe(r,a))}catch{}if(Object.keys(o.settings).length>0){q(`MDM settings found: ${Object.keys(o.settings).join(", ")}`);try{md("info","mdm_settings_loaded",{duration_ms:a,key_count:Object.keys(o.settings).length,error_count:o.errors.length})}catch{}}})()}replace(e,t,n){this.mdm=e,this.hkcu=t,this.wslInherits=n}reset(){this.mdm=null,this.hkcu=null,this.wslInherits=!1,this.loadPromise=null}}var H2="@builtin",wKe=["prependPlugins","appendPlugins"];function OKe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var kKe=new Fe(()=>new W2);function Wd(){return kKe.of(tn().host)}function PKe(e){Wd().startLoad(e)}async function V2(){let e=Wd();if(!e.loadPromise)PKe();await e.loadPromise}function q2(){return Wd().mdm??TKe}function Z2(){return Wd().hkcu??ec}function Y2(){return Wd().wslInherits}function Bx(e,t,{userWritable:n=!1}={}){let r=Pi(e,!1);if(!ce(r))return{settings:{},errors:[i_(t,{userWritable:n})],documentHasPolicyContent:!1,loadState:"didNotLoad"};let o=[],s=r;for(let f of n?o_:[]){if(!(f in s))continue;if(s=s===r?{...r}:s,delete s[f],!Yi(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 wKe){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(OKe(f)){if(Object.entries(f).filter(([g,_])=>g.endsWith(H2)||_!==!1).length>0){s=s===r?{...r}:s;let g=Zg(f,(_,y)=>!y.endsWith(H2)&&_===!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}=Hd(s,t),p=[...o,...a];return{settings:i??{},errors:n?p.map((f)=>({...f.severity==="warning"&&!f.startupFatal?f:{...IKe(f),severity:"warning",statusOnly:!0},userWritable:!0})):p,documentHasPolicyContent:l,loadState:c,...d&&{onlySubstitutes:d}}}function IKe({startupFatal:e,...t}){return t}function j2(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 B2(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 DKe=new Map([["ENOENT",qt("ENOENT")],["EACCES",qt("EACCES")],["EPERM",qt("EPERM")],["ENOEXEC",qt("ENOEXEC")],["EAGAIN",qt("EAGAIN")],["EMFILE",qt("EMFILE")],["ENOMEM",qt("ENOMEM")],["ETIMEDOUT",qt("ETIMEDOUT")],["ERR_CHILD_PROCESS_STDIO_MAXBUFFER",qt("ERR_CHILD_PROCESS_STDIO_MAXBUFFER")]]),LKe=new Map([["SIGTERM",qt("SIGTERM")],["SIGKILL",qt("SIGKILL")],["SIGINT",qt("SIGINT")]]);function MKe(e){if(!e)return;return DKe.get(e)??qt("other")}function NKe(e){if(!e)return;return LKe.get(e)??qt("other")}function K2(e,t){if(!t)return{};return{[`${e}_status`]:Xo(t.status),[`${e}_exit_code`]:t.exitCode??void 0,[`${e}_errno`]:MKe(t.errno),[`${e}_signal`]:NKe(t.signal),[`${e}_duration_ms`]:t.durationMs}}function UKe(e,t){return{is_wsl:Nd(),await_ms:t,...K2("hklm",e.outcomes.hklm),...K2("hkcu",e.outcomes.hkcu)}}async function FKe(e,t){let n=[],r=!1,o="absent";for(let _ of e.plistStdouts??[]){let{label:y,userWritable:S}=_;if(S&&r)continue;let b=_.stdout===null?{settings:{},errors:[j2(y,_.unreadReason,S,_.unreadErrno)],documentHasPolicyContent:!1,loadState:"didNotLoad",...S&&{userWritable:S}}:{...Bx(_.stdout,y,{userWritable:S}),...S&&{userWritable:S}};if(S?Ql(b.settings):b.documentHasPolicyContent)return{mdm:{...b,errors:[...n,...b.errors],documentHasPolicyContent:!0},hkcu:ec,wslInherits:!1};if(r||=Xl(b),n.push(...b.errors),!S)o=No(o,b.loadState)}let s=`Registry: ${Yh}\\${Md}`,i=null,a="disarmed";if(e.hklmStdout!==null){let _=B2(e.hklmStdout)??"";i=Bx(_,s);let y=Pi(_,!1);if(ce(y))a=mx(y)}else if(e.hklmUnreadReason!==void 0)i={settings:{},errors:[j2(s,e.hklmUnreadReason,!1)],documentHasPolicyContent:!1,loadState:"didNotLoad"};let l=i!==null&&Xl(i);if(i)n.push(...i.errors),o=No(o,i.loadState);let c=Nd(),d="disarmed",p=s,f=[];if(c){if(d=a,d!=="armed"){let _=await $Ke(t);if(f=_.links,_.flag==="armed"||d==="disarmed")d=_.flag,p=_.unreadableFlagPath??cr;if(d==="disarmed")n.push(..._.records),o=No(o,_.loadState)}}let m=d!=="disarmed",g={settings:{},errors:n,loadState:o};if(c&&!m){let _=new Set(i?.errors.filter((y)=>y.severity==="warning"));return{mdm:{...g,errors:g.errors.map((y)=>_.has(y)?{...y,wslIgnored:!0}:y),...f.length>0&&{managedDocumentLinks:f}},hkcu:ec,wslInherits:!1}}if(i&&l)return{mdm:i,hkcu:ec,wslInherits:m};if(d==="unreadable"){let _=await Gx(cr,t);return{mdm:{...g,errors:_?g.errors:[...g.errors,h2(p)],documentHasPolicyContent:!0,loadState:No(g.loadState,"loaded")},hkcu:ec,wslInherits:m}}if(e.hkcuStdout!==null&&!await zKe(m,t)){let _=Bx(B2(e.hkcuStdout)??"",`Registry: ${Jh}\\${Md}`,{userWritable:!0});if(!c||_.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:y,managedSourcesBehavior:S,...b}=_.settings;return{mdm:g,hkcu:{settings:b,errors:_.errors},wslInherits:m}}if(_.errors.length>0)return{mdm:g,hkcu:{settings:{},errors:_.errors},wslInherits:m}}return{mdm:g,hkcu:ec,wslInherits:m}}async function J2(e,t){if(Ee()&&t!==void 0)return(await UB(e,s_)).content;return ki(e,s_)}async function zKe(e,t){if(e&&await Gx(cr,t))return!0;return Gx(Ks(),t)}async function G2(e,t){let n;try{n=await J2(e,t)}catch(r){return!pt(r)}try{let r=zx(n,e,!0);return Xl({...r,loadState:Zi(r)})}catch{return!0}}function Kx(e){let t=pe(e);return t==="ENOENT"||t==="ENOTDIR"}async function $Ke(e){let t=[],n="absent",r=[],o=new Map;async function s(p,f){let m=Ji(cr,...p),g;try{g=await J2(m,e)}catch(S){if(Kx(S))return"disarmed";t.push(Bd(m,S)),n="didNotLoad"}let _=await nK(cr,p,f,o);if(_!==null)r.push(_);if(g===void 0)return"disarmed";let y=g.trim()===""?{}:Pi(g,!1);if(!ce(y))return t.push(i_(m)),n="didNotLoad","disarmed";return n=No(n,"loaded"),mx(y)}let i=Ji(cr,"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=Ji(cr,"managed-settings.d"),d;try{d=await ke().readdir(c)}catch(p){if(!Kx(p))t.push(Bd(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??=Ji(c,p.name)}return{flag:a,unreadableFlagPath:l,records:t,loadState:n,links:r}}async function Gx(e,t){if(await G2(Ji(e,"managed-settings.json"),t))return!0;let n=Ji(e,"managed-settings.d"),r;try{r=await ke().readdir(n)}catch(o){return!Kx(o)}for(let o of r)if((o.isFile()||o.isSymbolicLink())&&Nx(o.name)&&await G2(Ji(n,o.name),t))return!0;return!1}var jKe={user:"userSettings",project:"projectSettings",local:"localSettings"},X2={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},BKe=["user","project","local"];async function Q2(e={}){await V2();let t={store:new ha,cwd:HKe(e.cwd??ke().cwd()),allowedSources:(e.settingSources??BKe).map((a)=>jKe[a]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:q2,hkcu:Z2,wslInherits:Y2,credentialHelperKeysFrom:()=>"as_read",...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}},{effective:n,sources:r}=L2(t),o=v2(t)??void 0,s=r.map(({source:a,settings:l})=>({source:X2[a],settings:l,path:a==="policySettings"?void 0:Yl(a,t),...a==="policySettings"&&{policyOrigin:o}})),i={};for(let a of Object.keys(n)){let l=M2(a,t);if(l)i[a]={source:X2[l],path:l==="policySettings"?void 0:Yl(l,t),...l==="policySettings"&&{policyOrigin:o}}}return{effective:n,provenance:i,sources:s}}var KKe=new Set(["bypassPermissions","auto","acceptEdits"]),GKe=new Set(["project"]),WKe=new Set(["project","local"]);function VKe(e){let t=e.effective.permissions?.defaultMode;if(!t||!KKe.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((xV.includes(t)?WKe:GKe).has(r.source)){let{defaultMode:s,...i}=e.effective.permissions??{};return{...e.effective,permissions:i}}return e.effective}}return e.effective}import{execFile as Q1e}from"child_process";import{randomUUID as eGe}from"crypto";import{mkdir as f_,mkdtemp as tGe,readFile as nGe,rm as Yq,writeFile as Jq}from"fs/promises";import{createRequire as rGe}from"module";import{homedir as ep,tmpdir as oGe}from"os";import{dirname as Vq,isAbsolute as pT,join as ut,posix as Xq,resolve as tp,sep as sGe,win32 as Qq}from"path";import{fileURLToPath as iGe}from"url";import{setMaxListeners as qKe}from"events";var ZKe=50;function Vd(e=ZKe){let t=new AbortController;return qKe(e,t.signal),t}var nTt=new FinalizationRegistry(({parentSignalRef:e,handler:t})=>{e.deref()?.removeEventListener("abort",t)});var YKe="ask-withdrawn-by-asker",rTt=new DOMException(YKe,"AbortError");var oTt={"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 JKe="server-fallback-tombstone";var sTt=new DOMException(JKe,"AbortError");var XKe="subagent-park",iTt=new DOMException(XKe,"AbortError");import{spawn as a1e}from"child_process";import{existsSync as l1e}from"fs";import{createInterface as c1e}from"readline";import{StringDecoder as u1e}from"string_decoder";var QKe=/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9/_-]+/gi;var Wx={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>"]},e1e=[/\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 lTt=new RegExp(`(?:\\b(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-${tc("[A-Za-z0-9+/=%_-]")}|\\bxox[cd]-|(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-(?=[0-9])|xox[cd]-${tc("[A-Za-z0-9+/=%_-]")}(?=[A-Za-z0-9+/=%_-]{16}))`,"i"),eq=[[qd("sk-ant-","[A-Za-z0-9_-]",8,Vx(8)),"<token>"],[qd("sk-(?:proj|svcacct|admin)-","[A-Za-z0-9_-]",20,Vx(20)),"<token>"]],tq=["AKIA","ASIA","ABIA","ACCA","A3T[A-Z0-9]"],t1e=`(?:${tq.join("|")})`,nq=[[new RegExp(`(^|[^A-Za-z0-9+])${t1e}[A-Z0-9]{16}(?![A-Za-z0-9+=])`,"g"),"$1<token>"]],rq=[[qd("gh[opusr]_","[A-Za-z0-9]",20,tc("[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>"],[qd("gl(?:pat|dt|rt|ft|soat|oas|agent|ptt|cbt|imt|ffct)-","[A-Za-z0-9_=-]",20,tc("[A-Za-z0-9_=-]"),"(?:\\.[0-9a-z]{9})?"),"<token>"],[qd("(?:xox[abe-z](?:\\.xox[a-z])?|xapp|xwfp)-","[A-Za-z0-9+/=%_-]",10,"(?=[0-9])","",tc("[A-Za-z0-9+/=%_-]"),"gi"),"<token>"],[new RegExp(`(?:\\bxox[cd]-[A-Za-z0-9+/=%_-]{10,}|xox[cd]-${tc("[A-Za-z0-9+/=%_-]")}[A-Za-z0-9+/=%_-]{16,})`,"gi"),"<token>"],[QKe,"hooks.slack.com/<redacted>"]];var n1e=[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>"],r1e=/\beyJ(?:[A-Za-z0-9_-]{256}|[A-Za-z0-9_-]{8,2048}\.[A-Za-z0-9_-]{10})/,oq=[[/(^|[^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>"]],sq=[[/(^|[^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>"]],o1e=[Wx.bearer,Wx.basic,...eq,Wx.sk,...nq],s1e=[...rq,n1e,...oq,...sq],cTt=[[new RegExp(`sk-${Vx(20)}[A-Za-z0-9_-]{20,}`,"g"),"<token>"],...tq.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 Zd(e){return[...o1e,...s1e].reduce((t,[n,r])=>t.replace(n,r),String(e))}var uTt=[...e1e,...[...eq,...nq,...rq,...oq,...sq].map(([e])=>new RegExp(e.source,e.flags.replaceAll("g",""))),r1e];function qd(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 tc(e){return`(?=${e}{0,64}[0-9])`}function Vx(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 i1e(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")}function iq(e,t){let n={...e};if(!t)return n;let r=t.enabled===!0&&t.failIfUnavailable===void 0?{...t,failIfUnavailable:!0}:t,o=n.settings;if(o&&!i1e(o))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let s={sandbox:r};if(o)try{s={...We(o),sandbox:r}}catch{}return n.settings=ie(s),n}function qx(e,t,n){let r=String(n);if(r.length>1&&r.startsWith("-"))e.push(`--${t}=${r}`);else e.push(`--${t}`,r)}var d1e=2000,Zx=2048,cq="sdk-exit-after-stderr-drained",p1e=200;function Yx(e){return e==="exit"?cq:e}class uq{#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 a_=new uq,f1e=/[(),\u0000-\u001f\u007f-\u009f]/;function m1e(e){if(typeof e!=="string"||e.trim()==="")throw Error("Skill names must be non-empty strings.");if(!nf(e))throw new we(`Invalid skill name ${ie(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 we(`Invalid skill name ${ie(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(f1e.test(e))throw new we(`Invalid skill name ${ie(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 we(`Invalid skill name ${ie(e)}: wildcard-suffix names are not allowed; list each skill by its exact name.`,"wildcard-suffix skill name rejected");if(e.startsWith("/"))throw new we(`Invalid skill name ${ie(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 we(`Invalid skill name ${ie(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 we(`Invalid skill name ${ie(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=Vd();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(e){this.options=e;if(this.abortController=e.abortController||Vd(),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(Mn(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 Na()?"bun":"node"}spawnLocalProcess(e){let{command:t,args:n,cwd:r,env:o,signal:s}=e,i=a1e(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(_){Kt(`onProcessSpawned threw: ${Ot(_)}`)}let a=new u1e("utf8"),l=!1,c=!1,d=!1,p,f=Re(o.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr!==void 0;i.stderr.on("data",(_)=>{if(d)return;let y=a.write(_);if(this.stderrTail+=y,this.stderrTail.length>2*Zx)this.stderrTail=tf(Zd(this.stderrTail),Zx);if(f)Kt(y),this.options.stderr?.(y)}),i.stderr.on("error",(_)=>{Kt(`[ProcessTransport] stderr read failed: ${_.code??_.message}`)});let m=()=>{if(d)return;if(d=!0,p)clearTimeout(p);i.emit(cq,i.exitCode,i.signalCode);let _=i.stderr;if(y1e(_))_.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,p1e)}),{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:(_,y)=>i.on(Yx(_),y),once:(_,y)=>i.once(Yx(_),y),off:(_,y)=>i.off(Yx(_),y)}}initialize(){try{let{additionalDirectories:e=[],projectConfigRoot:t,agent:n,betas:r,cwd:o,executable:s=this.getDefaultExecutable(),executableArgs:i=[],extraArgs:a={},pathToClaudeCodeExecutable:l,env:c={...process.env},thinkingConfig:d,maxTurns:p,maxBudgetUsd:f,taskBudget:m,model:g,fallbackModel:_,jsonSchema:y,permissionMode:S,allowDangerouslySkipPermissions:b,permissionPromptToolName:E,permissionPrompts:C,continueConversation:v,resume:w,settingSources:L,skills:z,disallowedTools:U=[],tools:de,mcpServers:x,strictMcpConfig:R,canUseTool:O,includePartialMessages:D,plugins:B,pluginsViaInitialize:oe,sandbox:me}=this.options,{allowedTools:J=[]}=this.options;if(z!==void 0){let ye=z==="all"?["Skill"]:z.map((Qt)=>`Skill(${m1e(Qt)})`),Wt=new Set(J);J=[...J,...ye.filter((Qt)=>!Wt.has(Qt))]}let K=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(d){switch(d.type){case"enabled":if(d.budgetTokens===void 0)K.push("--thinking","adaptive");else K.push("--max-thinking-tokens",d.budgetTokens.toString());break;case"disabled":K.push("--thinking","disabled");break;case"adaptive":K.push("--thinking","adaptive");break}if(d.type!=="disabled"&&d.display)K.push("--thinking-display",d.display)}if(this.options.effort)K.push("--effort",this.options.effort);if(p)K.push("--max-turns",p.toString());if(f!==void 0)K.push("--max-budget-usd",f.toString());if(m)K.push("--task-budget",m.total.toString());if(g)K.push("--model",g);if(n)K.push("--agent",n);if(r&&r.length>0)K.push("--betas",r.join(","));if(y)K.push("--json-schema",ie(y));if(this.options.debugFile)K.push("--debug-file",this.options.debugFile);else if(this.options.debug)K.push("--debug");if(!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let ye=AB();if(ye)K.push("--debug-file",ye)}if(O){if(E)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");K.push("--permission-prompt-tool","stdio")}else if(E)K.push("--permission-prompt-tool",E);if(C)K.push("--permission-prompts",C);if(v)K.push("--continue");if(w)K.push(`--resume=${w}`);if(this.options.channels&&this.options.channels.length>0)for(let ye of this.options.channels)qx(K,"channels",ye);if(J.length>0)K.push("--allowedTools",J.join(","));if(U.length>0)K.push("--disallowedTools",U.join(","));if(de!==void 0)if(Array.isArray(de))if(de.length===0)K.push("--tools","");else K.push("--tools",de.join(","));else K.push("--tools","default");if(x&&Object.keys(x).length>0)K.push("--mcp-config",ie({mcpServers:x}));if(L!==void 0)K.push(`--setting-sources=${L.join(",")}`);if(R)K.push("--strict-mcp-config");if(S)K.push("--permission-mode",S);if(b)K.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.");K.push("--fallback-model",_)}if(this.options.includeHookEvents)K.push("--include-hook-events");if(D)K.push("--include-partial-messages");if(this.options.sessionMirror)K.push("--session-mirror");if(t!==void 0)K.push(`--project-config-root=${t}`);for(let ye of e)K.push("--add-dir",ye);if(oe)K.push("--await-initialize");else if(B&&B.length>0)for(let ye of B)if(ye.type==="local")K.push(ye.skipMcpDiscovery?"--plugin-dir-no-mcp":"--plugin-dir",ye.path);else throw Error(`Unsupported plugin type: ${ye.type}`);if(this.options.forkSession)K.push("--fork-session");if(this.options.resumeSessionAt)K.push(`--resume-session-at=${this.options.resumeSessionAt}`);if(this.options.resumeDropsTurn!==void 0)K.push(`--resume-drops-turn=${this.options.resumeDropsTurn}`);if(this.options.sessionId)K.push(`--session-id=${this.options.sessionId}`);if(this.options.persistSession===!1)K.push("--no-session-persistence");if(this.options.managedSettings)K.push("--managed-settings",this.options.managedSettings);let bt={...a??{}};if(this.options.settings)bt.settings=this.options.settings;let Xt=iq(bt,me);for(let[ye,Wt]of Object.entries(Xt))if(Wt===null)K.push(`--${ye}`);else qx(K,ye,Wt);if(!c.CLAUDE_CODE_ENTRYPOINT)c.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(delete c.NODE_OPTIONS,Re(c.DEBUG_CLAUDE_AGENT_SDK))c.DEBUG="1";else delete c.DEBUG;let dt=g1e(l),Tt=dt?l:s,Ct=dt?[...i,...K]:[...i,l,...K],Gt={command:Tt,args:Ct,cwd:o,env:c,signal:this.forwardedAbort.signal};if(this.options.spawnClaudeCodeProcess)Kt(`Spawning Claude Code (custom): ${Tt} ${Ct.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(Gt);else Kt(`Spawning Claude Code: ${Tt} ${Ct.join(" ")}`),this.process=this.spawnLocalProcess(Gt);if(this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,this.processStdin.on("error",(ye)=>{Kt(`[ProcessTransport] stdin write failed (child likely exited): ${ye.code??ye.message}`),this.ready=!1}),a_.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",(ye)=>{this.ready=!1;let Wt=ye,Qt=Wt.syscall!==void 0?Wt.syscall.startsWith("spawn"):fy(ye);if(Qt&&!Ye.killed)a_.untrack(Ye);if(this.abortController.signal.aborted)this.exitError=l_(),en(ye,{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"});else if(Qt&&fy(ye)){let{message:$o,telemetryMessage:Xi,errorClass:Ho}=h1e(l,dt),_n={telemetryMessage:`${Xi}${Jx(ye)}`,errorClass:Ho,code:mc(ye)};this.exitError=en(ReferenceError($o),_n),en(ye,_n),Kt(this.exitError.message)}else{let $o={telemetryMessage:Qt?`Failed to spawn Claude Code process${Jx(ye)}`:`Claude Code process error${Jx(ye)}`,errorClass:Qt?"spawn_failed":"process_error",code:mc(ye)};this.exitError=en(Error(`Failed to spawn Claude Code process: ${Zd(ye.message)}`),$o),en(ye,$o),Kt(this.exitError.message)}}),Ye.on("exit",(ye,Wt)=>{if(this.exitEventDelivered=!0,this.ready=!1,this.abortController.signal.aborted)this.exitError=l_();else{let Qt=this.getProcessExitError(ye,Wt);if(Qt)this.exitError=Qt,Kt(Qt.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 en(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 en(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=tf(Zd(this.stderrTail),Zx).trim();return e?`. stderr: ${e}`:""}write(e){if(this.abortController.signal.aborted)throw aq();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){Kt("[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 en(Error(`Cannot write to process that exited with error: ${this.exitError.message}`),{telemetryMessage:`Cannot write to process that exited with error: ${EO(this.exitError)??"untagged exit error"}`,errorClass:lq(this.exitError,"errorClass"),code:mc(this.exitError),exitCode:_1e(this.exitError),signal:lq(this.exitError,"signal")});Kt(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{if(!this.processStdin.write(e))Kt("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${Ot(t)}`)}}[Symbol.dispose](){this.close()}close(){if(this.spawnAbort(this.abortController.signal.aborted?l_():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?l_():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){Kt(`[ProcessTransport] onExit callback threw during close(): ${Ot(c)}`)}let s=()=>{if(this.abortController.signal.aborted)this.forwardedAbort.abort(this.abortController.signal.reason)},i=this.process;if(i&&!i.killed&&i.exitCode===null&&i.signalCode==null)setTimeout((a,l)=>{if(a.exitCode!==null||a.signalCode!=null){l();return}if(process.platform==="win32"){setTimeout((c,d)=>{if(c.exitCode===null)c.kill("SIGKILL");d()},5000,a,l).unref();return}a.kill("SIGTERM"),setTimeout((c)=>{if(c.exitCode===null)c.kill("SIGKILL")},5000,a).unref(),l()},d1e,i,s).unref(),i.once("exit",()=>a_.untrack(i));else if(i)a_.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=c1e({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=We(n)}catch(o){Kt(`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(aq());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 g1e(e){return![".js",".mjs",".tsx",".ts",".jsx"].some((n)=>e.endsWith(n))}function h1e(e,t){let n=t?"native binary":"executable",r=Zd(e);if(l1e(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=mc(e);return t===void 0?"":` (${t})`}function l_(){return en(new jn("Claude Code process aborted by user"),{telemetryMessage:"Claude Code process aborted by user",errorClass:"aborted"})}function aq(){return en(new jn("Operation aborted"),{telemetryMessage:"Operation aborted",errorClass:"aborted"})}function lq(e,t){let n=Object.hasOwn(e,t)?Reflect.get(e,t):void 0;return typeof n==="string"?n:void 0}function _1e(e){let t=Object.hasOwn(e,"exitCode")?Reflect.get(e,"exitCode"):void 0;return typeof t==="number"?t:void 0}function y1e(e){return typeof Reflect.get(e,"unref")==="function"}import{existsSync as S1e}from"fs";var nc="@anthropic-ai/claude-agent-sdk";function E1e(){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 dq(e,t={}){let n=t.platform??process.platform,r=t.arch??process.arch,o=t.exists??S1e,s=t.preferMusl??E1e(),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 b1e=["signed_out","identity_changed","transient","refresh_failed"];function pq(e){return b1e.some((t)=>t===e)}var c_=600000;function fq(e){return"method"in e&&"id"in e&&e.id!==null}var mq=Object.freeze({}),gq=Object.freeze({name:"claude-code",title:"Claude Code",description:"Anthropic's agentic coding tool",websiteUrl:"https://claude.com/claude-code"}),UTt=Symbol("swallow");class Qx{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 hq=["remote_tool_call","remote_plumbing_call","remote_tools_probe","remote_tools_reannounce"];var _q="2025-11-25";var C1e="notifications/tools/list_changed";function yq(e){return ce(e)&&!("id"in e)&&e.method===C1e}function eT(e){if(!ce(e))return{settings:{},ignored:[]};let{timeout:t,disableAutoBackground:n}=e,r=Hg(t),o=[];if(t!==void 0&&r===void 0)o.push("timeout");if(n!==void 0&&typeof n!=="boolean")o.push("disableAutoBackground");return{settings:{...r!==void 0&&{timeout:r},...n===!0&&{disableAutoBackground:n}},ignored:o}}var Sq=250,u_="sdk-manifest-capture:",rc=Symbol("suppressControlResponse");class d_{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 fd;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpServers=new Map;initializeWritten;initializeHasBeenWritten=!1;markInitializeWritten;writingFirstInitialize=!1;stopSdkMcpManifestCapture;sdkMcpToolsChangedDuringCapture=new Set;pendingMcpResponses=new Map;runEndedResolve;runEnded=!1;resultReceived=!1;runEndCeilingTimer;sessionState;lastErrorResultText;errorTextBeforeModelLessTurns;modelLessTurnEnded=!1;latestCommands;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,t){let n={type:"system",subtype:"mirror_error",error:t,key:e,uuid:cc(),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=c_){this.transport=e;this.isSingleUserTurn=t;this.canUseTool=n;this.hooks=r;this.abortController=o;this.jsonSchema=i;this.initConfig=a;this.onElicitation=l;this.getOAuthToken=c;this.getHostAuthToken=d;this.onUserDialog=p;this.verbatimPrompts=f;this.runEndCeilingMs=m;for(let[g,_]of s)this.connectSdkMcpServer(g,_);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initializeWritten=new Promise((g)=>{this.markInitializeWritten=()=>{this.initializeHasBeenWritten=!0,g()}}),this.initialization=this.initialize({first:!0}),this.initialization.catch(()=>{})}setError(e){this.inputStream.error(e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){if(this.clearRunEndCeiling(),this.cleanupPromise)return this.cleanupPromise;return this.cleanupPerformed=!0,this.cleanupCause=e,this.stopSdkMcpManifestCapture?.(),this.cleanupPromise=this.performCleanup(e),this.cleanupPromise}async performCleanup(e){for(let t of this.cleanupCallbacks)try{t()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let t of this.cancelControllers.values())t.abort();this.cancelControllers.clear(),this.transport.close()}catch(t){q(`[Query.cleanup] transport.close() failed: ${Ot(t)}`,{level:"error"})}try{let t=e??tT();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(),qn(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>=d_.UNMATCHED_CONTROL_RESPONSES_MAX){let n=this.unmatchedControlResponses.keys().next().value;if(n!==void 0)this.unmatchedControlResponses.delete(n)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else if(e.type==="keep_alive")continue;else if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}if(e.type==="system"&&e.subtype==="commands_changed"&&Array.isArray(e.commands))this.latestCommands=e.commands;if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary"||e.subtype==="session_metadata")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}if(e.type==="autocompact_state"){this.inputStream.enqueue(e);continue}if(e.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=e.is_error?e.subtype==="success"?e.result:e.errors.map((n)=>n.trim()).filter(Boolean).join("; "):void 0;if(this.lastErrorResultText=t||void 0,this.modelLessTurnEnded=e.subtype==="success"&&!e.is_error&&e.num_turns===0&&e.result==="",!this.modelLessTurnEnded)this.errorTextBeforeModelLessTurns=this.lastErrorResultText;if(this.resultReceived=!0,this.sessionState===void 0||this.sessionState==="idle"||!this.hasBidirectionalNeeds())this.endRun();else this.armRunEndCeiling()}else if(e.type==="system"&&e.subtype==="session_state_changed"){if(this.sessionState=e.state,e.state==="idle"){if(this.resultReceived)this.endRun()}else if(!(this.isSingleUserTurn&&this.runEnded)){if(this.runEnded=!1,e.state==="requires_action")this.clearRunEndCeiling();else if(this.resultReceived)this.armRunEndCeiling()}if("sdk_host_only"in e&&e.sdk_host_only===!0)continue}else{if(this.lastErrorResultText=void 0,e.type==="system"&&e.subtype==="init")this.modelLessTurnEnded=!1;else if(e.type!=="system"||e.subtype==="compact_boundary")this.errorTextBeforeModelLessTurns=void 0,this.modelLessTurnEnded=!1;if((e.type==="assistant"||e.type==="stream_event")&&e.parent_tool_use_id===null&&!(this.isSingleUserTurn&&this.runEnded))this.runEnded=!1,this.clearRunEndCeiling()}this.inputStream.enqueue(e)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();let t=this.lastErrorResultText??(this.modelLessTurnEnded?this.errorTextBeforeModelLessTurns:void 0);if(t!==void 0&&!(e instanceof jn)&&e?.name!=="SSEHttpError"){let n=en(Error(`Claude Code returned an error result: ${t}`),{telemetryMessage:"Claude Code returned an error result",errorClass:"error_result"});q(`[Query.readMessages] Replacing exit error with result text. Original: ${Ot(e)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cleanupPerformed){q(`[Query.handleControlRequest] Request ${e.request_id} (${e.request.subtype}) arrived after close — skipping`);return}if(this.cancelControllers.has(e.request_id)){q(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) — skipping`);return}let t=new AbortController;this.cancelControllers.set(e.request_id,t);try{let n;try{let r=await this.processControlRequest(e,t.signal);if(this.cleanupPerformed)return;if(r===rc)return;let o={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:r}};n=ie(o)+`
137
137
  `}catch(r){if(this.cleanupPerformed)return;let o={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:Ot(r)}};n=ie(o)+`
138
- `}try{await Promise.resolve(this.transport.write(n))}catch(r){q(`[Query.handleControlRequest] Response write failed: ${Ot(r)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(hq.some((n)=>n===e.request.subtype))return q(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),rc;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,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 rc;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(fq(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 rc;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 rc;return n}return q(`[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`),js("tengu_request_user_dialog_response_ignored",{shape:Xo("auto_cancel")}),rc}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(pq(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(!Eq(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)q(`[Query.initialize] Claude Code reported plugins_applied=${String(o.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return o}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[s,i]of Object.entries(this.hooks))if(i.length>0)this.initHooksPayload[s]=i.map((a)=>{let l=[];for(let c of a.hooks){let d=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(d,c),l.push(d)}return{matcher:a.matcher,hookCallbackIds:l,timeout:a.timeout}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([s,{settings:i}])=>Object.keys(i).length>0?[[s,i]]:[]),r=n.length>0?Object.fromEntries(n):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:r,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,r=async(p,f)=>{try{if(await this.sdkMcpServers.get(p)?.connection,n)return;let m=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:u_+"initialize",method:"initialize",params:{protocolVersion:_q,capabilities:mq,clientInfo:{...gq,version:"0.3.293"}}}},f);if(n)return;if(!("result"in m)){q(`[Query.captureSdkMcpServerManifests] '${p}' answered initialize with an error; leaving it to the CLI: ${ie(m)}`,{level:"warn"});return}let g=m.result;f.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let _=g.capabilities,y=typeof _==="object"&&_!==null&&"tools"in _&&_.tools!==void 0&&_.tools!==null,S;if(y){let C=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:u_+"tools-list",method:"tools/list"}},f);if(n)return;if(!("result"in C)){q(`[Query.captureSdkMcpServerManifests] '${p}' answered tools/list with an error; leaving it to the CLI: ${ie(C)}`,{level:"warn"});return}if(C.result.nextCursor===void 0)S=C.result}let E=We(ie(S===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:S}));t.set(p,{transport:f,manifest:E})}catch(m){if(!n)q(`[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 AO(Promise.race([s,i]),Sq);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"){kl("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)q(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${Sq} ms; the rest will handshake over the control channel`,{level:"warn"}),kl("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)kl("sdk_mcp_manifest_capture","partial",c);else pd("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 q(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(d).join(", ")}] captured in ${l} ms`),d}async interrupt(e){return Bt("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let r=t.response?.cancelled;return{still_queued:n.filter((o)=>typeof o==="string"),...Array.isArray(r)&&{cancelled:r.filter((o)=>typeof o==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let r=(s)=>{if(s.subtype==="success"){let{pending_permission_requests:i,pending_user_dialog_requests:a,...l}=s;t(l)}else n(new we(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests)q("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(tT());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 Bt("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 Bt("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return Bt("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 Bt("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=Bt("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(r)=>{if(r?.initialize===void 0)return n;let o=r.initialize,s=await n.then((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let r=++this.remoteControlCallGeneration,o=this.workSecretAnswerer,s=n?.reattachSessionId||(n?.workSecret===void 0?void 0:A1e(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&&Eq(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 Bt("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return Bt("sdk_side_question",async()=>{let r=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return r.response===null?null:{response:r.response,synthetic:r.synthetic??!1,...r.refusal_fallback&&{refusalFallback:{originalModel:r.refusal_fallback.original_model,fallbackModel:r.refusal_fallback.fallback_model,content:r.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest(t).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(Mn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(tT());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(Mn(n.reason??"Control request aborted")),!c)return;try{Promise.resolve(this.transport.write(ie({type:"control_cancel_request",request_id:r})+`
138
+ `}try{await Promise.resolve(this.transport.write(n))}catch(r){q(`[Query.handleControlRequest] Response write failed: ${Ot(r)}`,{level:"error"})}}finally{if(this.cancelControllers.get(e.request_id)===t)this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);if(t)t.abort(),this.cancelControllers.delete(e.request_id)}async processControlRequest(e,t){if(hq.some((n)=>n===e.request.subtype))return q(`[Query.processControlRequest] ${e.request.subtype} ${e.request_id} is for the machine serving this session's tools — leaving it unanswered`),rc;if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let n=e.request.computer_folder,r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,...e.request.mcp_server&&{mcpServer:{name:e.request.mcp_server.name,source:e.request.mcp_server.source}},decisionReason:e.request.decision_reason,...typeof e.request.decision_reason_type==="string"&&{decisionReasonType:e.request.decision_reason_type},...typeof e.request.decision_reason_code==="string"&&{decisionReasonCode:e.request.decision_reason_code},title:e.request.title,displayName:e.request.display_name,description:e.request.description,defaultToNo:e.request.default_to_no,suppressAlwaysAllowRule:e.request.suppress_always_allow_rule,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,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 rc;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(fq(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 rc;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 rc;return n}return q(`[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`),js("tengu_request_user_dialog_response_ignored",{shape:Xo("auto_cancel")}),rc}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(pq(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(!Eq(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)q(`[Query.initialize] Claude Code reported plugins_applied=${String(o.plugins_applied)} for ${this.initConfig.plugins.length} plugins sent with pluginDelivery 'initialize'; the process is running with the plugins it was launched with.`,{level:"warn"});return o}buildInitializeRequest(e){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[s,i]of Object.entries(this.hooks))if(i.length>0)this.initHooksPayload[s]=i.map((a)=>{let l=[];for(let c of a.hooks){let d=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(d,c),l.push(d)}return{matcher:a.matcher,hookCallbackIds:l,timeout:a.timeout}})}let t=this.sdkMcpServers.size>0?Array.from(this.sdkMcpServers.keys()):void 0,n=Array.from(this.sdkMcpServers).flatMap(([s,{settings:i}])=>Object.keys(i).length>0?[[s,i]]:[]),r=n.length>0?Object.fromEntries(n):void 0;return{subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,sdkMcpServerConfigs:r,sdkMcpServerManifests:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt==="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,systemPromptSnapshot:this.initConfig?.systemPromptSnapshot,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds,perTaskStopAffordance:this.initConfig?.perTaskStopAffordance,rapidFollowupPreempt:this.initConfig?.rapidFollowupPreempt,forwardNestedSubagentToolCalls:this.initConfig?.forwardNestedSubagentToolCalls,workspaceTrust:this.initConfig?.workspaceTrust,plugins:this.initConfig?.plugins}}async captureSdkMcpServerManifests(){let e=performance.now(),t=new Map,n=!1,r=async(p,f)=>{try{if(await this.sdkMcpServers.get(p)?.connection,n)return;let m=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:u_+"initialize",method:"initialize",params:{protocolVersion:_q,capabilities:mq,clientInfo:{...gq,version:"0.3.294"}}}},f);if(n)return;if(!("result"in m)){q(`[Query.captureSdkMcpServerManifests] '${p}' answered initialize with an error; leaving it to the CLI: ${ie(m)}`,{level:"warn"});return}let g=m.result;f.onmessage?.({jsonrpc:"2.0",method:"notifications/initialized"});let _=g.capabilities,y=typeof _==="object"&&_!==null&&"tools"in _&&_.tools!==void 0&&_.tools!==null,S;if(y){let C=await this.handleMcpControlRequest(p,{server_name:p,message:{jsonrpc:"2.0",id:u_+"tools-list",method:"tools/list"}},f);if(n)return;if(!("result"in C)){q(`[Query.captureSdkMcpServerManifests] '${p}' answered tools/list with an error; leaving it to the CLI: ${ie(C)}`,{level:"warn"});return}if(C.result.nextCursor===void 0)S=C.result}let E=We(ie(S===void 0?{initializeResult:g}:{initializeResult:g,toolsListResult:S}));t.set(p,{transport:f,manifest:E})}catch(m){if(!n)q(`[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 AO(Promise.race([s,i]),Sq);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"){kl("sdk_mcp_manifest_capture","closed",c);return}if(a===void 0)q(`[Query.captureSdkMcpServerManifests] ${t.size}/${o.length} in-process MCP servers captured within ${Sq} ms; the rest will handshake over the control channel`,{level:"warn"}),kl("sdk_mcp_manifest_capture","deadline",c);else if(t.size<o.length)kl("sdk_mcp_manifest_capture","partial",c);else pd("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 q(`[Query.captureSdkMcpServerManifests] manifests for [${Object.keys(d).join(", ")}] captured in ${l} ms`),d}async interrupt(e){return Bt("sdk_interrupt",async()=>{let t=await this.request({subtype:"interrupt",...e?.cancelQueued===!0&&{cancel_queued:!0}}),n=t.response?.still_queued;if(!Array.isArray(n))return;let r=t.response?.cancelled;return{still_queued:n.filter((o)=>typeof o==="string"),...Array.isArray(r)&&{cancelled:r.filter((o)=>typeof o==="string")}}})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}setUiHost(e){this.uiHost=e}async setMcpPermissionModeOverride(e,t){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:t})).response??{}}async setChromeBrowserHints(e){await this.request({subtype:"set_chrome_browser_hints",...e})}async setPromptSuggestionsPaused(e){await this.request({subtype:"set_prompt_suggestions_paused",paused:e})}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((t,n)=>{let r=(s)=>{if(s.subtype==="success"){let{pending_permission_requests:i,pending_user_dialog_requests:a,...l}=s;t(l)}else n(new we(s.error,"awaitControlResponse: CLI error verdict"));if(s.pending_permission_requests||s.pending_user_dialog_requests)q("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){n(tT());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 Bt("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 Bt("sdk_update_settings",async()=>{await this.request({subtype:"update_settings",source:e,settings:t})})}async rewindFiles(e,t){return Bt("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 Bt("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=Bt("sdk_claim_session",async()=>(await this.request({subtype:"claim_session",...e,include_initialize:e.include_initialize??!0})).response),n=this.initialization;return this.initialization=t.then(async(r)=>{if(r?.initialize===void 0)return n;let o=r.initialize,s=await n.then((l)=>({hooks_applied:l.hooks_applied,plugins_applied:l.plugins_applied}),()=>({hooks_applied:void 0,plugins_applied:void 0})),i=o.hooks_applied??s.hooks_applied,a=o.plugins_applied??s.plugins_applied;return{...o,...i!==void 0&&{hooks_applied:i},...a!==void 0&&{plugins_applied:a}}},()=>n),this.initialization.catch(()=>{}),t}async enableRemoteControl(e,t,n){let r=++this.remoteControlCallGeneration,o=this.workSecretAnswerer,s=n?.reattachSessionId||(n?.workSecret===void 0?void 0:A1e(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&&Eq(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 Bt("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:t?.persist})).response.title)}async askSideQuestion(e,t){return Bt("sdk_side_question",async()=>{let r=(await this.request({subtype:"side_question",question:e,...t?.history?.length&&{history:[...t.history]}},t)).response;return r.response===null?null:{response:r.response,synthetic:r.synthetic??!1,...r.refusal_fallback&&{refusalFallback:{originalModel:r.refusal_fallback.original_model,fallbackModel:r.refusal_fallback.fallback_model,content:r.refusal_fallback.content}}}},()=>t?.signal?.aborted?"cancelled":"error")}async launchUltrareview(e,t){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:t?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let t of e)if(t.request.subtype==="can_use_tool")this.handleControlRequest(t).catch(()=>{})}processPendingUserDialogRequests(e){for(let t of e)if(t.request.subtype==="request_user_dialog")this.handleControlRequest(t).catch(()=>{})}request(e,t){let n=t?.signal;if(n?.aborted)return Promise.reject(Mn(n.reason??"Control request aborted"));if(this.cleanupPerformed)return Promise.reject(tT());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(Mn(n.reason??"Control request aborted")),!c)return;try{Promise.resolve(this.transport.write(ie({type:"control_cancel_request",request_id:r})+`
139
139
  `)).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(en(Error(g.error),{telemetryMessage:`Claude Code control request failed (${e.subtype})`,errorClass:"control_request_failed",errorCode:typeof g.error_code==="string"&&v1e.test(g.error_code)?g.error_code:void 0}));if(!s&&(g.pending_permission_requests||g.pending_user_dialog_requests))q(`[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=ie(o)+`
140
140
  `,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 Bt("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 Bt("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 Bt("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 Bt("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins",...e?.holdOnCacheImpact&&{hold_on_cache_impact:!0}})).response)}async reloadSkills(){return Bt("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async reloadOutputStyles(){return Bt("sdk_reload_output_styles",async()=>(await this.request({subtype:"reload_output_styles"})).response)}async setMcpServers(e){return Bt("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}=eT(l);if(d.timeout!==c.settings.timeout||d.disableAutoBackground!==c.settings.disableAutoBackground)q(`[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`)}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){q("[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++,q(`[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(ie(this.verbatimPrompts?{...n,client_composed:!0}:n)+`
141
141
  `))}if(q(`[Query.streamInput] Finished processing ${t} messages from input stream`),t>0&&this.hasBidirectionalNeeds())q("[Query.streamInput] Has bidirectional needs, waiting for the run to end"),await this.waitForRunEnd();q("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(t){if(!(t instanceof jn))throw t}}endRun(){if(this.runEnded)return;if(this.runEnded=!0,this.clearRunEndCeiling(),this.runEndedResolve?.(),this.isSingleUserTurn)q("[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(()=>{q(`[Query.readMessages] No 'idle' ${this.runEndCeilingMs}ms after the last result, ending the run`),this.endRun()},Math.min(this.runEndCeilingMs,kh)),this.runEndCeilingTimer.unref?.()}clearRunEndCeiling(){clearTimeout(this.runEndCeilingTimer),this.runEndCeilingTimer=void 0}waitForRunEnd(){if(this.runEnded)return q("[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 Qx((o)=>this.sendMcpServerMessageToCli(e,o)),r=t.instance.connect(n).catch((o)=>{if(this.sdkMcpServers.get(e)?.transport===n)this.sdkMcpServers.delete(e);q(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${o}`,{level:"error"})});this.sdkMcpServers.set(e,{transport:n,settings:eT(t).settings,connection:r})}async disconnectSdkMcpServer(e){let t=this.sdkMcpServers.get(e);if(t){let n=`${e}:${u_}`;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(u_)){q(`[Query.sendMcpServerMessageToCli] Dropping late manifest-capture reply from '${e}' (${t.id})`);return}}let n={type:"control_request",request_id:cc(),request:{subtype:"mcp_message",server_name:e,message:t}};if(!this.initializeHasBeenWritten&&yq(t))this.sdkMcpToolsChangedDuringCapture.add(e);this.writeAfterInitialize(ie(n)+`
142
- `).catch((r)=>{q(`[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 tT(){return Error("Query closed before response received")}var v1e=/^[a-z][a-z0-9_]{0,63}$/;function Eq(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 A1e(e){try{let t=We(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=We(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 bq=typeof globalThis==="object"?globalThis:global;var Uo="1.9.0";var Cq=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function R1e(e){var t=new Set([e]),n=new Set,r=e.match(Cq);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(Cq);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 vq=R1e(Uo);var x1e=Uo.split(".")[0],Yd=Symbol.for("opentelemetry.js.api."+x1e),Jd=bq;function oc(e,t,n,r){var o;if(r===void 0)r=!1;var s=Jd[Yd]=(o=Jd[Yd])!==null&&o!==void 0?o:{version:Uo};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!==Uo){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Uo);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Uo+"."),!0}function Fo(e){var t,n,r=(t=Jd[Yd])===null||t===void 0?void 0:t.version;if(!r||!vq(r))return;return(n=Jd[Yd])===null||n===void 0?void 0:n[e]}function sc(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Uo+".");var n=Jd[Yd];if(n)delete n[e]}var T1e=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},w1e=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))},Aq=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 Xd("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("verbose",this._namespace,t)},e}();function Xd(e,t,n){var r=Fo("diag");if(!r)return;return n.unshift(t),r[e].apply(r,w1e([],T1e(n),!1))}var gn;(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"})(gn||(gn={}));function Rq(e,t){if(e<gn.NONE)e=gn.NONE;else if(e>gn.ALL)e=gn.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",gn.ERROR),warn:n("warn",gn.WARN),info:n("info",gn.INFO),debug:n("debug",gn.DEBUG),verbose:n("verbose",gn.VERBOSE)}}var O1e=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},k1e=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))},P1e="diag",Xs=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Fo("diag");if(!a)return;return a[o].apply(a,k1e([],O1e(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:gn.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=Fo("diag"),p=Rq((a=s.logLevel)!==null&&a!==void 0?a:gn.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 oc("diag",p,n,!0)};n.setLogger=r,n.disable=function(){sc(P1e,n)},n.createComponentLogger=function(o){return new Aq(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 I1e=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},D1e=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.")},xq=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=I1e(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=D1e(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 Dwt=Xs.instance();function Tq(e){if(e===void 0)e={};return new xq(new Map(Object.entries(e)))}function wq(e){return Symbol.for(e)}var L1e=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}(),Oq=new L1e;var kq={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},Pq={set:function(e,t,n){if(e==null)return;e[t]=n}};var M1e=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},N1e=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))},Iq=function(){function e(){}return e.prototype.active=function(){return Oq},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,N1e([r],M1e(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var U1e=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},F1e=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))},nT="context",z1e=new Iq,p_=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return oc(nT,t,Xs.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,F1e([t,n,r],U1e(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Fo(nT)||z1e},e.prototype.disable=function(){this._getContextManager().disable(),sc(nT,Xs.instance())},e}();var rT=p_.getInstance();var Dq=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 oT=wq("OpenTelemetry Baggage Key");function sT(e){return e.getValue(oT)||void 0}function Lq(){return sT(p_.getInstance().active())}function Mq(e,t){return e.setValue(oT,t)}function Nq(e){return e.deleteValue(oT)}var iT="propagation",$1e=new Dq,Uq=function(){function e(){this.createBaggage=Tq,this.getBaggage=sT,this.getActiveBaggage=Lq,this.setBaggage=Mq,this.deleteBaggage=Nq}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return oc(iT,t,Xs.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=Pq;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=kq;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){sc(iT,Xs.instance())},e.prototype._getGlobalPropagator=function(){return Fo(iT)||$1e},e}();var aT=Uq.getInstance();import{copyFile as H1e,readFile as j1e,rm as zq,writeFile as $q}from"fs/promises";import{homedir as Fq}from"os";import{join as lT}from"path";function Hq(e){return{globalConfig:lT(e||Fq(),".claude.json"),userSettings:lT(e||lT(Fq(),".claude"),"settings.json")}}function cT(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function ic(e,t,n,r){if(r)return B1e(r,e,t,n);try{if(n)await $q(t,n(await j1e(e)),{mode:384});else await H1e(e,t)}catch(o){if(pe(o)===void 0)throw o;if(!pt(o))await zq(t,{force:!0}).catch(()=>{}),q(`sessionStore resume: skipping ${e} (${pe(o)})`)}}async function B1e({backend:e,key:t},n,r,o){let s=await e.read([t]);if(!s.ok){if(s.error.code==="InvalidArgument")throw new we(`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)");q(`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 $q(r,o?o(a):a,{mode:384})}catch(l){if(pe(l)===void 0)throw l;if(!pt(l))await zq(r,{force:!0}).catch(()=>{}),q(`sessionStore resume: skipping ${n} (${pe(l)})`)}}import{createHash as K1e}from"crypto";import{homedir as gOt,userInfo as G1e}from"os";var jq="-credentials";function Bq(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?"":`-${K1e("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${OP().OAUTH_FILE_SUFFIX}${e}${o}`}var W1e=/^[a-zA-Z0-9._-]+$/;function Kq(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||G1e().username}catch{e="claude-code-user"}if(!W1e.test(e))return"claude-code-user";return e}class Gq{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var EOt=new Fe(()=>new Gq);function V1e(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 Wq(e,t,n){if(!e)return;let r=V1e(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as q1e}from"fs";import{isAbsolute as Z1e,relative as Y1e,resolve as J1e,sep as X1e}from"path";function uT(e){let t=J1e(e??"."),n;try{n=q1e(t)}catch{n=t}return je(n)}function hn(e,t){let n=uT(e);if(t===void 0)return Nr(n);return(t.CLAUDE_CONFIG_DIR?Wy(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??Kc(n)}function Qd(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function dT(e,t){let n=Y1e(t,e),r=n.split(X1e);if(r[0]===".."||Z1e(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 aGe=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function qq(e){let t;try{t=We(Ll(e.toString("utf8")))}catch{return e}if(!Zq(t))return e;let n=!1;for(let o of aGe)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(Zq(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?ie(t):e}function Zq(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function lGe(e,t){if(!e)return;let n=e;try{let r=We(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=ie(r)}catch{}await Jq(t,n,{mode:384})}function cGe(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=Bq(jq);return new Promise((t)=>{Q1e("security",["find-generic-password","-a",Kq(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function eZ(e,t,n,r,o=60000,s){if(!$e(t))return;let i=hn(n,r),a=await Zn(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=ut(oGe(),`claude-resume-${eGe()}`);try{let c=ut(l,"projects",i);await f_(c,{recursive:!0,mode:448});let d=ut(c,`${t}.jsonl`);await Bc(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??ut(ep(),".claude"),m;try{m=await nGe(ut(f,".credentials.json"),"utf-8")}catch(b){if(!pt(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await cGe()??m;await lGe(m,ut(l,".credentials.json"));let g=Hq(Kp("CLAUDE_CONFIG_DIR")),_=p||ep(),y=ut(_,".claude.json");await ic(y,ut(l,".claude.json"),void 0,cT(s,y,g.globalConfig,At.globalConfig())),await ic(ut(f,".config.json"),ut(l,".config.json"));for(let b of TP)if(b)await ic(ut(_,`.claude${b}.json`),ut(l,`.claude${b}.json`));let S=ut(f,"settings.json");if(await ic(S,ut(l,"settings.json"),qq,cT(s,S,g.userSettings,At.userSettings())),await ic(ut(f,"cowork_settings.json"),ut(l,"cowork_settings.json"),qq),e.listSubkeys)await uGe(e,{projectKey:i,sessionId:t},ut(c,t),o);return l}catch(c){throw await m_(l),c}}async function uGe(e,t,n,r){let o=await Zn(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=tp(n,s+".jsonl");if(!s||pT(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+sGe)){q(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Zn(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(Qd(d))l.push(d);else c.push(d);if(c.length>0)await f_(Vq(i),{recursive:!0}),await Bc(i,c);if(l.length>0){let d=l.at(-1),p=tp(n,s+".meta.json");await f_(Vq(p),{recursive:!0});let{type:f,...m}=d;await Jq(p,ie(m),{mode:384})}}}function tZ(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(Xq.isAbsolute(e.directory)||Qq.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&t===void 0)q("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return t}var dGe=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function fT(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o}=t,{systemPrompt:s,settings:i,managedSettings:a,settingSources:l,sandbox:c,...d}=e??{},p,f,m,g;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="custom")p=s.prompt,g=s.snapshot;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections,g=s.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.293";let{abortController:_=Vd(),additionalDirectories:y=[],projectConfigRoot:S,agent:b,agents:E,allowedTools:C=[],betas:v,canUseTool:w,continue:L,cwd:z,debug:U,debugFile:de,disallowedTools:x=[],tools:R,env:O,executable:D=Na()?"bun":"node",executableArgs:B=[],extraArgs:oe={},fallbackModel:me,enableFileCheckpointing:J,toolConfig:K,forkSession:bt,hooks:Xt,includeHookEvents:dt,includePartialMessages:Tt,forwardSubagentText:Ct,verbatimPrompts:Gt=!1,onElicitation:Ye,onUserDialog:ye,supportedDialogKinds:Wt,perTaskStopAffordance:Qt,rapidFollowupPreempt:$o,workspaceTrust:Xi,persistSession:Ho,sessionStore:_n,sessionStoreFlush:h_,thinking:Ge,effort:ur,maxThinkingTokens:In,maxTurns:Qs,maxBudgetUsd:Qi,taskBudget:np,mcpServers:ea,model:rp,outputFormat:_T,permissionMode:EZ,allowDangerouslySkipPermissions:bZ=!1,permissionPromptToolName:CZ,permissionPrompts:vZ,plugins:op,pluginDelivery:__="argv",getOAuthToken:yT,getHostAuthToken:ST,workload:ET,resume:bT,resumeSessionAt:AZ,resumeDropsTurn:RZ,sessionId:xZ,skills:CT,stderr:TZ,strictMcpConfig:wZ}=d,vT=EZ;if(_n&&Ho===!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(Wt!==void 0&&Wt.length>0&&!ye)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let OZ=tZ(Xi);if(_n&&L&&!bT&&!_n.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(_n&&J)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(_n&&d.spawnClaudeCodeProcess)q("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(Wq(!!w,vT??"default",C),__!=="argv"&&__!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let AT=__==="initialize"&&op!==void 0&&op.length>0,y_=d.pathToClaudeCodeExecutable;if(!y_){let Vt=iGe(import.meta.url),yn=rGe(Vt),Tr=dq((ta)=>yn.resolve(ta));if(!Tr)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.`);y_=Tr}let RT=_T?.type==="json_schema"?_T.schema:void 0,St=O?{...O}:{...process.env};if(!St.CLAUDE_CODE_ENTRYPOINT)St.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!St.CLAUDE_AGENT_SDK_VERSION)St.CLAUDE_AGENT_SDK_VERSION="0.3.293";if(J)St.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(St).some((Vt)=>Vt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))St.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";let S_=Cc(St.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),kZ=Number.isFinite(S_)&&S_>=0?S_:c_;if(yT)St.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(ST)St.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(K?.askUserQuestion?.previewFormat)St.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=K.askUserQuestion.previewFormat;for(let[Vt,yn]of[[K?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[K?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"]])if(Vt)St[yn]="1";else if(!O){for(let Tr of Object.keys(St))if(Tr.toUpperCase()===yn)delete St[Tr]}let E_={};if(aT.inject(rT.active(),E_),"traceparent"in E_){for(let Vt of["TRACEPARENT","TRACESTATE"])if(!(Vt in(O??{})))delete St[Vt]}for(let[Vt,yn]of Object.entries(E_)){let Tr=Vt.toUpperCase();if(!(Tr in(O??{})))St[Tr]=yn}let xT={},TT=new Map;if(ea)for(let[Vt,yn]of Object.entries(ea))if(yn.type==="sdk"&&yn.instance)TT.set(Vt,yn);else xT[Vt]=yn;let ac;if(Ge)switch(Ge.type){case"adaptive":ac={type:"adaptive",display:Ge.display};break;case"enabled":ac={type:"enabled",budgetTokens:Ge.budgetTokens,display:Ge.display};break;case"disabled":ac={type:"disabled"};break}else if(In!==void 0)ac=In===0?{type:"disabled"}:{type:"enabled",budgetTokens:In};if(r){if(St.CLAUDE_CONFIG_DIR=r,process.platform==="win32")St.CLAUDE_SECURESTORAGE_CONFIG_DIR=O?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??O?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let wT=new Xx({abortController:_,additionalDirectories:y,projectConfigRoot:S,agent:b,betas:v,cwd:z,debug:U,debugFile:de,executable:D,executableArgs:B,extraArgs:ET?{...oe,workload:ET}:oe,pathToClaudeCodeExecutable:y_,env:St,forkSession:bt,stderr:TZ,thinkingConfig:ac,effort:ur,maxTurns:Qs,maxBudgetUsd:Qi,taskBudget:np,model:rp,fallbackModel:me,jsonSchema:RT,permissionMode:vT,allowDangerouslySkipPermissions:bZ,permissionPromptToolName:CZ,permissionPrompts:vZ,continueConversation:_n?void 0:L,resume:bT,resumeSessionAt:AZ,resumeDropsTurn:RZ,sessionId:xZ,settings:typeof i==="object"?ie(i):i,managedSettings:a?ie(a):void 0,settingSources:l,skills:CT,allowedTools:C,disallowedTools:x,tools:R,mcpServers:xT,strictMcpConfig:wZ,canUseTool:!!w,hooks:!!Xt,includeHookEvents:dt,includePartialMessages:Tt,persistSession:Ho,sessionMirror:!!_n,plugins:op,pluginsViaInitialize:AT,sandbox:c,spawnClaudeCodeProcess:d.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),PZ={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:d.planModeInstructions,systemPromptSnapshot:g,appendSubagentSystemPrompt:d.appendSubagentSystemPrompt,toolAliases:d.toolAliases,excludeDynamicSections:m,agents:E,title:d.title,skills:CT,webSearchIsolationExemptMcpServers:d.webSearchIsolationExemptMcpServers,promptSuggestions:d.promptSuggestions,agentProgressSummaries:d.agentProgressSummaries,forwardSubagentText:Ct,supportedDialogKinds:Wt,perTaskStopAffordance:Qt,rapidFollowupPreempt:$o,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:OZ,plugins:AT?op:void 0,captureSdkMcpManifests:!Gp("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},b_=new d_(wT,n,w,Xt,_,TT,RT,PZ,Ye,yT,ST,ye,Gt,kZ);if(_n){let Vt=()=>ut(St.CLAUDE_CONFIG_DIR??ut(ep(),".claude"),"projects"),yn=h_==="eager",Tr=new ES(async(ta,C_)=>{let lc=dT(ta,Vt());if(lc)await _n.append(lc,C_);else q(`[SessionStore] dropping mirror frame: filePath ${ta} is not under ${Vt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(ta,C_)=>{let lc=dT(ta,Vt());if(lc)b_.reportMirrorError(lc,C_.message)},maxPendingEntries:yn?0:Lc,maxPendingBytes:yn?0:si});b_.setTranscriptMirrorBatcher(Tr)}return{queryInstance:b_,transport:wT,abortController:_,processEnv:St,verbatimPrompts:Gt}}function mT(e,t,n,r){if(typeof t==="string")e.writeAfterInitialize(ie({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,...r&&{client_composed:!0}})+`
142
+ `).catch((r)=>{q(`[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 tT(){return Error("Query closed before response received")}var v1e=/^[a-z][a-z0-9_]{0,63}$/;function Eq(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 A1e(e){try{let t=We(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=We(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 bq=typeof globalThis==="object"?globalThis:global;var Uo="1.9.0";var Cq=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function R1e(e){var t=new Set([e]),n=new Set,r=e.match(Cq);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(Cq);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 vq=R1e(Uo);var x1e=Uo.split(".")[0],Yd=Symbol.for("opentelemetry.js.api."+x1e),Jd=bq;function oc(e,t,n,r){var o;if(r===void 0)r=!1;var s=Jd[Yd]=(o=Jd[Yd])!==null&&o!==void 0?o:{version:Uo};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!==Uo){var i=Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Uo);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Uo+"."),!0}function Fo(e){var t,n,r=(t=Jd[Yd])===null||t===void 0?void 0:t.version;if(!r||!vq(r))return;return(n=Jd[Yd])===null||n===void 0?void 0:n[e]}function sc(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Uo+".");var n=Jd[Yd];if(n)delete n[e]}var T1e=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},w1e=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))},Aq=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 Xd("debug",this._namespace,t)},e.prototype.error=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("error",this._namespace,t)},e.prototype.info=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("info",this._namespace,t)},e.prototype.warn=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("warn",this._namespace,t)},e.prototype.verbose=function(){var t=[];for(var n=0;n<arguments.length;n++)t[n]=arguments[n];return Xd("verbose",this._namespace,t)},e}();function Xd(e,t,n){var r=Fo("diag");if(!r)return;return n.unshift(t),r[e].apply(r,w1e([],T1e(n),!1))}var gn;(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"})(gn||(gn={}));function Rq(e,t){if(e<gn.NONE)e=gn.NONE;else if(e>gn.ALL)e=gn.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",gn.ERROR),warn:n("warn",gn.WARN),info:n("info",gn.INFO),debug:n("debug",gn.DEBUG),verbose:n("verbose",gn.VERBOSE)}}var O1e=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},k1e=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))},P1e="diag",Xs=function(){function e(){function t(o){return function(){var s=[];for(var i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Fo("diag");if(!a)return;return a[o].apply(a,k1e([],O1e(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0)s={logLevel:gn.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=Fo("diag"),p=Rq((a=s.logLevel)!==null&&a!==void 0?a:gn.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 oc("diag",p,n,!0)};n.setLogger=r,n.disable=function(){sc(P1e,n)},n.createComponentLogger=function(o){return new Aq(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 I1e=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},D1e=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.")},xq=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=I1e(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=D1e(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 Dwt=Xs.instance();function Tq(e){if(e===void 0)e={};return new xq(new Map(Object.entries(e)))}function wq(e){return Symbol.for(e)}var L1e=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}(),Oq=new L1e;var kq={get:function(e,t){if(e==null)return;return e[t]},keys:function(e){if(e==null)return[];return Object.keys(e)}},Pq={set:function(e,t,n){if(e==null)return;e[t]=n}};var M1e=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},N1e=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))},Iq=function(){function e(){}return e.prototype.active=function(){return Oq},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,N1e([r],M1e(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}();var U1e=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},F1e=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))},nT="context",z1e=new Iq,p_=function(){function e(){}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalContextManager=function(t){return oc(nT,t,Xs.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,F1e([t,n,r],U1e(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Fo(nT)||z1e},e.prototype.disable=function(){this._getContextManager().disable(),sc(nT,Xs.instance())},e}();var rT=p_.getInstance();var Dq=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 oT=wq("OpenTelemetry Baggage Key");function sT(e){return e.getValue(oT)||void 0}function Lq(){return sT(p_.getInstance().active())}function Mq(e,t){return e.setValue(oT,t)}function Nq(e){return e.deleteValue(oT)}var iT="propagation",$1e=new Dq,Uq=function(){function e(){this.createBaggage=Tq,this.getBaggage=sT,this.getActiveBaggage=Lq,this.setBaggage=Mq,this.deleteBaggage=Nq}return e.getInstance=function(){if(!this._instance)this._instance=new e;return this._instance},e.prototype.setGlobalPropagator=function(t){return oc(iT,t,Xs.instance())},e.prototype.inject=function(t,n,r){if(r===void 0)r=Pq;return this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){if(r===void 0)r=kq;return this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){sc(iT,Xs.instance())},e.prototype._getGlobalPropagator=function(){return Fo(iT)||$1e},e}();var aT=Uq.getInstance();import{copyFile as H1e,readFile as j1e,rm as zq,writeFile as $q}from"fs/promises";import{homedir as Fq}from"os";import{join as lT}from"path";function Hq(e){return{globalConfig:lT(e||Fq(),".claude.json"),userSettings:lT(e||lT(Fq(),".claude"),"settings.json")}}function cT(e,t,n,r){return e!==void 0&&t===n?{backend:e,key:r}:void 0}async function ic(e,t,n,r){if(r)return B1e(r,e,t,n);try{if(n)await $q(t,n(await j1e(e)),{mode:384});else await H1e(e,t)}catch(o){if(pe(o)===void 0)throw o;if(!pt(o))await zq(t,{force:!0}).catch(()=>{}),q(`sessionStore resume: skipping ${e} (${pe(o)})`)}}async function B1e({backend:e,key:t},n,r,o){let s=await e.read([t]);if(!s.ok){if(s.error.code==="InvalidArgument")throw new we(`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)");q(`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 $q(r,o?o(a):a,{mode:384})}catch(l){if(pe(l)===void 0)throw l;if(!pt(l))await zq(r,{force:!0}).catch(()=>{}),q(`sessionStore resume: skipping ${n} (${pe(l)})`)}}import{createHash as K1e}from"crypto";import{homedir as gOt,userInfo as G1e}from"os";var jq="-credentials";function Bq(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?"":`-${K1e("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${OP().OAUTH_FILE_SUFFIX}${e}${o}`}var W1e=/^[a-zA-Z0-9._-]+$/;function Kq(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||G1e().username}catch{e="claude-code-user"}if(!W1e.test(e))return"claude-code-user";return e}class Gq{cache={data:null,cachedAt:0};generation=0;readInFlight=null;lastReadFailure=null;keychainHoldsItem=!1;lastKnown=null;legacyApiKeyPrefetch=null}var EOt=new Fe(()=>new Gq);function V1e(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 Wq(e,t,n){if(!e)return;let r=V1e(t,n);if(r===void 0)return;process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}import{realpathSync as q1e}from"fs";import{isAbsolute as Z1e,relative as Y1e,resolve as J1e,sep as X1e}from"path";function uT(e){let t=J1e(e??"."),n;try{n=q1e(t)}catch{n=t}return je(n)}function hn(e,t){let n=uT(e);if(t===void 0)return Nr(n);return(t.CLAUDE_CONFIG_DIR?Wy(t.CLAUDE_CODE_PROJECT_DIR_NAME):void 0)??Kc(n)}function Qd(e){return typeof e==="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}function dT(e,t){let n=Y1e(t,e),r=n.split(X1e);if(r[0]===".."||Z1e(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 aGe=["enabledPlugins","extraKnownMarketplaces","additionalMarketplaces"];function qq(e){let t;try{t=We(Ll(e.toString("utf8")))}catch{return e}if(!Zq(t))return e;let n=!1;for(let o of aGe)if(Object.hasOwn(t,o))delete t[o],n=!0;let r=t.env;if(Zq(r)&&Object.hasOwn(r,"CLAUDE_CONFIG_DIR"))delete r.CLAUDE_CONFIG_DIR,n=!0;return n?ie(t):e}function Zq(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}async function lGe(e,t){if(!e)return;let n=e;try{let r=We(e);if(r?.claudeAiOauth?.refreshToken)delete r.claudeAiOauth.refreshToken,n=ie(r)}catch{}await Jq(t,n,{mode:384})}function cGe(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=Bq(jq);return new Promise((t)=>{Q1e("security",["find-generic-password","-a",Kq(),"-w","-s",e],{encoding:"utf-8",timeout:5000,windowsHide:!0},(n,r)=>t(n?void 0:r.trim()||void 0))})}async function eZ(e,t,n,r,o=60000,s){if(!$e(t))return;let i=hn(n,r),a=await Zn(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=ut(oGe(),`claude-resume-${eGe()}`);try{let c=ut(l,"projects",i);await f_(c,{recursive:!0,mode:448});let d=ut(c,`${t}.jsonl`);await Bc(d,a);let p=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,f=p??ut(ep(),".claude"),m;try{m=await nGe(ut(f,".credentials.json"),"utf-8")}catch(b){if(!pt(b))throw b}if(!p&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN)m=await cGe()??m;await lGe(m,ut(l,".credentials.json"));let g=Hq(Kp("CLAUDE_CONFIG_DIR")),_=p||ep(),y=ut(_,".claude.json");await ic(y,ut(l,".claude.json"),void 0,cT(s,y,g.globalConfig,At.globalConfig())),await ic(ut(f,".config.json"),ut(l,".config.json"));for(let b of TP)if(b)await ic(ut(_,`.claude${b}.json`),ut(l,`.claude${b}.json`));let S=ut(f,"settings.json");if(await ic(S,ut(l,"settings.json"),qq,cT(s,S,g.userSettings,At.userSettings())),await ic(ut(f,"cowork_settings.json"),ut(l,"cowork_settings.json"),qq),e.listSubkeys)await uGe(e,{projectKey:i,sessionId:t},ut(c,t),o);return l}catch(c){throw await m_(l),c}}async function uGe(e,t,n,r){let o=await Zn(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=tp(n,s+".jsonl");if(!s||pT(s)||s.split(/[\\/]/).includes("..")||!i.startsWith(n+sGe)){q(`[SessionStore] skipping unsafe subpath from listSubkeys: ${s}`,{level:"warn"});continue}let a=await Zn(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(Qd(d))l.push(d);else c.push(d);if(c.length>0)await f_(Vq(i),{recursive:!0}),await Bc(i,c);if(l.length>0){let d=l.at(-1),p=tp(n,s+".meta.json");await f_(Vq(p),{recursive:!0});let{type:f,...m}=d;await Jq(p,ie(m),{mode:384})}}}function tZ(e){let t=e?.accepted===!0&&(typeof e.directory!=="string"||!(Xq.isAbsolute(e.directory)||Qq.isAbsolute(e.directory)))?void 0:e;if(e!==void 0&&t===void 0)q("workspaceTrust ignored: accepted requires an absolute directory, as it exists where Claude Code runs",{level:"warn"});return t}var dGe=["hooks","disableAllHooks","allowManagedHooksOnly","allowedHttpHookUrls","httpHookAllowedEnvVars"];function fT(e,t){let{isSingleUserTurn:n,resumeConfigDir:r,deferSpawn:o}=t,{systemPrompt:s,settings:i,managedSettings:a,settingSources:l,sandbox:c,...d}=e??{},p,f,m,g;if(s===void 0)p="";else if(typeof s==="string")p=s;else if(Array.isArray(s))p=s;else if(s.type==="custom")p=s.prompt,g=s.snapshot;else if(s.type==="preset")f=s.append,m=s.excludeDynamicSections,g=s.snapshot;process.env.CLAUDE_AGENT_SDK_VERSION="0.3.294";let{abortController:_=Vd(),additionalDirectories:y=[],projectConfigRoot:S,agent:b,agents:E,allowedTools:C=[],betas:v,canUseTool:w,continue:L,cwd:z,debug:U,debugFile:de,disallowedTools:x=[],tools:R,env:O,executable:D=Na()?"bun":"node",executableArgs:B=[],extraArgs:oe={},fallbackModel:me,enableFileCheckpointing:J,toolConfig:K,forkSession:bt,hooks:Xt,includeHookEvents:dt,includePartialMessages:Tt,forwardSubagentText:Ct,verbatimPrompts:Gt=!1,onElicitation:Ye,onUserDialog:ye,supportedDialogKinds:Wt,perTaskStopAffordance:Qt,rapidFollowupPreempt:$o,workspaceTrust:Xi,persistSession:Ho,sessionStore:_n,sessionStoreFlush:h_,thinking:Ge,effort:ur,maxThinkingTokens:In,maxTurns:Qs,maxBudgetUsd:Qi,taskBudget:np,mcpServers:ea,model:rp,outputFormat:_T,permissionMode:EZ,allowDangerouslySkipPermissions:bZ=!1,permissionPromptToolName:CZ,permissionPrompts:vZ,plugins:op,pluginDelivery:__="argv",getOAuthToken:yT,getHostAuthToken:ST,workload:ET,resume:bT,resumeSessionAt:AZ,resumeDropsTurn:RZ,sessionId:xZ,skills:CT,stderr:TZ,strictMcpConfig:wZ}=d,vT=EZ;if(_n&&Ho===!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(Wt!==void 0&&Wt.length>0&&!ye)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");let OZ=tZ(Xi);if(_n&&L&&!bT&&!_n.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(_n&&J)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");if(_n&&d.spawnClaudeCodeProcess)q("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"});if(Wq(!!w,vT??"default",C),__!=="argv"&&__!=="initialize")throw Error("Invalid pluginDelivery. Expected 'argv' or 'initialize'.");let AT=__==="initialize"&&op!==void 0&&op.length>0,y_=d.pathToClaudeCodeExecutable;if(!y_){let Vt=iGe(import.meta.url),yn=rGe(Vt),Tr=dq((ta)=>yn.resolve(ta));if(!Tr)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.`);y_=Tr}let RT=_T?.type==="json_schema"?_T.schema:void 0,St=O?{...O}:{...process.env};if(!St.CLAUDE_CODE_ENTRYPOINT)St.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!St.CLAUDE_AGENT_SDK_VERSION)St.CLAUDE_AGENT_SDK_VERSION="0.3.294";if(J)St.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true";if(!Object.keys(St).some((Vt)=>Vt.toUpperCase()==="CLAUDE_CODE_SDK_READS_SESSION_STATE"))St.CLAUDE_CODE_SDK_READS_SESSION_STATE="1";let S_=Cc(St.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS),kZ=Number.isFinite(S_)&&S_>=0?S_:c_;if(yT)St.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1";if(ST)St.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1";if(K?.askUserQuestion?.previewFormat)St.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=K.askUserQuestion.previewFormat;for(let[Vt,yn]of[[K?.askUserQuestion?.extendedQuestions,"CLAUDE_CODE_QUESTION_EXTENDED"],[K?.askUserQuestion?.optionalDescriptions,"CLAUDE_CODE_QUESTION_OPTIONAL_DESCRIPTIONS"]])if(Vt)St[yn]="1";else if(!O){for(let Tr of Object.keys(St))if(Tr.toUpperCase()===yn)delete St[Tr]}let E_={};if(aT.inject(rT.active(),E_),"traceparent"in E_){for(let Vt of["TRACEPARENT","TRACESTATE"])if(!(Vt in(O??{})))delete St[Vt]}for(let[Vt,yn]of Object.entries(E_)){let Tr=Vt.toUpperCase();if(!(Tr in(O??{})))St[Tr]=yn}let xT={},TT=new Map;if(ea)for(let[Vt,yn]of Object.entries(ea))if(yn.type==="sdk"&&yn.instance)TT.set(Vt,yn);else xT[Vt]=yn;let ac;if(Ge)switch(Ge.type){case"adaptive":ac={type:"adaptive",display:Ge.display};break;case"enabled":ac={type:"enabled",budgetTokens:Ge.budgetTokens,display:Ge.display};break;case"disabled":ac={type:"disabled"};break}else if(In!==void 0)ac=In===0?{type:"disabled"}:{type:"enabled",budgetTokens:In};if(r){if(St.CLAUDE_CONFIG_DIR=r,process.platform==="win32")St.CLAUDE_SECURESTORAGE_CONFIG_DIR=O?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??O?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}let wT=new Xx({abortController:_,additionalDirectories:y,projectConfigRoot:S,agent:b,betas:v,cwd:z,debug:U,debugFile:de,executable:D,executableArgs:B,extraArgs:ET?{...oe,workload:ET}:oe,pathToClaudeCodeExecutable:y_,env:St,forkSession:bt,stderr:TZ,thinkingConfig:ac,effort:ur,maxTurns:Qs,maxBudgetUsd:Qi,taskBudget:np,model:rp,fallbackModel:me,jsonSchema:RT,permissionMode:vT,allowDangerouslySkipPermissions:bZ,permissionPromptToolName:CZ,permissionPrompts:vZ,continueConversation:_n?void 0:L,resume:bT,resumeSessionAt:AZ,resumeDropsTurn:RZ,sessionId:xZ,settings:typeof i==="object"?ie(i):i,managedSettings:a?ie(a):void 0,settingSources:l,skills:CT,allowedTools:C,disallowedTools:x,tools:R,mcpServers:xT,strictMcpConfig:wZ,canUseTool:!!w,hooks:!!Xt,includeHookEvents:dt,includePartialMessages:Tt,persistSession:Ho,sessionMirror:!!_n,plugins:op,pluginsViaInitialize:AT,sandbox:c,spawnClaudeCodeProcess:d.spawnClaudeCodeProcess,onProcessSpawned:e?.onProcessSpawned,deferSpawn:o}),PZ={systemPrompt:p,appendSystemPrompt:f,planModeInstructions:d.planModeInstructions,systemPromptSnapshot:g,appendSubagentSystemPrompt:d.appendSubagentSystemPrompt,toolAliases:d.toolAliases,excludeDynamicSections:m,agents:E,title:d.title,skills:CT,webSearchIsolationExemptMcpServers:d.webSearchIsolationExemptMcpServers,promptSuggestions:d.promptSuggestions,agentProgressSummaries:d.agentProgressSummaries,forwardSubagentText:Ct,supportedDialogKinds:Wt,perTaskStopAffordance:Qt,rapidFollowupPreempt:$o,forwardNestedSubagentToolCalls:e?.forwardNestedSubagentToolCalls,workspaceTrust:OZ,plugins:AT?op:void 0,captureSdkMcpManifests:!Gp("CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS")},b_=new d_(wT,n,w,Xt,_,TT,RT,PZ,Ye,yT,ST,ye,Gt,kZ);if(_n){let Vt=()=>ut(St.CLAUDE_CONFIG_DIR??ut(ep(),".claude"),"projects"),yn=h_==="eager",Tr=new ES(async(ta,C_)=>{let lc=dT(ta,Vt());if(lc)await _n.append(lc,C_);else q(`[SessionStore] dropping mirror frame: filePath ${ta} is not under ${Vt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},{onError:(ta,C_)=>{let lc=dT(ta,Vt());if(lc)b_.reportMirrorError(lc,C_.message)},maxPendingEntries:yn?0:Lc,maxPendingBytes:yn?0:si});b_.setTranscriptMirrorBatcher(Tr)}return{queryInstance:b_,transport:wT,abortController:_,processEnv:St,verbatimPrompts:Gt}}function mT(e,t,n,r){if(typeof t==="string")e.writeAfterInitialize(ie({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,...r&&{client_composed:!0}})+`
143
143
  `).catch((o)=>n.abort(o));else e.streamInput(t).catch((o)=>n.abort(o))}var pGe=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"]);async function m_(e){for(let t=0;;t++)try{return await Yq(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!pGe.has(pe(n)??""))return;await qn((t+1)*100)}}function fGe(e,t){e.waitForExit().catch(()=>{}).finally(()=>m_(t))}function mGe({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore)return gGe(e,t);let{queryInstance:n,abortController:r,verbatimPrompts:o}=fT(t,{isSingleUserTurn:typeof e==="string"});return mT(n,e,r,o),n}function gGe(e,t){let{queryInstance:n,transport:r,abortController:o,processEnv:s,verbatimPrompts:i}=fT({...t},{isSingleUserTurn:typeof e==="string",deferSpawn:!0}),a=tp(t.cwd??"."),l=t.sessionStore,c=t.loadTimeoutMs??60000,d=t.resume;return(async()=>{if(!d)d=(await Zn(l.listSessions(hn(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 eZ(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(()=>fGe(r,f))}if(!n.isClosed())r.spawn()}).catch((f)=>{let m=Mn(f);r.spawnAbort(m),n.setError(m)}),mT(n,e,o,i),n}async function hGe(e={}){return(await nZ(e)).warm}async function nZ({options:e,initializeTimeoutMs:t=60000}){let n,r=e?.resume;if((r||e?.continue)&&e?.sessionStore){let a=tp(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 Zn(e.sessionStore.listSessions(hn(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 eZ(e.sessionStore,r,a,e.env,e.loadTimeoutMs)}let o,s,i;try{let g=function(){if(m)return;m=!0,p.close()},a=fT(n&&r&&r!==e?.resume?{...e,resume:r}:e,{isSingleUserTurn:!1,resumeConfigDir:n});o=a.queryInstance;let{transport:l,abortController:c,verbatimPrompts:d}=a;s=l;let p=a.queryInstance;if(n){let y=n;p.addCleanupCallback(()=>{i=l.waitForExit().catch(()=>{}).then(()=>m_(y))})}let f=`Subprocess initialization did not complete within ${t}ms — check authentication and network connectivity`;await Zn(p.initializationResult(),t,f).catch((y)=>{throw bO(y,f)?en(y,{telemetryMessage:`Subprocess initialization did not complete within ${t}ms`,errorClass:"initialize_timeout"}):y});let m=!1;return{warm:{query(y){if(m)throw Error("WarmQuery.query() can only be called once");m=!0;try{mT(p,y,c,d)}catch(S){throw p.close(),S}if(typeof y==="string")p.setIsSingleUserTurn(!0);return p},close:g,async[Symbol.asyncDispose](){m=!0,p.close(),await i}},query:p,transport:l}}catch(a){if(o?.close(),n&&!i){let l=s;i=(l?l.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>m_(n))}throw await i,a}}async function _Ge({options:e,initializeTimeoutMs:t=60000}={}){if(e?.resume||e?.continue||e?.forkSession)throw Error("prewarm(): resume/continue/forkSession describe a session; a spare has none — pass them to query() instead");let n=e?.cwd===void 0,r;if(e?.cwd!==void 0)r=e.cwd;else{let C=e?.env,v=C?.CLAUDE_CONFIG_DIR?.trim(),w=C?.HOME?.trim(),L=C===void 0?it():v||ut(w||ep(),".claude"),z=pT(L)?L:ut(ep(),".claude");if(!pT(z))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 U=ut(z,"spares");await f_(U,{recursive:!0,mode:448}),r=await tGe(ut(U,"spare-"))}function o(){return n?Yq(r,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve()}let{workspaceTrust:s,...i}=e??{};if(s!==void 0)q("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 Bt("sdk_prewarm",async()=>{try{return await nZ({options:{...i,cwd:r,extraArgs:{...i.extraArgs,"await-claim":null}},initializeTimeoutMs:t})}catch(C){throw await o(),C}}),d=Object.entries(e?.mcpServers??{}).filter(([,C])=>C.type==="sdk").map(([C])=>C),p;function f(){return p??=c.waitForExit().catch(()=>{}).then(o),p}let m=!1,g=!1,_=!1,y,S=new Promise((C,v)=>{y={resolve:C,reject:v}});S.catch(()=>{});let b=c.waitForExit().then(()=>{return},()=>{return});b.then(()=>{if(!m)_=!0,y.reject(Error("spare_exited: the spare process exited before it was claimed")),f()});let E={claimed:S,exited:b,claim({prompt:C,options:v}){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=dGe.filter((O)=>v.settings?.[O]!==void 0);if(w.length>0)throw new we(`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 v.cwd==="string"&&v.cwd.trim()!==""&&!Xq.isAbsolute(v.cwd)&&!Qq.isAbsolute(v.cwd)&&v.cwd!=="~"&&!v.cwd.startsWith("~/")?tp(v.cwd):v.cwd;m=!0;let z=tZ(v.workspaceTrust),U=l.claimSession({cwd:L,...v.permissionMode!==void 0&&{permission_mode:v.permissionMode},...v.env&&{env:v.env},...v.additionalDirectories&&{additional_directories:v.additionalDirectories},...v.appendSystemPrompt!==void 0&&{append_system_prompt:v.appendSystemPrompt},...v.title!==void 0&&{title:v.title},...v.agents&&{agents:v.agents},...z?.accepted===!0&&{workspace_trust:z},sdk_mcp_servers:d}),de=[];if(v.model!==void 0)de.push(["model",l.setModel(v.model)]);if(v.maxThinkingTokens!==void 0)de.push(["maxThinkingTokens",l.setMaxThinkingTokens(v.maxThinkingTokens)]);let x=v.settings!==void 0?l.applyFlagSettings(v.settings):void 0;if(x!==void 0)de.push(["settings",x]);for(let[,O]of de)O.catch(()=>{});function R(){c.endInput(),f()}if(U.then(async(O)=>{o();let D={cwd:O.cwd??L,sessionId:O.session_id,parkedMs:O.parked_ms,sdkMcpSettled:O.sdk_mcp_settled},B=await Promise.allSettled(de.map(([,J])=>J)),oe=B.flatMap((J,K)=>J.status==="rejected"?[`${String(de[K][0])}: ${Ot(J.reason)}`]:[]),me=x===void 0?void 0:B[de.findIndex(([J])=>J==="settings")];if(me?.status==="rejected")g=!0,l.close(),y.reject(Object.assign(new we(`settings_not_applied: ${Ot(me.reason)} — the prompt was not sent and the process was closed; start the session with query()`,"settings_not_applied"),{claim:D}));else if(oe.length>0)y.reject(Object.assign(new we(`option_not_applied: ${oe.join("; ")} — the prompt was sent and the session runs without these options`,"option_not_applied"),{claim:D}));else y.resolve(D)},(O)=>{R(),y.reject(O)}),x===void 0)return a.query(C);return Promise.all([U,x]).then(()=>{if(g)return;try{a.query(C)}catch{}},()=>{}),l},close(){if(g)return;if(g=!0,m)l.close();else a.close(),y.reject(Error("spare_closed: the spare was closed before it was claimed"));f()},async[Symbol.asyncDispose](){E.close(),await f()}};return E}import{randomUUID as pZ}from"crypto";import{constants as rZ}from"fs";import{open as yGe,readdir as iZ,rm as oZ,stat as SGe}from"fs/promises";import{join as zo}from"path";var EGe=64;function hT(e){return Ee()?e:void 0}async function aZ(e,t,n={},r){if(!$e(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let o=ie({type:"custom-title",customTitle:t.trim(),sessionId:e})+`
144
144
  `;await dZ(e,o,n,hT(r))}async function lZ(e,t,n={},r){if(!$e(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let s=oi(t).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");t=s}let o=ie({type:"tag",tag:t??"",sessionId:e})+`
145
145
  `;await dZ(e,o,n,hT(r))}async function cZ(e,t={},n){if(!$e(e))throw Error(`Invalid sessionId: ${e}`);let r=hT(n);for(let o of await CGe(t,r)){if(Ee()&&r!==void 0){let a=ci(o,r.isKeySegment);if(a!==void 0){if(await bGe(a,e,r))return;continue}}let s=zo(o,`${e}.jsonl`),i;try{({size:i}=await SGe(s))}catch(a){let l=pe(a);if(l==="ENOENT"||l==="ENOTDIR")continue;throw a}if(i===0)continue;await oZ(s,{force:!0}),await oZ(zo(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 bGe(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 CGe(e,t){if(e.dir){let r=await _o(e.dir,bf(t,Ee())),o=await sZ(r,t),s;try{s=await go(r)}catch{s=[]}for(let i of s){if(i===r)continue;o.push(...await sZ(i,t))}return o}let n=lt();if(Ee()&&t!==void 0){let r=await uZ(t);if(r===void 0)return[];if(r.laterPageFailed)throw Error("Session delete: project listing incomplete via storage");return r.names.map((o)=>zo(n,o))}try{return(await iZ(n,{withFileTypes:!0})).filter((o)=>o.isDirectory()||o.isSymbolicLink()).map((o)=>zo(n,o.name))}catch{return[]}}async function sZ(e,t){let n=Zt(t);if(n===void 0||!n.hoverRestOn)return Un(e);let r=await Un(e,n),o=Ba(e),s=process.platform==="win32",i=[];for(let a of r)if(a===o||await Ka(a,e,s,n))i.push(a);return i}async function uZ(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=vf(s,e.isKeySegment);if(i!==void 0)t.push(i)}n=o.value.cursor}while(n&&++r<EGe);return{names:t,laterPageFailed:Boolean(n)}}catch{return r===0&&t.length===0?void 0:{names:t,laterPageFailed:!0}}}async function dZ(e,t,n,r){let o=`${e}.jsonl`;if(n.dir){let a=await _o(n.dir,bf(r,Ee()));for(let c of await Un(a,Zt(r)))if(await g_(zo(c,o),t,gT(c,e,r)))return;let l;try{l=await go(a)}catch{l=[]}for(let c of l){if(c===a)continue;for(let d of await Un(c,Zt(r)))if(await g_(zo(d,o),t,gT(d,e,r)))return}throw Error(`Session ${e} not found in project directory for ${n.dir}`)}let s=lt();if(Ee()&&r!==void 0){let a=await uZ(r);if(a===void 0)throw new we(`Session ${e} not found (no projects directory)`,"Session not found (no projects directory)");let{names:l}=a;for(let c of l){let d=zo(s,c);if(await g_(zo(d,o),t,gT(d,e,r)))return}throw new we(`Session ${e} not found in any project directory`,"Session not found in any project directory")}let i;try{i=await iZ(s)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let a of i)if(await g_(zo(s,a,o),t))return;throw Error(`Session ${e} not found in any project directory`)}async function g_(e,t,n){if(Ee()&&n!==void 0)return vGe(n,t);let r;try{r=await yGe(e,rZ.O_WRONLY|rZ.O_APPEND)}catch(o){let s=pe(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 we(`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 vGe({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 gT(e,t,n){if(!Ee()||n===void 0)return;let r=ci(e,n.isKeySegment);return r===void 0?void 0:{backend:n.backend,key:n.transcriptKey(r,t)}}async function AGe(e,t,n){if(n?.sessionStore)return TGe(n.sessionStore,e,t,n.dir);return aZ(e,t,n)}async function RGe(e,t,n){if(n?.sessionStore)return wGe(n.sessionStore,e,t,n.dir);return lZ(e,t,n)}async function xGe(e,t){if(!$e(e))throw new we(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=hn(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return cZ(e,t)}async function TGe(e,t,n,r){if(!$e(t))throw new we(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!n.trim())throw Error("title must be non-empty");let o=hn(r);await e.append({projectKey:o,sessionId:t},[{type:"custom-title",customTitle:n.trim(),sessionId:t,uuid:pZ(),timestamp:new Date().toISOString()}])}async function wGe(e,t,n,r){if(!$e(t))throw new we(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(n!==null){let s=oi(n).trim();if(!s)throw Error("tag must be non-empty (use null to clear)");n=s}let o=hn(r);await e.append({projectKey:o,sessionId:t},[{type:"tag",tag:n??"",sessionId:t,uuid:pZ(),timestamp:new Date().toISOString()}])}async function Wkt(e){return Q2(e)}async function Zkt(e,t){if(t?.sessionStore)return $Ge(t.sessionStore,e,t);return xN(e,t)}async function Ykt(e){if(e?.sessionStore)return UGe(e.sessionStore,e);return HN(e)}async function Jkt(e,t){if(t?.sessionStore)return HGe(t.sessionStore,e,t);return jN(e,t)}async function Xkt(e,t){if(t?.sessionStore)return jGe(t.sessionStore,e,t);return oU(e,t)}async function Qkt(e,t,n,r){if(!$e(e))throw new we(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let o=Ee(),s=o?r:void 0,i=await as(e,n?.dir,Tn(s),o);if(!i)throw Error(`Session ${e} not found`);let a=hn(n?.dir),l=n?.batchSize&&n.batchSize>0?n.batchSize:Lc,c=s===void 0?void 0:ci(IGe(i.filePath),Ht),d=s!==void 0&&c!==void 0?{backend:s,projectKey:c}:void 0;if(d!==void 0)await av(d.backend,At.transcript(d.projectKey,e),{projectKey:a,sessionId:e},t,l);else await fZ(i.filePath,{projectKey:a,sessionId:e},t,l);if(n?.includeSubagents===!1)return;if(d!==void 0){let m=await yU(d.backend,d.projectKey,e),g=await SU(d.backend,d.projectKey,e,m);for(let _ of m){let y={projectKey:a,sessionId:e,subpath:gm(_)};await av(d.backend,_.kind==="agent"?At.transcript(d.projectKey,e,_.agentId,_.agentRelPath):At.journal(d.projectKey,e,_.agentRelPath),y,t,l);let S=g.get(y.subpath),b;if(S!==void 0)try{b=We(S)}catch(E){q(`importSessionToStore: skipping unreadable sidecar for ${y.subpath}: ${E}`)}if(b!==void 0)await t.append(y,[{type:"agent_metadata",...b}])}return}let p=i.filePath.replace(/\.jsonl$/,""),f=mZ(p,"subagents");for(let m of await NGe(f)){let g=DGe(p,m).split(LGe);g[g.length-1]=g.at(-1).replace(/\.jsonl$/,"");let _={projectKey:a,sessionId:e,subpath:g.join("/")};await fZ(m,_,t,l);let y=m.replace(/\.jsonl$/,".meta.json"),S;try{S=We(await PGe(y,"utf8"))}catch(b){if(!pt(b))q(`importSessionToStore: skipping unreadable sidecar ${y}: ${b}`)}if(S!==void 0)await t.append(_,[{type:"agent_metadata",...S}])}}async function fZ(e,t,n,r){let o=MGe({input:OGe(e,{encoding:"utf8"}),crlfDelay:1/0}),s=[],i=0;for await(let a of o){if(!a)continue;try{s.push(We(a))}catch(l){q(`importSessionToStore: skipping unparseable line in ${e}: ${l}`);continue}if(i+=a.length,s.length>=r||i>=si)await n.append(t,s),s=[],i=0}if(s.length>0)await n.append(t,s)}async function NGe(e){let t=[];async function n(r){let o;try{o=await kGe(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=mZ(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 ePt(e,t){if(t?.sessionStore)return BGe(t.sessionStore,e,t.dir);return mU(e,t)}async function tPt(e,t,n){if(n?.sessionStore)return KGe(n.sessionStore,e,t,n);return gU(e,t,n)}function gZ(e){return e.map((t)=>ie(t)).join(`