MCPcopy Index your code
hub / github.com/ChinaSiro/claude-code-sourcemap / saveEventsToFile

Method saveEventsToFile

package/cli.js:493–495  ·  view source on GitHub ↗
(q,K)

Source from the content-addressed store, hash-verified

491 }
492 $commands -join [char]0
493 `.trim(),$=await S7("powershell.exe",["-NoProfile","-Command",Y],{timeout:3000});if($.code!==0||!$.stdout?.trim())return[];return $.stdout.split("\x00").filter(Boolean)}let _=`currentpid=${String(q)}; for i in $(seq 1 ${K}); do cmd=$(ps -o command= -p $currentpid 2>/dev/null); if [ -n "$cmd" ]; then printf '%s\\0' "$cmd"; fi; ppid=$(ps -o ppid= -p $currentpid 2>/dev/null | tr -d ' '); if [ -z "$ppid" ] || [ "$ppid" = "0" ] || [ "$ppid" = "1" ]; then break; fi; currentpid=$ppid; done`,z=await S7("sh",["-c",_],{timeout:3000});if(z.code!==0||!z.stdout?.trim())return[];return z.stdout.split("\x00").filter(Boolean)}var u$6=y(()=>{XK()});import{stat as Dj_}from"fs/promises";function Zj_(){return process.platform==="linux"&&i6(process.env.CLAUDE_CODE_BUBBLEWRAP)}function Gj_(){if(process.platform!=="linux")return!1;return VV1??!1}async function tiq(){if(m$6!==void 0)return m$6;if(process.platform==="darwin")return m$6=null,null;try{let q=await siq(process.pid,10);for(let K of q){let _=K.toLowerCase();for(let z of o41)if(_.includes(z))return m$6=z,z}}catch{}return m$6=null,null}async function Tj_(){if(process.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"){if(a1.platform!=="darwin")return await tiq()||"pycharm"}return a1.terminal}function vj_(){if(process.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"){if(a1.platform!=="darwin"){if(m$6!==void 0)return m$6||"pycharm";return"pycharm"}}return a1.terminal}async function NV1(){if(process.env.TERMINAL_EMULATOR==="JetBrains-JediTerm")await tiq()}var fj_,VV1=null,m$6,BV;var J16=y(()=>{F4();y_();m8();XK();u$6();fj_=_1(async()=>{if(process.platform!=="linux")return!1;let{code:q}=await a8("test",["-f","/.dockerenv"]);return q===0});if(process.platform==="linux"){let q=process.arch==="x64"?"x86_64":"aarch64";Dj_(`/lib/libc.musl-${q}.so.1`).then(()=>{VV1=!0},()=>{VV1=!1})}BV={...a1,terminal:vj_(),getIsDocker:fj_,getIsBubblewrapSandbox:Zj_,isMuslEnvironment:Gj_,getTerminalWithJetBrainsDetectionAsync:Tj_,initJetBrainsDetection:NV1}});function kj_(q){try{let K=new URL(q);return K.search="",K.toString().replace(/\/$/,"")}catch{return}}async function qrq(){if(process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)return;try{let q=await $1.get("https://api.anthropic.com/mcp-registry/v0/servers?version=latest&visibility=commercial",{timeout:5000}),K=new Set;for(let _ of q.data.servers)for(let z of _.server.remotes??[]){let Y=kj_(z.url);if(Y)K.add(Y)}eiq=K,N(`[mcp-registry] Loaded ${K.size} official MCP URLs`)}catch(q){N(`Failed to fetch MCP registry: ${d6(q)}`,{level:"error"})}}function Krq(q){return eiq?.has(q)??!1}var eiq=void 0;var yV1=y(()=>{CK();_8();y8()});function Vj_(){return process.argv.includes("--agent-teams")}function nq(){if(!i6(process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS)&&!Vj_())return!1;if(!g8("tengu_amber_flint",!0))return!1;return!0}var i$=y(()=>{o1();m8()});import{AsyncLocalStorage as Nj_}from"async_hooks";function Au(){return _rq.getStore()}function KF(q,K){return _rq.run(q,K)}function yj_(q){return q?.agentType==="subagent"}function zrq(){let q=Au();if(!yj_(q)||!q.subagentName)return;return q.isBuiltIn?q.subagentName:"user-defined"}function EV1(){let q=Au();if(!q?.invokingRequestId||q.invocationEmitted)return;return q.invocationEmitted=!0,{invokingRequestId:q.invokingRequestId,invocationKind:q.invocationKind}}var _rq;var Ou=y(()=>{i$();_rq=new Nj_});import{AsyncLocalStorage as Ej_}from"async_hooks";function VP(){return LV1.getStore()}function $f8(q,K){return LV1.run(q,K)}function cW(){return LV1.getStore()!==void 0}function Af8(q){return{...q,isInProcess:!0}}var LV1;var JG=y(()=>{LV1=new Ej_});var SV1={};T8(SV1,{waitForTeammatesToBecomeIdle:()=>hV1,setDynamicTeamContext:()=>Lj_,runWithTeammateContext:()=>$f8,isTeammate:()=>$Y,isTeamLead:()=>MG,isPlanModeRequired:()=>fc6,isInProcessTeammate:()=>cW,hasWorkingInProcessTeammates:()=>RV1,hasActiveInProcessTeammates:()=>Of8,getTeammateContext:()=>VP,getTeammateColor:()=>vj,getTeamName:()=>$9,getParentSessionId:()=>_F,getDynamicTeamContext:()=>Dc6,getAgentName:()=>M_,getAgentId:()=>NP,createTeammateContext:()=>Af8,clearDynamicTeamContext:()=>Rj_});function _F(){let q=VP();if(q)return q.parentSessionId;return zL?.parentSessionId}function Lj_(q){zL=q}function Rj_(){zL=null}function Dc6(){return zL}function NP(){let q=VP();if(q)return q.agentId;return zL?.agentId}function M_(){let q=VP();if(q)return q.agentName;return zL?.agentName}function $9(q){let K=VP();if(K)return K.teamName;if(zL?.teamName)return zL.teamName;return q?.teamName}function $Y(){if(VP())return!0;return!!(zL?.agentId&&zL?.teamName)}function vj(){let q=VP();if(q)return q.color;return zL?.color}function fc6(){let q=VP();if(q)return q.planModeRequired;if(zL!==null)return zL.planModeRequired;return i6(process.env.CLAUDE_CODE_PLAN_MODE_REQUIRED)}function MG(q){if(!q?.leadAgentId)return!1;let K=NP(),_=q.leadAgentId;if(K===_)return!0;if(!K)return!0;return!1}function Of8(q){for(let K of Object.values(q.tasks))if(K.type==="in_process_teammate"&&K.status==="running")return!0;return!1}function RV1(q){for(let K of Object.values(q.tasks))if(K.type==="in_process_teammate"&&K.status==="running"&&!K.isIdle)return!0;return!1}function hV1(q,K){let _=[];for(let[z,Y]of Object.entries(K.tasks))if(Y.type==="in_process_teammate"&&Y.status==="running"&&!Y.isIdle)_.push(z);if(_.length===0)return Promise.resolve();return new Promise((z)=>{let Y=_.length,$=()=>{if(Y--,Y===0)z()};q((A)=>{let O={...A.tasks};for(let w of _){let j=O[w];if(j&&j.type==="in_process_teammate")if(j.isIdle)$();else O[w]={...j,onIdleCallbacks:[...j.onIdleCallbacks??[],$]}}return{...A,tasks:O}})})}var zL=null;var AY=y(()=>{JG();m8();JG()});var dG6={};T8(dG6,{isComputerUseMCPServer:()=>Sj_,getTerminalBundleId:()=>CV1,COMPUTER_USE_MCP_SERVER_NAME:()=>p$6,CLI_HOST_BUNDLE_ID:()=>wf8,CLI_CU_CAPABILITIES:()=>Zc6});function CV1(){let q=process.env.__CFBundleIdentifier;if(q)return q;return hj_[a1.terminal??""]??null}function Sj_(q){return Z2(q)===p$6}var p$6="computer-use",wf8="com.anthropic.claude-code.cli-no-window",hj_,Zc6;var wi=y(()=>{y_();hj_={"iTerm.app":"com.googlecode.iterm2",Apple_Terminal:"com.apple.Terminal",ghostty:"com.mitchellh.ghostty",kitty:"net.kovidgoyal.kitty",WarpTerminal:"dev.warp.Warp-Stable",vscode:"com.microsoft.VSCode"};Zc6={screenshotFiltering:"native",platform:"darwin"}});import{extname as Cj_}from"path";function wK(q){if(q.startsWith("mcp__"))return"mcp_tool";return q}function Jf8(){return i6(process.env.OTEL_LOG_TOOL_DETAILS)}function bj_(q,K){if(process.env.CLAUDE_CODE_ENTRYPOINT==="local-agent")return!0;if(q==="claudeai-proxy")return!0;if(K&&Krq(K))return!0;return!1}function zF(q,K,_){let z=uV1(q);if(!z)return{};if(!xj_.has(z.serverName)&&!bj_(K,_))return{};return{mcpServerName:z.serverName,mcpToolName:z.mcpToolName}}function uV1(q){if(!q.startsWith("mcp__"))return;let K=q.split("__");if(K.length<3)return;let _=K[1],z=K.slice(2).join("__");if(!_||!z)return;return{serverName:_,mcpToolName:z}}function $rq(q,K){if(q!=="Skill")return;if(typeof K==="object"&&K!==null&&"skill"in K&&typeof K.skill==="string")return K.skill;return}function xV1(q,K=0){if(typeof q==="string"){if(q.length>Ij_)return`${q.slice(0,uj_)}…[${q.length} chars]`;return q}if(typeof q==="number"||typeof q==="boolean"||q===null||q===void 0)return q;if(K>=mj_)return"<nested>";if(Array.isArray(q)){let _=q.slice(0,jf8).map((z)=>xV1(z,K+1));if(q.length>jf8)_.push(`…[${q.length} items]`);return _}if(typeof q==="object"){let _=Object.entries(q).filter(([Y])=>!Y.startsWith("_")),z=_.slice(0,jf8).map(([Y,$])=>[Y,xV1($,K+1)]);if(_.length>jf8)z.push(["…",`${_.length} keys`]);return Object.fromEntries(z)}return String(q)}function Arq(q){if(!Jf8())return;let K=xV1(q),_=g6(K);if(_.length>Yrq)_=_.slice(0,Yrq)+"…[truncated]";return _}function M16(q){let K=Cj_(q).toLowerCase();if(!K||K===".")return;let _=K.slice(1);if(_.length>pj_)return"other";return _}function Orq(q,K){if(!q.includes(".")&&!K)return;let _,z=new Set;if(K){let Y=M16(K);if(Y)z.add(Y),_=Y}for(let Y of q.split(gj_)){if(!Y)continue;let $=Y.split(Fj_);if($.length<2)continue;let A=$[0],O=A.lastIndexOf("/"),w=O>=0?A.slice(O+1):A;if(!Bj_.has(w))continue;for(let j=1;j<$.length;j++){let H=$[j];if(H.charCodeAt(0)===45)continue;let J=M16(H);if(J&&!z.has(J))z.add(J),_=_?_+","+J:J}}if(!_)return;return _}function Uj_(){let q=Au();if(q){let O={agentId:q.agentId,parentSessionId:q.parentSessionId,agentType:q.agentType};if(q.agentType==="teammate")O.teamName=q.teamName;return O}let K=NP(),_=_F(),z=$9(),$=$Y()?"teammate":K?"standalone":void 0;if(K||$||_||z)return{...K?{agentId:K}:{},...$?{agentType:$}:{},..._?{parentSessionId:_}:{},...z?{teamName:z}:{}};let A=mn8();if(A)return{parentSessionId:A};return{}}function cj_(){try{let q=process.memoryUsage(),K=process.cpuUsage(),_=Date.now(),z;if(Hf8&&bV1){let Y=_-bV1;if(Y>0){let $=K.user-Hf8.user,A=K.system-Hf8.system;z=($+A)/(Y*1000)*100}}return Hf8=K,bV1=_,{uptime:process.uptime(),rss:q.rss,heapTotal:q.heapTotal,heapUsed:q.heapUsed,external:q.external,arrayBuffers:q.arrayBuffers,constrainedMemory:process.constrainedMemory(),cpuUsage:K,cpuPercent:z}}catch{return}}async function Mf8(q={}){let K=q.model?String(q.model):D5(),_=typeof q.betas==="string"?q.betas:qL(K).join(","),[z,Y]=await Promise.all([dj_(),t$8()]),$=cj_();return{model:K,sessionId:N8(),userType:"external",..._.length>0?{betas:_}:{},envContext:z,...process.env.CLAUDE_CODE_ENTRYPOINT&&{entrypoint:process.env.CLAUDE_CODE_ENTRYPOINT},...process.env.CLAUDE_AGENT_SDK_VERSION&&{agentSdkVersion:process.env.CLAUDE_AGENT_SDK_VERSION},isInteractive:String(ET()),clientType:xX6(),...$&&{processMetrics:$},sweBenchRunId:process.env.SWE_BENCH_RUN_ID||"",sweBenchInstanceId:process.env.SWE_BENCH_INSTANCE_ID||"",sweBenchTaskId:process.env.SWE_BENCH_TASK_ID||"",...Uj_(),...yK()&&{subscriptionType:yK()},...{},...Y&&{rh:Y}}}function wrq(q,K,_={}){let{envContext:z,processMetrics:Y,rh:$,kairosActive:A,skillMode:O,observerMode:w,...j}=q,H={platform:z.platform,platform_raw:z.platformRaw,arch:z.arch,node_version:z.nodeVersion,terminal:z.terminal||"unknown",package_managers:z.packageManagers,runtimes:z.runtimes,is_running_with_bun:z.isRunningWithBun,is_ci:z.isCi,is_claubbit:z.isClaubbit,is_claude_code_remote:z.isClaudeCodeRemote,is_local_agent_mode:z.isLocalAgentMode,is_conductor:z.isConductor,is_github_action:z.isGithubAction,is_claude_code_action:z.isClaudeCodeAction,is_claude_ai_auth:z.isClaudeAiAuth,version:z.version,build_time:z.buildTime,deployment_environment:z.deploymentEnvironment};if(z.remoteEnvironmentType)H.remote_environment_type=z.remoteEnvironmentType;if(z.claudeCodeContainerId)H.claude_code_container_id=z.claudeCodeContainerId;if(z.claudeCodeRemoteSessionId)H.claude_code_remote_session_id=z.claudeCodeRemoteSessionId;if(z.tags)H.tags=z.tags.split(",").map((X)=>X.trim()).filter(Boolean);if(z.githubEventName)H.github_event_name=z.githubEventName;if(z.githubActionsRunnerEnvironment)H.github_actions_runner_environment=z.githubActionsRunnerEnvironment;if(z.githubActionsRunnerOs)H.github_actions_runner_os=z.githubActionsRunnerOs;if(z.githubActionRef)H.github_action_ref=z.githubActionRef;if(z.wslVersion)H.wsl_version=z.wslVersion;if(z.linuxDistroId)H.linux_distro_id=z.linuxDistroId;if(z.linuxDistroVersion)H.linux_distro_version=z.linuxDistroVersion;if(z.linuxKernel)H.linux_kernel=z.linuxKernel;if(z.vcs)H.vcs=z.vcs;if(z.versionBase)H.version_base=z.versionBase;let J={session_id:j.sessionId,model:j.model,user_type:j.userType,is_interactive:j.isInteractive==="true",client_type:j.clientType};if(j.betas)J.betas=j.betas;if(j.entrypoint)J.entrypoint=j.entrypoint;if(j.agentSdkVersion)J.agent_sdk_version=j.agentSdkVersion;if(j.sweBenchRunId)J.swe_bench_run_id=j.sweBenchRunId;if(j.sweBenchInstanceId)J.swe_bench_instance_id=j.sweBenchInstanceId;if(j.sweBenchTaskId)J.swe_bench_task_id=j.sweBenchTaskId;if(j.agentId)J.agent_id=j.agentId;if(j.parentSessionId)J.parent_session_id=j.parentSessionId;if(j.agentType)J.agent_type=j.agentType;if(j.teamName)J.team_name=j.teamName;if(K.githubActionsMetadata){let X=K.githubActionsMetadata;H.github_actions_metadata={actor_id:X.actorId,repository_id:X.repositoryId,repository_owner_id:X.repositoryOwnerId}}let M;if(K.accountUuid||K.organizationUuid)M={account_uuid:K.accountUuid,organization_uuid:K.organizationUuid};return{env:H,...Y&&{process:Buffer.from(g6(Y)).toString("base64")},...M&&{auth:M},core:J,additional:{...$&&{rh:$},...A&&{is_assistant_mode:!0},...O&&{skill_mode:O},...w&&{observer_mode:w},..._}}}var xj_,Ij_=512,uj_=128,Yrq=4096,jf8=20,mj_=2,pj_=10,Bj_,gj_,Fj_,Qj_,dj_,Hf8=null,bV1=null;var kj=y(()=>{F4();y_();J16();HG();aq();v8();m8();yV1();G7();E5();vK();Ou();l8();AY();xj_=new Set([(wi(),Eq(dG6)).COMPUTER_USE_MCP_SERVER_NAME]);Bj_=new Set(["rm","mv","cp","touch","mkdir","chmod","chown","cat","head","tail","sort","stat","diff","wc","grep","rg","sed"]),gj_=/\s*(?:&&|\|\||[;|])\s*/,Fj_=/\s+/;Qj_=_1(()=>{let q={ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION.match(/^\d+\.\d+\.\d+(?:-[a-z]+)?/);return q?q[0]:void 0}),dj_=_1(async()=>{let[q,K,_,z]=await Promise.all([a1.getPackageManagers(),a1.getRuntimes(),eL7(),qR7()]);return{platform:KD6(),platformRaw:process.env.CLAUDE_CODE_HOST_PLATFORM||process.platform,arch:a1.arch,nodeVersion:a1.nodeVersion,terminal:BV.terminal,packageManagers:q.join(","),runtimes:K.join(","),isRunningWithBun:a1.isRunningWithBun(),isCi:i6(!1),isClaubbit:i6(process.env.CLAUBBIT),isClaudeCodeRemote:i6(process.env.CLAUDE_CODE_REMOTE),isLocalAgentMode:process.env.CLAUDE_CODE_ENTRYPOINT==="local-agent",isConductor:a1.isConductor(),...process.env.CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE&&{remoteEnvironmentType:process.env.CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE},...{},...process.env.CLAUDE_CODE_CONTAINER_ID&&{claudeCodeContainerId:process.env.CLAUDE_CODE_CONTAINER_ID},...process.env.CLAUDE_CODE_REMOTE_SESSION_ID&&{claudeCodeRemoteSessionId:process.env.CLAUDE_CODE_REMOTE_SESSION_ID},...process.env.CLAUDE_CODE_TAGS&&{tags:process.env.CLAUDE_CODE_TAGS},isGithubAction:i6(process.env.GITHUB_ACTIONS),isClaudeCodeAction:i6(process.env.CLAUDE_CODE_ACTION),isClaudeAiAuth:d7(),version:{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION,versionBase:Qj_(),buildTime:{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.BUILD_TIME,deploymentEnvironment:a1.detectDeploymentEnvironment(),...i6(process.env.GITHUB_ACTIONS)&&{githubEventName:process.env.GITHUB_EVENT_NAME,githubActionsRunnerEnvironment:process.env.RUNNER_ENVIRONMENT,githubActionsRunnerOs:process.env.RUNNER_OS,githubActionRef:process.env.GITHUB_ACTION_PATH?.includes("claude-code-action/")?process.env.GITHUB_ACTION_PATH.split("claude-code-action/")[1]:void 0},...O_6()&&{wslVersion:O_6()},..._??{},...z.length>0?{vcs:z.join(",")}:{}}})});import{randomUUID as lj_}from"crypto";import{appendFile as nj_,mkdir as jrq,readdir as ij_,unlink as Hrq,writeFile as rj_}from"fs/promises";import*as Xf8 from"path";function Gc6(){return Xf8.join(c1(),"telemetry")}class mV1{endpoint;timeout;maxBatchSize;skipAuth;batchDelayMs;baseBackoffDelayMs;maxBackoffDelayMs;maxAttempts;isKilled;pendingExports=[];isShutdown=!1;schedule;cancelBackoff=null;attempts=0;isRetrying=!1;lastExportErrorContext;constructor(q={}){let K=q.baseUrl||(process.env.ANTHROPIC_BASE_URL==="https://api-staging.anthropic.com"?"https://api-staging.anthropic.com":"https://api.anthropic.com");this.endpoint=`${K}${q.path||"/api/event_logging/batch"}`,this.timeout=q.timeout||1e4,this.maxBatchSize=q.maxBatchSize||200,this.skipAuth=q.skipAuth??!1,this.batchDelayMs=q.batchDelayMs||100,this.baseBackoffDelayMs=q.baseBackoffDelayMs||500,this.maxBackoffDelayMs=q.maxBackoffDelayMs||30000,this.maxAttempts=q.maxAttempts??8,this.isKilled=q.isKilled??(()=>!1),this.schedule=q.schedule??((_,z)=>{let Y=setTimeout(_,z);return()=>clearTimeout(Y)}),this.retryPreviousBatches()}async getQueuedEventCount(){return(await this.loadEventsFromCurrentBatch()).length}getCurrentBatchFilePath(){return Xf8.join(Gc6(),`${Mrq}${N8()}.${Jrq}.json`)}async loadEventsFromFile(q){try{return await YA8(q)}catch{return[]}}async loadEventsFromCurrentBatch(){return this.loadEventsFromFile(this.getCurrentBatchFilePath())}async saveEventsToFile(q,K){try{if(K.length===0)try{await Hrq(q)}catch{}else{await jrq(Gc6(),{recursive:!0});let _=K.map((z)=>g6(z)).join(`
494`)+`
495`;await rj_(q,_,"utf8")}}catch(_){H6(_)}}async appendEventsToFile(q,K){if(K.length===0)return;try{await jrq(Gc6(),{recursive:!0});let _=K.map((z)=>g6(z)).join(`
496`)+`
497`;await nj_(q,_,"utf8")}catch(_){H6(_)}}async deleteFile(q){try{await Hrq(q)}catch{}}async retryPreviousBatches(){try{let q=`${Mrq}${N8()}.`,K;try{K=(await ij_(Gc6())).filter((_)=>_.startsWith(q)&&_.endsWith(".json")).filter((_)=>!_.includes(Jrq))}catch(_){if(e3(_))return;throw _}for(let _ of K){let z=Xf8.join(Gc6(),_);this.retryFileInBackground(z)}}catch(q){H6(q)}}async retryFileInBackground(q){if(this.attempts>=this.maxAttempts){await this.deleteFile(q);return}let K=await this.loadEventsFromFile(q);if(K.length===0){await this.deleteFile(q);return}let _=await this.sendEventsInBatches(K);if(_.length===0)await this.deleteFile(q);else await this.saveEventsToFile(q,_)}async export(q,K){if(this.isShutdown){K({code:X16.ExportResultCode.FAILED,error:Error("Exporter has been shutdown")});return}let _=this.doExport(q,K);this.pendingExports.push(_),_.finally(()=>{let z=this.pendingExports.indexOf(_);if(z>-1)this.pendingExports.splice(z,1)})}async doExport(q,K){try{let _=q.filter(($)=>$.instrumentationScope?.name==="com.anthropic.claude_code.events");if(_.length===0){K({code:X16.ExportResultCode.SUCCESS});return}let z=this.transformLogsToEvents(_).events;if(z.length===0){K({code:X16.ExportResultCode.SUCCESS});return}if(this.attempts>=this.maxAttempts){K({code:X16.ExportResultCode.FAILED,error:Error(`Dropped ${z.length} events: max attempts (${this.maxAttempts}) reached`)});return}let Y=await this.sendEventsInBatches(z);if(this.attempts++,Y.length>0){await this.queueFailedEvents(Y),this.scheduleBackoffRetry();let $=this.lastExportErrorContext?` (${this.lastExportErrorContext})`:"";K({code:X16.ExportResultCode.FAILED,error:Error(`Failed to export ${Y.length} events${$}`)});return}if(this.resetBackoff(),await this.getQueuedEventCount()>0&&!this.isRetrying)this.retryFailedEvents();K({code:X16.ExportResultCode.SUCCESS})}catch(_){H6(_),K({code:X16.ExportResultCode.FAILED,error:x1(_)})}}async sendEventsInBatches(q){let K=[];for(let Y=0;Y<q.length;Y+=this.maxBatchSize)K.push(q.slice(Y,Y+this.maxBatchSize));let _=[],z;for(let Y=0;Y<K.length;Y++){let $=K[Y];try{await this.sendBatchWithRetry({events:$})}catch(A){z=oj_(A);for(let O=Y;O<K.length;O++)_.push(...K[O]);break}if(Y<K.length-1&&this.batchDelayMs>0)await R7(this.batchDelayMs)}if(_.length>0&&z)this.lastExportErrorContext=z;return _}async queueFailedEvents(q){let K=this.getCurrentBatchFilePath();await this.appendEventsToFile(K,q);let _=this.lastExportErrorContext?` (${this.lastExportErrorContext})`:"",z=`1P event logging: ${q.length} events failed to export${_}`;H6(Error(z))}scheduleBackoffRetry(){if(this.cancelBackoff||this.isRetrying||this.isShutdown)return;let q=Math.min(this.baseBackoffDelayMs*this.attempts*this.attempts,this.maxBackoffDelayMs);this.cancelBackoff=this.schedule(async()=>{this.cancelBackoff=null,await this.retryFailedEvents()},q)}async retryFailedEvents(){let q=this.getCurrentBatchFilePath();while(!this.isShutdown){let K=await this.loadEventsFromFile(q);if(K.length===0)break;if(this.attempts>=this.maxAttempts){await this.deleteFile(q),this.resetBackoff();return}this.isRetrying=!0,await this.deleteFile(q);let _=await this.sendEventsInBatches(K);if(this.attempts++,this.isRetrying=!1,_.length>0){await this.saveEventsToFile(q,_),this.scheduleBackoffRetry();return}this.resetBackoff()}}resetBackoff(){if(this.attempts=0,this.cancelBackoff)this.cancelBackoff(),this.cancelBackoff=null}async sendBatchWithRetry(q){if(this.isKilled())throw Error("firstParty sink killswitch active");let K={"Content-Type":"application/json","User-Agent":n$(),"x-service-name":"claude-code"},_=l$()||i7(),z=this.skipAuth||!_;if(!z&&d7()){let O=Kq();if(!BW())z=!0;else if(O&&Gg(O.expiresAt))z=!0}let Y=z?{headers:{},error:"trust not established or Oauth token expired"}:DJ(),$=!Y.error,A=$?{...K,...Y.headers}:K;try{let O=await $1.post(this.endpoint,q,{timeout:this.timeout,headers:A});this.logSuccess(q.events.length,$,O.data);return}catch(O){if($&&$1.isAxiosError(O)&&O.response?.status===401){let w=await $1.post(this.endpoint,q,{timeout:this.timeout,headers:K});this.logSuccess(q.events.length,!1,w.data);return}throw O}}logSuccess(q,K,_){}hrTimeToDate(q){let[K,_]=q;return new Date(K*1000+_/1e6)}transformLogsToEvents(q){let K=[];for(let _ of q){let z=_.attributes||{};if(z.event_type==="GrowthbookExperimentEvent"){let P=this.hrTimeToDate(_.hrTime),W=z.account_uuid,D=z.organization_uuid;K.push({event_type:"GrowthbookExperimentEvent",event_data:kV1.toJSON({event_id:z.event_id,timestamp:P,experiment_id:z.experiment_id,variation_id:z.variation_id,environment:z.environment,user_attributes:z.user_attributes,experiment_metadata:z.experiment_metadata,device_id:z.device_id,session_id:z.session_id,auth:W||D?{account_uuid:W,organization_uuid:D}:void 0})});continue}let Y=z.event_name||_.body||"unknown",$=z.core_metadata,A=z.user_metadata,O=z.event_metadata||{};if(!$){K.push({event_type:"ClaudeCodeInternalEvent",event_data:Yf8.toJSON({event_id:z.event_id,event_name:Y,client_timestamp:this.hrTimeToDate(_.hrTime),session_id:N8(),additional_metadata:Buffer.from(g6({transform_error:"core_metadata attribute is missing"})).toString("base64")})});continue}let w=wrq($,A,O),{_PROTO_skill_name:j,_PROTO_plugin_name:H,_PROTO_marketplace_name:J,...M}=w.additional,X=f38(M);K.push({event_type:"ClaudeCodeInternalEvent",event_data:Yf8.toJSON({event_id:z.event_id,event_name:Y,client_timestamp:this.hrTimeToDate(_.hrTime),device_id:z.user_id,email:A?.email,auth:w.auth,...w.core,env:w.env,process:w.process,skill_name:typeof j==="string"?j:void 0,plugin_name:typeof H==="string"?H:void 0,marketplace_name:typeof J==="string"?J:void 0,additional_metadata:Object.keys(X).length>0?Buffer.from(g6(X)).toString("base64"):void 0})})}return{events:K}}async shutdown(){this.isShutdown=!0,this.resetBackoff(),await this.forceFlush()}async forceFlush(){await Promise.all(this.pendingExports)}}function oj_(q){if(!$1.isAxiosError(q))return d6(q);let K=[],_=q.response?.headers?.["request-id"];if(_)K.push(`request-id=${_}`);if(q.response?.status)K.push(`status=${q.response.status}`);if(q.code)K.push(`code=${q.code}`);if(q.message)K.push(q.message);return K.join(", ")}var X16,Jrq,Mrq="1p_failed_events.";var Xrq=y(()=>{CK();v8();iiq();riq();G7();V1();_8();m8();y8();jG();vO();E8();l8();pW();k8();kj();X16=O6(Oz(),1),Jrq=lj_()});function cG6(q){return XG(aj_,{})?.[q]===!0}var aj_="tengu_frond_boric";var pV1=y(()=>{o1()});var Trq={};T8(Trq,{shutdown1PEventLogging:()=>ji,shouldSampleEvent:()=>BV1,reinitialize1PEventLoggingIfConfigChanged:()=>YH_,logGrowthBookExperimentTo1P:()=>gV1,logEventTo1P:()=>Tc6,is1PEventLoggingEnabled:()=>B$6,initialize1PEventLogging:()=>Grq,getEventSamplingConfig:()=>Drq});import{randomUUID as Wrq}from"crypto";function Drq(){return XG(sj_,{})}function BV1(q){let _=Drq()[q];if(!_)return null;let z=_.sample_rate;if(typeof z!=="number"||z<0||z>1)return null;if(z>=1)return null;if(z<=0)return 0;return Math.random()<z?z:0}function frq(){return XG(tj_,{})}async function ji(){if(!P16)return;try{await P16.shutdown()}catch{}}function B$6(){return!j16()}async function ej_(q,K,_={}){try{let z=await Mf8({model:_.model,betas:_.betas}),Y={event_name:K,event_id:Wrq(),core_metadata:z,user_metadata:SG6(!0),event_metadata:_},$=CS();if($)Y.user_id=$;q.emit({body:K,attributes:Y})}catch(z){}}function Tc6(q,K={}){if(!B$6())return;if(!W16||cG6("firstParty"))return;ej_(W16,q,K)}function qH_(){return"production"}function gV1(q){if(!B$6())return;if(!W16||cG6("firstParty"))return;let K=CS(),{accountUuid:_,organizationUuid:z}=SG6(!0),Y={event_type:"GrowthbookExperimentEvent",event_id:Wrq(),experiment_id:q.experimentId,variation_id:q.variationId,...K&&{device_id:K},..._&&{account_uuid:_},...z&&{organization_uuid:z},...q.userAttributes&&{session_id:q.userAttributes.sessionId,user_attributes:g6(q.userAttributes)},...q.experimentMetadata&&{experiment_metadata:g6(q.experimentMetadata)},environment:qH_()};W16.emit({body:"growthbook_experiment",attributes:Y})}function Grq(){if(U4("1p_event_logging_start"),!B$6())return;let K=frq();Zrq=K,U4("1p_event_after_growthbook_config");let _=K.scheduledDelayMillis||parseInt(process.env.OTEL_LOGS_EXPORT_INTERVAL||KH_.toString()),z=K.maxExportBatchSize||_H_,Y=K.maxQueueSize||zH_,$=Z1(),A={[Wf8.ATTR_SERVICE_NAME]:"claude-code",[Wf8.ATTR_SERVICE_VERSION]:{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION};if($==="wsl"){let j=O_6();if(j)A["wsl.version"]=j}let O=Prq.resourceFromAttributes(A),w=new mV1({maxBatchSize:z,skipAuth:K.skipAuth,maxAttempts:K.maxAttempts,path:K.path,baseUrl:K.baseUrl,isKilled:()=>cG6("firstParty")});P16=new Pf8.LoggerProvider({resource:O,processors:[new Pf8.BatchLogRecordProcessor(w,{scheduledDelayMillis:_,maxExportBatchSize:z,maxQueueSize:Y})]}),W16=P16.getLogger("com.anthropic.claude_code.events",{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION)}async function YH_(){if(!B$6()||!P16)return;let q=frq();if(QJ(q,Zrq))return;let K=P16,_=W16;W16=null;try{await K.forceFlush()}catch{}P16=null;try{Grq()}catch(z){P16=K,W16=_,H6(z);return}K.shutdown().catch(()=>{})}var Prq,Pf8,Wf8,sj_="tengu_event_sampling_config",tj_="tengu_1p_event_batch_config",W16=null,P16=null,Zrq=null,KH_=1e4,_H_=200,zH_=8192;var Hi=y(()=>{VW6();V1();_8();E8();vK();l8();Cx();f$6();H16();Xrq();o1();kj();pV1();Prq=O6(pG6(),1),Pf8=O6(ZV1(),1),Wf8=O6(L$6(),1)});var Srq={};T8(Srq,{stopPeriodicGrowthBookRefresh:()=>lV1,setupPeriodicGrowthBookRefresh:()=>hrq,setGrowthBookConfigOverride:()=>wH_,resetGrowthBook:()=>Ec6,refreshGrowthBookFeatures:()=>Rrq,refreshGrowthBookAfterAuthChange:()=>U$6,onGrowthBookRefresh:()=>Nc6,initializeGrowthBook:()=>Xi,hasGrowthBookEnvOverride:()=>$H_,getGrowthBookConfigOverrides:()=>OH_,getFeatureValue_DEPRECATED:()=>Df8,getFeatureValue_CACHED_WITH_REFRESH:()=>gV,getFeatureValue_CACHED_MAY_BE_STALE:()=>g8,getDynamicConfig_CACHED_MAY_BE_STALE:()=>XG,getDynamicConfig_BLOCKS_ON_INIT:()=>gS,getApiBaseUrlHost:()=>yrq,getAllGrowthBookFeatures:()=>AH_,clearGrowthBookConfigOverrides:()=>jH_,checkStatsigFeatureGate_CACHED_MAY_BE_STALE:()=>tY,checkSecurityRestrictionGate:()=>cV1,checkGate_CACHED_OR_BLOCKING:()=>FV});function vrq(q){try{Promise.resolve(q()).catch((K)=>{H6(K)})}catch(K){H6(K)}}function Nc6(q){let K=!0,_=iG6.subscribe(()=>vrq(q));if(BS.size>0)queueMicrotask(()=>{if(K&&BS.size>0)vrq(q)});return()=>{K=!1,_()}}function rG6(){if(!UV1)UV1=!0;return krq}function $H_(q){let K=rG6();return K!==null&&q in K}function oG6(){return}function AH_(){if(BS.size>0)return Object.fromEntries(BS);return j8().cachedGrowthBookFeatures??{}}function OH_(){return oG6()??{}}function wH_(q,K){return}function jH_(){return}function yc6(q){if(FV1.has(q))return;let K=F$6.get(q);if(K)FV1.add(q),gV1({experimentId:K.experimentId,variationId:K.variationId,userAttributes:Erq(),experimentMetadata:{feature_id:q}})}async function Vrq(q){let K=q.getPayload();if(!K?.features||Object.keys(K.features).length===0)return!1;F$6.clear();let _={};for(let[z,Y]of Object.entries(K.features)){let $=Y;if("value"in $&&!("defaultValue"in $))_[z]={...$,defaultValue:$.value};else _[z]=$;if($.source==="experiment"&&$.experimentResult){let{experimentResult:A,experiment:O}=$;if(O?.key&&A.variationId!==void 0)F$6.set(z,{experimentId:O.key,variationId:A.variationId})}}await q.setPayload({...K,features:_}),BS.clear();for(let[z,Y]of Object.entries(_)){let $="value"in Y?Y.value:Y.defaultValue;if($!==void 0)BS.set(z,$)}return!0}function Nrq(){let q=Object.fromEntries(BS),K=j8();if(QJ(K.cachedGrowthBookFeatures,q))return;b8((_)=>({..._,cachedGrowthBookFeatures:q}))}function Mi(){return B$6()}function yrq(){let q=process.env.ANTHROPIC_BASE_URL;if(!q)return;try{let K=new URL(q).host;if(K==="api.anthropic.com")return;return K}catch{return}}function Erq(){let q=qbq(),K=q.email,_=yrq();return{id:q.deviceId,sessionId:q.sessionId,deviceID:q.deviceId,platform:q.platform,..._&&{apiBaseUrlHost:_},...q.organizationUuid&&{organizationUUID:q.organizationUuid},...q.accountUuid&&{accountUUID:q.accountUuid},...q.userType&&{userType:q.userType},...q.subscriptionType&&{subscriptionType:q.subscriptionType},...q.rateLimitTier&&{rateLimitTier:q.rateLimitTier},...q.firstTokenTime&&{firstTokenTime:q.firstTokenTime},...K&&{email:K},...q.appVersion&&{appVersion:q.appVersion},...q.githubActionsMetadata&&{githubActionsMetadata:q.githubActionsMetadata}}}async function Lrq(q,K,_){let z=rG6();if(z&&q in z)return z[q];let Y=oG6();if(Y&&q in Y)return Y[q];if(!Mi())return K;let $=await Xi();if(!$)return K;let A;if(BS.has(q))A=BS.get(q);else A=$.getFeatureValue(q,K);if(_)yc6(q);return A}async function Df8(q,K){return Lrq(q,K,!0)}function g8(q,K){let _=rG6();if(_&&q in _)return _[q];let z=oG6();if(z&&q in z)return z[q];if(!Mi())return K;if(F$6.has(q))yc6(q);else nG6.add(q);if(BS.has(q))return BS.get(q);try{let Y=j8().cachedGrowthBookFeatures?.[q];return Y!==void 0?Y:K}catch{return K}}function gV(q,K,_){return g8(q,K)}function tY(q){let K=rG6();if(K&&q in K)return Boolean(K[q]);let _=oG6();if(_&&q in _)return Boolean(_[q]);if(!Mi())return!1;if(F$6.has(q))yc6(q);else nG6.add(q);let z=j8(),Y=z.cachedGrowthBookFeatures?.[q];if(Y!==void 0)return Boolean(Y);return z.cachedStatsigGates?.[q]??!1}async function cV1(q){let K=rG6();if(K&&q in K)return Boolean(K[q]);let _=oG6();if(_&&q in _)return Boolean(_[q]);if(!Mi())return!1;if(Vc6)await Vc6;let z=j8(),Y=z.cachedStatsigGates?.[q];if(Y!==void 0)return Boolean(Y);let $=z.cachedGrowthBookFeatures?.[q];if($!==void 0)return Boolean($);return!1}async function FV(q){let K=rG6();if(K&&q in K)return Boolean(K[q]);let _=oG6();if(_&&q in _)return Boolean(_[q]);if(!Mi())return!1;if(j8().cachedGrowthBookFeatures?.[q]===!0){if(F$6.has(q))yc6(q);else nG6.add(q);return!0}return Lrq(q,!1,!0)}function U$6(){if(!Mi())return;try{Ec6(),iG6.emit(),Vc6=Xi().catch((q)=>{return H6(x1(q)),null}).finally(()=>{Vc6=null})}catch(q){H6(x1(q))}}function Ec6(){if(lV1(),vc6)process.off("beforeExit",vc6),vc6=null;if(kc6)process.off("exit",kc6),kc6=null;Ji?.destroy(),Ji=null,dV1=!1,Vc6=null,F$6.clear(),nG6.clear(),FV1.clear(),BS.clear(),QV1.cache?.clear?.(),Xi.cache?.clear?.(),krq=null,UV1=!1}async function Rrq(){if(!Mi())return;try{let q=await Xi();if(!q)return;if(await q.refreshFeatures(),q!==Ji)return;let K=await Vrq(q);if(q!==Ji)return;if(K)Nrq(),iG6.emit()}catch(q){H6(x1(q))}}function hrq(){if(!Mi())return;if(g$6)clearInterval(g$6);if(g$6=setInterval(()=>{Rrq()},HH_),g$6.unref?.(),!lG6)lG6=()=>{lV1()},process.once("beforeExit",lG6)}function lV1(){if(g$6)clearInterval(g$6),g$6=null;if(lG6)process.removeListener("beforeExit",lG6),lG6=null}async function gS(q,K){return Df8(q,K)}function XG(q,K){return g8(q,K)}var Ji=null,vc6=null,kc6=null,dV1=!1,F$6,BS,nG6,FV1,Vc6=null,iG6,krq=null,UV1=!1,QV1,Xi,HH_=21600000,g$6=null,lG6=null;var o1=y(()=>{UN7();VW6();v8();dN7();V1();_8();y8();jG();E8();l8();f$6();Hi();F$6=new Map,BS=new Map,nG6=new Set,FV1=new Set,iG6=Dz();QV1=_1(()=>{if(!Mi())return null;let q=Erq(),K=QN7(),_="https://api.anthropic.com/",Y=l$()||mX6()||i7()?DJ():{headers:{},error:"trust not established"},$=!Y.error;dV1=$;let A=new sY8({apiHost:_,clientKey:K,attributes:q,remoteEval:!0,cacheKeyAttributes:["id","organizationUUID"],...Y.error?{}:{apiHostRequestHeaders:Y.headers},...{}});if(Ji=A,!$)return{client:A,initialized:Promise.resolve()};let O=A.init({timeout:5000}).then(async(w)=>{if(Ji!==A)return;let j=await Vrq(A);if(Ji!==A)return;if(j){for(let H of nG6)yc6(H);nG6.clear(),Nrq(),iG6.emit()}}).catch((w)=>{});return vc6=()=>Ji?.destroy(),kc6=()=>Ji?.destroy(),process.on("beforeExit",vc6),process.on("exit",kc6),{client:A,initialized:O}}),Xi=_1(async()=>{let q=QV1();if(!q)return null;if(!dV1){if(l$()||mX6()||i7()){if(!DJ().error){if(Ec6(),q=QV1(),!q)return null}}}return await q.initialized,hrq(),q.client})});import{homedir as JH_}from"os";import{isAbsolute as MH_,join as ff8,normalize as nV1,sep as Crq}from"path";function l3(){let q=process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY;if(i6(q))return!1;if(k_(q))return!0;if(i6(process.env.CLAUDE_CODE_SIMPLE))return!1;if(i6(process.env.CLAUDE_CODE_REMOTE)&&!process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR)return!1;let K=N7();if(K.autoMemoryEnabled!==void 0)return K.autoMemoryEnabled;return!0}function Zf8(){if(!g8("tengu_passport_quail",!1))return!1;return!i7()||g8("tengu_slate_thimble",!1)}function D16(){if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR)return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR;return c1()}function brq(q,K){if(!q)return;let _=q;if(K&&(_.startsWith("~/")||_.startsWith("~\\"))){let Y=_.slice(2),$=nV1(Y||".");if($==="."||$==="..")return;_=ff8(JH_(),Y)}let z=nV1(_).replace(/[/\\]+$/,"");if(!MH_(z)||z.length<3||/^[A-Za-z]:$/.test(z)||z.startsWith("\\\\")||z.startsWith("//")||z.includes("\x00"))return;return(z+Crq).normalize("NFC")}function xrq(){return brq(process.env.CLAUDE_COWORK_MEMORY_PATH_OVERRIDE,!1)}function WH_(){let q=v1("policySettings")?.autoMemoryDirectory??v1("flagSettings")?.autoMemoryDirectory??v1("localSettings")?.autoMemoryDirectory??v1("userSettings")?.autoMemoryDirectory;return brq(q,!0)}function Gf8(){return xrq()!==void 0}function DH_(){return jH(Fz())??Fz()}function Tf8(){return ff8(Vj(),PH_)}function f16(q){return nV1(q).startsWith(Vj())}var XH_="memory",PH_="MEMORY.md",Vj;var rw=y(()=>{F4();v8();o1();m8();E5();dz();U1();Vj=_1(()=>{let q=xrq()??WH_();if(q)return q;let K=ff8(D16(),"projects");return(ff8(K,JP(DH_()),XH_)+Crq).normalize("NFC")},()=>Fz())});var vf8,kf8,Irq;var iV1=y(()=>{vf8=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],kf8=["normal","vim"],Irq=["auto","tmux","in-process"]});var Pi={};T8(Pi,{validateTeamMemWritePath:()=>TH_,validateTeamMemKey:()=>aV1,isTeamMemoryEnabled:()=>Nf8,isTeamMemPath:()=>grq,isTeamMemFile:()=>Lc6,getTeamMemPath:()=>wu,getTeamMemEntrypoint:()=>GH_,PathTraversalError:()=>lW});import{lstat as fH_,realpath as mrq}from"fs/promises";import{dirname as urq,join as Vf8,resolve as rV1,sep as oV1}from"path";function ZH_(q){if(q.includes("\x00"))throw new lW(`Null byte in path key: "${q}"`);let K;try{K=decodeURIComponent(q)}catch{K=q}if(K!==q&&(K.includes("..")||K.includes("/")))throw new lW(`URL-encoded traversal in path key: "${q}"`);let _=q.normalize("NFKC");if(_!==q&&(_.includes("..")||_.includes("/")||_.includes("\\")||_.includes("\x00")))throw new lW(`Unicode-normalized traversal in path key: "${q}"`);if(q.includes("\\"))throw new lW(`Backslash in path key: "${q}"`);if(q.startsWith("/"))throw new lW(`Absolute path key: "${q}"`);return q}function Nf8(){if(!l3())return!1;return g8("tengu_herring_clock",!1)}function wu(){return(Vf8(Vj(),"team")+oV1).normalize("NFC")}function GH_(){return Vf8(Vj(),"team","MEMORY.md")}async function prq(q){let K=[],_=q;for(let z=urq(_);_!==z;z=urq(_))try{let Y=await mrq(_);return K.length===0?Y:Vf8(Y,...K.reverse())}catch(Y){let $=s1(Y);if($==="ENOENT")try{if((await fH_(_)).isSymbolicLink())throw new lW(`Dangling symlink detected (target does not exist): "${_}"`)}catch(A){if(A instanceof lW)throw A}else if($==="ELOOP")throw new lW(`Symlink loop detected in path: "${_}"`);else if($!=="ENOTDIR"&&$!=="ENAMETOOLONG")throw new lW(`Cannot verify path containment (${$}): "${_}"`);K.push(_.slice(z.length+oV1.length)),_=z}return q}async function Brq(q){let K;try{K=await mrq(wu().replace(/[/\\]+$/,""))}catch(_){let z=s1(_);if(z==="ENOENT"||z==="ENOTDIR")return!0;return!1}if(q===K)return!0;return q.startsWith(K+oV1)}function grq(q){let K=rV1(q),_=wu();return K.startsWith(_)}async function TH_(q){if(q.includes("\x00"))throw new lW(`Null byte in path: "${q}"`);let K=rV1(q),_=wu();if(!K.startsWith(_))throw new lW(`Path escapes team memory directory: "${q}"`);let z=await prq(K);if(!await Brq(z))throw new lW(`Path escapes team memory directory via symlink: "${q}"`);return K}async function aV1(q){ZH_(q);let K=wu(),_=Vf8(K,q),z=rV1(_);if(!z.startsWith(K))throw new lW(`Key escapes team memory directory: "${q}"`);let Y=await prq(z);if(!await Brq(Y))throw new lW(`Key escapes team memory directory via symlink: "${q}"`);return z}function Lc6(q){return Nf8()&&grq(q)}var lW;var YL=y(()=>{o1();y8();rw();lW=class lW extends Error{constructor(q){super(q);this.name="PathTraversalError"}}});var G16={};T8(G16,{shouldSkipPluginAutoupdate:()=>aG6,saveGlobalConfig:()=>b8,saveCurrentProjectConfig:()=>jw,resetTrustDialogAcceptedCacheForTesting:()=>EH_,recordFirstStartTime:()=>$N1,isProjectConfigKey:()=>hH_,isPathTrusted:()=>RH_,isGlobalConfigKey:()=>yH_,isAutoUpdaterDisabled:()=>AF,getUserClaudeRulesDir:()=>bf8,getRemoteControlAtStartup:()=>$F,getProjectPathForConfig:()=>Sf8,getOrCreateUserID:()=>CS,getMemoryPath:()=>l$6,getManagedClaudeRulesDir:()=>Cf8,getGlobalConfigWriteCount:()=>SH_,getGlobalConfig:()=>j8,getCustomApiKeyStatus:()=>Sc6,getCurrentProjectConfig:()=>ww,getAutoUpdaterDisabledReason:()=>c$6,formatAutoUpdaterDisabledReason:()=>Cc6,enableConfigs:()=>d$6,checkHasTrustDialogAccepted:()=>l$,_wouldLoseAuthStateForTesting:()=>mH_,_setGlobalConfigCacheForTesting:()=>pH_,_getConfigForTesting:()=>uH_,PROJECT_CONFIG_KEYS:()=>crq,NOTIFICATION_CHANNELS:()=>vf8,GLOBAL_CONFIG_KEYS:()=>drq,EDITOR_MODES:()=>kf8,DEFAULT_GLOBAL_CONFIG:()=>Rf8,CONFIG_WRITE_DISPLAY_THRESHOLD:()=>CH_});import{randomBytes as vH_}from"crypto";import{unwatchFile as kH_,watchFile as VH_}from"fs";import{basename as KN1,dirname as _N1,join as $L,resolve as Ef8}from"path";function Wi(){return{numStartups:0,installMethod:void 0,autoUpdates:void 0,theme:"dark",preferredNotifChannel:"auto",verbose:!1,editorMode:"normal",autoCompactEnabled:!0,showTurnDuration:!0,hasSeenTasksHint:!1,hasUsedStash:!1,hasUsedBackgroundTask:!1,queuedCommandUpHintCount:0,diffTool:"auto",customApiKeyResponses:{approved:[],rejected:[]},env:{},tipsHistory:{},memoryUsageCount:0,promptQueueUseCount:0,btwUseCount:0,todoFeatureEnabled:!0,showExpandedTodos:!1,messageIdleNotifThresholdMs:60000,autoConnectIde:!1,autoInstallIdeExtension:!0,fileCheckpointingEnabled:!0,terminalProgressBarEnabled:!0,cachedStatsigGates:{},cachedDynamicConfigs:{},cachedGrowthBookFeatures:{},respectGitignore:!0,copyFullResponse:!1}}function yH_(q){return drq.includes(q)}function EH_(){lrq=!1}function l$(){return lrq||=LH_()}function LH_(){if(mX6())return!0;let q=j8(),K=Sf8();if(q.projects?.[K]?.hasTrustDialogAccepted)return!0;let z=H_6(Z8());while(!0){if(q.projects?.[z]?.hasTrustDialogAccepted)return!0;let $=H_6(Ef8(z,".."));if($===z)break;z=$}return!1}function RH_(q){let K=j8(),_=H_6(Ef8(q));while(!0){if(K.projects?.[_]?.hasTrustDialogAccepted)return!0;let z=H_6(Ef8(_,".."));if(z===_)return!1;_=z}}function hH_(q){return crq.includes(q)}function hf8(q){let K=YF.config;if(!K)return!1;let _=K.oauthAccount!==void 0&&q.oauthAccount===void 0,z=K.hasCompletedOnboarding===!0&&q.hasCompletedOnboarding!==!0;return _||z}function b8(q){let K=null;try{if(irq(XP(),Wi,(z)=>{let Y=q(z);if(Y===z)return z;return K={...Y,projects:Frq(z.projects)},K})&&K)Lf8(K)}catch(_){N(`Failed to save config with lock: ${_}`,{level:"error"});let z=Q$6(XP(),Wi);if(hf8(z)){N("saveGlobalConfig fallback: re-read config is missing auth that cache has; refusing to write. See GH #3117.",{level:"error"}),d("tengu_config_auth_loss_prevented",{});return}let Y=q(z);if(Y===z)return;K={...Y,projects:Frq(z.projects)},nrq(XP(),K,Rf8),Lf8(K)}}function SH_(){return zN1}function bH_(){let q=Rc6+yf8;if(q>0)d("tengu_config_cache_stats",{cache_hits:Rc6,cache_misses:yf8,hit_rate:Rc6/q});Rc6=0,yf8=0}function eV1(q){if(q.installMethod!==void 0)return q;let K=q,_="unknown",z=q.autoUpdates??!0;switch(K.autoUpdaterStatus){case"migrated":_="local";break;case"installed":_="native";break;case"disabled":z=!1;break;case"enabled":case"no_permissions":case"not_configured":_="global";break;case void 0:break}return{...q,installMethod:_,autoUpdates:z}}function Frq(q){if(!q)return q;let K={},_=!1;for(let[z,Y]of Object.entries(q)){let $=Y;if($.history!==void 0){_=!0;let{history:A,...O}=$;K[z]=O}else K[z]=Y}return _?K:q}function IH_(){if(tV1)return;tV1=!0;let q=XP();VH_(q,{interval:xH_,persistent:!1},(K)=>{if(K.mtimeMs<=YF.mtime)return;X8().readFile(q,{encoding:"utf-8"}).then((_)=>{if(K.mtimeMs<=YF.mtime)return;let z=m5(kB(_));if(z===null||typeof z!=="object")return;YF={config:eV1({...Wi(),...z}),mtime:K.mtimeMs},Z16={mtime:K.mtimeMs,size:K.size}}).catch(()=>{})}),pq(async()=>{kH_(q),tV1=!1})}function Lf8(q){YF={config:q,mtime:Date.now()},Z16=null}function j8(){if(YF.config)return Rc6++,YF.config;yf8++;try{let q=null;try{q=X8().statSync(XP())}catch{}let K=eV1(Q$6(XP(),Wi));return YF={config:K,mtime:q?.mtimeMs??Date.now()},Z16=q?{mtime:q.mtimeMs,size:q.size}:null,IH_(),K}catch{return eV1(Q$6(XP(),Wi))}}function $F(){let q=j8().remoteControlAtStartup;if(q!==void 0)return q;return!1}function Sc6(q){let K=j8();if(K.customApiKeyResponses?.approved?.includes(q))return"approved";if(K.customApiKeyResponses?.rejected?.includes(q))return"rejected";return"new"}function nrq(q,K,_){let z=_N1(q);X8().mkdirSync(z);let $=Sm6(K,(A,O)=>g6(A)!==g6(_[O]));if(lW6(q,g6($,null,2),{encoding:"utf-8",mode:384}),q===XP())zN1++}function irq(q,K,_){let z=K(),Y=_N1(q),$=X8();$.mkdirSync(Y);let A;try{let O=`${q}.lock`,w=Date.now();A=ECq(q,{lockfilePath:O,onCompromised:(X)=>{N(`Config lock compromised: ${X}`,{level:"error"})}});let j=Date.now()-w;if(j>100)N("Lock acquisition took longer than expected - another Claude instance may be running"),d("tengu_config_lock_contention",{lock_time_ms:j});if(Z16&&q===XP())try{let X=$.statSync(q);if(X.mtimeMs!==Z16.mtime||X.size!==Z16.size)d("tengu_config_stale_write",{read_mtime:Z16.mtime,write_mtime:X.mtimeMs,read_size:Z16.size,write_size:X.size})}catch(X){if(s1(X)!=="ENOENT")throw X}let H=Q$6(q,K);if(q===XP()&&hf8(H))return N("saveConfigWithLock: re-read config is missing auth that cache has; refusing to write to avoid wiping ~/.claude.json. See GH #3117.",{level:"error"}),d("tengu_config_auth_loss_prevented",{}),!1;let J=_(H);if(J===H)return!1;let M=Sm6(J,(X,P)=>g6(X)!==g6(z[P]));try{let X=KN1(q),P=YN1();try{$.mkdirSync(P)}catch(V){if(s1(V)!=="EEXIST")throw V}let W=60000,D=$.readdirStringSync(P).filter((V)=>V.startsWith(`${X}.backup.`)).sort().reverse(),f=D[0],G=f?Number(f.split(".backup.").pop()):0,Z=Number.isNaN(G)||Date.now()-G>=W;if(Z){let V=$L(P,`${X}.backup.${Date.now()}`);$.copyFileSync(q,V)}let T=5,v=Z?$.readdirStringSync(P).filter((V)=>V.startsWith(`${X}.backup.`)).sort().reverse():D;for(let V of v.slice(T))try{$.unlinkSync($L(P,V))}catch{}}catch(X){if(s1(X)!=="ENOENT")N(`Failed to backup config: ${X}`,{level:"error"})}if(lW6(q,g6(M,null,2),{encoding:"utf-8",mode:384}),q===XP())zN1++;return!0}finally{if(A)A()}}function d$6(){if(qN1)return;let q=Date.now();c8("info","enable_configs_started"),qN1=!0,Q$6(XP(),Wi,!0),c8("info","enable_configs_completed",{duration_ms:Date.now()-q})}function YN1(){return $L(c1(),"backups")}function Urq(q){let K=X8(),_=KN1(q),z=YN1();try{let A=K.readdirStringSync(z).filter((O)=>O.startsWith(`${_}.backup.`)).sort().at(-1);if(A)return $L(z,A)}catch{}let Y=_N1(q);try{let A=K.readdirStringSync(Y).filter((w)=>w.startsWith(`${_}.backup.`)).sort().at(-1);if(A)return $L(Y,A);let O=`${q}.backup`;try{return K.statSync(O),O}catch{}}catch{}return null}function Q$6(q,K,_){if(!qN1)throw Error("Config accessed before allowed.");let z=X8();try{let Y=z.readFileSync(q,{encoding:"utf-8"});try{let $=r8(kB(Y));return{...K(),...$}}catch($){let A=$ instanceof Error?$.message:String($);throw new hT(A,q,K())}}catch(Y){if(s1(Y)==="ENOENT"){let A=Urq(q);if(A)process.stderr.write(`
498Claude configuration file not found at: ${q}

Callers 2

retryFileInBackgroundMethod · 0.95
retryFailedEventsMethod · 0.95

Calls 4

Gc6Function · 0.85
g6Function · 0.85
H6Function · 0.85
joinMethod · 0.45

Tested by

no test coverage detected