Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- src/components/messageActions.tsxAdded+450
- src/components/permissions/FilePermissionDialog/useFilePermissionDialog.tsAdded+212
- src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsxAdded+115
- src/ink/Ansi.tsxAdded+292
- src/ink/root.tsAdded+184
- src/ink/stringWidth.tsAdded+222
- src/utils/argumentSubstitution.tsAdded+145
- src/utils/array.tsAdded+13
- src/utils/attribution.tsAdded+393
- src/utils/authFileDescriptor.tsAdded+196
- src/utils/autoModeDenials.tsAdded+26
- src/utils/autoUpdater.tsAdded+561
- src/utils/aws.tsAdded+74
- src/utils/backgroundHousekeeping.tsAdded+94
- src/utils/billing.tsAdded+78
- src/utils/binaryCheck.tsAdded+53
- src/utils/bundledMode.tsAdded+22
- src/utils/caCerts.tsAdded+115
- src/utils/classifierApprovals.tsAdded+88
- src/utils/classifierApprovalsHook.tsAdded+17
- src/utils/claudemd.tsAdded+1479
- src/utils/cleanup.tsAdded+602
- src/utils/cleanupRegistry.tsAdded+25
- src/utils/cliHighlight.tsAdded+54
- src/utils/codeIndexing.tsAdded+206
- src/utils/collapseBackgroundBashNotifications.tsAdded+84
- src/utils/collapseReadSearch.tsAdded+1109
- src/utils/collapseTeammateShutdowns.tsAdded+55
- src/utils/commandLifecycle.tsAdded+21
- src/utils/commitAttribution.tsAdded+961
- src/utils/completionCache.tsAdded+166
- src/utils/concurrentSessions.tsAdded+204
- src/utils/config.tsAdded+1818
- src/utils/configConstants.tsAdded+21
- src/utils/contentArray.tsAdded+51
- src/utils/context.tsAdded+221
- src/utils/contextSuggestions.tsAdded+235
- src/utils/cron.tsAdded+308
- src/utils/cronJitterConfig.tsAdded+75
- src/utils/cronScheduler.tsAdded+565
- src/utils/cronTasks.tsAdded+458
- src/utils/cronTasksLock.tsAdded+195
- src/utils/crossProjectResume.tsAdded+75
- src/utils/crypto.tsAdded+13
- src/utils/cwd.tsAdded+32
- src/utils/debug.tsAdded+268
- src/utils/debugFilter.tsAdded+157
- src/utils/desktopDeepLink.tsAdded+236
- src/utils/detectRepository.tsAdded+178
- src/utils/diagLogs.tsAdded+94
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450import { c as _c } from "react/compiler-runtime";import figures from 'figures';import type { RefObject } from 'react';import React, { useCallback, useMemo, useRef } from 'react';import { Box, Text } from '../ink.js';import { useKeybindings } from '../keybindings/useKeybinding.js';import { logEvent } from '../services/analytics/index.js';import type { NormalizedUserMessage, RenderableMessage } from '../types/message.js';import { isEmptyMessageText, SYNTHETIC_MESSAGES } from '../utils/messages.js';const NAVIGABLE_TYPES = ['user', 'assistant', 'grouped_tool_use', 'collapsed_read_search', 'system', 'attachment'] as const;export type NavigableType = (typeof NAVIGABLE_TYPES)[number];export type NavigableOf<T extends NavigableType> = Extract<RenderableMessage, { type: T;}>;export type NavigableMessage = RenderableMessage;
// Tier-2 blocklist (tier-1 is height > 0) — things that render but aren't actionable.export function isNavigableMessage(msg: NavigableMessage): boolean { switch (msg.type) { case 'assistant': { const b = msg.message.content[0]; // Text responses (minus AssistantTextMessage's return-null cases — tier-1 // misses unmeasured virtual items), or tool calls with extractable input. return b?.type === 'text' && !isEmptyMessageText(b.text) && !SYNTHETIC_MESSAGES.has(b.text) || b?.type === 'tool_use' && b.name in PRIMARY_INPUT; } case 'user': { if (msg.isMeta || msg.isCompactSummary) return false; const b = msg.message.content[0]; if (b?.type !== 'text') return false; // Interrupt etc. — synthetic, not user-authored. if (SYNTHETIC_MESSAGES.has(b.text)) return false; // Same filter as VirtualMessageList sticky-prompt: XML-wrapped (command // expansions, bash-stdout, etc.) aren't real prompts. return !stripSystemReminders(b.text).startsWith('<'); } case 'system': // biome-ignore lint/nursery/useExhaustiveSwitchCases: blocklist — fallthrough return-true is the design switch (msg.subtype) { case 'api_metrics': case 'stop_hook_summary': case 'turn_duration': case 'memory_saved': case 'agents_killed': case 'away_summary': case 'thinking': return false; } return true; case 'grouped_tool_use': case 'collapsed_read_search': return true; case 'attachment': switch (msg.attachment.type) { case 'queued_command': case 'diagnostics': case 'hook_blocking_error': case 'hook_error_during_execution': return true; } return false; }}type PrimaryInput = { label: string; extract: (input: Record<string, unknown>) => string | undefined;};const str = (k: string) => (i: Record<string, unknown>) => typeof i[k] === 'string' ? i[k] : undefined;const PRIMARY_INPUT: Record<string, PrimaryInput> = { Read: { label: 'path', extract: str('file_path') }, Edit: { label: 'path', extract: str('file_path') }, Write: { label: 'path', extract: str('file_path') }, NotebookEdit: { label: 'path', extract: str('notebook_path') }, Bash: { label: 'command', extract: str('command') }, Grep: { label: 'pattern', extract: str('pattern') }, Glob: { label: 'pattern', extract: str('pattern') }, WebFetch: { label: 'url', extract: str('url') }, WebSearch: { label: 'query', extract: str('query') }, Task: { label: 'prompt', extract: str('prompt') }, Agent: { label: 'prompt', extract: str('prompt') }, Tmux: { label: 'command', extract: i => Array.isArray(i.args) ? `tmux ${i.args.join(' ')}` : undefined }};
// Only AgentTool has renderGroupedToolUse — Edit/Bash/etc. stay as assistant tool_use blocks.export function toolCallOf(msg: NavigableMessage): { name: string; input: Record<string, unknown>;} | undefined { if (msg.type === 'assistant') { const b = msg.message.content[0]; if (b?.type === 'tool_use') return { name: b.name, input: b.input as Record<string, unknown> }; } if (msg.type === 'grouped_tool_use') { const b = msg.messages[0]?.message.content[0]; if (b?.type === 'tool_use') return { name: msg.toolName, input: b.input as Record<string, unknown> }; } return undefined;}export type MessageActionCaps = { copy: (text: string) => void; edit: (msg: NormalizedUserMessage) => Promise<void>;};
// Identity builder — preserves tuple type so `run`'s param narrows (array literal widens without this).function action<const T extends NavigableType, const K extends string>(a: { key: K; label: string | ((s: MessageActionsState) => string); types: readonly T[]; applies?: (s: MessageActionsState) => boolean; stays?: true; run: (m: NavigableOf<T>, caps: MessageActionCaps) => void;}) { return a;}export const MESSAGE_ACTIONS = [action({ key: 'enter', label: s => s.expanded ? 'collapse' : 'expand', types: ['grouped_tool_use', 'collapsed_read_search', 'attachment', 'system'], stays: true, // Empty — `stays` handled inline by dispatch. run: () => {}}), action({ key: 'enter', label: 'edit', types: ['user'], run: (m, c) => void c.edit(m)}), action({ key: 'c', label: 'copy', types: NAVIGABLE_TYPES, run: (m, c) => c.copy(copyTextOf(m))}), action({ key: 'p', // `!` safe: applies() guarantees toolName ∈ PRIMARY_INPUT. label: s => `copy ${PRIMARY_INPUT[s.toolName!]!.label}`, types: ['grouped_tool_use', 'assistant'], applies: s => s.toolName != null && s.toolName in PRIMARY_INPUT, run: (m, c) => { const tc = toolCallOf(m); if (!tc) return; const val = PRIMARY_INPUT[tc.name]?.extract(tc.input); if (val) c.copy(val); }})] as const;function isApplicable(a: (typeof MESSAGE_ACTIONS)[number], c: MessageActionsState): boolean { if (!(a.types as readonly string[]).includes(c.msgType)) return false; return !a.applies || a.applies(c);}export type MessageActionsState = { uuid: string; msgType: NavigableType; expanded: boolean; toolName?: string;};export type MessageActionsNav = { enterCursor: () => void; navigatePrev: () => void; navigateNext: () => void; navigatePrevUser: () => void; navigateNextUser: () => void; navigateTop: () => void; navigateBottom: () => void; getSelected: () => NavigableMessage | null;};export const MessageActionsSelectedContext = React.createContext(false);export const InVirtualListContext = React.createContext(false);
// bg must go on the Box that HAS marginTop (margin stays outside paint) — that's inside each consumer.export function useSelectedMessageBg() { return React.useContext(MessageActionsSelectedContext) ? "messageActionsBackground" : undefined;}
// Can't call useKeybindings here — hook runs outside <KeybindingSetup> provider. Returns handlers instead.export function useMessageActions(cursor: MessageActionsState | null, setCursor: React.Dispatch<React.SetStateAction<MessageActionsState | null>>, navRef: RefObject<MessageActionsNav | null>, caps: MessageActionCaps): { enter: () => void; handlers: Record<string, () => void>;} { // Refs keep handlers stable — no useKeybindings re-register per message append. const cursorRef = useRef(cursor); cursorRef.current = cursor; const capsRef = useRef(caps); capsRef.current = caps; const handlers = useMemo(() => { const h: Record<string, () => void> = { 'messageActions:prev': () => navRef.current?.navigatePrev(), 'messageActions:next': () => navRef.current?.navigateNext(), 'messageActions:prevUser': () => navRef.current?.navigatePrevUser(), 'messageActions:nextUser': () => navRef.current?.navigateNextUser(), 'messageActions:top': () => navRef.current?.navigateTop(), 'messageActions:bottom': () => navRef.current?.navigateBottom(), 'messageActions:escape': () => setCursor(c => c?.expanded ? { ...c, expanded: false } : null), // ctrl+c skips the collapse step — from expanded-during-streaming, two-stage // would mean 3 presses to interrupt (collapse→null→cancel). 'messageActions:ctrlc': () => setCursor(null) }; for (const key of new Set(MESSAGE_ACTIONS.map(a_1 => a_1.key))) { h[`messageActions:${key}`] = () => { const c_0 = cursorRef.current; if (!c_0) return; const a_0 = MESSAGE_ACTIONS.find(a => a.key === key && isApplicable(a, c_0)); if (!a_0) return; if (a_0.stays) { setCursor(c_1 => c_1 ? { ...c_1, expanded: !c_1.expanded } : null); return; } const m = navRef.current?.getSelected(); if (!m) return; (a_0.run as (m: NavigableMessage, c_0: MessageActionCaps) => void)(m, capsRef.current); setCursor(null); }; } return h; }, [setCursor, navRef]); const enter = useCallback(() => { logEvent('tengu_message_actions_enter', {}); navRef.current?.enterCursor(); }, [navRef]); return { enter, handlers };}
// Must mount inside <KeybindingSetup>.export function MessageActionsKeybindings(t0) { const $ = _c(2); const { handlers, isActive } = t0; let t1; if ($[0] !== isActive) { t1 = { context: "MessageActions", isActive }; $[0] = isActive; $[1] = t1; } else { t1 = $[1]; } useKeybindings(handlers, t1); return null;}
// borderTop-only Box matches PromptInput's ─── line for stable footer height.export function MessageActionsBar(t0) { const $ = _c(28); const { cursor } = t0; let T0; let T1; let t1; let t2; let t3; let t4; let t5; let t6; let t7; if ($[0] !== cursor) { const applicable = MESSAGE_ACTIONS.filter(a => isApplicable(a, cursor)); T1 = Box; t4 = "column"; t5 = 0; t6 = 1; if ($[10] === Symbol.for("react.memo_cache_sentinel")) { t7 = <Box borderStyle="single" borderTop={true} borderBottom={false} borderLeft={false} borderRight={false} borderDimColor={true} />; $[10] = t7; } else { t7 = $[10]; } T0 = Box; t1 = 2; t2 = 1; t3 = applicable.map((a_0, i) => { const label = typeof a_0.label === "function" ? a_0.label(cursor) : a_0.label; return <React.Fragment key={a_0.key}>{i > 0 && <Text dimColor={true}> · </Text>}<Text bold={true} dimColor={false}>{a_0.key}</Text><Text dimColor={true}> {label}</Text></React.Fragment>; }); $[0] = cursor; $[1] = T0; $[2] = T1; $[3] = t1; $[4] = t2; $[5] = t3; $[6] = t4; $[7] = t5; $[8] = t6; $[9] = t7; } else { T0 = $[1]; T1 = $[2]; t1 = $[3]; t2 = $[4]; t3 = $[5]; t4 = $[6]; t5 = $[7]; t6 = $[8]; t7 = $[9]; } let t10; let t11; let t12; let t8; let t9; if ($[11] === Symbol.for("react.memo_cache_sentinel")) { t8 = <Text dimColor={true}> · </Text>; t9 = <Text bold={true} dimColor={false}>{figures.arrowUp}{figures.arrowDown}</Text>; t10 = <Text dimColor={true}> navigate · </Text>; t11 = <Text bold={true} dimColor={false}>esc</Text>; t12 = <Text dimColor={true}> back</Text>; $[11] = t10; $[12] = t11; $[13] = t12; $[14] = t8; $[15] = t9; } else { t10 = $[11]; t11 = $[12]; t12 = $[13]; t8 = $[14]; t9 = $[15]; } let t13; if ($[16] !== T0 || $[17] !== t1 || $[18] !== t2 || $[19] !== t3) { t13 = <T0 paddingX={t1} paddingY={t2}>{t3}{t8}{t9}{t10}{t11}{t12}</T0>; $[16] = T0; $[17] = t1; $[18] = t2; $[19] = t3; $[20] = t13; } else { t13 = $[20]; } let t14; if ($[21] !== T1 || $[22] !== t13 || $[23] !== t4 || $[24] !== t5 || $[25] !== t6 || $[26] !== t7) { t14 = <T1 flexDirection={t4} flexShrink={t5} paddingY={t6}>{t7}{t13}</T1>; $[21] = T1; $[22] = t13; $[23] = t4; $[24] = t5; $[25] = t6; $[26] = t7; $[27] = t14; } else { t14 = $[27]; } return t14;}export function stripSystemReminders(text: string): string { const CLOSE = '</system-reminder>'; let t = text.trimStart(); while (t.startsWith('<system-reminder>')) { const end = t.indexOf(CLOSE); if (end < 0) break; t = t.slice(end + CLOSE.length).trimStart(); } return t;}export function copyTextOf(msg: NavigableMessage): string { switch (msg.type) { case 'user': { const b = msg.message.content[0]; return b?.type === 'text' ? stripSystemReminders(b.text) : ''; } case 'assistant': { const b = msg.message.content[0]; if (b?.type === 'text') return b.text; const tc = toolCallOf(msg); return tc ? PRIMARY_INPUT[tc.name]?.extract(tc.input) ?? '' : ''; } case 'grouped_tool_use': return msg.results.map(toolResultText).filter(Boolean).join('\n\n'); case 'collapsed_read_search': return msg.messages.flatMap(m => m.type === 'user' ? [toolResultText(m)] : m.type === 'grouped_tool_use' ? m.results.map(toolResultText) : []).filter(Boolean).join('\n\n'); case 'system': if ('content' in msg) return msg.content; if ('error' in msg) return String(msg.error); return msg.subtype; case 'attachment': { const a = msg.attachment; if (a.type === 'queued_command') { const p = a.prompt; return typeof p === 'string' ? p : p.flatMap(b => b.type === 'text' ? [b.text] : []).join('\n'); } return `[${a.type}]`; } }}function toolResultText(r: NormalizedUserMessage): string { const b = r.message.content[0]; if (b?.type !== 'tool_result') return ''; const c = b.content; if (typeof c === 'string') return c; if (!c) return ''; return c.flatMap(x => x.type === 'text' ? [x.text] : []).join('\n');}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjoz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ICAgICAgYm9yZGVyTGVmdD17ZmFsc2V9XG4gICAgICAgIGJvcmRlclJpZ2h0PXtmYWxzZX1cbiAgICAgICAgYm9yZGVyRGltQ29sb3JcbiAgICAgIC8+XG4gICAgICA8Qm94IHBhZGRpbmdYPXsyfSBwYWRkaW5nWT17MX0+XG4gICAgICAgIHthcHBsaWNhYmxlLm1hcCgoYSwgaSkgPT4ge1xuICAgICAgICAgIGNvbnN0IGxhYmVsID1cbiAgICAgICAgICAgIHR5cGVvZiBhLmxhYmVsID09PSAnZnVuY3Rpb24nID8gYS5sYWJlbChjdXJzb3IpIDogYS5sYWJlbFxuICAgICAgICAgIHJldHVybiAoXG4gICAgICAgICAgICA8UmVhY3QuRnJhZ21lbnQga2V5PXthLmtleX0+XG4gICAgICAgICAgICAgIHtpID4gMCAmJiA8VGV4dCBkaW1Db2xvcj4gwrcgPC9UZXh0Pn1cbiAgICAgICAgICAgICAgey8qIGRpbUNvbG9yPXtmYWxzZX0gZm9yY2VzIFNHUiAyMiDigJQgYm9yZGVyRGltQ29sb3Igc2libGluZyBibGVlZHMgZGltIGludG8gZmlyc3QgY2VsbCAqL31cbiAgICAgICAgICAgICAgPFRleHQgYm9sZCBkaW1Db2xvcj17ZmFsc2V9PlxuICAgICAgICAgICAgICAgIHthLmtleX1cbiAgICAgICAgICAgICAgPC9UZXh0PlxuICAgICAgICAgICAgICA8VGV4dCBkaW1Db2xvcj4ge2xhYmVsfTwvVGV4dD5cbiAgICAgICAgICAgIDwvUmVhY3QuRnJhZ21lbnQ+XG4gICAgICAgICAgKVxuICAgICAgICB9KX1cbiAgICAgICAgPFRleHQgZGltQ29sb3I+IMK3IDwvVGV4dD5cbiAgICAgICAgPFRleHQgYm9sZCBkaW1Db2xvcj17ZmFsc2V9PlxuICAgICAgICAgIHtmaWd1cmVzLmFycm93VXB9XG4gICAgICAgICAge2ZpZ3VyZXMuYXJyb3dEb3dufVxuICAgICAgICA8L1RleHQ+XG4gICAgICAgIDxUZXh0IGRpbU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vb2xDYWxsT2YobXNnKVxuICAgICAgcmV0dXJuIHRjID8gKFBSSU1BUllfSU5QVVRbdGMubmFtZV0/LmV4dHJhY3QodGMuaW5wdXQpID8/ICcnKSA6ICcnXG4gICAgfVxuICAgIGNhc2UgJ2dyb3VwZWRfdG9vbF91c2UnOlxuICAgICAgcmV0dXJuIG1zZy5yZXN1bHRzLm1hcCh0b29sUmVzdWx0VGV4dCkuZmlsdGVyKEJvb2xlYW4pLmpvaW4oJ1xcblxcbicpXG4gICAgY2FzZSAnY29sbGFwc2VkX3JlYWRfc2VhcmNoJzpcbiAgICAgIHJldHVybiBtc2cubWVzc2FnZXNcbiAgICAgICAgLmZsYXRNYXAobSA9PlxuICAgICAgICAgIG0udHlwZSA9PT0gJ3VzZXInXG4gICAgICAgICAgICA/IFt0b29sUmVzdWx0VGV4dChtKV1cbiAgICAgICAgICAgIDogbS50eXBlID09PSAnZ3JvdXBlZF90b29sX3VzZSdcbiAgICAgICAgICAgICAgPyBtLnJlc3VsdHMubWFwKHRvb2xSZXN1bHRUZXh0KVxuICAgICAgICAgICAgICA6IFtdLFxuICAgICAgICApXG4gICAgICAgIC5maWx0ZXIoQm9vbGVhbilcbiAgICAgICAgLmpvaW4oJ1xcblxcbicpXG4gICAgY2FzZSAnc3lzdGVtJzpcbiAgICAgIGlmICgnY29udGVudCcgaW4gbXNnKSByZXR1cm4gbXNnLmNvbnRlbnRcbiAgICAgIGlmICgnZXJyb3InIGluIG1zZykgcmV0dXJuIFN0cmluZyhtc2cuZXJyb3IpXG4gICAgICByZXR1cm4gbXNnLnN1YnR5cGVcbiAgICBjYXNlICdhdHRhY2htZW50Jzoge1xuICAgICAgY29uc3QgYSA9IG1zZy5hdHRhY2htZW50XG4gICAgICBpZiAoYS50eXBlID09PSAncXVldWVkX2NvbW1hbmQnKSB7XG4gICAgICAgIGNvbnN0IHAgPSBhLnByb21wdFxuICAgICAgICByZXR1cm4gdHlwZW9mIHAgPT09ICdzdHJpbmcnXG4gICAgICA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BRSxNQUFNLENBQUM7RUFDeEQsTUFBTWMsQ0FBQyxHQUFHcUosQ0FBQyxDQUFDcEosT0FBTyxDQUFDQyxPQUFPLENBQUMsQ0FBQyxDQUFDO0VBQzlCLElBQUlGLENBQUMsRUFBRUwsSUFBSSxLQUFLLGFBQWEsRUFBRSxPQUFPLEVBQUU7RUFDeEMsTUFBTWdFLENBQUMsR0FBRzNELENBQUMsQ0FBQ0UsT0FBTztFQUNuQixJQUFJLE9BQU95RCxDQUFDLEtBQUssUUFBUSxFQUFFLE9BQU9BLENBQUM7RUFDbkMsSUFBSSxDQUFDQSxDQUFDLEVBQUUsT0FBTyxFQUFFO0VBQ2pCLE9BQU9BLENBQUMsQ0FBQ3FGLE9BQU8sQ0FBQ00sQ0FBQyxJQUFLQSxDQUFDLENBQUMzSixJQUFJLEtBQUssTUFBTSxHQUFHLENBQUMySixDQUFDLENBQUNuSixJQUFJLENBQUMsR0FBRyxFQUFHLENBQUMsQ0FBQ2tDLElBQUksQ0FBQyxJQUFJLENBQUM7QUFDdkUiLCJpZ25vcmVMaXN0IjpbXX0=123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import { useCallback, useMemo, useState } from 'react'import { useAppState } from 'src/state/AppState.js'import { useKeybindings } from '../../../keybindings/useKeybinding.js'import { type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, logEvent,} from '../../../services/analytics/index.js'import { sanitizeToolNameForAnalytics } from '../../../services/analytics/metadata.js'import type { PermissionUpdate } from '../../../utils/permissions/PermissionUpdateSchema.js'import type { CompletionType } from '../../../utils/unaryLogging.js'import type { ToolUseConfirm } from '../PermissionRequest.js'import { type FileOperationType, getFilePermissionOptions, type PermissionOption, type PermissionOptionWithLabel,} from './permissionOptions.js'import { PERMISSION_HANDLERS, type PermissionHandlerParams,} from './usePermissionHandler.js'
export interface ToolInput { [key: string]: unknown}
export type UseFilePermissionDialogProps<T extends ToolInput> = { filePath: string completionType: CompletionType languageName: string | Promise<string> toolUseConfirm: ToolUseConfirm onDone: () => void onReject: () => void parseInput: (input: unknown) => T operationType?: FileOperationType}
export type UseFilePermissionDialogResult<T> = { options: PermissionOptionWithLabel[] onChange: (option: PermissionOption, input: T, feedback?: string) => void acceptFeedback: string rejectFeedback: string focusedOption: string setFocusedOption: (option: string) => void handleInputModeToggle: (value: string) => void yesInputMode: boolean noInputMode: boolean}
/** * Hook for handling file permission dialogs with common logic */export function useFilePermissionDialog<T extends ToolInput>({ filePath, completionType, languageName, toolUseConfirm, onDone, onReject, parseInput, operationType = 'write',}: UseFilePermissionDialogProps<T>): UseFilePermissionDialogResult<T> { const toolPermissionContext = useAppState(s => s.toolPermissionContext) const [acceptFeedback, setAcceptFeedback] = useState('') const [rejectFeedback, setRejectFeedback] = useState('') const [focusedOption, setFocusedOption] = useState('yes') const [yesInputMode, setYesInputMode] = useState(false) const [noInputMode, setNoInputMode] = useState(false) // Track whether user ever entered feedback mode (persists after collapse) const [yesFeedbackModeEntered, setYesFeedbackModeEntered] = useState(false) const [noFeedbackModeEntered, setNoFeedbackModeEntered] = useState(false)
// Generate options based on context const options = useMemo( () => getFilePermissionOptions({ filePath, toolPermissionContext, operationType, onRejectFeedbackChange: setRejectFeedback, onAcceptFeedbackChange: setAcceptFeedback, yesInputMode, noInputMode, }), [filePath, toolPermissionContext, operationType, yesInputMode, noInputMode], )
// Handle option selection using shared handlers const onChange = useCallback( (option: PermissionOption, input: T, feedback?: string) => { const params: PermissionHandlerParams = { messageId: toolUseConfirm.assistantMessage.message.id, path: filePath, toolUseConfirm, toolPermissionContext, onDone, onReject, completionType, languageName, operationType, }
// Override the input in toolUseConfirm to pass the parsed input const originalOnAllow = toolUseConfirm.onAllow toolUseConfirm.onAllow = ( _input: unknown, permissionUpdates: PermissionUpdate[], feedback?: string, ) => { originalOnAllow(input, permissionUpdates, feedback) }
const handler = PERMISSION_HANDLERS[option.type] handler(params, { feedback, hasFeedback: !!feedback, enteredFeedbackMode: option.type === 'accept-once' ? yesFeedbackModeEntered : noFeedbackModeEntered, scope: option.type === 'accept-session' ? option.scope : undefined, }) }, [ filePath, completionType, languageName, toolUseConfirm, toolPermissionContext, onDone, onReject, operationType, yesFeedbackModeEntered, noFeedbackModeEntered, ], )
// Handler for confirm:cycleMode - select accept-session option const handleCycleMode = useCallback(() => { const sessionOption = options.find(o => o.option.type === 'accept-session') if (sessionOption) { const parsedInput = parseInput(toolUseConfirm.input) onChange(sessionOption.option, parsedInput) } }, [options, parseInput, toolUseConfirm.input, onChange])
// Register keyboard shortcut handler via keybindings system useKeybindings( { 'confirm:cycleMode': handleCycleMode }, { context: 'Confirmation' }, )
// Wrap setFocusedOption and reset input mode when navigating away const handleFocusedOptionChange = useCallback( (value: string) => { // Reset input mode when navigating away, but only if no text typed if (value !== 'yes' && yesInputMode && !acceptFeedback.trim()) { setYesInputMode(false) } if (value !== 'no' && noInputMode && !rejectFeedback.trim()) { setNoInputMode(false) } setFocusedOption(value) }, [yesInputMode, noInputMode, acceptFeedback, rejectFeedback], )
// Handle Tab key toggling input mode for Yes/No options const handleInputModeToggle = useCallback( (value: string) => { const analyticsProps = { toolName: sanitizeToolNameForAnalytics( toolUseConfirm.tool.name, ) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, isMcp: toolUseConfirm.tool.isMcp ?? false, }
if (value === 'yes') { if (yesInputMode) { setYesInputMode(false) logEvent('tengu_accept_feedback_mode_collapsed', analyticsProps) } else { setYesInputMode(true) setYesFeedbackModeEntered(true) logEvent('tengu_accept_feedback_mode_entered', analyticsProps) } } else if (value === 'no') { if (noInputMode) { setNoInputMode(false) logEvent('tengu_reject_feedback_mode_collapsed', analyticsProps) } else { setNoInputMode(true) setNoFeedbackModeEntered(true) logEvent('tengu_reject_feedback_mode_entered', analyticsProps) } } }, [yesInputMode, noInputMode, toolUseConfirm], )
return { options, onChange, acceptFeedback, rejectFeedback, focusedOption, setFocusedOption: handleFocusedOptionChange, handleInputModeToggle, yesInputMode, noInputMode, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import { c as _c } from "react/compiler-runtime";import React from 'react';import { Box, Text, useTheme } from '../../../ink.js';import { FallbackPermissionRequest } from '../FallbackPermissionRequest.js';import { FilePermissionDialog } from '../FilePermissionDialog/FilePermissionDialog.js';import type { ToolInput } from '../FilePermissionDialog/useFilePermissionDialog.js';import type { PermissionRequestProps, ToolUseConfirm } from '../PermissionRequest.js';function pathFromToolUse(toolUseConfirm: ToolUseConfirm): string | null { const tool = toolUseConfirm.tool; if ('getPath' in tool && typeof tool.getPath === 'function') { try { return tool.getPath(toolUseConfirm.input); } catch { return null; } } return null;}export function FilesystemPermissionRequest(t0) { const $ = _c(30); const { toolUseConfirm, onDone, onReject, verbose, toolUseContext, workerBadge } = t0; const [theme] = useTheme(); let t1; if ($[0] !== toolUseConfirm) { t1 = pathFromToolUse(toolUseConfirm); $[0] = toolUseConfirm; $[1] = t1; } else { t1 = $[1]; } const path = t1; let t2; if ($[2] !== toolUseConfirm.input || $[3] !== toolUseConfirm.tool) { t2 = toolUseConfirm.tool.userFacingName(toolUseConfirm.input as never); $[2] = toolUseConfirm.input; $[3] = toolUseConfirm.tool; $[4] = t2; } else { t2 = $[4]; } const userFacingName = t2; const isReadOnly = toolUseConfirm.tool.isReadOnly(toolUseConfirm.input); const userFacingReadOrEdit = isReadOnly ? "Read" : "Edit"; const title = `${userFacingReadOrEdit} file`; const parseInput = _temp; if (!path) { let t3; if ($[5] !== onDone || $[6] !== onReject || $[7] !== toolUseConfirm || $[8] !== toolUseContext || $[9] !== verbose || $[10] !== workerBadge) { t3 = <FallbackPermissionRequest toolUseConfirm={toolUseConfirm} toolUseContext={toolUseContext} onDone={onDone} onReject={onReject} verbose={verbose} workerBadge={workerBadge} />; $[5] = onDone; $[6] = onReject; $[7] = toolUseConfirm; $[8] = toolUseContext; $[9] = verbose; $[10] = workerBadge; $[11] = t3; } else { t3 = $[11]; } return t3; } let t3; if ($[12] !== theme || $[13] !== toolUseConfirm.input || $[14] !== toolUseConfirm.tool || $[15] !== verbose) { t3 = toolUseConfirm.tool.renderToolUseMessage(toolUseConfirm.input as never, { theme, verbose }); $[12] = theme; $[13] = toolUseConfirm.input; $[14] = toolUseConfirm.tool; $[15] = verbose; $[16] = t3; } else { t3 = $[16]; } let t4; if ($[17] !== t3 || $[18] !== userFacingName) { t4 = <Box flexDirection="column" paddingX={2} paddingY={1}><Text>{userFacingName}({t3})</Text></Box>; $[17] = t3; $[18] = userFacingName; $[19] = t4; } else { t4 = $[19]; } const content = t4; const t5 = isReadOnly ? "read" : "write"; let t6; if ($[20] !== content || $[21] !== onDone || $[22] !== onReject || $[23] !== path || $[24] !== t5 || $[25] !== title || $[26] !== toolUseConfirm || $[27] !== toolUseContext || $[28] !== workerBadge) { t6 = <FilePermissionDialog toolUseConfirm={toolUseConfirm} toolUseContext={toolUseContext} onDone={onDone} onReject={onReject} workerBadge={workerBadge} title={title} content={content} path={path} parseInput={parseInput} operationType={t5} completionType="tool_use_single" />; $[20] = content; $[21] = onDone; $[22] = onReject; $[23] = path; $[24] = t5; $[25] = title; $[26] = toolUseConfirm; $[27] = toolUseContext; $[28] = workerBadge; $[29] = t6; } else { t6 = $[29]; } return t6;}function _temp(input) { return input as ToolInput;}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIkJveCIsIlRleHQiLCJ1c2VUaGVtZSIsIkZhbGxiYWNrUGVybWlzc2lvblJlcXVlc3QiLCJGaWxlUGVybWlzc2lvbkRpYWxvZyIsIlRvb2xJbnB1dCI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BQVZBLFdBQVMsQ0FBQyxDQUNQLGFBQTZCLENBQTdCLENBQUFNLEVBQTRCLENBQUMsQ0FDN0IsY0FBaUIsQ0FBakIsaUJBQWlCLEdBQ2hDO0lBQUFyQixDQUFBLE9BQUFvQixPQUFBO0lBQUFwQixDQUFBLE9BQUFFLE1BQUE7SUFBQUYsQ0FBQSxPQUFBRyxRQUFBO0lBQUFILENBQUEsT0FBQVMsSUFBQTtJQUFBVCxDQUFBLE9BQUFxQixFQUFBO0lBQUFyQixDQUFBLE9BQUFjLEtBQUE7SUFBQWQsQ0FBQSxPQUFBTixjQUFBO0lBQUFNLENBQUEsT0FBQUssY0FBQTtJQUFBTCxDQUFBLE9BQUFNLFdBQUE7SUFBQU4sQ0FBQSxPQUFBc0IsRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQXRCLENBQUE7RUFBQTtFQUFBLE9BWkZzQixFQVlFO0FBQUE7QUFoRUMsU0FBQU4sTUFBQW5CLEtBQUE7RUFBQSxPQXFCNkNBLEtBQUssSUFBSVAsU0FBUztBQUFBIiwiaWdub3JlTGlzdCI6W119123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292import { c as _c } from "react/compiler-runtime";import React from 'react';import Link from './components/Link.js';import Text from './components/Text.js';import type { Color } from './styles.js';import { type NamedColor, Parser, type Color as TermioColor, type TextStyle } from './termio.js';type Props = { children: string; /** When true, force all text to be rendered with dim styling */ dimColor?: boolean;};type SpanProps = { color?: Color; backgroundColor?: Color; dim?: boolean; bold?: boolean; italic?: boolean; underline?: boolean; strikethrough?: boolean; inverse?: boolean; hyperlink?: string;};
/** * Component that parses ANSI escape codes and renders them using Text components. * * Use this as an escape hatch when you have pre-formatted ANSI strings from * external tools (like cli-highlight) that need to be rendered in Ink. * * Memoized to prevent re-renders when parent changes but children string is the same. */export const Ansi = React.memo(function Ansi(t0) { const $ = _c(12); const { children, dimColor } = t0; if (typeof children !== "string") { let t1; if ($[0] !== children || $[1] !== dimColor) { t1 = dimColor ? <Text dim={true}>{String(children)}</Text> : <Text>{String(children)}</Text>; $[0] = children; $[1] = dimColor; $[2] = t1; } else { t1 = $[2]; } return t1; } if (children === "") { return null; } let t1; let t2; if ($[3] !== children || $[4] !== dimColor) { t2 = Symbol.for("react.early_return_sentinel"); bb0: { const spans = parseToSpans(children); if (spans.length === 0) { t2 = null; break bb0; } if (spans.length === 1 && !hasAnyProps(spans[0].props)) { t2 = dimColor ? <Text dim={true}>{spans[0].text}</Text> : <Text>{spans[0].text}</Text>; break bb0; } let t3; if ($[7] !== dimColor) { t3 = (span, i) => { const hyperlink = span.props.hyperlink; if (dimColor) { span.props.dim = true; } const hasTextProps = hasAnyTextProps(span.props); if (hyperlink) { return hasTextProps ? <Link key={i} url={hyperlink}><StyledText color={span.props.color} backgroundColor={span.props.backgroundColor} dim={span.props.dim} bold={span.props.bold} italic={span.props.italic} underline={span.props.underline} strikethrough={span.props.strikethrough} inverse={span.props.inverse}>{span.text}</StyledText></Link> : <Link key={i} url={hyperlink}>{span.text}</Link>; } return hasTextProps ? <StyledText key={i} color={span.props.color} backgroundColor={span.props.backgroundColor} dim={span.props.dim} bold={span.props.bold} italic={span.props.italic} underline={span.props.underline} strikethrough={span.props.strikethrough} inverse={span.props.inverse}>{span.text}</StyledText> : span.text; }; $[7] = dimColor; $[8] = t3; } else { t3 = $[8]; } t1 = spans.map(t3); } $[3] = children; $[4] = dimColor; $[5] = t1; $[6] = t2; } else { t1 = $[5]; t2 = $[6]; } if (t2 !== Symbol.for("react.early_return_sentinel")) { return t2; } const content = t1; let t3; if ($[9] !== content || $[10] !== dimColor) { t3 = dimColor ? <Text dim={true}>{content}</Text> : <Text>{content}</Text>; $[9] = content; $[10] = dimColor; $[11] = t3; } else { t3 = $[11]; } return t3;});type Span = { text: string; props: SpanProps;};
/** * Parse an ANSI string into spans using the termio parser. */function parseToSpans(input: string): Span[] { const parser = new Parser(); const actions = parser.feed(input); const spans: Span[] = []; let currentHyperlink: string | undefined; for (const action of actions) { if (action.type === 'link') { if (action.action.type === 'start') { currentHyperlink = action.action.url; } else { currentHyperlink = undefined; } continue; } if (action.type === 'text') { const text = action.graphemes.map(g => g.value).join(''); if (!text) continue; const props = textStyleToSpanProps(action.style); if (currentHyperlink) { props.hyperlink = currentHyperlink; }
// Try to merge with previous span if props match const lastSpan = spans[spans.length - 1]; if (lastSpan && propsEqual(lastSpan.props, props)) { lastSpan.text += text; } else { spans.push({ text, props }); } } } return spans;}
/** * Convert termio's TextStyle to SpanProps. */function textStyleToSpanProps(style: TextStyle): SpanProps { const props: SpanProps = {}; if (style.bold) props.bold = true; if (style.dim) props.dim = true; if (style.italic) props.italic = true; if (style.underline !== 'none') props.underline = true; if (style.strikethrough) props.strikethrough = true; if (style.inverse) props.inverse = true; const fgColor = colorToString(style.fg); if (fgColor) props.color = fgColor; const bgColor = colorToString(style.bg); if (bgColor) props.backgroundColor = bgColor; return props;}
// Map termio named colors to the ansi: formatconst NAMED_COLOR_MAP: Record<NamedColor, string> = { black: 'ansi:black', red: 'ansi:red', green: 'ansi:green', yellow: 'ansi:yellow', blue: 'ansi:blue', magenta: 'ansi:magenta', cyan: 'ansi:cyan', white: 'ansi:white', brightBlack: 'ansi:blackBright', brightRed: 'ansi:redBright', brightGreen: 'ansi:greenBright', brightYellow: 'ansi:yellowBright', brightBlue: 'ansi:blueBright', brightMagenta: 'ansi:magentaBright', brightCyan: 'ansi:cyanBright', brightWhite: 'ansi:whiteBright'};
/** * Convert termio's Color to the string format used by Ink. */function colorToString(color: TermioColor): Color | undefined { switch (color.type) { case 'named': return NAMED_COLOR_MAP[color.name] as Color; case 'indexed': return `ansi256(${color.index})` as Color; case 'rgb': return `rgb(${color.r},${color.g},${color.b})` as Color; case 'default': return undefined; }}
/** * Check if two SpanProps are equal for merging. */function propsEqual(a: SpanProps, b: SpanProps): boolean { return a.color === b.color && a.backgroundColor === b.backgroundColor && a.bold === b.bold && a.dim === b.dim && a.italic === b.italic && a.underline === b.underline && a.strikethrough === b.strikethrough && a.inverse === b.inverse && a.hyperlink === b.hyperlink;}function hasAnyProps(props: SpanProps): boolean { return props.color !== undefined || props.backgroundColor !== undefined || props.dim === true || props.bold === true || props.italic === true || props.underline === true || props.strikethrough === true || props.inverse === true || props.hyperlink !== undefined;}function hasAnyTextProps(props: SpanProps): boolean { return props.color !== undefined || props.backgroundColor !== undefined || props.dim === true || props.bold === true || props.italic === true || props.underline === true || props.strikethrough === true || props.inverse === true;}
// Text style props without weight (bold/dim) - these are handled separatelytype BaseTextStyleProps = { color?: Color; backgroundColor?: Color; italic?: boolean; underline?: boolean; strikethrough?: boolean; inverse?: boolean;};
// Wrapper component that handles bold/dim mutual exclusivity for Textfunction StyledText(t0) { const $ = _c(14); let bold; let children; let dim; let rest; if ($[0] !== t0) { ({ bold, dim, children, ...rest } = t0); $[0] = t0; $[1] = bold; $[2] = children; $[3] = dim; $[4] = rest; } else { bold = $[1]; children = $[2]; dim = $[3]; rest = $[4]; } if (dim) { let t1; if ($[5] !== children || $[6] !== rest) { t1 = <Text {...rest} dim={true}>{children}</Text>; $[5] = children; $[6] = rest; $[7] = t1; } else { t1 = $[7]; } return t1; } if (bold) { let t1; if ($[8] !== children || $[9] !== rest) { t1 = <Text {...rest} bold={true}>{children}</Text>; $[8] = children; $[9] = rest; $[10] = t1; } else { t1 = $[10]; } return t1; } let t1; if ($[11] !== children || $[12] !== rest) { t1 = <Text {...rest}>{children}</Text>; $[11] = children; $[12] = rest; $[13] = t1; } else { t1 = $[13]; } return t1;}//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ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QUFBIiwiaWdub3JlTGlzdCI6W119123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184import type { ReactNode } from 'react'import { logForDebugging } from 'src/utils/debug.js'import { Stream } from 'stream'import type { FrameEvent } from './frame.js'import Ink, { type Options as InkOptions } from './ink.js'import instances from './instances.js'
export type RenderOptions = { /** * Output stream where app will be rendered. * * @default process.stdout */ stdout?: NodeJS.WriteStream /** * Input stream where app will listen for input. * * @default process.stdin */ stdin?: NodeJS.ReadStream /** * Error stream. * @default process.stderr */ stderr?: NodeJS.WriteStream /** * Configure whether Ink should listen to Ctrl+C keyboard input and exit the app. This is needed in case `process.stdin` is in raw mode, because then Ctrl+C is ignored by default and process is expected to handle it manually. * * @default true */ exitOnCtrlC?: boolean
/** * Patch console methods to ensure console output doesn't mix with Ink output. * * @default true */ patchConsole?: boolean
/** * Called after each frame render with timing and flicker information. */ onFrame?: (event: FrameEvent) => void}
export type Instance = { /** * Replace previous root node with a new one or update props of the current root node. */ rerender: Ink['render'] /** * Manually unmount the whole Ink app. */ unmount: Ink['unmount'] /** * Returns a promise, which resolves when app is unmounted. */ waitUntilExit: Ink['waitUntilExit'] cleanup: () => void}
/** * A managed Ink root, similar to react-dom's createRoot API. * Separates instance creation from rendering so the same root * can be reused for multiple sequential screens. */export type Root = { render: (node: ReactNode) => void unmount: () => void waitUntilExit: () => Promise<void>}
/** * Mount a component and render the output. */export const renderSync = ( node: ReactNode, options?: NodeJS.WriteStream | RenderOptions,): Instance => { const opts = getOptions(options) const inkOptions: InkOptions = { stdout: process.stdout, stdin: process.stdin, stderr: process.stderr, exitOnCtrlC: true, patchConsole: true, ...opts, }
const instance: Ink = getInstance( inkOptions.stdout, () => new Ink(inkOptions), )
instance.render(node)
return { rerender: instance.render, unmount() { instance.unmount() }, waitUntilExit: instance.waitUntilExit, cleanup: () => instances.delete(inkOptions.stdout), }}
const wrappedRender = async ( node: ReactNode, options?: NodeJS.WriteStream | RenderOptions,): Promise<Instance> => { // Preserve the microtask boundary that `await loadYoga()` used to provide. // Without it, the first render fires synchronously before async startup work // (e.g. useReplBridge notification state) settles, and the subsequent Static // write overwrites scrollback instead of appending below the logo. await Promise.resolve() const instance = renderSync(node, options) logForDebugging( `[render] first ink render: ${Math.round(process.uptime() * 1000)}ms since process start`, ) return instance}
export default wrappedRender
/** * Create an Ink root without rendering anything yet. * Like react-dom's createRoot — call root.render() to mount a tree. */export async function createRoot({ stdout = process.stdout, stdin = process.stdin, stderr = process.stderr, exitOnCtrlC = true, patchConsole = true, onFrame,}: RenderOptions = {}): Promise<Root> { // See wrappedRender — preserve microtask boundary from the old WASM await. await Promise.resolve() const instance = new Ink({ stdout, stdin, stderr, exitOnCtrlC, patchConsole, onFrame, })
// Register in the instances map so that code that looks up the Ink // instance by stdout (e.g. external editor pause/resume) can find it. instances.set(stdout, instance)
return { render: node => instance.render(node), unmount: () => instance.unmount(), waitUntilExit: () => instance.waitUntilExit(), }}
const getOptions = ( stdout: NodeJS.WriteStream | RenderOptions | undefined = {},): RenderOptions => { if (stdout instanceof Stream) { return { stdout, stdin: process.stdin, } }
return stdout}
const getInstance = ( stdout: NodeJS.WriteStream, createInstance: () => Ink,): Ink => { let instance = instances.get(stdout)
if (!instance) { instance = createInstance() instances.set(stdout, instance) }
return instance}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import emojiRegex from 'emoji-regex'import { eastAsianWidth } from 'get-east-asian-width'import stripAnsi from 'strip-ansi'import { getGraphemeSegmenter } from '../utils/intl.js'
const EMOJI_REGEX = emojiRegex()
/** * Fallback JavaScript implementation of stringWidth when Bun.stringWidth is not available. * * Get the display width of a string as it would appear in a terminal. * * This is a more accurate alternative to the string-width package that correctly handles * characters like ⚠ (U+26A0) which string-width incorrectly reports as width 2. * * The implementation uses eastAsianWidth directly with ambiguousAsWide: false, * which correctly treats ambiguous-width characters as narrow (width 1) as * recommended by the Unicode standard for Western contexts. */function stringWidthJavaScript(str: string): number { if (typeof str !== 'string' || str.length === 0) { return 0 }
// Fast path: pure ASCII string (no ANSI codes, no wide chars) let isPureAscii = true for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i) // Check for non-ASCII or ANSI escape (0x1b) if (code >= 127 || code === 0x1b) { isPureAscii = false break } } if (isPureAscii) { // Count printable characters (exclude control chars) let width = 0 for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i) if (code > 0x1f) { width++ } } return width }
// Strip ANSI if escape character is present if (str.includes('\x1b')) { str = stripAnsi(str) if (str.length === 0) { return 0 } }
// Fast path: simple Unicode (no emoji, variation selectors, or joiners) if (!needsSegmentation(str)) { let width = 0 for (const char of str) { const codePoint = char.codePointAt(0)! if (!isZeroWidth(codePoint)) { width += eastAsianWidth(codePoint, { ambiguousAsWide: false }) } } return width }
let width = 0
for (const { segment: grapheme } of getGraphemeSegmenter().segment(str)) { // Check for emoji first (most emoji sequences are width 2) EMOJI_REGEX.lastIndex = 0 if (EMOJI_REGEX.test(grapheme)) { width += getEmojiWidth(grapheme) continue }
// Calculate width for non-emoji graphemes // For grapheme clusters (like Devanagari conjuncts with virama+ZWJ), only count // the first non-zero-width character's width since the cluster renders as one glyph for (const char of grapheme) { const codePoint = char.codePointAt(0)! if (!isZeroWidth(codePoint)) { width += eastAsianWidth(codePoint, { ambiguousAsWide: false }) break } } }
return width}
function needsSegmentation(str: string): boolean { for (const char of str) { const cp = char.codePointAt(0)! // Emoji ranges if (cp >= 0x1f300 && cp <= 0x1faff) return true if (cp >= 0x2600 && cp <= 0x27bf) return true if (cp >= 0x1f1e6 && cp <= 0x1f1ff) return true // Variation selectors, ZWJ if (cp >= 0xfe00 && cp <= 0xfe0f) return true if (cp === 0x200d) return true } return false}
function getEmojiWidth(grapheme: string): number { // Regional indicators: single = 1, pair = 2 const first = grapheme.codePointAt(0)! if (first >= 0x1f1e6 && first <= 0x1f1ff) { let count = 0 for (const _ of grapheme) count++ return count === 1 ? 1 : 2 }
// Incomplete keycap: digit/symbol + VS16 without U+20E3 if (grapheme.length === 2) { const second = grapheme.codePointAt(1) if ( second === 0xfe0f && ((first >= 0x30 && first <= 0x39) || first === 0x23 || first === 0x2a) ) { return 1 } }
return 2}
function isZeroWidth(codePoint: number): boolean { // Fast path for common printable range if (codePoint >= 0x20 && codePoint < 0x7f) return false if (codePoint >= 0xa0 && codePoint < 0x0300) return codePoint === 0x00ad
// Control characters if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) return true
// Zero-width and invisible characters if ( (codePoint >= 0x200b && codePoint <= 0x200d) || // ZW space/joiner codePoint === 0xfeff || // BOM (codePoint >= 0x2060 && codePoint <= 0x2064) // Word joiner etc. ) { return true }
// Variation selectors if ( (codePoint >= 0xfe00 && codePoint <= 0xfe0f) || (codePoint >= 0xe0100 && codePoint <= 0xe01ef) ) { return true }
// Combining diacritical marks if ( (codePoint >= 0x0300 && codePoint <= 0x036f) || (codePoint >= 0x1ab0 && codePoint <= 0x1aff) || (codePoint >= 0x1dc0 && codePoint <= 0x1dff) || (codePoint >= 0x20d0 && codePoint <= 0x20ff) || (codePoint >= 0xfe20 && codePoint <= 0xfe2f) ) { return true }
// Indic script combining marks (covers Devanagari through Malayalam) if (codePoint >= 0x0900 && codePoint <= 0x0d4f) { // Signs and vowel marks at start of each script block const offset = codePoint & 0x7f if (offset <= 0x03) return true // Signs at block start if (offset >= 0x3a && offset <= 0x4f) return true // Vowel signs, virama if (offset >= 0x51 && offset <= 0x57) return true // Stress signs if (offset >= 0x62 && offset <= 0x63) return true // Vowel signs }
// Thai/Lao combining marks // Note: U+0E32 (SARA AA), U+0E33 (SARA AM), U+0EB2, U+0EB3 are spacing vowels (width 1), not combining marks if ( codePoint === 0x0e31 || // Thai MAI HAN-AKAT (codePoint >= 0x0e34 && codePoint <= 0x0e3a) || // Thai vowel signs (skip U+0E32, U+0E33) (codePoint >= 0x0e47 && codePoint <= 0x0e4e) || // Thai vowel signs and marks codePoint === 0x0eb1 || // Lao MAI KAN (codePoint >= 0x0eb4 && codePoint <= 0x0ebc) || // Lao vowel signs (skip U+0EB2, U+0EB3) (codePoint >= 0x0ec8 && codePoint <= 0x0ecd) // Lao tone marks ) { return true }
// Arabic formatting if ( (codePoint >= 0x0600 && codePoint <= 0x0605) || codePoint === 0x06dd || codePoint === 0x070f || codePoint === 0x08e2 ) { return true }
// Surrogates, tag characters if (codePoint >= 0xd800 && codePoint <= 0xdfff) return true if (codePoint >= 0xe0000 && codePoint <= 0xe007f) return true
return false}
// Note: complex-script graphemes like Devanagari क्ष (ka+virama+ZWJ+ssa) render// as a single ligature glyph but occupy 2 terminal cells (wcwidth sums the base// consonants). Bun.stringWidth=2 matches terminal cell allocation, which is what// we need for cursor positioning — the JS fallback's grapheme-cluster width of 1// would desync Ink's layout from the terminal.//// Bun.stringWidth is resolved once at module scope rather than checked on every// call — typeof guards deopt property access and this is a hot path (~100k calls/frame).const bunStringWidth = typeof Bun !== 'undefined' && typeof Bun.stringWidth === 'function' ? Bun.stringWidth : null
const BUN_STRING_WIDTH_OPTS = { ambiguousIsNarrow: true } as const
export const stringWidth: (str: string) => number = bunStringWidth ? str => bunStringWidth(str, BUN_STRING_WIDTH_OPTS) : stringWidthJavaScript123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145/** * Utility for substituting $ARGUMENTS placeholders in skill/command prompts. * * Supports: * - $ARGUMENTS - replaced with the full arguments string * - $ARGUMENTS[0], $ARGUMENTS[1], etc. - replaced with individual indexed arguments * - $0, $1, etc. - shorthand for $ARGUMENTS[0], $ARGUMENTS[1] * - Named arguments (e.g., $foo, $bar) - when argument names are defined in frontmatter * * Arguments are parsed using shell-quote for proper shell argument handling. */
import { tryParseShellCommand } from './bash/shellQuote.js'
/** * Parse an arguments string into an array of individual arguments. * Uses shell-quote for proper shell argument parsing including quoted strings. * * Examples: * - "foo bar baz" => ["foo", "bar", "baz"] * - 'foo "hello world" baz' => ["foo", "hello world", "baz"] * - "foo 'hello world' baz" => ["foo", "hello world", "baz"] */export function parseArguments(args: string): string[] { if (!args || !args.trim()) { return [] }
// Return $KEY to preserve variable syntax literally (don't expand variables) const result = tryParseShellCommand(args, key => `$${key}`) if (!result.success) { // Fall back to simple whitespace split if parsing fails return args.split(/\s+/).filter(Boolean) }
// Filter to only string tokens (ignore shell operators, etc.) return result.tokens.filter( (token): token is string => typeof token === 'string', )}
/** * Parse argument names from the frontmatter 'arguments' field. * Accepts either a space-separated string or an array of strings. * * Examples: * - "foo bar baz" => ["foo", "bar", "baz"] * - ["foo", "bar", "baz"] => ["foo", "bar", "baz"] */export function parseArgumentNames( argumentNames: string | string[] | undefined,): string[] { if (!argumentNames) { return [] }
// Filter out empty strings and numeric-only names (which conflict with $0, $1 shorthand) const isValidName = (name: string): boolean => typeof name === 'string' && name.trim() !== '' && !/^\d+$/.test(name)
if (Array.isArray(argumentNames)) { return argumentNames.filter(isValidName) } if (typeof argumentNames === 'string') { return argumentNames.split(/\s+/).filter(isValidName) } return []}
/** * Generate argument hint showing remaining unfilled args. * @param argNames - Array of argument names from frontmatter * @param typedArgs - Arguments the user has typed so far * @returns Hint string like "[arg2] [arg3]" or undefined if all filled */export function generateProgressiveArgumentHint( argNames: string[], typedArgs: string[],): string | undefined { const remaining = argNames.slice(typedArgs.length) if (remaining.length === 0) return undefined return remaining.map(name => `[${name}]`).join(' ')}
/** * Substitute $ARGUMENTS placeholders in content with actual argument values. * * @param content - The content containing placeholders * @param args - The raw arguments string (may be undefined/null) * @param appendIfNoPlaceholder - If true and no placeholders are found, appends "ARGUMENTS: {args}" to content * @param argumentNames - Optional array of named arguments (e.g., ["foo", "bar"]) that map to indexed positions * @returns The content with placeholders substituted */export function substituteArguments( content: string, args: string | undefined, appendIfNoPlaceholder = true, argumentNames: string[] = [],): string { // undefined/null means no args provided - return content unchanged // empty string is a valid input that should replace placeholders with empty if (args === undefined || args === null) { return content }
const parsedArgs = parseArguments(args) const originalContent = content
// Replace named arguments (e.g., $foo, $bar) with their values // Named arguments map to positions: argumentNames[0] -> parsedArgs[0], etc. for (let i = 0; i < argumentNames.length; i++) { const name = argumentNames[i] if (!name) continue
// Match $name but not $name[...] or $nameXxx (word chars) // Also ensure we match word boundaries to avoid partial matches content = content.replace( new RegExp(`\\$${name}(?![\\[\\w])`, 'g'), parsedArgs[i] ?? '', ) }
// Replace indexed arguments ($ARGUMENTS[0], $ARGUMENTS[1], etc.) content = content.replace(/\$ARGUMENTS\[(\d+)\]/g, (_, indexStr: string) => { const index = parseInt(indexStr, 10) return parsedArgs[index] ?? '' })
// Replace shorthand indexed arguments ($0, $1, etc.) content = content.replace(/\$(\d+)(?!\w)/g, (_, indexStr: string) => { const index = parseInt(indexStr, 10) return parsedArgs[index] ?? '' })
// Replace $ARGUMENTS with the full arguments string content = content.replaceAll('$ARGUMENTS', args)
// If no placeholders were found and appendIfNoPlaceholder is true, append // But only if args is non-empty (empty string means command invoked with no args) if (content === originalContent && appendIfNoPlaceholder && args) { content = content + `\n\nARGUMENTS: ${args}` }
return content}12345678910111213export function intersperse<A>(as: A[], separator: (index: number) => A): A[] { return as.flatMap((a, i) => (i ? [separator(i), a] : [a]))}
export function count<T>(arr: readonly T[], pred: (x: T) => unknown): number { let n = 0 for (const x of arr) n += +!!pred(x) return n}
export function uniq<T>(xs: Iterable<T>): T[] { return [...new Set(xs)]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393import { feature } from 'bun:bundle'import { stat } from 'fs/promises'import { getClientType } from '../bootstrap/state.js'import { getRemoteSessionUrl, isRemoteSessionLocal, PRODUCT_URL,} from '../constants/product.js'import { TERMINAL_OUTPUT_TAGS } from '../constants/xml.js'import type { AppState } from '../state/AppState.js'import { FILE_EDIT_TOOL_NAME } from '../tools/FileEditTool/constants.js'import { FILE_READ_TOOL_NAME } from '../tools/FileReadTool/prompt.js'import { FILE_WRITE_TOOL_NAME } from '../tools/FileWriteTool/prompt.js'import { GLOB_TOOL_NAME } from '../tools/GlobTool/prompt.js'import { GREP_TOOL_NAME } from '../tools/GrepTool/prompt.js'import type { Entry } from '../types/logs.js'import { type AttributionData, calculateCommitAttribution, isInternalModelRepo, isInternalModelRepoCached, sanitizeModelName,} from './commitAttribution.js'import { logForDebugging } from './debug.js'import { parseJSONL } from './json.js'import { logError } from './log.js'import { getCanonicalName, getMainLoopModel, getPublicModelDisplayName, getPublicModelName,} from './model/model.js'import { isMemoryFileAccess } from './sessionFileAccessHooks.js'import { getTranscriptPath } from './sessionStorage.js'import { readTranscriptForLoad } from './sessionStoragePortable.js'import { getInitialSettings } from './settings/settings.js'import { isUndercover } from './undercover.js'
export type AttributionTexts = { commit: string pr: string}
/** * Returns attribution text for commits and PRs based on user settings. * Handles: * - Dynamic model name via getPublicModelName() * - Custom attribution settings (settings.attribution.commit/pr) * - Backward compatibility with deprecated includeCoAuthoredBy setting * - Remote mode: returns session URL for attribution */export function getAttributionTexts(): AttributionTexts { if (process.env.USER_TYPE === 'ant' && isUndercover()) { return { commit: '', pr: '' } }
if (getClientType() === 'remote') { const remoteSessionId = process.env.CLAUDE_CODE_REMOTE_SESSION_ID if (remoteSessionId) { const ingressUrl = process.env.SESSION_INGRESS_URL // Skip for local dev - URLs won't persist if (!isRemoteSessionLocal(remoteSessionId, ingressUrl)) { const sessionUrl = getRemoteSessionUrl(remoteSessionId, ingressUrl) return { commit: sessionUrl, pr: sessionUrl } } } return { commit: '', pr: '' } }
// @[MODEL LAUNCH]: Update the hardcoded fallback model name below (guards against codename leaks). // For internal repos, use the real model name. For external repos, // fall back to "Claude Opus 4.6" for unrecognized models to avoid leaking codenames. const model = getMainLoopModel() const isKnownPublicModel = getPublicModelDisplayName(model) !== null const modelName = isInternalModelRepoCached() || isKnownPublicModel ? getPublicModelName(model) : 'Claude Opus 4.6' const defaultAttribution = `🤖 Generated with [Claude Code](${PRODUCT_URL})` const defaultCommit = `Co-Authored-By: ${modelName} <noreply@anthropic.com>`
const settings = getInitialSettings()
// New attribution setting takes precedence over deprecated includeCoAuthoredBy if (settings.attribution) { return { commit: settings.attribution.commit ?? defaultCommit, pr: settings.attribution.pr ?? defaultAttribution, } }
// Backward compatibility: deprecated includeCoAuthoredBy setting if (settings.includeCoAuthoredBy === false) { return { commit: '', pr: '' } }
return { commit: defaultCommit, pr: defaultAttribution }}
/** * Check if a message content string is terminal output rather than a user prompt. * Terminal output includes bash input/output tags and caveat messages about local commands. */function isTerminalOutput(content: string): boolean { for (const tag of TERMINAL_OUTPUT_TAGS) { if (content.includes(`<${tag}>`)) { return true } } return false}
/** * Count user messages with visible text content in a list of non-sidechain messages. * Excludes tool_result blocks, terminal output, and empty messages. * * Callers should pass messages already filtered to exclude sidechain messages. */export function countUserPromptsInMessages( messages: ReadonlyArray<{ type: string; message?: { content?: unknown } }>,): number { let count = 0
for (const message of messages) { if (message.type !== 'user') { continue }
const content = message.message?.content if (!content) { continue }
let hasUserText = false
if (typeof content === 'string') { if (isTerminalOutput(content)) { continue } hasUserText = content.trim().length > 0 } else if (Array.isArray(content)) { hasUserText = content.some(block => { if (!block || typeof block !== 'object' || !('type' in block)) { return false } return ( (block.type === 'text' && typeof block.text === 'string' && !isTerminalOutput(block.text)) || block.type === 'image' || block.type === 'document' ) }) }
if (hasUserText) { count++ } }
return count}
/** * Count non-sidechain user messages in transcript entries. * Used to calculate the number of "steers" (user prompts - 1). * * Counts user messages that contain actual user-typed text, * excluding tool_result blocks, sidechain messages, and terminal output. */function countUserPromptsFromEntries(entries: ReadonlyArray<Entry>): number { const nonSidechain = entries.filter( entry => entry.type === 'user' && !('isSidechain' in entry && entry.isSidechain), ) return countUserPromptsInMessages(nonSidechain)}
/** * Get full attribution data from the provided AppState's attribution state. * Uses ALL tracked files from the attribution state (not just staged files) * because for PR attribution, files may not be staged yet. * Returns null if no attribution data is available. */async function getPRAttributionData( appState: AppState,): Promise<AttributionData | null> { const attribution = appState.attribution
if (!attribution) { return null }
// Handle both Map and plain object (in case of serialization) const fileStates = attribution.fileStates const isMap = fileStates instanceof Map const trackedFiles = isMap ? Array.from(fileStates.keys()) : Object.keys(fileStates)
if (trackedFiles.length === 0) { return null }
try { return await calculateCommitAttribution([attribution], trackedFiles) } catch (error) { logError(error as Error) return null }}
const MEMORY_ACCESS_TOOL_NAMES = new Set([ FILE_READ_TOOL_NAME, GREP_TOOL_NAME, GLOB_TOOL_NAME, FILE_EDIT_TOOL_NAME, FILE_WRITE_TOOL_NAME,])
/** * Count memory file accesses in transcript entries. * Uses the same detection conditions as the PostToolUse session file access hooks. */function countMemoryFileAccessFromEntries( entries: ReadonlyArray<Entry>,): number { let count = 0 for (const entry of entries) { if (entry.type !== 'assistant') continue const content = entry.message?.content if (!Array.isArray(content)) continue for (const block of content) { if ( block.type !== 'tool_use' || !MEMORY_ACCESS_TOOL_NAMES.has(block.name) ) continue if (isMemoryFileAccess(block.name, block.input)) count++ } } return count}
/** * Read session transcript entries and compute prompt count and memory access * count. Pre-compact entries are skipped — the N-shot count and memory-access * count should reflect only the current conversation arc, not accumulated * prompts from before a compaction boundary. */async function getTranscriptStats(): Promise<{ promptCount: number memoryAccessCount: number}> { try { const filePath = getTranscriptPath() const fileSize = (await stat(filePath)).size // Fused reader: attr-snap lines (84% of a long session by bytes) are // skipped at the fd level so peak scales with output, not file size. The // one surviving attr-snap at EOF is a no-op for the count functions // (neither checks type === 'attribution-snapshot'). When the last // boundary has preservedSegment the reader returns full (no truncate); // the findLastIndex below still slices to post-boundary. const scan = await readTranscriptForLoad(filePath, fileSize) const buf = scan.postBoundaryBuf const entries = parseJSONL<Entry>(buf) const lastBoundaryIdx = entries.findLastIndex( e => e.type === 'system' && 'subtype' in e && e.subtype === 'compact_boundary', ) const postBoundary = lastBoundaryIdx >= 0 ? entries.slice(lastBoundaryIdx + 1) : entries return { promptCount: countUserPromptsFromEntries(postBoundary), memoryAccessCount: countMemoryFileAccessFromEntries(postBoundary), } } catch { return { promptCount: 0, memoryAccessCount: 0 } }}
/** * Get enhanced PR attribution text with Claude contribution stats. * * Format: "🤖 Generated with Claude Code (93% 3-shotted by claude-opus-4-5)" * * Rules: * - Shows Claude contribution percentage from commit attribution * - Shows N-shotted where N is the prompt count (1-shotted, 2-shotted, etc.) * - Shows short model name (e.g., claude-opus-4-5) * - Returns default attribution if stats can't be computed * * @param getAppState Function to get the current AppState (from command context) */export async function getEnhancedPRAttribution( getAppState: () => AppState,): Promise<string> { if (process.env.USER_TYPE === 'ant' && isUndercover()) { return '' }
if (getClientType() === 'remote') { const remoteSessionId = process.env.CLAUDE_CODE_REMOTE_SESSION_ID if (remoteSessionId) { const ingressUrl = process.env.SESSION_INGRESS_URL // Skip for local dev - URLs won't persist if (!isRemoteSessionLocal(remoteSessionId, ingressUrl)) { return getRemoteSessionUrl(remoteSessionId, ingressUrl) } } return '' }
const settings = getInitialSettings()
// If user has custom PR attribution, use that if (settings.attribution?.pr) { return settings.attribution.pr }
// Backward compatibility: deprecated includeCoAuthoredBy setting if (settings.includeCoAuthoredBy === false) { return '' }
const defaultAttribution = `🤖 Generated with [Claude Code](${PRODUCT_URL})`
// Get AppState first const appState = getAppState()
logForDebugging( `PR Attribution: appState.attribution exists: ${!!appState.attribution}`, ) if (appState.attribution) { const fileStates = appState.attribution.fileStates const isMap = fileStates instanceof Map const fileCount = isMap ? fileStates.size : Object.keys(fileStates).length logForDebugging(`PR Attribution: fileStates count: ${fileCount}`) }
// Get attribution stats (transcript is read once for both prompt count and memory access) const [attributionData, { promptCount, memoryAccessCount }, isInternal] = await Promise.all([ getPRAttributionData(appState), getTranscriptStats(), isInternalModelRepo(), ])
const claudePercent = attributionData?.summary.claudePercent ?? 0
logForDebugging( `PR Attribution: claudePercent: ${claudePercent}, promptCount: ${promptCount}, memoryAccessCount: ${memoryAccessCount}`, )
// Get short model name, sanitized for non-internal repos const rawModelName = getCanonicalName(getMainLoopModel()) const shortModelName = isInternal ? rawModelName : sanitizeModelName(rawModelName)
// If no attribution data, return default if (claudePercent === 0 && promptCount === 0 && memoryAccessCount === 0) { logForDebugging('PR Attribution: returning default (no data)') return defaultAttribution }
// Build the enhanced attribution: "🤖 Generated with Claude Code (93% 3-shotted by claude-opus-4-5, 2 memories recalled)" const memSuffix = memoryAccessCount > 0 ? `, ${memoryAccessCount} ${memoryAccessCount === 1 ? 'memory' : 'memories'} recalled` : '' const summary = `🤖 Generated with [Claude Code](${PRODUCT_URL}) (${claudePercent}% ${promptCount}-shotted by ${shortModelName}${memSuffix})`
// Append trailer lines for squash-merge survival. Only for allowlisted repos // (INTERNAL_MODEL_REPOS) and only in builds with COMMIT_ATTRIBUTION enabled — // attributionTrailer.ts contains excluded strings, so reach it via dynamic // import behind feature(). When the repo is configured with // squash_merge_commit_message=PR_BODY (cli, apps), the PR body becomes the // squash commit body verbatim — trailer lines at the end become proper git // trailers on the squash commit. if (feature('COMMIT_ATTRIBUTION') && isInternal && attributionData) { const { buildPRTrailers } = await import('./attributionTrailer.js') const trailers = buildPRTrailers(attributionData, appState.attribution) const result = `${summary}\n\n${trailers.join('\n')}` logForDebugging(`PR Attribution: returning with trailers: ${result}`) return result }
logForDebugging(`PR Attribution: returning summary: ${summary}`) return summary}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196import { mkdirSync, writeFileSync } from 'fs'import { getApiKeyFromFd, getOauthTokenFromFd, setApiKeyFromFd, setOauthTokenFromFd,} from '../bootstrap/state.js'import { logForDebugging } from './debug.js'import { isEnvTruthy } from './envUtils.js'import { errorMessage, isENOENT } from './errors.js'import { getFsImplementation } from './fsOperations.js'
/** * Well-known token file locations in CCR. The Go environment-manager creates * /home/claude/.claude/remote/ and will (eventually) write these files too. * Until then, this module writes them on successful FD read so subprocesses * spawned inside the CCR container can find the token without inheriting * the FD — which they can't: pipe FDs don't cross tmux/shell boundaries. */const CCR_TOKEN_DIR = '/home/claude/.claude/remote'export const CCR_OAUTH_TOKEN_PATH = `${CCR_TOKEN_DIR}/.oauth_token`export const CCR_API_KEY_PATH = `${CCR_TOKEN_DIR}/.api_key`export const CCR_SESSION_INGRESS_TOKEN_PATH = `${CCR_TOKEN_DIR}/.session_ingress_token`
/** * Best-effort write of the token to a well-known location for subprocess * access. CCR-gated: outside CCR there's no /home/claude/ and no reason to * put a token on disk that the FD was meant to keep off disk. */export function maybePersistTokenForSubprocesses( path: string, token: string, tokenName: string,): void { if (!isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) { return } try { // eslint-disable-next-line custom-rules/no-sync-fs -- one-shot startup write in CCR, caller is sync mkdirSync(CCR_TOKEN_DIR, { recursive: true, mode: 0o700 }) // eslint-disable-next-line custom-rules/no-sync-fs -- one-shot startup write in CCR, caller is sync writeFileSync(path, token, { encoding: 'utf8', mode: 0o600 }) logForDebugging(`Persisted ${tokenName} to ${path} for subprocess access`) } catch (error) { logForDebugging( `Failed to persist ${tokenName} to disk (non-fatal): ${errorMessage(error)}`, { level: 'error' }, ) }}
/** * Fallback read from a well-known file. The path only exists in CCR (env-manager * creates the directory), so file-not-found is the expected outcome everywhere * else — treated as "no fallback", not an error. */export function readTokenFromWellKnownFile( path: string, tokenName: string,): string | null { try { const fsOps = getFsImplementation() // eslint-disable-next-line custom-rules/no-sync-fs -- fallback read for CCR subprocess path, one-shot at startup, caller is sync const token = fsOps.readFileSync(path, { encoding: 'utf8' }).trim() if (!token) { return null } logForDebugging(`Read ${tokenName} from well-known file ${path}`) return token } catch (error) { // ENOENT is the expected outcome outside CCR — stay silent. Anything // else (EACCES from perm misconfig, etc.) is worth surfacing in the // debug log so subprocess auth failures aren't mysterious. if (!isENOENT(error)) { logForDebugging( `Failed to read ${tokenName} from ${path}: ${errorMessage(error)}`, { level: 'debug' }, ) } return null }}
/** * Shared FD-or-well-known-file credential reader. * * Priority order: * 1. File descriptor (legacy path) — env var points at a pipe FD passed by * the Go env-manager via cmd.ExtraFiles. Pipe is drained on first read * and doesn't cross exec/tmux boundaries. * 2. Well-known file — written by this function on successful FD read (and * eventually by the env-manager directly). Covers subprocesses that can't * inherit the FD. * * Returns null if neither source has a credential. Cached in global state. */function getCredentialFromFd({ envVar, wellKnownPath, label, getCached, setCached,}: { envVar: string wellKnownPath: string label: string getCached: () => string | null | undefined setCached: (value: string | null) => void}): string | null { const cached = getCached() if (cached !== undefined) { return cached }
const fdEnv = process.env[envVar] if (!fdEnv) { // No FD env var — either we're not in CCR, or we're a subprocess whose // parent stripped the (useless) FD env var. Try the well-known file. const fromFile = readTokenFromWellKnownFile(wellKnownPath, label) setCached(fromFile) return fromFile }
const fd = parseInt(fdEnv, 10) if (Number.isNaN(fd)) { logForDebugging( `${envVar} must be a valid file descriptor number, got: ${fdEnv}`, { level: 'error' }, ) setCached(null) return null }
try { // Use /dev/fd on macOS/BSD, /proc/self/fd on Linux const fsOps = getFsImplementation() const fdPath = process.platform === 'darwin' || process.platform === 'freebsd' ? `/dev/fd/${fd}` : `/proc/self/fd/${fd}`
// eslint-disable-next-line custom-rules/no-sync-fs -- legacy FD path, read once at startup, caller is sync const token = fsOps.readFileSync(fdPath, { encoding: 'utf8' }).trim() if (!token) { logForDebugging(`File descriptor contained empty ${label}`, { level: 'error', }) setCached(null) return null } logForDebugging(`Successfully read ${label} from file descriptor ${fd}`) setCached(token) maybePersistTokenForSubprocesses(wellKnownPath, token, label) return token } catch (error) { logForDebugging( `Failed to read ${label} from file descriptor ${fd}: ${errorMessage(error)}`, { level: 'error' }, ) // FD env var was set but read failed — typically a subprocess that // inherited the env var but not the FD (ENXIO). Try the well-known file. const fromFile = readTokenFromWellKnownFile(wellKnownPath, label) setCached(fromFile) return fromFile }}
/** * Get the CCR-injected OAuth token. See getCredentialFromFd for FD-vs-disk * rationale. Env var: CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR. * Well-known file: /home/claude/.claude/remote/.oauth_token. */export function getOAuthTokenFromFileDescriptor(): string | null { return getCredentialFromFd({ envVar: 'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR', wellKnownPath: CCR_OAUTH_TOKEN_PATH, label: 'OAuth token', getCached: getOauthTokenFromFd, setCached: setOauthTokenFromFd, })}
/** * Get the CCR-injected API key. See getCredentialFromFd for FD-vs-disk * rationale. Env var: CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR. * Well-known file: /home/claude/.claude/remote/.api_key. */export function getApiKeyFromFileDescriptor(): string | null { return getCredentialFromFd({ envVar: 'CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR', wellKnownPath: CCR_API_KEY_PATH, label: 'API key', getCached: getApiKeyFromFd, setCached: setApiKeyFromFd, })}1234567891011121314151617181920212223242526/** * Tracks commands recently denied by the auto mode classifier. * Populated from useCanUseTool.ts, read from RecentDenialsTab.tsx in /permissions. */
import { feature } from 'bun:bundle'
export type AutoModeDenial = { toolName: string /** Human-readable description of the denied command (e.g. bash command string) */ display: string reason: string timestamp: number}
let DENIALS: readonly AutoModeDenial[] = []const MAX_DENIALS = 20
export function recordAutoModeDenial(denial: AutoModeDenial): void { if (!feature('TRANSCRIPT_CLASSIFIER')) return DENIALS = [denial, ...DENIALS.slice(0, MAX_DENIALS - 1)]}
export function getAutoModeDenials(): readonly AutoModeDenial[] { return DENIALS}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561import axios from 'axios'import { constants as fsConstants } from 'fs'import { access, writeFile } from 'fs/promises'import { homedir } from 'os'import { join } from 'path'import { getDynamicConfig_BLOCKS_ON_INIT } from 'src/services/analytics/growthbook.js'import { type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, logEvent,} from 'src/services/analytics/index.js'import { type ReleaseChannel, saveGlobalConfig } from './config.js'import { logForDebugging } from './debug.js'import { env } from './env.js'import { getClaudeConfigHomeDir } from './envUtils.js'import { ClaudeError, getErrnoCode, isENOENT } from './errors.js'import { execFileNoThrowWithCwd } from './execFileNoThrow.js'import { getFsImplementation } from './fsOperations.js'import { gracefulShutdownSync } from './gracefulShutdown.js'import { logError } from './log.js'import { gte, lt } from './semver.js'import { getInitialSettings } from './settings/settings.js'import { filterClaudeAliases, getShellConfigPaths, readFileLines, writeFileLines,} from './shellConfig.js'import { jsonParse } from './slowOperations.js'
const GCS_BUCKET_URL = 'https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases'
class AutoUpdaterError extends ClaudeError {}
export type InstallStatus = | 'success' | 'no_permissions' | 'install_failed' | 'in_progress'
export type AutoUpdaterResult = { version: string | null status: InstallStatus notifications?: string[]}
export type MaxVersionConfig = { external?: string ant?: string external_message?: string ant_message?: string}
/** * Checks if the current version meets the minimum required version from Statsig config * Terminates the process with an error message if the version is too old * * NOTE ON SHA-BASED VERSIONING: * We use SemVer-compliant versioning with build metadata format (X.X.X+SHA) for continuous deployment. * According to SemVer specs, build metadata (the +SHA part) is ignored when comparing versions. * * Versioning approach: * 1. For version requirements/compatibility (assertMinVersion), we use semver comparison that ignores build metadata * 2. For updates ('claude update'), we use exact string comparison to detect any change, including SHA * - This ensures users always get the latest build, even when only the SHA changes * - The UI clearly shows both versions including build metadata * * This approach keeps version comparison logic simple while maintaining traceability via the SHA. */export async function assertMinVersion(): Promise<void> { if (process.env.NODE_ENV === 'test') { return }
try { const versionConfig = await getDynamicConfig_BLOCKS_ON_INIT<{ minVersion: string }>('tengu_version_config', { minVersion: '0.0.0' })
if ( versionConfig.minVersion && lt(MACRO.VERSION, versionConfig.minVersion) ) { // biome-ignore lint/suspicious/noConsole:: intentional console output console.error(`It looks like your version of Claude Code (${MACRO.VERSION}) needs an update.A newer version (${versionConfig.minVersion} or higher) is required to continue.
To update, please run: claude update
This will ensure you have access to the latest features and improvements.`) gracefulShutdownSync(1) } } catch (error) { logError(error as Error) }}
/** * Returns the maximum allowed version for the current user type. * For ants, returns the `ant` field (dev version format). * For external users, returns the `external` field (clean semver). * This is used as a server-side kill switch to pause auto-updates during incidents. * Returns undefined if no cap is configured. */export async function getMaxVersion(): Promise<string | undefined> { const config = await getMaxVersionConfig() if (process.env.USER_TYPE === 'ant') { return config.ant || undefined } return config.external || undefined}
/** * Returns the server-driven message explaining the known issue, if configured. * Shown in the warning banner when the current version exceeds the max allowed version. */export async function getMaxVersionMessage(): Promise<string | undefined> { const config = await getMaxVersionConfig() if (process.env.USER_TYPE === 'ant') { return config.ant_message || undefined } return config.external_message || undefined}
async function getMaxVersionConfig(): Promise<MaxVersionConfig> { try { return await getDynamicConfig_BLOCKS_ON_INIT<MaxVersionConfig>( 'tengu_max_version_config', {}, ) } catch (error) { logError(error as Error) return {} }}
/** * Checks if a target version should be skipped due to user's minimumVersion setting. * This is used when switching to stable channel - the user can choose to stay on their * current version until stable catches up, preventing downgrades. */export function shouldSkipVersion(targetVersion: string): boolean { const settings = getInitialSettings() const minimumVersion = settings?.minimumVersion if (!minimumVersion) { return false } // Skip if target version is less than minimum const shouldSkip = !gte(targetVersion, minimumVersion) if (shouldSkip) { logForDebugging( `Skipping update to ${targetVersion} - below minimumVersion ${minimumVersion}`, ) } return shouldSkip}
// Lock file for auto-updater to prevent concurrent updatesconst LOCK_TIMEOUT_MS = 5 * 60 * 1000 // 5 minute timeout for locks
/** * Get the path to the lock file * This is a function to ensure it's evaluated at runtime after test setup */export function getLockFilePath(): string { return join(getClaudeConfigHomeDir(), '.update.lock')}
/** * Attempts to acquire a lock for auto-updater * @returns true if lock was acquired, false if another process holds the lock */async function acquireLock(): Promise<boolean> { const fs = getFsImplementation() const lockPath = getLockFilePath()
// Check for existing lock: 1 stat() on the happy path (fresh lock or ENOENT), // 2 on stale-lock recovery (re-verify staleness immediately before unlink). try { const stats = await fs.stat(lockPath) const age = Date.now() - stats.mtimeMs if (age < LOCK_TIMEOUT_MS) { return false } // Lock is stale, remove it before taking over. Re-verify staleness // immediately before unlinking to close a TOCTOU race: if two processes // both observe the stale lock, A unlinks + writes a fresh lock, then B // would unlink A's fresh lock and both believe they hold it. A fresh // lock has a recent mtime, so re-checking staleness makes B back off. try { const recheck = await fs.stat(lockPath) if (Date.now() - recheck.mtimeMs < LOCK_TIMEOUT_MS) { return false } await fs.unlink(lockPath) } catch (err) { if (!isENOENT(err)) { logError(err as Error) return false } } } catch (err) { if (!isENOENT(err)) { logError(err as Error) return false } // ENOENT: no lock file, proceed to create one }
// Create lock file atomically with O_EXCL (flag: 'wx'). If another process // wins the race and creates it first, we get EEXIST and back off. // Lazy-mkdir the config dir on ENOENT. try { await writeFile(lockPath, `${process.pid}`, { encoding: 'utf8', flag: 'wx', }) return true } catch (err) { const code = getErrnoCode(err) if (code === 'EEXIST') { return false } if (code === 'ENOENT') { try { // fs.mkdir from getFsImplementation() is always recursive:true and // swallows EEXIST internally, so a dir-creation race cannot reach the // catch below — only writeFile's EEXIST (true lock contention) can. await fs.mkdir(getClaudeConfigHomeDir()) await writeFile(lockPath, `${process.pid}`, { encoding: 'utf8', flag: 'wx', }) return true } catch (mkdirErr) { if (getErrnoCode(mkdirErr) === 'EEXIST') { return false } logError(mkdirErr as Error) return false } } logError(err as Error) return false }}
/** * Releases the update lock if it's held by this process */async function releaseLock(): Promise<void> { const fs = getFsImplementation() const lockPath = getLockFilePath() try { const lockData = await fs.readFile(lockPath, { encoding: 'utf8' }) if (lockData === `${process.pid}`) { await fs.unlink(lockPath) } } catch (err) { if (isENOENT(err)) { return } logError(err as Error) }}
async function getInstallationPrefix(): Promise<string | null> { // Run from home directory to avoid reading project-level .npmrc/.bunfig.toml const isBun = env.isRunningWithBun() let prefixResult = null if (isBun) { prefixResult = await execFileNoThrowWithCwd('bun', ['pm', 'bin', '-g'], { cwd: homedir(), }) } else { prefixResult = await execFileNoThrowWithCwd( 'npm', ['-g', 'config', 'get', 'prefix'], { cwd: homedir() }, ) } if (prefixResult.code !== 0) { logError(new Error(`Failed to check ${isBun ? 'bun' : 'npm'} permissions`)) return null } return prefixResult.stdout.trim()}
export async function checkGlobalInstallPermissions(): Promise<{ hasPermissions: boolean npmPrefix: string | null}> { try { const prefix = await getInstallationPrefix() if (!prefix) { return { hasPermissions: false, npmPrefix: null } }
try { await access(prefix, fsConstants.W_OK) return { hasPermissions: true, npmPrefix: prefix } } catch { logError( new AutoUpdaterError( 'Insufficient permissions for global npm install.', ), ) return { hasPermissions: false, npmPrefix: prefix } } } catch (error) { logError(error as Error) return { hasPermissions: false, npmPrefix: null } }}
export async function getLatestVersion( channel: ReleaseChannel,): Promise<string | null> { const npmTag = channel === 'stable' ? 'stable' : 'latest'
// Run from home directory to avoid reading project-level .npmrc // which could be maliciously crafted to redirect to an attacker's registry const result = await execFileNoThrowWithCwd( 'npm', ['view', `${MACRO.PACKAGE_URL}@${npmTag}`, 'version', '--prefer-online'], { abortSignal: AbortSignal.timeout(5000), cwd: homedir() }, ) if (result.code !== 0) { logForDebugging(`npm view failed with code ${result.code}`) if (result.stderr) { logForDebugging(`npm stderr: ${result.stderr.trim()}`) } else { logForDebugging('npm stderr: (empty)') } if (result.stdout) { logForDebugging(`npm stdout: ${result.stdout.trim()}`) } return null } return result.stdout.trim()}
export type NpmDistTags = { latest: string | null stable: string | null}
/** * Get npm dist-tags (latest and stable versions) from the registry. * This is used by the doctor command to show users what versions are available. */export async function getNpmDistTags(): Promise<NpmDistTags> { // Run from home directory to avoid reading project-level .npmrc const result = await execFileNoThrowWithCwd( 'npm', ['view', MACRO.PACKAGE_URL, 'dist-tags', '--json', '--prefer-online'], { abortSignal: AbortSignal.timeout(5000), cwd: homedir() }, )
if (result.code !== 0) { logForDebugging(`npm view dist-tags failed with code ${result.code}`) return { latest: null, stable: null } }
try { const parsed = jsonParse(result.stdout.trim()) as Record<string, unknown> return { latest: typeof parsed.latest === 'string' ? parsed.latest : null, stable: typeof parsed.stable === 'string' ? parsed.stable : null, } } catch (error) { logForDebugging(`Failed to parse dist-tags: ${error}`) return { latest: null, stable: null } }}
/** * Get the latest version from GCS bucket for a given release channel. * This is used by installations that don't have npm (e.g. package manager installs). */export async function getLatestVersionFromGcs( channel: ReleaseChannel,): Promise<string | null> { try { const response = await axios.get(`${GCS_BUCKET_URL}/${channel}`, { timeout: 5000, responseType: 'text', }) return response.data.trim() } catch (error) { logForDebugging(`Failed to fetch ${channel} from GCS: ${error}`) return null }}
/** * Get available versions from GCS bucket (for native installations). * Fetches both latest and stable channel pointers. */export async function getGcsDistTags(): Promise<NpmDistTags> { const [latest, stable] = await Promise.all([ getLatestVersionFromGcs('latest'), getLatestVersionFromGcs('stable'), ])
return { latest, stable }}
/** * Get version history from npm registry (ant-only feature) * Returns versions sorted newest-first, limited to the specified count * * Uses NATIVE_PACKAGE_URL when available because: * 1. Native installation is the primary installation method for ant users * 2. Not all JS package versions have corresponding native packages * 3. This prevents rollback from listing versions that don't have native binaries */export async function getVersionHistory(limit: number): Promise<string[]> { if (process.env.USER_TYPE !== 'ant') { return [] }
// Use native package URL when available to ensure we only show versions // that have native binaries (not all JS package versions have native builds) const packageUrl = MACRO.NATIVE_PACKAGE_URL ?? MACRO.PACKAGE_URL
// Run from home directory to avoid reading project-level .npmrc const result = await execFileNoThrowWithCwd( 'npm', ['view', packageUrl, 'versions', '--json', '--prefer-online'], // Longer timeout for version list { abortSignal: AbortSignal.timeout(30000), cwd: homedir() }, )
if (result.code !== 0) { logForDebugging(`npm view versions failed with code ${result.code}`) if (result.stderr) { logForDebugging(`npm stderr: ${result.stderr.trim()}`) } return [] }
try { const versions = jsonParse(result.stdout.trim()) as string[] // Take last N versions, then reverse to get newest first return versions.slice(-limit).reverse() } catch (error) { logForDebugging(`Failed to parse version history: ${error}`) return [] }}
export async function installGlobalPackage( specificVersion?: string | null,): Promise<InstallStatus> { if (!(await acquireLock())) { logError( new AutoUpdaterError('Another process is currently installing an update'), ) // Log the lock contention logEvent('tengu_auto_updater_lock_contention', { pid: process.pid, currentVersion: MACRO.VERSION as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, }) return 'in_progress' }
try { await removeClaudeAliasesFromShellConfigs() // Check if we're using npm from Windows path in WSL if (!env.isRunningWithBun() && env.isNpmFromWindowsPath()) { logError(new Error('Windows NPM detected in WSL environment')) logEvent('tengu_auto_updater_windows_npm_in_wsl', { currentVersion: MACRO.VERSION as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, }) // biome-ignore lint/suspicious/noConsole:: intentional console output console.error(`Error: Windows NPM detected in WSL
You're running Claude Code in WSL but using the Windows NPM installation from /mnt/c/.This configuration is not supported for updates.
To fix this issue: 1. Install Node.js within your Linux distribution: e.g. sudo apt install nodejs npm 2. Make sure Linux NPM is in your PATH before the Windows version 3. Try updating again with 'claude update'`) return 'install_failed' }
const { hasPermissions } = await checkGlobalInstallPermissions() if (!hasPermissions) { return 'no_permissions' }
// Use specific version if provided, otherwise use latest const packageSpec = specificVersion ? `${MACRO.PACKAGE_URL}@${specificVersion}` : MACRO.PACKAGE_URL
// Run from home directory to avoid reading project-level .npmrc/.bunfig.toml // which could be maliciously crafted to redirect to an attacker's registry const packageManager = env.isRunningWithBun() ? 'bun' : 'npm' const installResult = await execFileNoThrowWithCwd( packageManager, ['install', '-g', packageSpec], { cwd: homedir() }, ) if (installResult.code !== 0) { const error = new AutoUpdaterError( `Failed to install new version of claude: ${installResult.stdout} ${installResult.stderr}`, ) logError(error) return 'install_failed' }
// Set installMethod to 'global' to track npm global installations saveGlobalConfig(current => ({ ...current, installMethod: 'global', }))
return 'success' } finally { // Ensure we always release the lock await releaseLock() }}
/** * Remove claude aliases from shell configuration files * This helps clean up old installation methods when switching to native or npm global */async function removeClaudeAliasesFromShellConfigs(): Promise<void> { const configMap = getShellConfigPaths()
// Process each shell config file for (const [, configFile] of Object.entries(configMap)) { try { const lines = await readFileLines(configFile) if (!lines) continue
const { filtered, hadAlias } = filterClaudeAliases(lines)
if (hadAlias) { await writeFileLines(configFile, filtered) logForDebugging(`Removed claude alias from ${configFile}`) } } catch (error) { // Don't fail the whole operation if one file can't be processed logForDebugging(`Failed to remove alias from ${configFile}: ${error}`, { level: 'error', }) } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import { logForDebugging } from './debug.js'
/** AWS short-term credentials format. */export type AwsCredentials = { AccessKeyId: string SecretAccessKey: string SessionToken: string Expiration?: string}
/** Output from `aws sts get-session-token` or `aws sts assume-role`. */export type AwsStsOutput = { Credentials: AwsCredentials}
type AwsError = { name: string}
export function isAwsCredentialsProviderError(err: unknown) { return (err as AwsError | undefined)?.name === 'CredentialsProviderError'}
/** Typeguard to validate AWS STS assume-role output */export function isValidAwsStsOutput(obj: unknown): obj is AwsStsOutput { if (!obj || typeof obj !== 'object') { return false }
const output = obj as Record<string, unknown>
// Check if Credentials exists and has required fields if (!output.Credentials || typeof output.Credentials !== 'object') { return false }
const credentials = output.Credentials as Record<string, unknown>
return ( typeof credentials.AccessKeyId === 'string' && typeof credentials.SecretAccessKey === 'string' && typeof credentials.SessionToken === 'string' && credentials.AccessKeyId.length > 0 && credentials.SecretAccessKey.length > 0 && credentials.SessionToken.length > 0 )}
/** Throws if STS caller identity cannot be retrieved. */export async function checkStsCallerIdentity(): Promise<void> { const { STSClient, GetCallerIdentityCommand } = await import( '@aws-sdk/client-sts' ) await new STSClient().send(new GetCallerIdentityCommand({}))}
/** * Clear AWS credential provider cache by forcing a refresh * This ensures that any changes to ~/.aws/credentials are picked up immediately */export async function clearAwsIniCache(): Promise<void> { try { logForDebugging('Clearing AWS credential provider cache') const { fromIni } = await import('@aws-sdk/credential-providers') const iniProvider = fromIni({ ignoreCache: true }) await iniProvider() // This updates the global file cache logForDebugging('AWS credential provider cache refreshed') } catch (_error) { // Ignore errors - we're just clearing the cache logForDebugging( 'Failed to clear AWS credential cache (this is expected if no credentials are configured)', ) }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import { feature } from 'bun:bundle'import { initAutoDream } from '../services/autoDream/autoDream.js'import { initMagicDocs } from '../services/MagicDocs/magicDocs.js'import { initSkillImprovement } from './hooks/skillImprovement.js'
/* eslint-disable @typescript-eslint/no-require-imports */const extractMemoriesModule = feature('EXTRACT_MEMORIES') ? (require('../services/extractMemories/extractMemories.js') as typeof import('../services/extractMemories/extractMemories.js')) : nullconst registerProtocolModule = feature('LODESTONE') ? (require('./deepLink/registerProtocol.js') as typeof import('./deepLink/registerProtocol.js')) : null
/* eslint-enable @typescript-eslint/no-require-imports */
import { getIsInteractive, getLastInteractionTime } from '../bootstrap/state.js'import { cleanupNpmCacheForAnthropicPackages, cleanupOldMessageFilesInBackground, cleanupOldVersionsThrottled,} from './cleanup.js'import { cleanupOldVersions } from './nativeInstaller/index.js'import { autoUpdateMarketplacesAndPluginsInBackground } from './plugins/pluginAutoupdate.js'
// 24 hours in millisecondsconst RECURRING_CLEANUP_INTERVAL_MS = 24 * 60 * 60 * 1000
// 10 minutes after start.const DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION = 10 * 60 * 1000
export function startBackgroundHousekeeping(): void { void initMagicDocs() void initSkillImprovement() if (feature('EXTRACT_MEMORIES')) { extractMemoriesModule!.initExtractMemories() } initAutoDream() void autoUpdateMarketplacesAndPluginsInBackground() if (feature('LODESTONE') && getIsInteractive()) { void registerProtocolModule!.ensureDeepLinkProtocolRegistered() }
let needsCleanup = true async function runVerySlowOps(): Promise<void> { // If the user did something in the last minute, don't make them wait for these slow operations to run. if ( getIsInteractive() && getLastInteractionTime() > Date.now() - 1000 * 60 ) { setTimeout( runVerySlowOps, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION, ).unref() return }
if (needsCleanup) { needsCleanup = false await cleanupOldMessageFilesInBackground() }
// If the user did something in the last minute, don't make them wait for these slow operations to run. if ( getIsInteractive() && getLastInteractionTime() > Date.now() - 1000 * 60 ) { setTimeout( runVerySlowOps, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION, ).unref() return }
await cleanupOldVersions() }
setTimeout( runVerySlowOps, DELAY_VERY_SLOW_OPERATIONS_THAT_HAPPEN_EVERY_SESSION, ).unref()
// For long-running sessions, schedule recurring cleanup every 24 hours. // Both cleanup functions use marker files and locks to throttle to once per day // and skip immediately if another process holds the lock. if (process.env.USER_TYPE === 'ant') { const interval = setInterval(() => { void cleanupNpmCacheForAnthropicPackages() void cleanupOldVersionsThrottled() }, RECURRING_CLEANUP_INTERVAL_MS)
// Don't let this interval keep the process alive interval.unref() }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import { getAnthropicApiKey, getAuthTokenSource, getSubscriptionType, isClaudeAISubscriber,} from './auth.js'import { getGlobalConfig } from './config.js'import { isEnvTruthy } from './envUtils.js'
export function hasConsoleBillingAccess(): boolean { // Check if cost reporting is disabled via environment variable if (isEnvTruthy(process.env.DISABLE_COST_WARNINGS)) { return false }
const isSubscriber = isClaudeAISubscriber()
// This might be wrong if user is signed into Max but also using an API key, but // we already show a warning on launch in that case if (isSubscriber) return false
// Check if user has any form of authentication const authSource = getAuthTokenSource() const hasApiKey = getAnthropicApiKey() !== null
// If user has no authentication at all (logged out), don't show costs if (!authSource.hasToken && !hasApiKey) { return false }
const config = getGlobalConfig() const orgRole = config.oauthAccount?.organizationRole const workspaceRole = config.oauthAccount?.workspaceRole
if (!orgRole || !workspaceRole) { return false // hide cost for grandfathered users who have not re-authed since we've added roles }
// Users have billing access if they are admins or billing roles at either workspace or organization level return ( ['admin', 'billing'].includes(orgRole) || ['workspace_admin', 'workspace_billing'].includes(workspaceRole) )}
// Mock billing access for /mock-limits testing (set by mockRateLimits.ts)let mockBillingAccessOverride: boolean | null = null
export function setMockBillingAccessOverride(value: boolean | null): void { mockBillingAccessOverride = value}
export function hasClaudeAiBillingAccess(): boolean { // Check for mock billing access first (for /mock-limits testing) if (mockBillingAccessOverride !== null) { return mockBillingAccessOverride }
if (!isClaudeAISubscriber()) { return false }
const subscriptionType = getSubscriptionType()
// Consumer plans (Max/Pro) - individual users always have billing access if (subscriptionType === 'max' || subscriptionType === 'pro') { return true }
// Team/Enterprise - check for admin or billing roles const config = getGlobalConfig() const orgRole = config.oauthAccount?.organizationRole
return ( !!orgRole && ['admin', 'billing', 'owner', 'primary_owner'].includes(orgRole) )}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import { logForDebugging } from './debug.js'import { which } from './which.js'
// Session cache to avoid repeated checksconst binaryCache = new Map<string, boolean>()
/** * Check if a binary/command is installed and available on the system. * Uses 'which' on Unix systems (macOS, Linux, WSL) and 'where' on Windows. * * @param command - The command name to check (e.g., 'gopls', 'rust-analyzer') * @returns Promise<boolean> - true if the command exists, false otherwise */export async function isBinaryInstalled(command: string): Promise<boolean> { // Edge case: empty or whitespace-only command if (!command || !command.trim()) { logForDebugging('[binaryCheck] Empty command provided, returning false') return false }
// Trim the command to handle whitespace const trimmedCommand = command.trim()
// Check cache first const cached = binaryCache.get(trimmedCommand) if (cached !== undefined) { logForDebugging( `[binaryCheck] Cache hit for '${trimmedCommand}': ${cached}`, ) return cached }
let exists = false if (await which(trimmedCommand).catch(() => null)) { exists = true }
// Cache the result binaryCache.set(trimmedCommand, exists)
logForDebugging( `[binaryCheck] Binary '${trimmedCommand}' ${exists ? 'found' : 'not found'}`, )
return exists}
/** * Clear the binary check cache (useful for testing) */export function clearBinaryCache(): void { binaryCache.clear()}12345678910111213141516171819202122/** * Detects if the current runtime is Bun. * Returns true when: * - Running a JS file via the `bun` command * - Running a Bun-compiled standalone executable */export function isRunningWithBun(): boolean { // https://bun.com/guides/util/detect-bun return process.versions.bun !== undefined}
/** * Detects if running as a Bun-compiled standalone executable. * This checks for embedded files which are present in compiled binaries. */export function isInBundledMode(): boolean { return ( typeof Bun !== 'undefined' && Array.isArray(Bun.embeddedFiles) && Bun.embeddedFiles.length > 0 )}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import memoize from 'lodash-es/memoize.js'import { logForDebugging } from './debug.js'import { hasNodeOption } from './envUtils.js'import { getFsImplementation } from './fsOperations.js'
/** * Load CA certificates for TLS connections. * * Since setting `ca` on an HTTPS agent replaces the default certificate store, * we must always include base CAs (either system or bundled Mozilla) when returning. * * Returns undefined when no custom CA configuration is needed, allowing the * runtime's default certificate handling to apply. * * Behavior: * - Neither NODE_EXTRA_CA_CERTS nor --use-system-ca/--use-openssl-ca set: undefined (runtime defaults) * - NODE_EXTRA_CA_CERTS only: bundled Mozilla CAs + extra cert file contents * - --use-system-ca or --use-openssl-ca only: system CAs * - --use-system-ca + NODE_EXTRA_CA_CERTS: system CAs + extra cert file contents * * Memoized for performance. Call clearCACertsCache() to invalidate after * environment variable changes (e.g., after trust dialog applies settings.json). * * Reads ONLY `process.env.NODE_EXTRA_CA_CERTS`. `caCertsConfig.ts` populates * that env var from settings.json at CLI init; this module stays config-free * so `proxy.ts`/`mtls.ts` don't transitively pull in the command registry. */export const getCACertificates = memoize((): string[] | undefined => { const useSystemCA = hasNodeOption('--use-system-ca') || hasNodeOption('--use-openssl-ca')
const extraCertsPath = process.env.NODE_EXTRA_CA_CERTS
logForDebugging( `CA certs: useSystemCA=${useSystemCA}, extraCertsPath=${extraCertsPath}`, )
// If neither is set, return undefined (use runtime defaults, no override) if (!useSystemCA && !extraCertsPath) { return undefined }
// Deferred load: Bun's node:tls module eagerly materializes ~150 Mozilla // root certificates (~750KB heap) on import, even if tls.rootCertificates // is never accessed. Most users hit the early return above, so we only // pay this cost when custom CA handling is actually needed. /* eslint-disable @typescript-eslint/no-require-imports */ const tls = require('tls') as typeof import('tls') /* eslint-enable @typescript-eslint/no-require-imports */
const certs: string[] = []
if (useSystemCA) { // Load system CA store (Bun API) const getCACerts = ( tls as typeof tls & { getCACertificates?: (type: string) => string[] } ).getCACertificates const systemCAs = getCACerts?.('system') if (systemCAs && systemCAs.length > 0) { certs.push(...systemCAs) logForDebugging( `CA certs: Loaded ${certs.length} system CA certificates (--use-system-ca)`, ) } else if (!getCACerts && !extraCertsPath) { // Under Node.js where getCACertificates doesn't exist and no extra certs, // return undefined to let Node.js handle --use-system-ca natively. logForDebugging( 'CA certs: --use-system-ca set but system CA API unavailable, deferring to runtime', ) return undefined } else { // System CA API returned empty or unavailable; fall back to bundled root certs certs.push(...tls.rootCertificates) logForDebugging( `CA certs: Loaded ${certs.length} bundled root certificates as base (--use-system-ca fallback)`, ) } } else { // Must include bundled Mozilla CAs as base since ca replaces defaults certs.push(...tls.rootCertificates) logForDebugging( `CA certs: Loaded ${certs.length} bundled root certificates as base`, ) }
// Append extra certs from file if (extraCertsPath) { try { const extraCert = getFsImplementation().readFileSync(extraCertsPath, { encoding: 'utf8', }) certs.push(extraCert) logForDebugging( `CA certs: Appended extra certificates from NODE_EXTRA_CA_CERTS (${extraCertsPath})`, ) } catch (error) { logForDebugging( `CA certs: Failed to read NODE_EXTRA_CA_CERTS file (${extraCertsPath}): ${error}`, { level: 'error' }, ) } }
return certs.length > 0 ? certs : undefined})
/** * Clear the CA certificates cache. * Call this when environment variables that affect CA certs may have changed * (e.g., NODE_EXTRA_CA_CERTS, NODE_OPTIONS). */export function clearCACertsCache(): void { getCACertificates.cache.clear?.() logForDebugging('Cleared CA certificates cache')}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788/** * Tracks which tool uses were auto-approved by classifiers. * Populated from useCanUseTool.ts and permissions.ts, read from UserToolSuccessMessage.tsx. */
import { feature } from 'bun:bundle'import { createSignal } from './signal.js'
type ClassifierApproval = { classifier: 'bash' | 'auto-mode' matchedRule?: string reason?: string}
const CLASSIFIER_APPROVALS = new Map<string, ClassifierApproval>()const CLASSIFIER_CHECKING = new Set<string>()const classifierChecking = createSignal()
export function setClassifierApproval( toolUseID: string, matchedRule: string,): void { if (!feature('BASH_CLASSIFIER')) { return } CLASSIFIER_APPROVALS.set(toolUseID, { classifier: 'bash', matchedRule, })}
export function getClassifierApproval(toolUseID: string): string | undefined { if (!feature('BASH_CLASSIFIER')) { return undefined } const approval = CLASSIFIER_APPROVALS.get(toolUseID) if (!approval || approval.classifier !== 'bash') return undefined return approval.matchedRule}
export function setYoloClassifierApproval( toolUseID: string, reason: string,): void { if (!feature('TRANSCRIPT_CLASSIFIER')) { return } CLASSIFIER_APPROVALS.set(toolUseID, { classifier: 'auto-mode', reason })}
export function getYoloClassifierApproval( toolUseID: string,): string | undefined { if (!feature('TRANSCRIPT_CLASSIFIER')) { return undefined } const approval = CLASSIFIER_APPROVALS.get(toolUseID) if (!approval || approval.classifier !== 'auto-mode') return undefined return approval.reason}
export function setClassifierChecking(toolUseID: string): void { if (!feature('BASH_CLASSIFIER') && !feature('TRANSCRIPT_CLASSIFIER')) return CLASSIFIER_CHECKING.add(toolUseID) classifierChecking.emit()}
export function clearClassifierChecking(toolUseID: string): void { if (!feature('BASH_CLASSIFIER') && !feature('TRANSCRIPT_CLASSIFIER')) return CLASSIFIER_CHECKING.delete(toolUseID) classifierChecking.emit()}
export const subscribeClassifierChecking = classifierChecking.subscribe
export function isClassifierChecking(toolUseID: string): boolean { return CLASSIFIER_CHECKING.has(toolUseID)}
export function deleteClassifierApproval(toolUseID: string): void { CLASSIFIER_APPROVALS.delete(toolUseID)}
export function clearClassifierApprovals(): void { CLASSIFIER_APPROVALS.clear() CLASSIFIER_CHECKING.clear() classifierChecking.emit()}1234567891011121314151617/** * React hook for classifierApprovals store. * Split from classifierApprovals.ts so pure-state importers (permissions.ts, * toolExecution.ts, postCompactCleanup.ts) do not pull React into print.ts. */
import { useSyncExternalStore } from 'react'import { isClassifierChecking, subscribeClassifierChecking,} from './classifierApprovals.js'
export function useIsClassifierChecking(toolUseID: string): boolean { return useSyncExternalStore(subscribeClassifierChecking, () => isClassifierChecking(toolUseID), )}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479/** * Files are loaded in the following order: * * 1. Managed memory (eg. /etc/claude-code/CLAUDE.md) - Global instructions for all users * 2. User memory (~/.claude/CLAUDE.md) - Private global instructions for all projects * 3. Project memory (CLAUDE.md, .claude/CLAUDE.md, and .claude/rules/*.md in project roots) - Instructions checked into the codebase * 4. Local memory (CLAUDE.local.md in project roots) - Private project-specific instructions * * Files are loaded in reverse order of priority, i.e. the latest files are highest priority * with the model paying more attention to them. * * File discovery: * - User memory is loaded from the user's home directory * - Project and Local files are discovered by traversing from the current directory up to root * - Files closer to the current directory have higher priority (loaded later) * - CLAUDE.md, .claude/CLAUDE.md, and all .md files in .claude/rules/ are checked in each directory for Project memory * * Memory @include directive: * - Memory files can include other files using @ notation * - Syntax: @path, @./relative/path, @~/home/path, or @/absolute/path * - @path (without prefix) is treated as a relative path (same as @./path) * - Works in leaf text nodes only (not inside code blocks or code strings) * - Included files are added as separate entries before the including file * - Circular references are prevented by tracking processed files * - Non-existent files are silently ignored */
import { feature } from 'bun:bundle'import ignore from 'ignore'import memoize from 'lodash-es/memoize.js'import { Lexer } from 'marked'import { basename, dirname, extname, isAbsolute, join, parse, relative, sep,} from 'path'import picomatch from 'picomatch'import { logEvent } from 'src/services/analytics/index.js'import { getAdditionalDirectoriesForClaudeMd, getOriginalCwd,} from '../bootstrap/state.js'import { truncateEntrypointContent } from '../memdir/memdir.js'import { getAutoMemEntrypoint, isAutoMemoryEnabled } from '../memdir/paths.js'import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js'import { getCurrentProjectConfig, getManagedClaudeRulesDir, getMemoryPath, getUserClaudeRulesDir,} from './config.js'import { logForDebugging } from './debug.js'import { logForDiagnosticsNoPII } from './diagLogs.js'import { getClaudeConfigHomeDir, isEnvTruthy } from './envUtils.js'import { getErrnoCode } from './errors.js'import { normalizePathForComparison } from './file.js'import { cacheKeys, type FileStateCache } from './fileStateCache.js'import { parseFrontmatter, splitPathInFrontmatter,} from './frontmatterParser.js'import { getFsImplementation, safeResolvePath } from './fsOperations.js'import { findCanonicalGitRoot, findGitRoot } from './git.js'import { executeInstructionsLoadedHooks, hasInstructionsLoadedHook, type InstructionsLoadReason, type InstructionsMemoryType,} from './hooks.js'import type { MemoryType } from './memory/types.js'import { expandPath } from './path.js'import { pathInWorkingPath } from './permissions/filesystem.js'import { isSettingSourceEnabled } from './settings/constants.js'import { getInitialSettings } from './settings/settings.js'
/* eslint-disable @typescript-eslint/no-require-imports */const teamMemPaths = feature('TEAMMEM') ? (require('../memdir/teamMemPaths.js') as typeof import('../memdir/teamMemPaths.js')) : null/* eslint-enable @typescript-eslint/no-require-imports */
let hasLoggedInitialLoad = false
const MEMORY_INSTRUCTION_PROMPT = 'Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.'// Recommended max character count for a memory fileexport const MAX_MEMORY_CHARACTER_COUNT = 40000
// File extensions that are allowed for @include directives// This prevents binary files (images, PDFs, etc.) from being loaded into memoryconst TEXT_FILE_EXTENSIONS = new Set([ // Markdown and text '.md', '.txt', '.text', // Data formats '.json', '.yaml', '.yml', '.toml', '.xml', '.csv', // Web '.html', '.htm', '.css', '.scss', '.sass', '.less', // JavaScript/TypeScript '.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.mts', '.cts', // Python '.py', '.pyi', '.pyw', // Ruby '.rb', '.erb', '.rake', // Go '.go', // Rust '.rs', // Java/Kotlin/Scala '.java', '.kt', '.kts', '.scala', // C/C++ '.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hxx', // C# '.cs', // Swift '.swift', // Shell '.sh', '.bash', '.zsh', '.fish', '.ps1', '.bat', '.cmd', // Config '.env', '.ini', '.cfg', '.conf', '.config', '.properties', // Database '.sql', '.graphql', '.gql', // Protocol '.proto', // Frontend frameworks '.vue', '.svelte', '.astro', // Templating '.ejs', '.hbs', '.pug', '.jade', // Other languages '.php', '.pl', '.pm', '.lua', '.r', '.R', '.dart', '.ex', '.exs', '.erl', '.hrl', '.clj', '.cljs', '.cljc', '.edn', '.hs', '.lhs', '.elm', '.ml', '.mli', '.f', '.f90', '.f95', '.for', // Build files '.cmake', '.make', '.makefile', '.gradle', '.sbt', // Documentation '.rst', '.adoc', '.asciidoc', '.org', '.tex', '.latex', // Lock files (often text-based) '.lock', // Misc '.log', '.diff', '.patch',])
export type MemoryFileInfo = { path: string type: MemoryType content: string parent?: string // Path of the file that included this one globs?: string[] // Glob patterns for file paths this rule applies to // True when auto-injection transformed `content` (stripped HTML comments, // stripped frontmatter, truncated MEMORY.md) such that it no longer matches // the bytes on disk. When set, `rawContent` holds the unmodified disk bytes // so callers can cache a `isPartialView` readFileState entry — presence in // cache provides dedup + change detection, but Edit/Write still require an // explicit Read before proceeding. contentDiffersFromDisk?: boolean rawContent?: string}
function pathInOriginalCwd(path: string): boolean { return pathInWorkingPath(path, getOriginalCwd())}
/** * Parses raw content to extract both content and glob patterns from frontmatter * @param rawContent Raw file content with frontmatter * @returns Object with content and globs (undefined if no paths or match-all pattern) */function parseFrontmatterPaths(rawContent: string): { content: string paths?: string[]} { const { frontmatter, content } = parseFrontmatter(rawContent)
if (!frontmatter.paths) { return { content } }
const patterns = splitPathInFrontmatter(frontmatter.paths) .map(pattern => { // Remove /** suffix - ignore library treats 'path' as matching both // the path itself and everything inside it return pattern.endsWith('/**') ? pattern.slice(0, -3) : pattern }) .filter((p: string) => p.length > 0)
// If all patterns are ** (match-all), treat as no globs (undefined) // This means the file applies to all paths if (patterns.length === 0 || patterns.every((p: string) => p === '**')) { return { content } }
return { content, paths: patterns }}
/** * Strip block-level HTML comments (<!-- ... -->) from markdown content. * * Uses the marked lexer to identify comments at the block level only, so * comments inside inline code spans and fenced code blocks are preserved. * Inline HTML comments inside a paragraph are also left intact; the intended * use case is authorial notes that occupy their own lines. * * Unclosed comments (`<!--` with no matching `-->`) are left in place so a * typo doesn't silently swallow the rest of the file. */export function stripHtmlComments(content: string): { content: string stripped: boolean} { if (!content.includes('<!--')) { return { content, stripped: false } } // gfm:false is fine here — html-block detection is a CommonMark rule. return stripHtmlCommentsFromTokens(new Lexer({ gfm: false }).lex(content))}
function stripHtmlCommentsFromTokens(tokens: ReturnType<Lexer['lex']>): { content: string stripped: boolean} { let result = '' let stripped = false
// A well-formed HTML comment span. Non-greedy so multiple comments on the // same line are matched independently; [\s\S] to span newlines. const commentSpan = /<!--[\s\S]*?-->/g
for (const token of tokens) { if (token.type === 'html') { const trimmed = token.raw.trimStart() if (trimmed.startsWith('<!--') && trimmed.includes('-->')) { // Per CommonMark, a type-2 HTML block ends at the *line* containing // `-->`, so text after `-->` on that line is part of this token. // Strip only the comment spans and keep any residual content. const residue = token.raw.replace(commentSpan, '') stripped = true if (residue.trim().length > 0) { // Residual content exists (e.g. `<!-- note --> Use bun`): keep it. result += residue } continue } } result += token.raw }
return { content: result, stripped }}
/** * Parses raw memory file content into a MemoryFileInfo. Pure function — no I/O. * * When includeBasePath is given, @include paths are resolved in the same lex * pass and returned alongside the parsed file (so processMemoryFile doesn't * need to lex the same content a second time). */function parseMemoryFileContent( rawContent: string, filePath: string, type: MemoryType, includeBasePath?: string,): { info: MemoryFileInfo | null; includePaths: string[] } { // Skip non-text files to prevent loading binary data (images, PDFs, etc.) into memory const ext = extname(filePath).toLowerCase() if (ext && !TEXT_FILE_EXTENSIONS.has(ext)) { logForDebugging(`Skipping non-text file in @include: ${filePath}`) return { info: null, includePaths: [] } }
const { content: withoutFrontmatter, paths } = parseFrontmatterPaths(rawContent)
// Lex once so strip and @include-extract share the same tokens. gfm:false // is required by extract (so ~/path doesn't tokenize as strikethrough) and // doesn't affect strip (html blocks are a CommonMark rule). const hasComment = withoutFrontmatter.includes('<!--') const tokens = hasComment || includeBasePath !== undefined ? new Lexer({ gfm: false }).lex(withoutFrontmatter) : undefined
// Only rebuild via tokens when a comment actually needs stripping — // marked normalises \r\n during lex, so round-tripping a CRLF file // through token.raw would spuriously flip contentDiffersFromDisk. const strippedContent = hasComment && tokens ? stripHtmlCommentsFromTokens(tokens).content : withoutFrontmatter
const includePaths = tokens && includeBasePath !== undefined ? extractIncludePathsFromTokens(tokens, includeBasePath) : []
// Truncate MEMORY.md entrypoints to the line AND byte caps let finalContent = strippedContent if (type === 'AutoMem' || type === 'TeamMem') { finalContent = truncateEntrypointContent(strippedContent).content }
// Covers frontmatter strip, HTML comment strip, and MEMORY.md truncation const contentDiffersFromDisk = finalContent !== rawContent return { info: { path: filePath, type, content: finalContent, globs: paths, contentDiffersFromDisk, rawContent: contentDiffersFromDisk ? rawContent : undefined, }, includePaths, }}
function handleMemoryFileReadError(error: unknown, filePath: string): void { const code = getErrnoCode(error) // ENOENT = file doesn't exist, EISDIR = is a directory — both expected if (code === 'ENOENT' || code === 'EISDIR') { return } // Log permission errors (EACCES) as they're actionable if (code === 'EACCES') { // Don't log the full file path to avoid PII/security issues logEvent('tengu_claude_md_permission_error', { is_access_error: 1, has_home_dir: filePath.includes(getClaudeConfigHomeDir()) ? 1 : 0, }) }}
/** * Used by processMemoryFile → getMemoryFiles so the event loop stays * responsive during the directory walk (many readFile attempts, most * ENOENT). When includeBasePath is given, @include paths are resolved in * the same lex pass and returned alongside the parsed file. */async function safelyReadMemoryFileAsync( filePath: string, type: MemoryType, includeBasePath?: string,): Promise<{ info: MemoryFileInfo | null; includePaths: string[] }> { try { const fs = getFsImplementation() const rawContent = await fs.readFile(filePath, { encoding: 'utf-8' }) return parseMemoryFileContent(rawContent, filePath, type, includeBasePath) } catch (error) { handleMemoryFileReadError(error, filePath) return { info: null, includePaths: [] } }}
type MarkdownToken = { type: string text?: string href?: string tokens?: MarkdownToken[] raw?: string items?: MarkdownToken[]}
// Extract @path include references from pre-lexed tokens and resolve to// absolute paths. Skips html tokens so @paths inside block comments are// ignored — the caller may pass pre-strip tokens.function extractIncludePathsFromTokens( tokens: ReturnType<Lexer['lex']>, basePath: string,): string[] { const absolutePaths = new Set<string>()
// Extract @paths from a text string and add resolved paths to absolutePaths. function extractPathsFromText(textContent: string) { const includeRegex = /(?:^|\s)@((?:[^\s\\]|\\ )+)/g let match while ((match = includeRegex.exec(textContent)) !== null) { let path = match[1] if (!path) continue
// Strip fragment identifiers (#heading, #section-name, etc.) const hashIndex = path.indexOf('#') if (hashIndex !== -1) { path = path.substring(0, hashIndex) } if (!path) continue
// Unescape the spaces in the path path = path.replace(/\\ /g, ' ')
// Accept @path, @./path, @~/path, or @/path if (path) { const isValidPath = path.startsWith('./') || path.startsWith('~/') || (path.startsWith('/') && path !== '/') || (!path.startsWith('@') && !path.match(/^[#%^&*()]+/) && path.match(/^[a-zA-Z0-9._-]/))
if (isValidPath) { const resolvedPath = expandPath(path, dirname(basePath)) absolutePaths.add(resolvedPath) } } } }
// Recursively process elements to find text nodes function processElements(elements: MarkdownToken[]) { for (const element of elements) { if (element.type === 'code' || element.type === 'codespan') { continue }
// For html tokens that contain comments, strip the comment spans and // check the residual for @paths (e.g. `<!-- note --> @./file.md`). // Other html tokens (non-comment tags) are skipped entirely. if (element.type === 'html') { const raw = element.raw || '' const trimmed = raw.trimStart() if (trimmed.startsWith('<!--') && trimmed.includes('-->')) { const commentSpan = /<!--[\s\S]*?-->/g const residue = raw.replace(commentSpan, '') if (residue.trim().length > 0) { extractPathsFromText(residue) } } continue }
// Process text nodes if (element.type === 'text') { extractPathsFromText(element.text || '') }
// Recurse into children tokens if (element.tokens) { processElements(element.tokens) }
// Special handling for list structures if (element.items) { processElements(element.items) } } }
processElements(tokens as MarkdownToken[]) return [...absolutePaths]}
const MAX_INCLUDE_DEPTH = 5
/** * Checks whether a CLAUDE.md file path is excluded by the claudeMdExcludes setting. * Only applies to User, Project, and Local memory types. * Managed, AutoMem, and TeamMem types are never excluded. * * Matches both the original path and the realpath-resolved path to handle symlinks * (e.g., /tmp -> /private/tmp on macOS). */function isClaudeMdExcluded(filePath: string, type: MemoryType): boolean { if (type !== 'User' && type !== 'Project' && type !== 'Local') { return false }
const patterns = getInitialSettings().claudeMdExcludes if (!patterns || patterns.length === 0) { return false }
const matchOpts = { dot: true } const normalizedPath = filePath.replaceAll('\\', '/')
// Build an expanded pattern list that includes realpath-resolved versions of // absolute patterns. This handles symlinks like /tmp -> /private/tmp on macOS: // the user writes "/tmp/project/CLAUDE.md" in their exclude, but the system // resolves the CWD to "/private/tmp/project/...", so the file path uses the // real path. By resolving the patterns too, both sides match. const expandedPatterns = resolveExcludePatterns(patterns).filter( p => p.length > 0, ) if (expandedPatterns.length === 0) { return false }
return picomatch.isMatch(normalizedPath, expandedPatterns, matchOpts)}
/** * Expands exclude patterns by resolving symlinks in absolute path prefixes. * For each absolute pattern (starting with /), tries to resolve the longest * existing directory prefix via realpathSync and adds the resolved version. * Glob patterns (containing *) have their static prefix resolved. */function resolveExcludePatterns(patterns: string[]): string[] { const fs = getFsImplementation() const expanded: string[] = patterns.map(p => p.replaceAll('\\', '/'))
for (const normalized of expanded) { // Only resolve absolute patterns — glob-only patterns like "**/*.md" don't have // a filesystem prefix to resolve if (!normalized.startsWith('/')) { continue }
// Find the static prefix before any glob characters const globStart = normalized.search(/[*?{[]/) const staticPrefix = globStart === -1 ? normalized : normalized.slice(0, globStart) const dirToResolve = dirname(staticPrefix)
try { // sync IO: called from sync context (isClaudeMdExcluded -> processMemoryFile -> getMemoryFiles) const resolvedDir = fs.realpathSync(dirToResolve).replaceAll('\\', '/') if (resolvedDir !== dirToResolve) { const resolvedPattern = resolvedDir + normalized.slice(dirToResolve.length) expanded.push(resolvedPattern) } } catch { // Directory doesn't exist; skip resolution for this pattern } }
return expanded}
/** * Recursively processes a memory file and all its @include references * Returns an array of MemoryFileInfo objects with includes first, then main file */export async function processMemoryFile( filePath: string, type: MemoryType, processedPaths: Set<string>, includeExternal: boolean, depth: number = 0, parent?: string,): Promise<MemoryFileInfo[]> { // Skip if already processed or max depth exceeded. // Normalize paths for comparison to handle Windows drive letter casing // differences (e.g., C:\Users vs c:\Users). const normalizedPath = normalizePathForComparison(filePath) if (processedPaths.has(normalizedPath) || depth >= MAX_INCLUDE_DEPTH) { return [] }
// Skip if path is excluded by claudeMdExcludes setting if (isClaudeMdExcluded(filePath, type)) { return [] }
// Resolve symlink path early for @import resolution const { resolvedPath, isSymlink } = safeResolvePath( getFsImplementation(), filePath, )
processedPaths.add(normalizedPath) if (isSymlink) { processedPaths.add(normalizePathForComparison(resolvedPath)) }
const { info: memoryFile, includePaths: resolvedIncludePaths } = await safelyReadMemoryFileAsync(filePath, type, resolvedPath) if (!memoryFile || !memoryFile.content.trim()) { return [] }
// Add parent information if (parent) { memoryFile.parent = parent }
const result: MemoryFileInfo[] = []
// Add the main file first (parent before children) result.push(memoryFile)
for (const resolvedIncludePath of resolvedIncludePaths) { const isExternal = !pathInOriginalCwd(resolvedIncludePath) if (isExternal && !includeExternal) { continue }
// Recursively process included files with this file as parent const includedFiles = await processMemoryFile( resolvedIncludePath, type, processedPaths, includeExternal, depth + 1, filePath, // Pass current file as parent ) result.push(...includedFiles) }
return result}
/** * Processes all .md files in the .claude/rules/ directory and its subdirectories * @param rulesDir The path to the rules directory * @param type Type of memory file (User, Project, Local) * @param processedPaths Set of already processed file paths * @param includeExternal Whether to include external files * @param conditionalRule If true, only include files with frontmatter paths; if false, only include files without frontmatter paths * @param visitedDirs Set of already visited directory real paths (for cycle detection) * @returns Array of MemoryFileInfo objects */export async function processMdRules({ rulesDir, type, processedPaths, includeExternal, conditionalRule, visitedDirs = new Set(),}: { rulesDir: string type: MemoryType processedPaths: Set<string> includeExternal: boolean conditionalRule: boolean visitedDirs?: Set<string>}): Promise<MemoryFileInfo[]> { if (visitedDirs.has(rulesDir)) { return [] }
try { const fs = getFsImplementation()
const { resolvedPath: resolvedRulesDir, isSymlink } = safeResolvePath( fs, rulesDir, )
visitedDirs.add(rulesDir) if (isSymlink) { visitedDirs.add(resolvedRulesDir) }
const result: MemoryFileInfo[] = [] let entries: import('fs').Dirent[] try { entries = await fs.readdir(resolvedRulesDir) } catch (e: unknown) { const code = getErrnoCode(e) if (code === 'ENOENT' || code === 'EACCES' || code === 'ENOTDIR') { return [] } throw e }
for (const entry of entries) { const entryPath = join(rulesDir, entry.name) const { resolvedPath: resolvedEntryPath, isSymlink } = safeResolvePath( fs, entryPath, )
// Use Dirent methods for non-symlinks to avoid extra stat calls. // For symlinks, we need stat to determine what the target is. const stats = isSymlink ? await fs.stat(resolvedEntryPath) : null const isDirectory = stats ? stats.isDirectory() : entry.isDirectory() const isFile = stats ? stats.isFile() : entry.isFile()
if (isDirectory) { result.push( ...(await processMdRules({ rulesDir: resolvedEntryPath, type, processedPaths, includeExternal, conditionalRule, visitedDirs, })), ) } else if (isFile && entry.name.endsWith('.md')) { const files = await processMemoryFile( resolvedEntryPath, type, processedPaths, includeExternal, ) result.push( ...files.filter(f => (conditionalRule ? f.globs : !f.globs)), ) } }
return result } catch (error) { if (error instanceof Error && error.message.includes('EACCES')) { logEvent('tengu_claude_rules_md_permission_error', { is_access_error: 1, has_home_dir: rulesDir.includes(getClaudeConfigHomeDir()) ? 1 : 0, }) } return [] }}
export const getMemoryFiles = memoize( async (forceIncludeExternal: boolean = false): Promise<MemoryFileInfo[]> => { const startTime = Date.now() logForDiagnosticsNoPII('info', 'memory_files_started')
const result: MemoryFileInfo[] = [] const processedPaths = new Set<string>() const config = getCurrentProjectConfig() const includeExternal = forceIncludeExternal || config.hasClaudeMdExternalIncludesApproved || false
// Process Managed file first (always loaded - policy settings) const managedClaudeMd = getMemoryPath('Managed') result.push( ...(await processMemoryFile( managedClaudeMd, 'Managed', processedPaths, includeExternal, )), ) // Process Managed .claude/rules/*.md files const managedClaudeRulesDir = getManagedClaudeRulesDir() result.push( ...(await processMdRules({ rulesDir: managedClaudeRulesDir, type: 'Managed', processedPaths, includeExternal, conditionalRule: false, })), )
// Process User file (only if userSettings is enabled) if (isSettingSourceEnabled('userSettings')) { const userClaudeMd = getMemoryPath('User') result.push( ...(await processMemoryFile( userClaudeMd, 'User', processedPaths, true, // User memory can always include external files )), ) // Process User ~/.claude/rules/*.md files const userClaudeRulesDir = getUserClaudeRulesDir() result.push( ...(await processMdRules({ rulesDir: userClaudeRulesDir, type: 'User', processedPaths, includeExternal: true, conditionalRule: false, })), ) }
// Then process Project and Local files const dirs: string[] = [] const originalCwd = getOriginalCwd() let currentDir = originalCwd
while (currentDir !== parse(currentDir).root) { dirs.push(currentDir) currentDir = dirname(currentDir) }
// When running from a git worktree nested inside its main repo (e.g., // .claude/worktrees/<name>/ from `claude -w`), the upward walk passes // through both the worktree root and the main repo root. Both contain // checked-in files like CLAUDE.md and .claude/rules/*.md, so the same // content gets loaded twice. Skip Project-type (checked-in) files from // directories above the worktree but within the main repo — the worktree // already has its own checkout. CLAUDE.local.md is gitignored so it only // exists in the main repo and is still loaded. // See: https://github.com/anthropics/claude-code/issues/29599 const gitRoot = findGitRoot(originalCwd) const canonicalRoot = findCanonicalGitRoot(originalCwd) const isNestedWorktree = gitRoot !== null && canonicalRoot !== null && normalizePathForComparison(gitRoot) !== normalizePathForComparison(canonicalRoot) && pathInWorkingPath(gitRoot, canonicalRoot)
// Process from root downward to CWD for (const dir of dirs.reverse()) { // In a nested worktree, skip checked-in files from the main repo's // working tree (dirs inside canonicalRoot but outside the worktree). const skipProject = isNestedWorktree && pathInWorkingPath(dir, canonicalRoot) && !pathInWorkingPath(dir, gitRoot)
// Try reading CLAUDE.md (Project) - only if projectSettings is enabled if (isSettingSourceEnabled('projectSettings') && !skipProject) { const projectPath = join(dir, 'CLAUDE.md') result.push( ...(await processMemoryFile( projectPath, 'Project', processedPaths, includeExternal, )), )
// Try reading .claude/CLAUDE.md (Project) const dotClaudePath = join(dir, '.claude', 'CLAUDE.md') result.push( ...(await processMemoryFile( dotClaudePath, 'Project', processedPaths, includeExternal, )), )
// Try reading .claude/rules/*.md files (Project) const rulesDir = join(dir, '.claude', 'rules') result.push( ...(await processMdRules({ rulesDir, type: 'Project', processedPaths, includeExternal, conditionalRule: false, })), ) }
// Try reading CLAUDE.local.md (Local) - only if localSettings is enabled if (isSettingSourceEnabled('localSettings')) { const localPath = join(dir, 'CLAUDE.local.md') result.push( ...(await processMemoryFile( localPath, 'Local', processedPaths, includeExternal, )), ) } }
// Process CLAUDE.md from additional directories (--add-dir) if env var is enabled // This is controlled by CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD and defaults to off // Note: we don't check isSettingSourceEnabled('projectSettings') here because --add-dir // is an explicit user action and the SDK defaults settingSources to [] when not specified if (isEnvTruthy(process.env.CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD)) { const additionalDirs = getAdditionalDirectoriesForClaudeMd() for (const dir of additionalDirs) { // Try reading CLAUDE.md from the additional directory const projectPath = join(dir, 'CLAUDE.md') result.push( ...(await processMemoryFile( projectPath, 'Project', processedPaths, includeExternal, )), )
// Try reading .claude/CLAUDE.md from the additional directory const dotClaudePath = join(dir, '.claude', 'CLAUDE.md') result.push( ...(await processMemoryFile( dotClaudePath, 'Project', processedPaths, includeExternal, )), )
// Try reading .claude/rules/*.md files from the additional directory const rulesDir = join(dir, '.claude', 'rules') result.push( ...(await processMdRules({ rulesDir, type: 'Project', processedPaths, includeExternal, conditionalRule: false, })), ) } }
// Memdir entrypoint (memory.md) - only if feature is on and file exists if (isAutoMemoryEnabled()) { const { info: memdirEntry } = await safelyReadMemoryFileAsync( getAutoMemEntrypoint(), 'AutoMem', ) if (memdirEntry) { const normalizedPath = normalizePathForComparison(memdirEntry.path) if (!processedPaths.has(normalizedPath)) { processedPaths.add(normalizedPath) result.push(memdirEntry) } } }
// Team memory entrypoint - only if feature is on and file exists if (feature('TEAMMEM') && teamMemPaths!.isTeamMemoryEnabled()) { const { info: teamMemEntry } = await safelyReadMemoryFileAsync( teamMemPaths!.getTeamMemEntrypoint(), 'TeamMem', ) if (teamMemEntry) { const normalizedPath = normalizePathForComparison(teamMemEntry.path) if (!processedPaths.has(normalizedPath)) { processedPaths.add(normalizedPath) result.push(teamMemEntry) } } }
const totalContentLength = result.reduce( (sum, f) => sum + f.content.length, 0, )
logForDiagnosticsNoPII('info', 'memory_files_completed', { duration_ms: Date.now() - startTime, file_count: result.length, total_content_length: totalContentLength, })
const typeCounts: Record<string, number> = {} for (const f of result) { typeCounts[f.type] = (typeCounts[f.type] ?? 0) + 1 }
if (!hasLoggedInitialLoad) { hasLoggedInitialLoad = true logEvent('tengu_claudemd__initial_load', { file_count: result.length, total_content_length: totalContentLength, user_count: typeCounts['User'] ?? 0, project_count: typeCounts['Project'] ?? 0, local_count: typeCounts['Local'] ?? 0, managed_count: typeCounts['Managed'] ?? 0, automem_count: typeCounts['AutoMem'] ?? 0, ...(feature('TEAMMEM') ? { teammem_count: typeCounts['TeamMem'] ?? 0 } : {}), duration_ms: Date.now() - startTime, }) }
// Fire InstructionsLoaded hook for each instruction file loaded // (fire-and-forget, audit/observability only). // AutoMem/TeamMem are intentionally excluded — they're a separate // memory system, not "instructions" in the CLAUDE.md/rules sense. // Gated on !forceIncludeExternal: the forceIncludeExternal=true variant // is only used by getExternalClaudeMdIncludes() for approval checks, not // for building context — firing the hook there would double-fire on startup. // The one-shot flag is consumed on every !forceIncludeExternal cache miss // (NOT gated on hasInstructionsLoadedHook) so the flag is released even // when no hook is configured — otherwise a mid-session hook registration // followed by a direct .cache.clear() would spuriously fire with a stale // 'session_start' reason. if (!forceIncludeExternal) { const eagerLoadReason = consumeNextEagerLoadReason() if (eagerLoadReason !== undefined && hasInstructionsLoadedHook()) { for (const file of result) { if (!isInstructionsMemoryType(file.type)) continue const loadReason = file.parent ? 'include' : eagerLoadReason void executeInstructionsLoadedHooks( file.path, file.type, loadReason, { globs: file.globs, parentFilePath: file.parent, }, ) } } }
return result },)
function isInstructionsMemoryType( type: MemoryType,): type is InstructionsMemoryType { return ( type === 'User' || type === 'Project' || type === 'Local' || type === 'Managed' )}
// Load reason to report for top-level (non-included) files on the next eager// getMemoryFiles() pass. Set to 'compact' by resetGetMemoryFilesCache when// compaction clears the cache, so the InstructionsLoaded hook reports the// reload correctly instead of misreporting it as 'session_start'. One-shot:// reset to 'session_start' after being read.let nextEagerLoadReason: InstructionsLoadReason = 'session_start'
// Whether the InstructionsLoaded hook should fire on the next cache miss.// true initially (for session_start), consumed after firing, re-enabled only// by resetGetMemoryFilesCache(). Callers that only need cache invalidation// for correctness (e.g. worktree enter/exit, settings sync, /memory dialog)// should use clearMemoryFileCaches() instead to avoid spurious hook fires.let shouldFireHook = true
function consumeNextEagerLoadReason(): InstructionsLoadReason | undefined { if (!shouldFireHook) return undefined shouldFireHook = false const reason = nextEagerLoadReason nextEagerLoadReason = 'session_start' return reason}
/** * Clears the getMemoryFiles memoize cache * without firing the InstructionsLoaded hook. * * Use this for cache invalidation that is purely for correctness (e.g. * worktree enter/exit, settings sync, /memory dialog). For events that * represent instructions actually being reloaded into context (e.g. * compaction), use resetGetMemoryFilesCache() instead. */export function clearMemoryFileCaches(): void { // ?.cache because tests spyOn this, which replaces the memoize wrapper. getMemoryFiles.cache?.clear?.()}
export function resetGetMemoryFilesCache( reason: InstructionsLoadReason = 'session_start',): void { nextEagerLoadReason = reason shouldFireHook = true clearMemoryFileCaches()}
export function getLargeMemoryFiles(files: MemoryFileInfo[]): MemoryFileInfo[] { return files.filter(f => f.content.length > MAX_MEMORY_CHARACTER_COUNT)}
/** * When tengu_moth_copse is on, the findRelevantMemories prefetch surfaces * memory files via attachments, so the MEMORY.md index is no longer injected * into the system prompt. Callsites that care about "what's actually in * context" (context builder, /context viz) should filter through this. */export function filterInjectedMemoryFiles( files: MemoryFileInfo[],): MemoryFileInfo[] { const skipMemoryIndex = getFeatureValue_CACHED_MAY_BE_STALE( 'tengu_moth_copse', false, ) if (!skipMemoryIndex) return files return files.filter(f => f.type !== 'AutoMem' && f.type !== 'TeamMem')}
export const getClaudeMds = ( memoryFiles: MemoryFileInfo[], filter?: (type: MemoryType) => boolean,): string => { const memories: string[] = [] const skipProjectLevel = getFeatureValue_CACHED_MAY_BE_STALE( 'tengu_paper_halyard', false, )
for (const file of memoryFiles) { if (filter && !filter(file.type)) continue if (skipProjectLevel && (file.type === 'Project' || file.type === 'Local')) continue if (file.content) { const description = file.type === 'Project' ? ' (project instructions, checked into the codebase)' : file.type === 'Local' ? " (user's private project instructions, not checked in)" : feature('TEAMMEM') && file.type === 'TeamMem' ? ' (shared team memory, synced across the organization)' : file.type === 'AutoMem' ? " (user's auto-memory, persists across conversations)" : " (user's private global instructions for all projects)"
const content = file.content.trim() if (feature('TEAMMEM') && file.type === 'TeamMem') { memories.push( `Contents of ${file.path}${description}:\n\n<team-memory-content source="shared">\n${content}\n</team-memory-content>`, ) } else { memories.push(`Contents of ${file.path}${description}:\n\n${content}`) } } }
if (memories.length === 0) { return '' }
return `${MEMORY_INSTRUCTION_PROMPT}\n\n${memories.join('\n\n')}`}
/** * Gets managed and user conditional rules that match the target path. * This is the first phase of nested memory loading. * * @param targetPath The target file path to match against glob patterns * @param processedPaths Set of already processed file paths (will be mutated) * @returns Array of MemoryFileInfo objects for matching conditional rules */export async function getManagedAndUserConditionalRules( targetPath: string, processedPaths: Set<string>,): Promise<MemoryFileInfo[]> { const result: MemoryFileInfo[] = []
// Process Managed conditional .claude/rules/*.md files const managedClaudeRulesDir = getManagedClaudeRulesDir() result.push( ...(await processConditionedMdRules( targetPath, managedClaudeRulesDir, 'Managed', processedPaths, false, )), )
if (isSettingSourceEnabled('userSettings')) { // Process User conditional .claude/rules/*.md files const userClaudeRulesDir = getUserClaudeRulesDir() result.push( ...(await processConditionedMdRules( targetPath, userClaudeRulesDir, 'User', processedPaths, true, )), ) }
return result}
/** * Gets memory files for a single nested directory (between CWD and target). * Loads CLAUDE.md, unconditional rules, and conditional rules for that directory. * * @param dir The directory to process * @param targetPath The target file path (for conditional rule matching) * @param processedPaths Set of already processed file paths (will be mutated) * @returns Array of MemoryFileInfo objects */export async function getMemoryFilesForNestedDirectory( dir: string, targetPath: string, processedPaths: Set<string>,): Promise<MemoryFileInfo[]> { const result: MemoryFileInfo[] = []
// Process project memory files (CLAUDE.md and .claude/CLAUDE.md) if (isSettingSourceEnabled('projectSettings')) { const projectPath = join(dir, 'CLAUDE.md') result.push( ...(await processMemoryFile( projectPath, 'Project', processedPaths, false, )), ) const dotClaudePath = join(dir, '.claude', 'CLAUDE.md') result.push( ...(await processMemoryFile( dotClaudePath, 'Project', processedPaths, false, )), ) }
// Process local memory file (CLAUDE.local.md) if (isSettingSourceEnabled('localSettings')) { const localPath = join(dir, 'CLAUDE.local.md') result.push( ...(await processMemoryFile(localPath, 'Local', processedPaths, false)), ) }
const rulesDir = join(dir, '.claude', 'rules')
// Process project unconditional .claude/rules/*.md files, which were not eagerly loaded // Use a separate processedPaths set to avoid marking conditional rule files as processed const unconditionalProcessedPaths = new Set(processedPaths) result.push( ...(await processMdRules({ rulesDir, type: 'Project', processedPaths: unconditionalProcessedPaths, includeExternal: false, conditionalRule: false, })), )
// Process project conditional .claude/rules/*.md files result.push( ...(await processConditionedMdRules( targetPath, rulesDir, 'Project', processedPaths, false, )), )
// processedPaths must be seeded with unconditional paths for subsequent directories for (const path of unconditionalProcessedPaths) { processedPaths.add(path) }
return result}
/** * Gets conditional rules for a CWD-level directory (from root up to CWD). * Only processes conditional rules since unconditional rules are already loaded eagerly. * * @param dir The directory to process * @param targetPath The target file path (for conditional rule matching) * @param processedPaths Set of already processed file paths (will be mutated) * @returns Array of MemoryFileInfo objects */export async function getConditionalRulesForCwdLevelDirectory( dir: string, targetPath: string, processedPaths: Set<string>,): Promise<MemoryFileInfo[]> { const rulesDir = join(dir, '.claude', 'rules') return processConditionedMdRules( targetPath, rulesDir, 'Project', processedPaths, false, )}
/** * Processes all .md files in the .claude/rules/ directory and its subdirectories, * filtering to only include files with frontmatter paths that match the target path * @param targetPath The file path to match against frontmatter glob patterns * @param rulesDir The path to the rules directory * @param type Type of memory file (User, Project, Local) * @param processedPaths Set of already processed file paths * @param includeExternal Whether to include external files * @returns Array of MemoryFileInfo objects that match the target path */export async function processConditionedMdRules( targetPath: string, rulesDir: string, type: MemoryType, processedPaths: Set<string>, includeExternal: boolean,): Promise<MemoryFileInfo[]> { const conditionedRuleMdFiles = await processMdRules({ rulesDir, type, processedPaths, includeExternal, conditionalRule: true, })
// Filter to only include files whose globs patterns match the targetPath return conditionedRuleMdFiles.filter(file => { if (!file.globs || file.globs.length === 0) { return false }
// For Project rules: glob patterns are relative to the directory containing .claude // For Managed/User rules: glob patterns are relative to the original CWD const baseDir = type === 'Project' ? dirname(dirname(rulesDir)) // Parent of .claude : getOriginalCwd() // Project root for managed/user rules
const relativePath = isAbsolute(targetPath) ? relative(baseDir, targetPath) : targetPath // ignore() throws on empty strings, paths escaping the base (../), // and absolute paths (Windows cross-drive relative() returns absolute). // Files outside baseDir can't match baseDir-relative globs anyway. if ( !relativePath || relativePath.startsWith('..') || isAbsolute(relativePath) ) { return false } return ignore().add(file.globs).ignores(relativePath) })}
export type ExternalClaudeMdInclude = { path: string parent: string}
export function getExternalClaudeMdIncludes( files: MemoryFileInfo[],): ExternalClaudeMdInclude[] { const externals: ExternalClaudeMdInclude[] = [] for (const file of files) { if (file.type !== 'User' && file.parent && !pathInOriginalCwd(file.path)) { externals.push({ path: file.path, parent: file.parent }) } } return externals}
export function hasExternalClaudeMdIncludes(files: MemoryFileInfo[]): boolean { return getExternalClaudeMdIncludes(files).length > 0}
export async function shouldShowClaudeMdExternalIncludesWarning(): Promise<boolean> { const config = getCurrentProjectConfig() if ( config.hasClaudeMdExternalIncludesApproved || config.hasClaudeMdExternalIncludesWarningShown ) { return false }
return hasExternalClaudeMdIncludes(await getMemoryFiles(true))}
/** * Check if a file path is a memory file (CLAUDE.md, CLAUDE.local.md, or .claude/rules/*.md) */export function isMemoryFilePath(filePath: string): boolean { const name = basename(filePath)
// CLAUDE.md or CLAUDE.local.md anywhere if (name === 'CLAUDE.md' || name === 'CLAUDE.local.md') { return true }
// .md files in .claude/rules/ directories if ( name.endsWith('.md') && filePath.includes(`${sep}.claude${sep}rules${sep}`) ) { return true }
return false}
/** * Get all memory file paths from both standard discovery and readFileState. * Combines: * - getMemoryFiles() paths (CWD upward to root) * - readFileState paths matching memory patterns (includes child directories) */export function getAllMemoryFilePaths( files: MemoryFileInfo[], readFileState: FileStateCache,): string[] { const paths = new Set<string>() for (const file of files) { if (file.content.trim().length > 0) { paths.add(file.path) } }
// Add memory files from readFileState (includes child directories) for (const filePath of cacheKeys(readFileState)) { if (isMemoryFilePath(filePath)) { paths.add(filePath) } }
return Array.from(paths)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602import * as fs from 'fs/promises'import { homedir } from 'os'import { join } from 'path'import { logEvent } from '../services/analytics/index.js'import { CACHE_PATHS } from './cachePaths.js'import { logForDebugging } from './debug.js'import { getClaudeConfigHomeDir } from './envUtils.js'import { type FsOperations, getFsImplementation } from './fsOperations.js'import { cleanupOldImageCaches } from './imageStore.js'import * as lockfile from './lockfile.js'import { logError } from './log.js'import { cleanupOldVersions } from './nativeInstaller/index.js'import { cleanupOldPastes } from './pasteStore.js'import { getProjectsDir } from './sessionStorage.js'import { getSettingsWithAllErrors } from './settings/allErrors.js'import { getSettings_DEPRECATED, rawSettingsContainsKey,} from './settings/settings.js'import { TOOL_RESULTS_SUBDIR } from './toolResultStorage.js'import { cleanupStaleAgentWorktrees } from './worktree.js'
const DEFAULT_CLEANUP_PERIOD_DAYS = 30
function getCutoffDate(): Date { const settings = getSettings_DEPRECATED() || {} const cleanupPeriodDays = settings.cleanupPeriodDays ?? DEFAULT_CLEANUP_PERIOD_DAYS const cleanupPeriodMs = cleanupPeriodDays * 24 * 60 * 60 * 1000 return new Date(Date.now() - cleanupPeriodMs)}
export type CleanupResult = { messages: number errors: number}
export function addCleanupResults( a: CleanupResult, b: CleanupResult,): CleanupResult { return { messages: a.messages + b.messages, errors: a.errors + b.errors, }}
export function convertFileNameToDate(filename: string): Date { const isoStr = filename .split('.')[0]! .replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/, 'T$1:$2:$3.$4Z') return new Date(isoStr)}
async function cleanupOldFilesInDirectory( dirPath: string, cutoffDate: Date, isMessagePath: boolean,): Promise<CleanupResult> { const result: CleanupResult = { messages: 0, errors: 0 }
try { const files = await getFsImplementation().readdir(dirPath)
for (const file of files) { try { // Convert filename format where all ':.' were replaced with '-' const timestamp = convertFileNameToDate(file.name) if (timestamp < cutoffDate) { await getFsImplementation().unlink(join(dirPath, file.name)) // Increment the appropriate counter if (isMessagePath) { result.messages++ } else { result.errors++ } } } catch (error) { // Log but continue processing other files logError(error as Error) } } } catch (error: unknown) { // Ignore if directory doesn't exist if (error instanceof Error && 'code' in error && error.code !== 'ENOENT') { logError(error) } }
return result}
export async function cleanupOldMessageFiles(): Promise<CleanupResult> { const fsImpl = getFsImplementation() const cutoffDate = getCutoffDate() const errorPath = CACHE_PATHS.errors() const baseCachePath = CACHE_PATHS.baseLogs()
// Clean up message and error logs let result = await cleanupOldFilesInDirectory(errorPath, cutoffDate, false)
// Clean up MCP logs try { let dirents try { dirents = await fsImpl.readdir(baseCachePath) } catch { return result }
const mcpLogDirs = dirents .filter( dirent => dirent.isDirectory() && dirent.name.startsWith('mcp-logs-'), ) .map(dirent => join(baseCachePath, dirent.name))
for (const mcpLogDir of mcpLogDirs) { // Clean up files in MCP log directory result = addCleanupResults( result, await cleanupOldFilesInDirectory(mcpLogDir, cutoffDate, true), ) await tryRmdir(mcpLogDir, fsImpl) } } catch (error: unknown) { if (error instanceof Error && 'code' in error && error.code !== 'ENOENT') { logError(error) } }
return result}
async function unlinkIfOld( filePath: string, cutoffDate: Date, fsImpl: FsOperations,): Promise<boolean> { const stats = await fsImpl.stat(filePath) if (stats.mtime < cutoffDate) { await fsImpl.unlink(filePath) return true } return false}
async function tryRmdir(dirPath: string, fsImpl: FsOperations): Promise<void> { try { await fsImpl.rmdir(dirPath) } catch { // not empty / doesn't exist }}
export async function cleanupOldSessionFiles(): Promise<CleanupResult> { const cutoffDate = getCutoffDate() const result: CleanupResult = { messages: 0, errors: 0 } const projectsDir = getProjectsDir() const fsImpl = getFsImplementation()
let projectDirents try { projectDirents = await fsImpl.readdir(projectsDir) } catch { return result }
for (const projectDirent of projectDirents) { if (!projectDirent.isDirectory()) continue const projectDir = join(projectsDir, projectDirent.name)
// Single readdir per project directory — partition into files and session dirs let entries try { entries = await fsImpl.readdir(projectDir) } catch { result.errors++ continue }
for (const entry of entries) { if (entry.isFile()) { if (!entry.name.endsWith('.jsonl') && !entry.name.endsWith('.cast')) { continue } try { if ( await unlinkIfOld(join(projectDir, entry.name), cutoffDate, fsImpl) ) { result.messages++ } } catch { result.errors++ } } else if (entry.isDirectory()) { // Session directory — clean up tool-results/<toolDir>/* beneath it const sessionDir = join(projectDir, entry.name) const toolResultsDir = join(sessionDir, TOOL_RESULTS_SUBDIR) let toolDirs try { toolDirs = await fsImpl.readdir(toolResultsDir) } catch { // No tool-results dir — still try to remove an empty session dir await tryRmdir(sessionDir, fsImpl) continue } for (const toolEntry of toolDirs) { if (toolEntry.isFile()) { try { if ( await unlinkIfOld( join(toolResultsDir, toolEntry.name), cutoffDate, fsImpl, ) ) { result.messages++ } } catch { result.errors++ } } else if (toolEntry.isDirectory()) { const toolDirPath = join(toolResultsDir, toolEntry.name) let toolFiles try { toolFiles = await fsImpl.readdir(toolDirPath) } catch { continue } for (const tf of toolFiles) { if (!tf.isFile()) continue try { if ( await unlinkIfOld( join(toolDirPath, tf.name), cutoffDate, fsImpl, ) ) { result.messages++ } } catch { result.errors++ } } await tryRmdir(toolDirPath, fsImpl) } } await tryRmdir(toolResultsDir, fsImpl) await tryRmdir(sessionDir, fsImpl) } }
await tryRmdir(projectDir, fsImpl) }
return result}
/** * Generic helper for cleaning up old files in a single directory * @param dirPath Path to the directory to clean * @param extension File extension to filter (e.g., '.md', '.jsonl') * @param removeEmptyDir Whether to remove the directory if empty after cleanup */async function cleanupSingleDirectory( dirPath: string, extension: string, removeEmptyDir: boolean = true,): Promise<CleanupResult> { const cutoffDate = getCutoffDate() const result: CleanupResult = { messages: 0, errors: 0 } const fsImpl = getFsImplementation()
let dirents try { dirents = await fsImpl.readdir(dirPath) } catch { return result }
for (const dirent of dirents) { if (!dirent.isFile() || !dirent.name.endsWith(extension)) continue try { if (await unlinkIfOld(join(dirPath, dirent.name), cutoffDate, fsImpl)) { result.messages++ } } catch { result.errors++ } }
if (removeEmptyDir) { await tryRmdir(dirPath, fsImpl) }
return result}
export function cleanupOldPlanFiles(): Promise<CleanupResult> { const plansDir = join(getClaudeConfigHomeDir(), 'plans') return cleanupSingleDirectory(plansDir, '.md')}
export async function cleanupOldFileHistoryBackups(): Promise<CleanupResult> { const cutoffDate = getCutoffDate() const result: CleanupResult = { messages: 0, errors: 0 } const fsImpl = getFsImplementation()
try { const configDir = getClaudeConfigHomeDir() const fileHistoryStorageDir = join(configDir, 'file-history')
let dirents try { dirents = await fsImpl.readdir(fileHistoryStorageDir) } catch { return result }
const fileHistorySessionsDirs = dirents .filter(dirent => dirent.isDirectory()) .map(dirent => join(fileHistoryStorageDir, dirent.name))
await Promise.all( fileHistorySessionsDirs.map(async fileHistorySessionDir => { try { const stats = await fsImpl.stat(fileHistorySessionDir) if (stats.mtime < cutoffDate) { await fsImpl.rm(fileHistorySessionDir, { recursive: true, force: true, }) result.messages++ } } catch { result.errors++ } }), )
await tryRmdir(fileHistoryStorageDir, fsImpl) } catch (error) { logError(error as Error) }
return result}
export async function cleanupOldSessionEnvDirs(): Promise<CleanupResult> { const cutoffDate = getCutoffDate() const result: CleanupResult = { messages: 0, errors: 0 } const fsImpl = getFsImplementation()
try { const configDir = getClaudeConfigHomeDir() const sessionEnvBaseDir = join(configDir, 'session-env')
let dirents try { dirents = await fsImpl.readdir(sessionEnvBaseDir) } catch { return result }
const sessionEnvDirs = dirents .filter(dirent => dirent.isDirectory()) .map(dirent => join(sessionEnvBaseDir, dirent.name))
for (const sessionEnvDir of sessionEnvDirs) { try { const stats = await fsImpl.stat(sessionEnvDir) if (stats.mtime < cutoffDate) { await fsImpl.rm(sessionEnvDir, { recursive: true, force: true }) result.messages++ } } catch { result.errors++ } }
await tryRmdir(sessionEnvBaseDir, fsImpl) } catch (error) { logError(error as Error) }
return result}
/** * Cleans up old debug log files from ~/.claude/debug/ * Preserves the 'latest' symlink which points to the current session's log. * Debug logs can grow very large (especially with the infinite logging loop bug) * and accumulate indefinitely without this cleanup. */export async function cleanupOldDebugLogs(): Promise<CleanupResult> { const cutoffDate = getCutoffDate() const result: CleanupResult = { messages: 0, errors: 0 } const fsImpl = getFsImplementation() const debugDir = join(getClaudeConfigHomeDir(), 'debug')
let dirents try { dirents = await fsImpl.readdir(debugDir) } catch { return result }
for (const dirent of dirents) { // Preserve the 'latest' symlink if ( !dirent.isFile() || !dirent.name.endsWith('.txt') || dirent.name === 'latest' ) { continue } try { if (await unlinkIfOld(join(debugDir, dirent.name), cutoffDate, fsImpl)) { result.messages++ } } catch { result.errors++ } }
// Intentionally do NOT remove debugDir even if empty — needed for future logs return result}
const ONE_DAY_MS = 24 * 60 * 60 * 1000
/** * Clean up old npm cache entries for Anthropic packages. * This helps reduce disk usage since we publish many dev versions per day. * Only runs once per day for Ant users. */export async function cleanupNpmCacheForAnthropicPackages(): Promise<void> { const markerPath = join(getClaudeConfigHomeDir(), '.npm-cache-cleanup')
try { const stat = await fs.stat(markerPath) if (Date.now() - stat.mtimeMs < ONE_DAY_MS) { logForDebugging('npm cache cleanup: skipping, ran recently') return } } catch { // File doesn't exist, proceed with cleanup }
try { await lockfile.lock(markerPath, { retries: 0, realpath: false }) } catch { logForDebugging('npm cache cleanup: skipping, lock held') return }
logForDebugging('npm cache cleanup: starting')
const npmCachePath = join(homedir(), '.npm', '_cacache')
const NPM_CACHE_RETENTION_COUNT = 5
const startTime = Date.now() try { const cacache = await import('cacache') const cutoff = startTime - ONE_DAY_MS
// Stream index entries and collect all Anthropic package entries. // Previous implementation used cacache.verify() which does a full // integrity check + GC of the ENTIRE cache — O(all content blobs). // On large caches this took 60+ seconds and blocked the event loop. const stream = cacache.ls.stream(npmCachePath) const anthropicEntries: { key: string; time: number }[] = [] for await (const entry of stream as AsyncIterable<{ key: string time: number }>) { if (entry.key.includes('@anthropic-ai/claude-')) { anthropicEntries.push({ key: entry.key, time: entry.time }) } }
// Group by package name (everything before the last @version separator) const byPackage = new Map<string, { key: string; time: number }[]>() for (const entry of anthropicEntries) { const atVersionIdx = entry.key.lastIndexOf('@') const pkgName = atVersionIdx > 0 ? entry.key.slice(0, atVersionIdx) : entry.key const existing = byPackage.get(pkgName) ?? [] existing.push(entry) byPackage.set(pkgName, existing) }
// Remove entries older than 1 day OR beyond the top N most recent per package const keysToRemove: string[] = [] for (const [, entries] of byPackage) { entries.sort((a, b) => b.time - a.time) // newest first for (let i = 0; i < entries.length; i++) { const entry = entries[i]! if (entry.time < cutoff || i >= NPM_CACHE_RETENTION_COUNT) { keysToRemove.push(entry.key) } } }
await Promise.all( keysToRemove.map(key => cacache.rm.entry(npmCachePath, key)), )
await fs.writeFile(markerPath, new Date().toISOString())
const durationMs = Date.now() - startTime if (keysToRemove.length > 0) { logForDebugging( `npm cache cleanup: Removed ${keysToRemove.length} old @anthropic-ai entries in ${durationMs}ms`, ) } else { logForDebugging(`npm cache cleanup: completed in ${durationMs}ms`) } logEvent('tengu_npm_cache_cleanup', { success: true, durationMs, entriesRemoved: keysToRemove.length, }) } catch (error) { logError(error as Error) logEvent('tengu_npm_cache_cleanup', { success: false, durationMs: Date.now() - startTime, }) } finally { await lockfile.unlock(markerPath, { realpath: false }).catch(() => {}) }}
/** * Throttled wrapper around cleanupOldVersions for recurring cleanup in long-running sessions. * Uses a marker file and lock to ensure it runs at most once per 24 hours, * and does not block if another process is already running cleanup. * The regular cleanupOldVersions() should still be used for installer flows. */export async function cleanupOldVersionsThrottled(): Promise<void> { const markerPath = join(getClaudeConfigHomeDir(), '.version-cleanup')
try { const stat = await fs.stat(markerPath) if (Date.now() - stat.mtimeMs < ONE_DAY_MS) { logForDebugging('version cleanup: skipping, ran recently') return } } catch { // File doesn't exist, proceed with cleanup }
try { await lockfile.lock(markerPath, { retries: 0, realpath: false }) } catch { logForDebugging('version cleanup: skipping, lock held') return }
logForDebugging('version cleanup: starting (throttled)')
try { await cleanupOldVersions() await fs.writeFile(markerPath, new Date().toISOString()) } catch (error) { logError(error as Error) } finally { await lockfile.unlock(markerPath, { realpath: false }).catch(() => {}) }}
export async function cleanupOldMessageFilesInBackground(): Promise<void> { // If settings have validation errors but the user explicitly set cleanupPeriodDays, // skip cleanup entirely rather than falling back to the default (30 days). // This prevents accidentally deleting files when the user intended a different retention period. const { errors } = getSettingsWithAllErrors() if (errors.length > 0 && rawSettingsContainsKey('cleanupPeriodDays')) { logForDebugging( 'Skipping cleanup: settings have validation errors but cleanupPeriodDays was explicitly set. Fix settings errors to enable cleanup.', ) return }
await cleanupOldMessageFiles() await cleanupOldSessionFiles() await cleanupOldPlanFiles() await cleanupOldFileHistoryBackups() await cleanupOldSessionEnvDirs() await cleanupOldDebugLogs() await cleanupOldImageCaches() await cleanupOldPastes(getCutoffDate()) const removedWorktrees = await cleanupStaleAgentWorktrees(getCutoffDate()) if (removedWorktrees > 0) { logEvent('tengu_worktree_cleanup', { removed: removedWorktrees }) } if (process.env.USER_TYPE === 'ant') { await cleanupNpmCacheForAnthropicPackages() }}12345678910111213141516171819202122232425/** * Global registry for cleanup functions that should run during graceful shutdown. * This module is separate from gracefulShutdown.ts to avoid circular dependencies. */
// Global registry for cleanup functionsconst cleanupFunctions = new Set<() => Promise<void>>()
/** * Register a cleanup function to run during graceful shutdown. * @param cleanupFn - Function to run during cleanup (can be sync or async) * @returns Unregister function that removes the cleanup handler */export function registerCleanup(cleanupFn: () => Promise<void>): () => void { cleanupFunctions.add(cleanupFn) return () => cleanupFunctions.delete(cleanupFn) // Return unregister function}
/** * Run all registered cleanup functions. * Used internally by gracefulShutdown. */export async function runCleanupFunctions(): Promise<void> { await Promise.all(Array.from(cleanupFunctions).map(fn => fn()))}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354// highlight.js's type defs carry `/// <reference lib="dom" />`. SSETransport,// mcp/client, ssh, dumpPrompts use DOM types (TextDecodeOptions, RequestInfo)// that only typecheck because this file's `typeof import('highlight.js')` pulls// lib.dom in. tsconfig has lib: ["ESNext"] only — fixing the actual DOM-type// deps is a separate sweep; this ref preserves the status quo./// <reference lib="dom" />
import { extname } from 'path'
export type CliHighlight = { highlight: typeof import('cli-highlight').highlight supportsLanguage: typeof import('cli-highlight').supportsLanguage}
// One promise shared by Fallback.tsx, markdown.ts, events.ts, getLanguageName.// The highlight.js import piggybacks: cli-highlight has already pulled it into// the module cache, so the second import() is a cache hit — no extra bytes// faulted in.let cliHighlightPromise: Promise<CliHighlight | null> | undefined
let loadedGetLanguage: typeof import('highlight.js').getLanguage | undefined
async function loadCliHighlight(): Promise<CliHighlight | null> { try { const cliHighlight = await import('cli-highlight') // cache hit — cli-highlight already loaded highlight.js const highlightJs = await import('highlight.js') loadedGetLanguage = highlightJs.getLanguage return { highlight: cliHighlight.highlight, supportsLanguage: cliHighlight.supportsLanguage, } } catch { return null }}
export function getCliHighlightPromise(): Promise<CliHighlight | null> { cliHighlightPromise ??= loadCliHighlight() return cliHighlightPromise}
/** * eg. "foo/bar.ts" → "TypeScript". Awaits the shared cli-highlight load, * then reads highlight.js's language registry. All callers are telemetry * (OTel counter attributes, permission-dialog unary events) — none block * on this, they fire-and-forget or the consumer already handles Promise<string>. */export async function getLanguageName(file_path: string): Promise<string> { await getCliHighlightPromise() const ext = extname(file_path).slice(1) if (!ext) return 'unknown' return loadedGetLanguage?.(ext)?.name ?? 'unknown'}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206/** * Utility functions for detecting code indexing tool usage. * * Tracks usage of common code indexing solutions like Sourcegraph, Cody, etc. * both via CLI commands and MCP server integrations. */
/** * Known code indexing tool identifiers. * These are the normalized names used in analytics events. */export type CodeIndexingTool = // Code search engines | 'sourcegraph' | 'hound' | 'seagoat' | 'bloop' | 'gitloop' // AI coding assistants with indexing | 'cody' | 'aider' | 'continue' | 'github-copilot' | 'cursor' | 'tabby' | 'codeium' | 'tabnine' | 'augment' | 'windsurf' | 'aide' | 'pieces' | 'qodo' | 'amazon-q' | 'gemini' // MCP code indexing servers | 'claude-context' | 'code-index-mcp' | 'local-code-search' | 'autodev-codebase' // Context providers | 'openctx'
/** * Mapping of CLI command prefixes to code indexing tools. * The key is the command name (first word of the command). */const CLI_COMMAND_MAPPING: Record<string, CodeIndexingTool> = { // Sourcegraph ecosystem src: 'sourcegraph', cody: 'cody', // AI coding assistants aider: 'aider', tabby: 'tabby', tabnine: 'tabnine', augment: 'augment', pieces: 'pieces', qodo: 'qodo', aide: 'aide', // Code search tools hound: 'hound', seagoat: 'seagoat', bloop: 'bloop', gitloop: 'gitloop', // Cloud provider AI assistants q: 'amazon-q', gemini: 'gemini',}
/** * Mapping of MCP server name patterns to code indexing tools. * Patterns are matched case-insensitively against the server name. */const MCP_SERVER_PATTERNS: Array<{ pattern: RegExp tool: CodeIndexingTool}> = [ // Sourcegraph ecosystem { pattern: /^sourcegraph$/i, tool: 'sourcegraph' }, { pattern: /^cody$/i, tool: 'cody' }, { pattern: /^openctx$/i, tool: 'openctx' }, // AI coding assistants { pattern: /^aider$/i, tool: 'aider' }, { pattern: /^continue$/i, tool: 'continue' }, { pattern: /^github[-_]?copilot$/i, tool: 'github-copilot' }, { pattern: /^copilot$/i, tool: 'github-copilot' }, { pattern: /^cursor$/i, tool: 'cursor' }, { pattern: /^tabby$/i, tool: 'tabby' }, { pattern: /^codeium$/i, tool: 'codeium' }, { pattern: /^tabnine$/i, tool: 'tabnine' }, { pattern: /^augment[-_]?code$/i, tool: 'augment' }, { pattern: /^augment$/i, tool: 'augment' }, { pattern: /^windsurf$/i, tool: 'windsurf' }, { pattern: /^aide$/i, tool: 'aide' }, { pattern: /^codestory$/i, tool: 'aide' }, { pattern: /^pieces$/i, tool: 'pieces' }, { pattern: /^qodo$/i, tool: 'qodo' }, { pattern: /^amazon[-_]?q$/i, tool: 'amazon-q' }, { pattern: /^gemini[-_]?code[-_]?assist$/i, tool: 'gemini' }, { pattern: /^gemini$/i, tool: 'gemini' }, // Code search tools { pattern: /^hound$/i, tool: 'hound' }, { pattern: /^seagoat$/i, tool: 'seagoat' }, { pattern: /^bloop$/i, tool: 'bloop' }, { pattern: /^gitloop$/i, tool: 'gitloop' }, // MCP code indexing servers { pattern: /^claude[-_]?context$/i, tool: 'claude-context' }, { pattern: /^code[-_]?index[-_]?mcp$/i, tool: 'code-index-mcp' }, { pattern: /^code[-_]?index$/i, tool: 'code-index-mcp' }, { pattern: /^local[-_]?code[-_]?search$/i, tool: 'local-code-search' }, { pattern: /^codebase$/i, tool: 'autodev-codebase' }, { pattern: /^autodev[-_]?codebase$/i, tool: 'autodev-codebase' }, { pattern: /^code[-_]?context$/i, tool: 'claude-context' },]
/** * Detects if a bash command is using a code indexing CLI tool. * * @param command - The full bash command string * @returns The code indexing tool identifier, or undefined if not a code indexing command * * @example * detectCodeIndexingFromCommand('src search "pattern"') // returns 'sourcegraph' * detectCodeIndexingFromCommand('cody chat --message "help"') // returns 'cody' * detectCodeIndexingFromCommand('ls -la') // returns undefined */export function detectCodeIndexingFromCommand( command: string,): CodeIndexingTool | undefined { // Extract the first word (command name) const trimmed = command.trim() const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase()
if (!firstWord) { return undefined }
// Check for npx/bunx prefixed commands if (firstWord === 'npx' || firstWord === 'bunx') { const secondWord = trimmed.split(/\s+/)[1]?.toLowerCase() if (secondWord && secondWord in CLI_COMMAND_MAPPING) { return CLI_COMMAND_MAPPING[secondWord] } }
return CLI_COMMAND_MAPPING[firstWord]}
/** * Detects if an MCP tool is from a code indexing server. * * @param toolName - The MCP tool name (format: mcp__serverName__toolName) * @returns The code indexing tool identifier, or undefined if not a code indexing tool * * @example * detectCodeIndexingFromMcpTool('mcp__sourcegraph__search') // returns 'sourcegraph' * detectCodeIndexingFromMcpTool('mcp__cody__chat') // returns 'cody' * detectCodeIndexingFromMcpTool('mcp__filesystem__read') // returns undefined */export function detectCodeIndexingFromMcpTool( toolName: string,): CodeIndexingTool | undefined { // MCP tool names follow the format: mcp__serverName__toolName if (!toolName.startsWith('mcp__')) { return undefined }
const parts = toolName.split('__') if (parts.length < 3) { return undefined }
const serverName = parts[1] if (!serverName) { return undefined }
for (const { pattern, tool } of MCP_SERVER_PATTERNS) { if (pattern.test(serverName)) { return tool } }
return undefined}
/** * Detects if an MCP server name corresponds to a code indexing tool. * * @param serverName - The MCP server name * @returns The code indexing tool identifier, or undefined if not a code indexing server * * @example * detectCodeIndexingFromMcpServerName('sourcegraph') // returns 'sourcegraph' * detectCodeIndexingFromMcpServerName('filesystem') // returns undefined */export function detectCodeIndexingFromMcpServerName( serverName: string,): CodeIndexingTool | undefined { for (const { pattern, tool } of MCP_SERVER_PATTERNS) { if (pattern.test(serverName)) { return tool } }
return undefined}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { STATUS_TAG, SUMMARY_TAG, TASK_NOTIFICATION_TAG,} from '../constants/xml.js'import { BACKGROUND_BASH_SUMMARY_PREFIX } from '../tasks/LocalShellTask/LocalShellTask.js'import type { NormalizedUserMessage, RenderableMessage,} from '../types/message.js'import { isFullscreenEnvEnabled } from './fullscreen.js'import { extractTag } from './messages.js'
function isCompletedBackgroundBash( msg: RenderableMessage,): msg is NormalizedUserMessage { if (msg.type !== 'user') return false const content = msg.message.content[0] if (content?.type !== 'text') return false if (!content.text.includes(`<${TASK_NOTIFICATION_TAG}`)) return false // Only collapse successful completions — failed/killed stay visible individually. if (extractTag(content.text, STATUS_TAG) !== 'completed') return false // The prefix constant distinguishes bash-kind LocalShellTask completions from // agent/workflow/monitor notifications. Monitor-kind completions have their // own summary wording and deliberately don't collapse here. return ( extractTag(content.text, SUMMARY_TAG)?.startsWith( BACKGROUND_BASH_SUMMARY_PREFIX, ) ?? false )}
/** * Collapses consecutive completed-background-bash task-notifications into a * single synthetic "N background commands completed" notification. Failed/killed * tasks and agent/workflow notifications are left alone. Monitor stream * events (enqueueStreamEvent) have no <status> tag and never match. * * Pass-through in verbose mode so ctrl+O shows each completion. */export function collapseBackgroundBashNotifications( messages: RenderableMessage[], verbose: boolean,): RenderableMessage[] { if (!isFullscreenEnvEnabled()) return messages if (verbose) return messages
const result: RenderableMessage[] = [] let i = 0
while (i < messages.length) { const msg = messages[i]! if (isCompletedBackgroundBash(msg)) { let count = 0 while (i < messages.length && isCompletedBackgroundBash(messages[i]!)) { count++ i++ } if (count === 1) { result.push(msg) } else { // Synthesize a task-notification that UserAgentNotificationMessage // already knows how to render — no new renderer needed. result.push({ ...msg, message: { role: 'user', content: [ { type: 'text', text: `<${TASK_NOTIFICATION_TAG}><${STATUS_TAG}>completed</${STATUS_TAG}><${SUMMARY_TAG}>${count} background commands completed</${SUMMARY_TAG}></${TASK_NOTIFICATION_TAG}>`, }, ], }, }) } } else { result.push(msg) i++ } }
return result}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109import { feature } from 'bun:bundle'import type { UUID } from 'crypto'import { findToolByName, type Tools } from '../Tool.js'import { extractBashCommentLabel } from '../tools/BashTool/commentLabel.js'import { BASH_TOOL_NAME } from '../tools/BashTool/toolName.js'import { FILE_EDIT_TOOL_NAME } from '../tools/FileEditTool/constants.js'import { FILE_WRITE_TOOL_NAME } from '../tools/FileWriteTool/prompt.js'import { REPL_TOOL_NAME } from '../tools/REPLTool/constants.js'import { getReplPrimitiveTools } from '../tools/REPLTool/primitiveTools.js'import { type BranchAction, type CommitKind, detectGitOperation, type PrAction,} from '../tools/shared/gitOperationTracking.js'import { TOOL_SEARCH_TOOL_NAME } from '../tools/ToolSearchTool/prompt.js'import type { CollapsedReadSearchGroup, CollapsibleMessage, RenderableMessage, StopHookInfo, SystemStopHookSummaryMessage,} from '../types/message.js'import { getDisplayPath } from './file.js'import { isFullscreenEnvEnabled } from './fullscreen.js'import { isAutoManagedMemoryFile, isAutoManagedMemoryPattern, isMemoryDirectory, isShellCommandTargetingMemory,} from './memoryFileDetection.js'
/* eslint-disable @typescript-eslint/no-require-imports */const teamMemOps = feature('TEAMMEM') ? (require('./teamMemoryOps.js') as typeof import('./teamMemoryOps.js')) : nullconst SNIP_TOOL_NAME = feature('HISTORY_SNIP') ? ( require('../tools/SnipTool/prompt.js') as typeof import('../tools/SnipTool/prompt.js') ).SNIP_TOOL_NAME : null/* eslint-enable @typescript-eslint/no-require-imports */
/** * Result of checking if a tool use is a search or read operation. */export type SearchOrReadResult = { isCollapsible: boolean isSearch: boolean isRead: boolean isList: boolean isREPL: boolean /** True if this is a Write/Edit targeting a memory file */ isMemoryWrite: boolean /** * True for meta-operations that should be absorbed into a collapse group * without incrementing any count (Snip, ToolSearch). They remain visible * in verbose mode via the groupMessages iteration. */ isAbsorbedSilently: boolean /** MCP server name when this is an MCP tool */ mcpServerName?: string /** Bash command that is NOT a search/read (under fullscreen mode) */ isBash?: boolean}
/** * Extract the primary file/directory path from a tool_use input. * Handles both `file_path` (Read/Write/Edit) and `path` (Grep/Glob). */function getFilePathFromToolInput(toolInput: unknown): string | undefined { const input = toolInput as | { file_path?: string; path?: string; pattern?: string; glob?: string } | undefined return input?.file_path ?? input?.path}
/** * Check if a search tool use targets memory files by examining its path, pattern, and glob. */function isMemorySearch(toolInput: unknown): boolean { const input = toolInput as | { path?: string; pattern?: string; glob?: string; command?: string } | undefined if (!input) { return false } // Check if the search path targets a memory file or directory (Grep/Glob tools) if (input.path) { if (isAutoManagedMemoryFile(input.path) || isMemoryDirectory(input.path)) { return true } } // Check glob patterns that indicate memory file access if (input.glob && isAutoManagedMemoryPattern(input.glob)) { return true } // For shell commands (bash grep/rg, PowerShell Select-String, etc.), // check if the command targets memory paths if (input.command && isShellCommandTargetingMemory(input.command)) { return true } return false}
/** * Check if a Write or Edit tool use targets a memory file and should be collapsed. */function isMemoryWriteOrEdit(toolName: string, toolInput: unknown): boolean { if (toolName !== FILE_WRITE_TOOL_NAME && toolName !== FILE_EDIT_TOOL_NAME) { return false } const filePath = getFilePathFromToolInput(toolInput) return filePath !== undefined && isAutoManagedMemoryFile(filePath)}
// ~5 lines × ~60 cols. Generous static cap — the renderer lets Ink wrap.const MAX_HINT_CHARS = 300
/** * Format a bash command for the ⎿ hint. Drops blank lines, collapses runs of * inline whitespace, then caps total length. Newlines are preserved so the * renderer can indent continuation lines under ⎿. */function commandAsHint(command: string): string { const cleaned = '$ ' + command .split('\n') .map(l => l.replace(/\s+/g, ' ').trim()) .filter(l => l !== '') .join('\n') return cleaned.length > MAX_HINT_CHARS ? cleaned.slice(0, MAX_HINT_CHARS - 1) + '…' : cleaned}
/** * Checks if a tool is a search/read operation using the tool's isSearchOrReadCommand method. * Also treats Write/Edit of memory files as collapsible. * Returns detailed information about whether it's a search or read operation. */export function getToolSearchOrReadInfo( toolName: string, toolInput: unknown, tools: Tools,): SearchOrReadResult { // REPL is absorbed silently — its inner tool calls are emitted as virtual // messages (isVirtual: true) via newMessages and flow through this function // as regular Read/Grep/Bash messages. The REPL wrapper itself contributes // no counts and doesn't break the group, so consecutive REPL calls merge. if (toolName === REPL_TOOL_NAME) { return { isCollapsible: true, isSearch: false, isRead: false, isList: false, isREPL: true, isMemoryWrite: false, isAbsorbedSilently: true, } }
// Memory file writes/edits are collapsible if (isMemoryWriteOrEdit(toolName, toolInput)) { return { isCollapsible: true, isSearch: false, isRead: false, isList: false, isREPL: false, isMemoryWrite: true, isAbsorbedSilently: false, } }
// Meta-operations absorbed silently: Snip (context cleanup) and ToolSearch // (lazy tool schema loading). Neither should break a collapse group or // contribute to its count, but both stay visible in verbose mode. if ( (feature('HISTORY_SNIP') && toolName === SNIP_TOOL_NAME) || (isFullscreenEnvEnabled() && toolName === TOOL_SEARCH_TOOL_NAME) ) { return { isCollapsible: true, isSearch: false, isRead: false, isList: false, isREPL: false, isMemoryWrite: false, isAbsorbedSilently: true, } }
// Fallback to REPL primitives: in REPL mode, Bash/Read/Grep/etc. are // stripped from the execution tools list, but REPL emits them as virtual // messages. Without the fallback they'd return isCollapsible: false and // vanish from the summary line. const tool = findToolByName(tools, toolName) ?? findToolByName(getReplPrimitiveTools(), toolName) if (!tool?.isSearchOrReadCommand) { return { isCollapsible: false, isSearch: false, isRead: false, isList: false, isREPL: false, isMemoryWrite: false, isAbsorbedSilently: false, } } // The tool's isSearchOrReadCommand method handles its own input validation via safeParse, // so passing the raw input is safe. The type assertion is necessary because Tool[] uses // the default generic which expects { [x: string]: any }, but we receive unknown at runtime. const result = tool.isSearchOrReadCommand( toolInput as { [x: string]: unknown }, ) const isList = result.isList ?? false const isCollapsible = result.isSearch || result.isRead || isList // Under fullscreen mode, non-search/read Bash commands are also collapsible // as their own category — "Ran N bash commands" instead of breaking the group. return { isCollapsible: isCollapsible || (isFullscreenEnvEnabled() ? toolName === BASH_TOOL_NAME : false), isSearch: result.isSearch, isRead: result.isRead, isList, isREPL: false, isMemoryWrite: false, isAbsorbedSilently: false, ...(tool.isMcp && { mcpServerName: tool.mcpInfo?.serverName }), isBash: isFullscreenEnvEnabled() ? !isCollapsible && toolName === BASH_TOOL_NAME : undefined, }}
/** * Check if a tool_use content block is a search/read operation. * Returns { isSearch, isRead, isREPL } if it's a collapsible search/read, null otherwise. */export function getSearchOrReadFromContent( content: { type: string; name?: string; input?: unknown } | undefined, tools: Tools,): { isSearch: boolean isRead: boolean isList: boolean isREPL: boolean isMemoryWrite: boolean isAbsorbedSilently: boolean mcpServerName?: string isBash?: boolean} | null { if (content?.type === 'tool_use' && content.name) { const info = getToolSearchOrReadInfo(content.name, content.input, tools) if (info.isCollapsible || info.isREPL) { return { isSearch: info.isSearch, isRead: info.isRead, isList: info.isList, isREPL: info.isREPL, isMemoryWrite: info.isMemoryWrite, isAbsorbedSilently: info.isAbsorbedSilently, mcpServerName: info.mcpServerName, isBash: info.isBash, } } } return null}
/** * Checks if a tool is a search/read operation (for backwards compatibility). */function isToolSearchOrRead( toolName: string, toolInput: unknown, tools: Tools,): boolean { return getToolSearchOrReadInfo(toolName, toolInput, tools).isCollapsible}
/** * Get the tool name, input, and search/read info from a message if it's a collapsible tool use. * Returns null if the message is not a collapsible tool use. */function getCollapsibleToolInfo( msg: RenderableMessage, tools: Tools,): { name: string input: unknown isSearch: boolean isRead: boolean isList: boolean isREPL: boolean isMemoryWrite: boolean isAbsorbedSilently: boolean mcpServerName?: string isBash?: boolean} | null { if (msg.type === 'assistant') { const content = msg.message.content[0] const info = getSearchOrReadFromContent(content, tools) if (info && content?.type === 'tool_use') { return { name: content.name, input: content.input, ...info } } } if (msg.type === 'grouped_tool_use') { // For grouped tool uses, check the first message's input const firstContent = msg.messages[0]?.message.content[0] const info = getSearchOrReadFromContent( firstContent ? { type: 'tool_use', name: msg.toolName, input: firstContent.input } : undefined, tools, ) if (info && firstContent?.type === 'tool_use') { return { name: msg.toolName, input: firstContent.input, ...info } } } return null}
/** * Check if a message is assistant text that should break a group. */function isTextBreaker(msg: RenderableMessage): boolean { if (msg.type === 'assistant') { const content = msg.message.content[0] if (content?.type === 'text' && content.text.trim().length > 0) { return true } } return false}
/** * Check if a message is a non-collapsible tool use that should break a group. * This includes tool uses like Edit, Write, etc. */function isNonCollapsibleToolUse( msg: RenderableMessage, tools: Tools,): boolean { if (msg.type === 'assistant') { const content = msg.message.content[0] if ( content?.type === 'tool_use' && !isToolSearchOrRead(content.name, content.input, tools) ) { return true } } if (msg.type === 'grouped_tool_use') { const firstContent = msg.messages[0]?.message.content[0] if ( firstContent?.type === 'tool_use' && !isToolSearchOrRead(msg.toolName, firstContent.input, tools) ) { return true } } return false}
function isPreToolHookSummary( msg: RenderableMessage,): msg is SystemStopHookSummaryMessage { return ( msg.type === 'system' && msg.subtype === 'stop_hook_summary' && msg.hookLabel === 'PreToolUse' )}
/** * Check if a message should be skipped (not break the group, just passed through). * This includes thinking blocks, redacted thinking, attachments, etc. */function shouldSkipMessage(msg: RenderableMessage): boolean { if (msg.type === 'assistant') { const content = msg.message.content[0] // Skip thinking blocks and other non-text, non-tool content if (content?.type === 'thinking' || content?.type === 'redacted_thinking') { return true } } // Skip attachment messages if (msg.type === 'attachment') { return true } // Skip system messages if (msg.type === 'system') { return true } return false}
/** * Type predicate: Check if a message is a collapsible tool use. */function isCollapsibleToolUse( msg: RenderableMessage, tools: Tools,): msg is CollapsibleMessage { if (msg.type === 'assistant') { const content = msg.message.content[0] return ( content?.type === 'tool_use' && isToolSearchOrRead(content.name, content.input, tools) ) } if (msg.type === 'grouped_tool_use') { const firstContent = msg.messages[0]?.message.content[0] return ( firstContent?.type === 'tool_use' && isToolSearchOrRead(msg.toolName, firstContent.input, tools) ) } return false}
/** * Type predicate: Check if a message is a tool result for collapsible tools. * Returns true if ALL tool results in the message are for tracked collapsible tools. */function isCollapsibleToolResult( msg: RenderableMessage, collapsibleToolUseIds: Set<string>,): msg is CollapsibleMessage { if (msg.type === 'user') { const toolResults = msg.message.content.filter( (c): c is { type: 'tool_result'; tool_use_id: string } => c.type === 'tool_result', ) // Only return true if there are tool results AND all of them are for collapsible tools return ( toolResults.length > 0 && toolResults.every(r => collapsibleToolUseIds.has(r.tool_use_id)) ) } return false}
/** * Get all tool use IDs from a single message (handles grouped tool uses). */function getToolUseIdsFromMessage(msg: RenderableMessage): string[] { if (msg.type === 'assistant') { const content = msg.message.content[0] if (content?.type === 'tool_use') { return [content.id] } } if (msg.type === 'grouped_tool_use') { return msg.messages .map(m => { const content = m.message.content[0] return content.type === 'tool_use' ? content.id : '' }) .filter(Boolean) } return []}
/** * Get all tool use IDs from a collapsed read/search group. */export function getToolUseIdsFromCollapsedGroup( message: CollapsedReadSearchGroup,): string[] { const ids: string[] = [] for (const msg of message.messages) { ids.push(...getToolUseIdsFromMessage(msg)) } return ids}
/** * Check if any tool in a collapsed group is in progress. */export function hasAnyToolInProgress( message: CollapsedReadSearchGroup, inProgressToolUseIDs: Set<string>,): boolean { return getToolUseIdsFromCollapsedGroup(message).some(id => inProgressToolUseIDs.has(id), )}
/** * Get the underlying NormalizedMessage for display (timestamp/model). * Handles nested GroupedToolUseMessage within collapsed groups. * Returns a NormalizedAssistantMessage or NormalizedUserMessage (never GroupedToolUseMessage). */export function getDisplayMessageFromCollapsed( message: CollapsedReadSearchGroup,): Exclude<CollapsibleMessage, { type: 'grouped_tool_use' }> { const firstMsg = message.displayMessage if (firstMsg.type === 'grouped_tool_use') { return firstMsg.displayMessage } return firstMsg}
/** * Count the number of tool uses in a message (handles grouped tool uses). */function countToolUses(msg: RenderableMessage): number { if (msg.type === 'grouped_tool_use') { return msg.messages.length } return 1}
/** * Extract file paths from read tool inputs in a message. * Returns an array of file paths (may have duplicates if same file is read multiple times in one grouped message). */function getFilePathsFromReadMessage(msg: RenderableMessage): string[] { const paths: string[] = []
if (msg.type === 'assistant') { const content = msg.message.content[0] if (content?.type === 'tool_use') { const input = content.input as { file_path?: string } | undefined if (input?.file_path) { paths.push(input.file_path) } } } else if (msg.type === 'grouped_tool_use') { for (const m of msg.messages) { const content = m.message.content[0] if (content?.type === 'tool_use') { const input = content.input as { file_path?: string } | undefined if (input?.file_path) { paths.push(input.file_path) } } } }
return paths}
/** * Scan a bash tool result for commit SHAs and PR URLs and push them into the * group accumulator. Called only for results whose tool_use_id was recorded * in bashCommands (non-search/read bash). */function scanBashResultForGitOps( msg: CollapsibleMessage, group: GroupAccumulator,): void { if (msg.type !== 'user') return const out = msg.toolUseResult as | { stdout?: string; stderr?: string } | undefined if (!out?.stdout && !out?.stderr) return // git push writes the ref update to stderr — scan both streams. const combined = (out.stdout ?? '') + '\n' + (out.stderr ?? '') for (const c of msg.message.content) { if (c.type !== 'tool_result') continue const command = group.bashCommands?.get(c.tool_use_id) if (!command) continue const { commit, push, branch, pr } = detectGitOperation(command, combined) if (commit) group.commits?.push(commit) if (push) group.pushes?.push(push) if (branch) group.branches?.push(branch) if (pr) group.prs?.push(pr) if (commit || push || branch || pr) { group.gitOpBashCount = (group.gitOpBashCount ?? 0) + 1 } }}
type GroupAccumulator = { messages: CollapsibleMessage[] searchCount: number readFilePaths: Set<string> // Count of read operations that don't have file paths (e.g., Bash cat commands) readOperationCount: number // Count of directory-listing operations (ls, tree, du) listCount: number toolUseIds: Set<string> // Memory file operation counts (tracked separately from regular counts) memorySearchCount: number memoryReadFilePaths: Set<string> memoryWriteCount: number // Team memory file operation counts (tracked separately) teamMemorySearchCount?: number teamMemoryReadFilePaths?: Set<string> teamMemoryWriteCount?: number // Non-memory search patterns for display beneath the collapsed summary nonMemSearchArgs: string[] /** Most recently added non-memory operation, pre-formatted for display */ latestDisplayHint: string | undefined // MCP tool calls (tracked separately so display says "Queried slack" not "Read N files") mcpCallCount?: number mcpServerNames?: Set<string> // Bash commands that aren't search/read (tracked separately for "Ran N bash commands") bashCount?: number // Bash tool_use_id → command string, so tool results can be scanned for // commit SHAs / PR URLs (surfaced as "committed abc123, created PR #42") bashCommands?: Map<string, string> commits?: { sha: string; kind: CommitKind }[] pushes?: { branch: string }[] branches?: { ref: string; action: BranchAction }[] prs?: { number: number; url?: string; action: PrAction }[] gitOpBashCount?: number // PreToolUse hook timing absorbed from hook summary messages hookTotalMs: number hookCount: number hookInfos: StopHookInfo[] // relevant_memories attachments absorbed into this group (auto-injected // memories, not explicit Read calls). Paths mirrored into readFilePaths + // memoryReadFilePaths so the inline "recalled N memories" text is accurate. relevantMemories?: { path: string; content: string; mtimeMs: number }[]}
function createEmptyGroup(): GroupAccumulator { const group: GroupAccumulator = { messages: [], searchCount: 0, readFilePaths: new Set(), readOperationCount: 0, listCount: 0, toolUseIds: new Set(), memorySearchCount: 0, memoryReadFilePaths: new Set(), memoryWriteCount: 0, nonMemSearchArgs: [], latestDisplayHint: undefined, hookTotalMs: 0, hookCount: 0, hookInfos: [], } if (feature('TEAMMEM')) { group.teamMemorySearchCount = 0 group.teamMemoryReadFilePaths = new Set() group.teamMemoryWriteCount = 0 } group.mcpCallCount = 0 group.mcpServerNames = new Set() if (isFullscreenEnvEnabled()) { group.bashCount = 0 group.bashCommands = new Map() group.commits = [] group.pushes = [] group.branches = [] group.prs = [] group.gitOpBashCount = 0 } return group}
function createCollapsedGroup( group: GroupAccumulator,): CollapsedReadSearchGroup { const firstMsg = group.messages[0]! // When file-path-based reads exist, use unique file count (Set.size) only. // Adding bash operation count on top would double-count — e.g. Read(README.md) // followed by Bash(wc -l README.md) should still show as 1 file, not 2. // Fall back to operation count only when there are no file-path reads (bash-only). const totalReadCount = group.readFilePaths.size > 0 ? group.readFilePaths.size : group.readOperationCount // memoryReadFilePaths ⊆ readFilePaths (both populated from Read tool calls), // so this count is safe to subtract from totalReadCount at readCount below. // Absorbed relevant_memories attachments are NOT in readFilePaths — added // separately after the subtraction so readCount stays correct. const toolMemoryReadCount = group.memoryReadFilePaths.size const memoryReadCount = toolMemoryReadCount + (group.relevantMemories?.length ?? 0) // Non-memory read file paths: exclude memory and team memory paths const teamMemReadPaths = feature('TEAMMEM') ? group.teamMemoryReadFilePaths : undefined const nonMemReadFilePaths = [...group.readFilePaths].filter( p => !group.memoryReadFilePaths.has(p) && !(teamMemReadPaths?.has(p) ?? false), ) const teamMemSearchCount = feature('TEAMMEM') ? (group.teamMemorySearchCount ?? 0) : 0 const teamMemReadCount = feature('TEAMMEM') ? (group.teamMemoryReadFilePaths?.size ?? 0) : 0 const teamMemWriteCount = feature('TEAMMEM') ? (group.teamMemoryWriteCount ?? 0) : 0 const result: CollapsedReadSearchGroup = { type: 'collapsed_read_search', // Subtract memory + team memory counts so regular counts only reflect non-memory operations searchCount: Math.max( 0, group.searchCount - group.memorySearchCount - teamMemSearchCount, ), readCount: Math.max( 0, totalReadCount - toolMemoryReadCount - teamMemReadCount, ), listCount: group.listCount, // REPL operations are intentionally not collapsed (see isCollapsible: false at line 32), // so replCount in collapsed groups is always 0. The replCount field is kept for // sub-agent progress display in AgentTool/UI.tsx which has a separate code path. replCount: 0, memorySearchCount: group.memorySearchCount, memoryReadCount, memoryWriteCount: group.memoryWriteCount, readFilePaths: nonMemReadFilePaths, searchArgs: group.nonMemSearchArgs, latestDisplayHint: group.latestDisplayHint, messages: group.messages, displayMessage: firstMsg, uuid: `collapsed-${firstMsg.uuid}` as UUID, timestamp: firstMsg.timestamp, } if (feature('TEAMMEM')) { result.teamMemorySearchCount = teamMemSearchCount result.teamMemoryReadCount = teamMemReadCount result.teamMemoryWriteCount = teamMemWriteCount } if ((group.mcpCallCount ?? 0) > 0) { result.mcpCallCount = group.mcpCallCount result.mcpServerNames = [...(group.mcpServerNames ?? [])] } if (isFullscreenEnvEnabled()) { if ((group.bashCount ?? 0) > 0) { result.bashCount = group.bashCount result.gitOpBashCount = group.gitOpBashCount } if ((group.commits?.length ?? 0) > 0) result.commits = group.commits if ((group.pushes?.length ?? 0) > 0) result.pushes = group.pushes if ((group.branches?.length ?? 0) > 0) result.branches = group.branches if ((group.prs?.length ?? 0) > 0) result.prs = group.prs } if (group.hookCount > 0) { result.hookTotalMs = group.hookTotalMs result.hookCount = group.hookCount result.hookInfos = group.hookInfos } if (group.relevantMemories && group.relevantMemories.length > 0) { result.relevantMemories = group.relevantMemories } return result}
/** * Collapse consecutive Read/Search operations into summary groups. * * Rules: * - Groups consecutive search/read tool uses (Grep, Glob, Read, and Bash search/read commands) * - Includes their corresponding tool results in the group * - Breaks groups when assistant text appears */export function collapseReadSearchGroups( messages: RenderableMessage[], tools: Tools,): RenderableMessage[] { const result: RenderableMessage[] = [] let currentGroup = createEmptyGroup() let deferredSkippable: RenderableMessage[] = []
function flushGroup(): void { if (currentGroup.messages.length === 0) { return } result.push(createCollapsedGroup(currentGroup)) for (const deferred of deferredSkippable) { result.push(deferred) } deferredSkippable = [] currentGroup = createEmptyGroup() }
for (const msg of messages) { if (isCollapsibleToolUse(msg, tools)) { // This is a collapsible tool use - type predicate narrows to CollapsibleMessage const toolInfo = getCollapsibleToolInfo(msg, tools)!
if (toolInfo.isMemoryWrite) { // Memory file write/edit — check if it's team memory const count = countToolUses(msg) if ( feature('TEAMMEM') && teamMemOps?.isTeamMemoryWriteOrEdit(toolInfo.name, toolInfo.input) ) { currentGroup.teamMemoryWriteCount = (currentGroup.teamMemoryWriteCount ?? 0) + count } else { currentGroup.memoryWriteCount += count } } else if (toolInfo.isAbsorbedSilently) { // Snip/ToolSearch absorbed silently — no count, no summary text. // Hidden from the default view but still shown in verbose mode // (Ctrl+O) via the groupMessages iteration in CollapsedReadSearchContent. } else if (toolInfo.mcpServerName) { // MCP search/read — counted separately so the summary says // "Queried slack N times" instead of "Read N files". const count = countToolUses(msg) currentGroup.mcpCallCount = (currentGroup.mcpCallCount ?? 0) + count currentGroup.mcpServerNames?.add(toolInfo.mcpServerName) const input = toolInfo.input as { query?: string } | undefined if (input?.query) { currentGroup.latestDisplayHint = `"${input.query}"` } } else if (isFullscreenEnvEnabled() && toolInfo.isBash) { // Non-search/read Bash command — counted separately so the summary // says "Ran N bash commands" instead of breaking the group. const count = countToolUses(msg) currentGroup.bashCount = (currentGroup.bashCount ?? 0) + count const input = toolInfo.input as { command?: string } | undefined if (input?.command) { // Prefer the stripped `# comment` if present (it's what Claude wrote // for the human — same trigger as the comment-as-label tool-use render). currentGroup.latestDisplayHint = extractBashCommentLabel(input.command) ?? commandAsHint(input.command) // Remember tool_use_id → command so the result (arriving next) can // be scanned for commit SHA / PR URL. for (const id of getToolUseIdsFromMessage(msg)) { currentGroup.bashCommands?.set(id, input.command) } } } else if (toolInfo.isList) { // Directory-listing bash commands (ls, tree, du) — counted separately // so the summary says "Listed N directories" instead of "Read N files". currentGroup.listCount += countToolUses(msg) const input = toolInfo.input as { command?: string } | undefined if (input?.command) { currentGroup.latestDisplayHint = commandAsHint(input.command) } } else if (toolInfo.isSearch) { // Use the isSearch flag from the tool to properly categorize bash search commands const count = countToolUses(msg) currentGroup.searchCount += count // Check if the search targets memory files (via path or glob pattern) if ( feature('TEAMMEM') && teamMemOps?.isTeamMemorySearch(toolInfo.input) ) { currentGroup.teamMemorySearchCount = (currentGroup.teamMemorySearchCount ?? 0) + count } else if (isMemorySearch(toolInfo.input)) { currentGroup.memorySearchCount += count } else { // Regular (non-memory) search — collect pattern for display const input = toolInfo.input as { pattern?: string } | undefined if (input?.pattern) { currentGroup.nonMemSearchArgs.push(input.pattern) currentGroup.latestDisplayHint = `"${input.pattern}"` } } } else { // For reads, track unique file paths instead of counting operations const filePaths = getFilePathsFromReadMessage(msg) for (const filePath of filePaths) { currentGroup.readFilePaths.add(filePath) if (feature('TEAMMEM') && teamMemOps?.isTeamMemFile(filePath)) { currentGroup.teamMemoryReadFilePaths?.add(filePath) } else if (isAutoManagedMemoryFile(filePath)) { currentGroup.memoryReadFilePaths.add(filePath) } else { // Non-memory file read — update display hint currentGroup.latestDisplayHint = getDisplayPath(filePath) } } // If no file paths found (e.g., Bash read commands like ls, cat), count the operations if (filePaths.length === 0) { currentGroup.readOperationCount += countToolUses(msg) // Use the Bash command as the display hint (truncated for readability) const input = toolInfo.input as { command?: string } | undefined if (input?.command) { currentGroup.latestDisplayHint = commandAsHint(input.command) } } }
// Track tool use IDs for matching results for (const id of getToolUseIdsFromMessage(msg)) { currentGroup.toolUseIds.add(id) }
currentGroup.messages.push(msg) } else if (isCollapsibleToolResult(msg, currentGroup.toolUseIds)) { currentGroup.messages.push(msg) // Scan bash results for commit SHAs / PR URLs to surface in the summary if (isFullscreenEnvEnabled() && currentGroup.bashCommands?.size) { scanBashResultForGitOps(msg, currentGroup) } } else if (currentGroup.messages.length > 0 && isPreToolHookSummary(msg)) { // Absorb PreToolUse hook summaries into the group instead of deferring currentGroup.hookCount += msg.hookCount currentGroup.hookTotalMs += msg.totalDurationMs ?? msg.hookInfos.reduce((sum, h) => sum + (h.durationMs ?? 0), 0) currentGroup.hookInfos.push(...msg.hookInfos) } else if ( currentGroup.messages.length > 0 && msg.type === 'attachment' && msg.attachment.type === 'relevant_memories' ) { // Absorb auto-injected memory attachments so "recalled N memories" // renders inline with "ran N bash commands" instead of as a separate // ⏺ block. Do NOT add paths to readFilePaths/memoryReadFilePaths — // that would poison the readOperationCount fallback (bash-only reads // have no paths; adding memory paths makes readFilePaths.size > 0 and // suppresses the fallback). createCollapsedGroup adds .length to // memoryReadCount after the readCount subtraction instead. currentGroup.relevantMemories ??= [] currentGroup.relevantMemories.push(...msg.attachment.memories) } else if (shouldSkipMessage(msg)) { // Don't flush the group for skippable messages (thinking, attachments, system) // If a group is in progress, defer these messages to output after the collapsed group // This preserves the visual ordering where the collapsed badge appears at the position // of the first tool use, not displaced by intervening skippable messages. // Exception: nested_memory attachments are pushed through even during a group so // ⎿ Loaded lines cluster tightly instead of being split by the badge's marginTop. if ( currentGroup.messages.length > 0 && !(msg.type === 'attachment' && msg.attachment.type === 'nested_memory') ) { deferredSkippable.push(msg) } else { result.push(msg) } } else if (isTextBreaker(msg)) { // Assistant text breaks the group flushGroup() result.push(msg) } else if (isNonCollapsibleToolUse(msg, tools)) { // Non-collapsible tool use breaks the group flushGroup() result.push(msg) } else { // User messages with non-collapsible tool results break the group flushGroup() result.push(msg) } }
flushGroup() return result}
/** * Generate a summary text for search/read/REPL counts. * @param searchCount Number of search operations * @param readCount Number of read operations * @param isActive Whether the group is still in progress (use present tense) or completed (use past tense) * @param replCount Number of REPL executions (optional) * @param memoryCounts Optional memory file operation counts * @returns Summary text like "Searching for 3 patterns, reading 2 files, REPL'd 5 times…" */export function getSearchReadSummaryText( searchCount: number, readCount: number, isActive: boolean, replCount: number = 0, memoryCounts?: { memorySearchCount: number memoryReadCount: number memoryWriteCount: number teamMemorySearchCount?: number teamMemoryReadCount?: number teamMemoryWriteCount?: number }, listCount: number = 0,): string { const parts: string[] = []
// Memory operations first if (memoryCounts) { const { memorySearchCount, memoryReadCount, memoryWriteCount } = memoryCounts if (memoryReadCount > 0) { const verb = isActive ? parts.length === 0 ? 'Recalling' : 'recalling' : parts.length === 0 ? 'Recalled' : 'recalled' parts.push( `${verb} ${memoryReadCount} ${memoryReadCount === 1 ? 'memory' : 'memories'}`, ) } if (memorySearchCount > 0) { const verb = isActive ? parts.length === 0 ? 'Searching' : 'searching' : parts.length === 0 ? 'Searched' : 'searched' parts.push(`${verb} memories`) } if (memoryWriteCount > 0) { const verb = isActive ? parts.length === 0 ? 'Writing' : 'writing' : parts.length === 0 ? 'Wrote' : 'wrote' parts.push( `${verb} ${memoryWriteCount} ${memoryWriteCount === 1 ? 'memory' : 'memories'}`, ) } // Team memory operations if (feature('TEAMMEM') && teamMemOps) { teamMemOps.appendTeamMemorySummaryParts(memoryCounts, isActive, parts) } }
if (searchCount > 0) { const searchVerb = isActive ? parts.length === 0 ? 'Searching for' : 'searching for' : parts.length === 0 ? 'Searched for' : 'searched for' parts.push( `${searchVerb} ${searchCount} ${searchCount === 1 ? 'pattern' : 'patterns'}`, ) }
if (readCount > 0) { const readVerb = isActive ? parts.length === 0 ? 'Reading' : 'reading' : parts.length === 0 ? 'Read' : 'read' parts.push(`${readVerb} ${readCount} ${readCount === 1 ? 'file' : 'files'}`) }
if (listCount > 0) { const listVerb = isActive ? parts.length === 0 ? 'Listing' : 'listing' : parts.length === 0 ? 'Listed' : 'listed' parts.push( `${listVerb} ${listCount} ${listCount === 1 ? 'directory' : 'directories'}`, ) }
if (replCount > 0) { const replVerb = isActive ? "REPL'ing" : "REPL'd" parts.push(`${replVerb} ${replCount} ${replCount === 1 ? 'time' : 'times'}`) }
const text = parts.join(', ') return isActive ? `${text}…` : text}
/** * Summarize a list of recent tool activities into a compact description. * Rolls up trailing consecutive search/read operations using pre-computed * isSearch/isRead classifications from recording time. Falls back to the * last activity's description for non-collapsible tool uses. */export function summarizeRecentActivities( activities: readonly { activityDescription?: string isSearch?: boolean isRead?: boolean }[],): string | undefined { if (activities.length === 0) { return undefined } // Count trailing search/read activities from the end of the list let searchCount = 0 let readCount = 0 for (let i = activities.length - 1; i >= 0; i--) { const activity = activities[i]! if (activity.isSearch) { searchCount++ } else if (activity.isRead) { readCount++ } else { break } } const collapsibleCount = searchCount + readCount if (collapsibleCount >= 2) { return getSearchReadSummaryText(searchCount, readCount, true) } // Fall back to most recent activity with a description (some tools like // SendMessage don't implement getActivityDescription, so search backward) for (let i = activities.length - 1; i >= 0; i--) { if (activities[i]?.activityDescription) { return activities[i]!.activityDescription } } return undefined}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import type { AttachmentMessage, RenderableMessage } from '../types/message.js'
function isTeammateShutdownAttachment( msg: RenderableMessage,): msg is AttachmentMessage { return ( msg.type === 'attachment' && msg.attachment.type === 'task_status' && msg.attachment.taskType === 'in_process_teammate' && msg.attachment.status === 'completed' )}
/** * Collapses consecutive in-process teammate shutdown task_status attachments * into a single `teammate_shutdown_batch` attachment with a count. */export function collapseTeammateShutdowns( messages: RenderableMessage[],): RenderableMessage[] { const result: RenderableMessage[] = [] let i = 0
while (i < messages.length) { const msg = messages[i]! if (isTeammateShutdownAttachment(msg)) { let count = 0 while ( i < messages.length && isTeammateShutdownAttachment(messages[i]!) ) { count++ i++ } if (count === 1) { result.push(msg) } else { result.push({ type: 'attachment', uuid: msg.uuid, timestamp: msg.timestamp, attachment: { type: 'teammate_shutdown_batch', count, }, }) } } else { result.push(msg) i++ } }
return result}123456789101112131415161718192021type CommandLifecycleState = 'started' | 'completed'
type CommandLifecycleListener = ( uuid: string, state: CommandLifecycleState,) => void
let listener: CommandLifecycleListener | null = null
export function setCommandLifecycleListener( cb: CommandLifecycleListener | null,): void { listener = cb}
export function notifyCommandLifecycle( uuid: string, state: CommandLifecycleState,): void { listener?.(uuid, state)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961import { createHash, randomUUID, type UUID } from 'crypto'import { stat } from 'fs/promises'import { isAbsolute, join, relative, sep } from 'path'import { getOriginalCwd, getSessionId } from '../bootstrap/state.js'import type { AttributionSnapshotMessage, FileAttributionState,} from '../types/logs.js'import { getCwd } from './cwd.js'import { logForDebugging } from './debug.js'import { execFileNoThrowWithCwd } from './execFileNoThrow.js'import { getFsImplementation } from './fsOperations.js'import { isGeneratedFile } from './generatedFiles.js'import { getRemoteUrlForDir, resolveGitDir } from './git/gitFilesystem.js'import { findGitRoot, gitExe } from './git.js'import { logError } from './log.js'import { getCanonicalName, type ModelName } from './model/model.js'import { sequential } from './sequential.js'
/** * List of repos where internal model names are allowed in trailers. * Includes both SSH and HTTPS URL formats. * * NOTE: This is intentionally a repo allowlist, not an org-wide check. * The anthropics and anthropic-experimental orgs contain PUBLIC repos * (e.g. anthropics/claude-code, anthropic-experimental/sandbox-runtime). * Undercover mode must stay ON in those to prevent codename leaks. * Only add repos here that are confirmed PRIVATE. */const INTERNAL_MODEL_REPOS = [ 'github.com:anthropics/claude-cli-internal', 'github.com/anthropics/claude-cli-internal', 'github.com:anthropics/anthropic', 'github.com/anthropics/anthropic', 'github.com:anthropics/apps', 'github.com/anthropics/apps', 'github.com:anthropics/casino', 'github.com/anthropics/casino', 'github.com:anthropics/dbt', 'github.com/anthropics/dbt', 'github.com:anthropics/dotfiles', 'github.com/anthropics/dotfiles', 'github.com:anthropics/terraform-config', 'github.com/anthropics/terraform-config', 'github.com:anthropics/hex-export', 'github.com/anthropics/hex-export', 'github.com:anthropics/feedback-v2', 'github.com/anthropics/feedback-v2', 'github.com:anthropics/labs', 'github.com/anthropics/labs', 'github.com:anthropics/argo-rollouts', 'github.com/anthropics/argo-rollouts', 'github.com:anthropics/starling-configs', 'github.com/anthropics/starling-configs', 'github.com:anthropics/ts-tools', 'github.com/anthropics/ts-tools', 'github.com:anthropics/ts-capsules', 'github.com/anthropics/ts-capsules', 'github.com:anthropics/feldspar-testing', 'github.com/anthropics/feldspar-testing', 'github.com:anthropics/trellis', 'github.com/anthropics/trellis', 'github.com:anthropics/claude-for-hiring', 'github.com/anthropics/claude-for-hiring', 'github.com:anthropics/forge-web', 'github.com/anthropics/forge-web', 'github.com:anthropics/infra-manifests', 'github.com/anthropics/infra-manifests', 'github.com:anthropics/mycro_manifests', 'github.com/anthropics/mycro_manifests', 'github.com:anthropics/mycro_configs', 'github.com/anthropics/mycro_configs', 'github.com:anthropics/mobile-apps', 'github.com/anthropics/mobile-apps',]
/** * Get the repo root for attribution operations. * Uses getCwd() which respects agent worktree overrides (AsyncLocalStorage), * then resolves to git root to handle `cd subdir` case. * Falls back to getOriginalCwd() if git root can't be determined. */export function getAttributionRepoRoot(): string { const cwd = getCwd() return findGitRoot(cwd) ?? getOriginalCwd()}
// Cache for repo classification result. Primed once per process.// 'internal' = remote matches INTERNAL_MODEL_REPOS allowlist// 'external' = has a remote, not on allowlist (public/open-source repo)// 'none' = no remote URL (not a git repo, or no remote configured)let repoClassCache: 'internal' | 'external' | 'none' | null = null
/** * Synchronously return the cached repo classification. * Returns null if the async check hasn't run yet. */export function getRepoClassCached(): 'internal' | 'external' | 'none' | null { return repoClassCache}
/** * Synchronously return the cached result of isInternalModelRepo(). * Returns false if the check hasn't run yet (safe default: don't leak). */export function isInternalModelRepoCached(): boolean { return repoClassCache === 'internal'}
/** * Check if the current repo is in the allowlist for internal model names. * Memoized - only checks once per process. */export const isInternalModelRepo = sequential(async (): Promise<boolean> => { if (repoClassCache !== null) { return repoClassCache === 'internal' }
const cwd = getAttributionRepoRoot() const remoteUrl = await getRemoteUrlForDir(cwd)
if (!remoteUrl) { repoClassCache = 'none' return false } const isInternal = INTERNAL_MODEL_REPOS.some(repo => remoteUrl.includes(repo)) repoClassCache = isInternal ? 'internal' : 'external' return isInternal})
/** * Sanitize a surface key to use public model names. * Converts internal model variants to their public equivalents. */export function sanitizeSurfaceKey(surfaceKey: string): string { // Split surface key into surface and model parts (e.g., "cli/opus-4-5-fast" -> ["cli", "opus-4-5-fast"]) const slashIndex = surfaceKey.lastIndexOf('/') if (slashIndex === -1) { return surfaceKey }
const surface = surfaceKey.slice(0, slashIndex) const model = surfaceKey.slice(slashIndex + 1) const sanitizedModel = sanitizeModelName(model)
return `${surface}/${sanitizedModel}`}
// @[MODEL LAUNCH]: Add a mapping for the new model ID so git commit trailers show the public name./** * Sanitize a model name to its public equivalent. * Maps internal variants to their public names based on model family. */export function sanitizeModelName(shortName: string): string { // Map internal variants to public equivalents based on model family if (shortName.includes('opus-4-6')) return 'claude-opus-4-6' if (shortName.includes('opus-4-5')) return 'claude-opus-4-5' if (shortName.includes('opus-4-1')) return 'claude-opus-4-1' if (shortName.includes('opus-4')) return 'claude-opus-4' if (shortName.includes('sonnet-4-6')) return 'claude-sonnet-4-6' if (shortName.includes('sonnet-4-5')) return 'claude-sonnet-4-5' if (shortName.includes('sonnet-4')) return 'claude-sonnet-4' if (shortName.includes('sonnet-3-7')) return 'claude-sonnet-3-7' if (shortName.includes('haiku-4-5')) return 'claude-haiku-4-5' if (shortName.includes('haiku-3-5')) return 'claude-haiku-3-5' // Unknown models get a generic name return 'claude'}
/** * Attribution state for tracking Claude's contributions to files. */export type AttributionState = { // File states keyed by relative path (from cwd) fileStates: Map<string, FileAttributionState> // Session baseline states for net change calculation sessionBaselines: Map<string, { contentHash: string; mtime: number }> // Surface from which edits were made surface: string // HEAD SHA at session start (for detecting external commits) startingHeadSha: string | null // Total prompts in session (for steer count calculation) promptCount: number // Prompts at last commit (to calculate steers for current commit) promptCountAtLastCommit: number // Permission prompt tracking permissionPromptCount: number permissionPromptCountAtLastCommit: number // ESC press tracking (user cancelled permission prompt) escapeCount: number escapeCountAtLastCommit: number}
/** * Summary of Claude's contribution for a commit. */export type AttributionSummary = { claudePercent: number claudeChars: number humanChars: number surfaces: string[]}
/** * Per-file attribution details for git notes. */export type FileAttribution = { claudeChars: number humanChars: number percent: number surface: string}
/** * Full attribution data for git notes JSON. */export type AttributionData = { version: 1 summary: AttributionSummary files: Record<string, FileAttribution> surfaceBreakdown: Record<string, { claudeChars: number; percent: number }> excludedGenerated: string[] sessions: string[]}
/** * Get the current client surface from environment. */export function getClientSurface(): string { return process.env.CLAUDE_CODE_ENTRYPOINT ?? 'cli'}
/** * Build a surface key that includes the model name. * Format: "surface/model" (e.g., "cli/claude-sonnet") */export function buildSurfaceKey(surface: string, model: ModelName): string { return `${surface}/${getCanonicalName(model)}`}
/** * Compute SHA-256 hash of content. */export function computeContentHash(content: string): string { return createHash('sha256').update(content).digest('hex')}
/** * Normalize file path to relative path from cwd for consistent tracking. * Resolves symlinks to handle /tmp vs /private/tmp on macOS. */export function normalizeFilePath(filePath: string): string { const fs = getFsImplementation() const cwd = getAttributionRepoRoot()
if (!isAbsolute(filePath)) { return filePath }
// Resolve symlinks in both paths for consistent comparison // (e.g., /tmp -> /private/tmp on macOS) let resolvedPath = filePath let resolvedCwd = cwd
try { resolvedPath = fs.realpathSync(filePath) } catch { // File may not exist yet, use original path }
try { resolvedCwd = fs.realpathSync(cwd) } catch { // Keep original cwd }
if ( resolvedPath.startsWith(resolvedCwd + sep) || resolvedPath === resolvedCwd ) { // Normalize to forward slashes so keys match git diff output on Windows return relative(resolvedCwd, resolvedPath).replaceAll(sep, '/') }
// Fallback: try original comparison if (filePath.startsWith(cwd + sep) || filePath === cwd) { return relative(cwd, filePath).replaceAll(sep, '/') }
return filePath}
/** * Expand a relative path to absolute path. */export function expandFilePath(filePath: string): string { if (isAbsolute(filePath)) { return filePath } return join(getAttributionRepoRoot(), filePath)}
/** * Create an empty attribution state for a new session. */export function createEmptyAttributionState(): AttributionState { return { fileStates: new Map(), sessionBaselines: new Map(), surface: getClientSurface(), startingHeadSha: null, promptCount: 0, promptCountAtLastCommit: 0, permissionPromptCount: 0, permissionPromptCountAtLastCommit: 0, escapeCount: 0, escapeCountAtLastCommit: 0, }}
/** * Compute the character contribution for a file modification. * Returns the FileAttributionState to store, or null if tracking failed. */function computeFileModificationState( existingFileStates: Map<string, FileAttributionState>, filePath: string, oldContent: string, newContent: string, mtime: number,): FileAttributionState | null { const normalizedPath = normalizeFilePath(filePath)
try { // Calculate Claude's character contribution let claudeContribution: number
if (oldContent === '' || newContent === '') { // New file or full deletion - contribution is the content length claudeContribution = oldContent === '' ? newContent.length : oldContent.length } else { // Find actual changed region via common prefix/suffix matching. // This correctly handles same-length replacements (e.g., "Esc" → "esc") // where Math.abs(newLen - oldLen) would be 0. const minLen = Math.min(oldContent.length, newContent.length) let prefixEnd = 0 while ( prefixEnd < minLen && oldContent[prefixEnd] === newContent[prefixEnd] ) { prefixEnd++ } let suffixLen = 0 while ( suffixLen < minLen - prefixEnd && oldContent[oldContent.length - 1 - suffixLen] === newContent[newContent.length - 1 - suffixLen] ) { suffixLen++ } const oldChangedLen = oldContent.length - prefixEnd - suffixLen const newChangedLen = newContent.length - prefixEnd - suffixLen claudeContribution = Math.max(oldChangedLen, newChangedLen) }
// Get current file state if it exists const existingState = existingFileStates.get(normalizedPath) const existingContribution = existingState?.claudeContribution ?? 0
return { contentHash: computeContentHash(newContent), claudeContribution: existingContribution + claudeContribution, mtime, } } catch (error) { logError(error as Error) return null }}
/** * Get a file's modification time (mtimeMs), falling back to Date.now() if * the file doesn't exist. This is async so it can be precomputed before * entering a sync setAppState callback. */export async function getFileMtime(filePath: string): Promise<number> { const normalizedPath = normalizeFilePath(filePath) const absPath = expandFilePath(normalizedPath) try { const stats = await stat(absPath) return stats.mtimeMs } catch { return Date.now() }}
/** * Track a file modification by Claude. * Called after Edit/Write tool completes. */export function trackFileModification( state: AttributionState, filePath: string, oldContent: string, newContent: string, _userModified: boolean, mtime: number = Date.now(),): AttributionState { const normalizedPath = normalizeFilePath(filePath) const newFileState = computeFileModificationState( state.fileStates, filePath, oldContent, newContent, mtime, ) if (!newFileState) { return state }
const newFileStates = new Map(state.fileStates) newFileStates.set(normalizedPath, newFileState)
logForDebugging( `Attribution: Tracked ${newFileState.claudeContribution} chars for ${normalizedPath}`, )
return { ...state, fileStates: newFileStates, }}
/** * Track a file creation by Claude (e.g., via bash command). * Used when Claude creates a new file through a non-tracked mechanism. */export function trackFileCreation( state: AttributionState, filePath: string, content: string, mtime: number = Date.now(),): AttributionState { // A creation is simply a modification from empty to the new content return trackFileModification(state, filePath, '', content, false, mtime)}
/** * Track a file deletion by Claude (e.g., via bash rm command). * Used when Claude deletes a file through a non-tracked mechanism. */export function trackFileDeletion( state: AttributionState, filePath: string, oldContent: string,): AttributionState { const normalizedPath = normalizeFilePath(filePath) const existingState = state.fileStates.get(normalizedPath) const existingContribution = existingState?.claudeContribution ?? 0 const deletedChars = oldContent.length
const newFileState: FileAttributionState = { contentHash: '', // Empty hash for deleted files claudeContribution: existingContribution + deletedChars, mtime: Date.now(), }
const newFileStates = new Map(state.fileStates) newFileStates.set(normalizedPath, newFileState)
logForDebugging( `Attribution: Tracked deletion of ${normalizedPath} (${deletedChars} chars removed, total contribution: ${newFileState.claudeContribution})`, )
return { ...state, fileStates: newFileStates, }}
// --
/** * Track multiple file changes in bulk, mutating a single Map copy. * This avoids the O(n²) cost of copying the Map per file when processing * large git diffs (e.g., jj operations that touch hundreds of thousands of files). */export function trackBulkFileChanges( state: AttributionState, changes: ReadonlyArray<{ path: string type: 'modified' | 'created' | 'deleted' oldContent: string newContent: string mtime?: number }>,): AttributionState { // Create ONE copy of the Map, then mutate it for each file const newFileStates = new Map(state.fileStates)
for (const change of changes) { const mtime = change.mtime ?? Date.now() if (change.type === 'deleted') { const normalizedPath = normalizeFilePath(change.path) const existingState = newFileStates.get(normalizedPath) const existingContribution = existingState?.claudeContribution ?? 0 const deletedChars = change.oldContent.length
newFileStates.set(normalizedPath, { contentHash: '', claudeContribution: existingContribution + deletedChars, mtime, })
logForDebugging( `Attribution: Tracked deletion of ${normalizedPath} (${deletedChars} chars removed, total contribution: ${existingContribution + deletedChars})`, ) } else { const newFileState = computeFileModificationState( newFileStates, change.path, change.oldContent, change.newContent, mtime, ) if (newFileState) { const normalizedPath = normalizeFilePath(change.path) newFileStates.set(normalizedPath, newFileState)
logForDebugging( `Attribution: Tracked ${newFileState.claudeContribution} chars for ${normalizedPath}`, ) } } }
return { ...state, fileStates: newFileStates, }}
/** * Calculate final attribution for staged files. * Compares session baseline to committed state. */export async function calculateCommitAttribution( states: AttributionState[], stagedFiles: string[],): Promise<AttributionData> { const cwd = getAttributionRepoRoot() const sessionId = getSessionId()
const files: Record<string, FileAttribution> = {} const excludedGenerated: string[] = [] const surfaces = new Set<string>() const surfaceCounts: Record<string, number> = {}
let totalClaudeChars = 0 let totalHumanChars = 0
// Merge file states from all sessions const mergedFileStates = new Map<string, FileAttributionState>() const mergedBaselines = new Map< string, { contentHash: string; mtime: number } >()
for (const state of states) { surfaces.add(state.surface)
// Merge baselines (earliest baseline wins) // Handle both Map and plain object (in case of serialization) const baselines = state.sessionBaselines instanceof Map ? state.sessionBaselines : new Map( Object.entries( (state.sessionBaselines ?? {}) as Record< string, { contentHash: string; mtime: number } >, ), ) for (const [path, baseline] of baselines) { if (!mergedBaselines.has(path)) { mergedBaselines.set(path, baseline) } }
// Merge file states (accumulate contributions) // Handle both Map and plain object (in case of serialization) const fileStates = state.fileStates instanceof Map ? state.fileStates : new Map( Object.entries( (state.fileStates ?? {}) as Record<string, FileAttributionState>, ), ) for (const [path, fileState] of fileStates) { const existing = mergedFileStates.get(path) if (existing) { mergedFileStates.set(path, { ...fileState, claudeContribution: existing.claudeContribution + fileState.claudeContribution, }) } else { mergedFileStates.set(path, fileState) } } }
// Process files in parallel const fileResults = await Promise.all( stagedFiles.map(async file => { // Skip generated files if (isGeneratedFile(file)) { return { type: 'generated' as const, file } }
const absPath = join(cwd, file) const fileState = mergedFileStates.get(file) const baseline = mergedBaselines.get(file)
// Get the surface for this file const fileSurface = states[0]!.surface
let claudeChars = 0 let humanChars = 0
// Check if file was deleted const deleted = await isFileDeleted(file)
if (deleted) { // File was deleted if (fileState) { // Claude deleted this file (tracked deletion) claudeChars = fileState.claudeContribution humanChars = 0 } else { // Human deleted this file (untracked deletion) // Use diff size to get the actual change size const diffSize = await getGitDiffSize(file) humanChars = diffSize > 0 ? diffSize : 100 // Minimum attribution for a deletion } } else { try { // Only need file size, not content - stat() avoids loading GB-scale // build artifacts into memory when they appear in the working tree. // stats.size (bytes) is an adequate proxy for char count here. const stats = await stat(absPath)
if (fileState) { // We have tracked modifications for this file claudeChars = fileState.claudeContribution humanChars = 0 } else if (baseline) { // File was modified but not tracked - human modification const diffSize = await getGitDiffSize(file) humanChars = diffSize > 0 ? diffSize : stats.size } else { // New file not created by Claude humanChars = stats.size } } catch { // File doesn't exist or stat failed - skip it return null } }
// Ensure non-negative values claudeChars = Math.max(0, claudeChars) humanChars = Math.max(0, humanChars)
const total = claudeChars + humanChars const percent = total > 0 ? Math.round((claudeChars / total) * 100) : 0
return { type: 'file' as const, file, claudeChars, humanChars, percent, surface: fileSurface, } }), )
// Aggregate results for (const result of fileResults) { if (!result) continue
if (result.type === 'generated') { excludedGenerated.push(result.file) continue }
files[result.file] = { claudeChars: result.claudeChars, humanChars: result.humanChars, percent: result.percent, surface: result.surface, }
totalClaudeChars += result.claudeChars totalHumanChars += result.humanChars
surfaceCounts[result.surface] = (surfaceCounts[result.surface] ?? 0) + result.claudeChars }
const totalChars = totalClaudeChars + totalHumanChars const claudePercent = totalChars > 0 ? Math.round((totalClaudeChars / totalChars) * 100) : 0
// Calculate surface breakdown (percentage of total content per surface) const surfaceBreakdown: Record< string, { claudeChars: number; percent: number } > = {} for (const [surface, chars] of Object.entries(surfaceCounts)) { // Calculate what percentage of TOTAL content this surface contributed const percent = totalChars > 0 ? Math.round((chars / totalChars) * 100) : 0 surfaceBreakdown[surface] = { claudeChars: chars, percent } }
return { version: 1, summary: { claudePercent, claudeChars: totalClaudeChars, humanChars: totalHumanChars, surfaces: Array.from(surfaces), }, files, surfaceBreakdown, excludedGenerated, sessions: [sessionId], }}
/** * Get the size of changes for a file from git diff. * Returns the number of characters added/removed (absolute difference). * For new files, returns the total file size. * For deleted files, returns the size of the deleted content. */export async function getGitDiffSize(filePath: string): Promise<number> { const cwd = getAttributionRepoRoot()
try { // Use git diff --stat to get a summary of changes const result = await execFileNoThrowWithCwd( gitExe(), ['diff', '--cached', '--stat', '--', filePath], { cwd, timeout: 5000 }, )
if (result.code !== 0 || !result.stdout) { return 0 }
// Parse the stat output to extract additions and deletions // Format: " file | 5 ++---" or " file | 10 +" const lines = result.stdout.split('\n').filter(Boolean) let totalChanges = 0
for (const line of lines) { // Skip the summary line (e.g., "1 file changed, 3 insertions(+), 2 deletions(-)") if (line.includes('file changed') || line.includes('files changed')) { const insertMatch = line.match(/(\d+) insertions?/) const deleteMatch = line.match(/(\d+) deletions?/)
// Use line-based changes and approximate chars per line (~40 chars average) const insertions = insertMatch ? parseInt(insertMatch[1]!, 10) : 0 const deletions = deleteMatch ? parseInt(deleteMatch[1]!, 10) : 0 totalChanges += (insertions + deletions) * 40 } }
return totalChanges } catch { return 0 }}
/** * Check if a file was deleted in the staged changes. */export async function isFileDeleted(filePath: string): Promise<boolean> { const cwd = getAttributionRepoRoot()
try { const result = await execFileNoThrowWithCwd( gitExe(), ['diff', '--cached', '--name-status', '--', filePath], { cwd, timeout: 5000 }, )
if (result.code === 0 && result.stdout) { // Format: "D\tfilename" for deleted files return result.stdout.trim().startsWith('D\t') } } catch { // Ignore errors }
return false}
/** * Get staged files from git. */export async function getStagedFiles(): Promise<string[]> { const cwd = getAttributionRepoRoot()
try { const result = await execFileNoThrowWithCwd( gitExe(), ['diff', '--cached', '--name-only'], { cwd, timeout: 5000 }, )
if (result.code === 0 && result.stdout) { return result.stdout.split('\n').filter(Boolean) } } catch (error) { logError(error as Error) }
return []}
// formatAttributionTrailer moved to attributionTrailer.ts for tree-shaking// (contains excluded strings that should not be in external builds)
/** * Check if we're in a transient git state (rebase, merge, cherry-pick). */export async function isGitTransientState(): Promise<boolean> { const gitDir = await resolveGitDir(getAttributionRepoRoot()) if (!gitDir) return false
const indicators = [ 'rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'BISECT_LOG', ]
const results = await Promise.all( indicators.map(async indicator => { try { await stat(join(gitDir, indicator)) return true } catch { return false } }), )
return results.some(exists => exists)}
/** * Convert attribution state to snapshot message for persistence. */export function stateToSnapshotMessage( state: AttributionState, messageId: UUID,): AttributionSnapshotMessage { const fileStates: Record<string, FileAttributionState> = {}
for (const [path, fileState] of state.fileStates) { fileStates[path] = fileState }
return { type: 'attribution-snapshot', messageId, surface: state.surface, fileStates, promptCount: state.promptCount, promptCountAtLastCommit: state.promptCountAtLastCommit, permissionPromptCount: state.permissionPromptCount, permissionPromptCountAtLastCommit: state.permissionPromptCountAtLastCommit, escapeCount: state.escapeCount, escapeCountAtLastCommit: state.escapeCountAtLastCommit, }}
/** * Restore attribution state from snapshot messages. */export function restoreAttributionStateFromSnapshots( snapshots: AttributionSnapshotMessage[],): AttributionState { const state = createEmptyAttributionState()
// Snapshots are full-state dumps (see stateToSnapshotMessage), not deltas. // The last snapshot has the most recent count for every path — fileStates // never shrinks. Iterating and SUMMING counts across snapshots causes // quadratic growth on restore (837 snapshots × 280 files → 1.15 quadrillion // "chars" tracked for a 5KB file over a 5-day session). const lastSnapshot = snapshots[snapshots.length - 1] if (!lastSnapshot) { return state }
state.surface = lastSnapshot.surface for (const [path, fileState] of Object.entries(lastSnapshot.fileStates)) { state.fileStates.set(path, fileState) }
// Restore prompt counts from the last snapshot (most recent state) state.promptCount = lastSnapshot.promptCount ?? 0 state.promptCountAtLastCommit = lastSnapshot.promptCountAtLastCommit ?? 0 state.permissionPromptCount = lastSnapshot.permissionPromptCount ?? 0 state.permissionPromptCountAtLastCommit = lastSnapshot.permissionPromptCountAtLastCommit ?? 0 state.escapeCount = lastSnapshot.escapeCount ?? 0 state.escapeCountAtLastCommit = lastSnapshot.escapeCountAtLastCommit ?? 0
return state}
/** * Restore attribution state from log snapshots on session resume. */export function attributionRestoreStateFromLog( attributionSnapshots: AttributionSnapshotMessage[], onUpdateState: (newState: AttributionState) => void,): void { const state = restoreAttributionStateFromSnapshots(attributionSnapshots) onUpdateState(state)}
/** * Increment promptCount and save an attribution snapshot. * Used to persist the prompt count across compaction. * * @param attribution - Current attribution state * @param saveSnapshot - Function to save the snapshot (allows async handling by caller) * @returns New attribution state with incremented promptCount */export function incrementPromptCount( attribution: AttributionState, saveSnapshot: (snapshot: AttributionSnapshotMessage) => void,): AttributionState { const newAttribution = { ...attribution, promptCount: attribution.promptCount + 1, } const snapshot = stateToSnapshotMessage(newAttribution, randomUUID()) saveSnapshot(snapshot) return newAttribution}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import chalk from 'chalk'import { mkdir, readFile, writeFile } from 'fs/promises'import { homedir } from 'os'import { dirname, join } from 'path'import { pathToFileURL } from 'url'import { color } from '../components/design-system/color.js'import { supportsHyperlinks } from '../ink/supports-hyperlinks.js'import { logForDebugging } from './debug.js'import { isENOENT } from './errors.js'import { execFileNoThrow } from './execFileNoThrow.js'import { logError } from './log.js'import type { ThemeName } from './theme.js'
const EOL = '\n'
type ShellInfo = { name: string rcFile: string cacheFile: string completionLine: string shellFlag: string}
function detectShell(): ShellInfo | null { const shell = process.env.SHELL || '' const home = homedir() const claudeDir = join(home, '.claude')
if (shell.endsWith('/zsh') || shell.endsWith('/zsh.exe')) { const cacheFile = join(claudeDir, 'completion.zsh') return { name: 'zsh', rcFile: join(home, '.zshrc'), cacheFile, completionLine: `[[ -f "${cacheFile}" ]] && source "${cacheFile}"`, shellFlag: 'zsh', } } if (shell.endsWith('/bash') || shell.endsWith('/bash.exe')) { const cacheFile = join(claudeDir, 'completion.bash') return { name: 'bash', rcFile: join(home, '.bashrc'), cacheFile, completionLine: `[ -f "${cacheFile}" ] && source "${cacheFile}"`, shellFlag: 'bash', } } if (shell.endsWith('/fish') || shell.endsWith('/fish.exe')) { const xdg = process.env.XDG_CONFIG_HOME || join(home, '.config') const cacheFile = join(claudeDir, 'completion.fish') return { name: 'fish', rcFile: join(xdg, 'fish', 'config.fish'), cacheFile, completionLine: `[ -f "${cacheFile}" ] && source "${cacheFile}"`, shellFlag: 'fish', } } return null}
function formatPathLink(filePath: string): string { if (!supportsHyperlinks()) { return filePath } const fileUrl = pathToFileURL(filePath).href return `\x1b]8;;${fileUrl}\x07${filePath}\x1b]8;;\x07`}
/** * Generate and cache the completion script, then add a source line to the * shell's rc file. Returns a user-facing status message. */export async function setupShellCompletion(theme: ThemeName): Promise<string> { const shell = detectShell() if (!shell) { return '' }
// Ensure the cache directory exists try { await mkdir(dirname(shell.cacheFile), { recursive: true }) } catch (e: unknown) { logError(e) return `${EOL}${color('warning', theme)(`Could not write ${shell.name} completion cache`)}${EOL}${chalk.dim(`Run manually: claude completion ${shell.shellFlag} > ${shell.cacheFile}`)}${EOL}` }
// Generate the completion script by writing directly to the cache file. // Using --output avoids piping through stdout where process.exit() can // truncate output before the pipe buffer drains. const claudeBin = process.argv[1] || 'claude' const result = await execFileNoThrow(claudeBin, [ 'completion', shell.shellFlag, '--output', shell.cacheFile, ]) if (result.code !== 0) { return `${EOL}${color('warning', theme)(`Could not generate ${shell.name} shell completions`)}${EOL}${chalk.dim(`Run manually: claude completion ${shell.shellFlag} > ${shell.cacheFile}`)}${EOL}` }
// Check if rc file already sources completions let existing = '' try { existing = await readFile(shell.rcFile, { encoding: 'utf-8' }) if ( existing.includes('claude completion') || existing.includes(shell.cacheFile) ) { return `${EOL}${color('success', theme)(`Shell completions updated for ${shell.name}`)}${EOL}${chalk.dim(`See ${formatPathLink(shell.rcFile)}`)}${EOL}` } } catch (e: unknown) { if (!isENOENT(e)) { logError(e) return `${EOL}${color('warning', theme)(`Could not install ${shell.name} shell completions`)}${EOL}${chalk.dim(`Add this to ${formatPathLink(shell.rcFile)}:`)}${EOL}${chalk.dim(shell.completionLine)}${EOL}` } }
// Append source line to rc file try { const configDir = dirname(shell.rcFile) await mkdir(configDir, { recursive: true })
const separator = existing && !existing.endsWith('\n') ? '\n' : '' const content = `${existing}${separator}\n# Claude Code shell completions\n${shell.completionLine}\n` await writeFile(shell.rcFile, content, { encoding: 'utf-8' })
return `${EOL}${color('success', theme)(`Installed ${shell.name} shell completions`)}${EOL}${chalk.dim(`Added to ${formatPathLink(shell.rcFile)}`)}${EOL}${chalk.dim(`Run: source ${shell.rcFile}`)}${EOL}` } catch (error) { logError(error) return `${EOL}${color('warning', theme)(`Could not install ${shell.name} shell completions`)}${EOL}${chalk.dim(`Add this to ${formatPathLink(shell.rcFile)}:`)}${EOL}${chalk.dim(shell.completionLine)}${EOL}` }}
/** * Regenerate cached shell completion scripts in ~/.claude/. * Called after `claude update` so completions stay in sync with the new binary. */export async function regenerateCompletionCache(): Promise<void> { const shell = detectShell() if (!shell) { return }
logForDebugging(`update: Regenerating ${shell.name} completion cache`)
const claudeBin = process.argv[1] || 'claude' const result = await execFileNoThrow(claudeBin, [ 'completion', shell.shellFlag, '--output', shell.cacheFile, ])
if (result.code !== 0) { logForDebugging( `update: Failed to regenerate ${shell.name} completion cache`, ) return }
logForDebugging( `update: Regenerated ${shell.name} completion cache at ${shell.cacheFile}`, )}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204import { feature } from 'bun:bundle'import { chmod, mkdir, readdir, readFile, unlink, writeFile } from 'fs/promises'import { join } from 'path'import { getOriginalCwd, getSessionId, onSessionSwitch,} from '../bootstrap/state.js'import { registerCleanup } from './cleanupRegistry.js'import { logForDebugging } from './debug.js'import { getClaudeConfigHomeDir } from './envUtils.js'import { errorMessage, isFsInaccessible } from './errors.js'import { isProcessRunning } from './genericProcessUtils.js'import { getPlatform } from './platform.js'import { jsonParse, jsonStringify } from './slowOperations.js'import { getAgentId } from './teammate.js'
export type SessionKind = 'interactive' | 'bg' | 'daemon' | 'daemon-worker'export type SessionStatus = 'busy' | 'idle' | 'waiting'
function getSessionsDir(): string { return join(getClaudeConfigHomeDir(), 'sessions')}
/** * Kind override from env. Set by the spawner (`claude --bg`, daemon * supervisor) so the child can register without the parent having to * write the file for it — cleanup-on-exit wiring then works for free. * Gated so the env-var string is DCE'd from external builds. */function envSessionKind(): SessionKind | undefined { if (feature('BG_SESSIONS')) { const k = process.env.CLAUDE_CODE_SESSION_KIND if (k === 'bg' || k === 'daemon' || k === 'daemon-worker') return k } return undefined}
/** * True when this REPL is running inside a `claude --bg` tmux session. * Exit paths (/exit, ctrl+c, ctrl+d) should detach the attached client * instead of killing the process. */export function isBgSession(): boolean { return envSessionKind() === 'bg'}
/** * Write a PID file for this session and register cleanup. * * Registers all top-level sessions — interactive CLI, SDK (vscode, desktop, * typescript, python, -p), bg/daemon spawns — so `claude ps` sees everything * the user might be running. Skips only teammates/subagents, which would * conflate swarm usage with genuine concurrency and pollute ps with noise. * * Returns true if registered, false if skipped. * Errors logged to debug, never thrown. */export async function registerSession(): Promise<boolean> { if (getAgentId() != null) return false
const kind: SessionKind = envSessionKind() ?? 'interactive' const dir = getSessionsDir() const pidFile = join(dir, `${process.pid}.json`)
registerCleanup(async () => { try { await unlink(pidFile) } catch { // ENOENT is fine (already deleted or never written) } })
try { await mkdir(dir, { recursive: true, mode: 0o700 }) await chmod(dir, 0o700) await writeFile( pidFile, jsonStringify({ pid: process.pid, sessionId: getSessionId(), cwd: getOriginalCwd(), startedAt: Date.now(), kind, entrypoint: process.env.CLAUDE_CODE_ENTRYPOINT, ...(feature('UDS_INBOX') ? { messagingSocketPath: process.env.CLAUDE_CODE_MESSAGING_SOCKET } : {}), ...(feature('BG_SESSIONS') ? { name: process.env.CLAUDE_CODE_SESSION_NAME, logPath: process.env.CLAUDE_CODE_SESSION_LOG, agent: process.env.CLAUDE_CODE_AGENT, } : {}), }), ) // --resume / /resume mutates getSessionId() via switchSession. Without // this, the PID file's sessionId goes stale and `claude ps` sparkline // reads the wrong transcript. onSessionSwitch(id => { void updatePidFile({ sessionId: id }) }) return true } catch (e) { logForDebugging(`[concurrentSessions] register failed: ${errorMessage(e)}`) return false }}
/** * Update this session's name in its PID registry file so ListPeers * can surface it. Best-effort: silently no-op if name is falsy, the * file doesn't exist (session not registered), or read/write fails. */async function updatePidFile(patch: Record<string, unknown>): Promise<void> { const pidFile = join(getSessionsDir(), `${process.pid}.json`) try { const data = jsonParse(await readFile(pidFile, 'utf8')) as Record< string, unknown > await writeFile(pidFile, jsonStringify({ ...data, ...patch })) } catch (e) { logForDebugging( `[concurrentSessions] updatePidFile failed: ${errorMessage(e)}`, ) }}
export async function updateSessionName( name: string | undefined,): Promise<void> { if (!name) return await updatePidFile({ name })}
/** * Record this session's Remote Control session ID so peer enumeration can * dedup: a session reachable over both UDS and bridge should only appear * once (local wins). Cleared on bridge teardown so stale IDs don't * suppress a legitimately-remote session after reconnect. */export async function updateSessionBridgeId( bridgeSessionId: string | null,): Promise<void> { await updatePidFile({ bridgeSessionId })}
/** * Push live activity state for `claude ps`. Fire-and-forget from REPL's * status-change effect — a dropped write just means ps falls back to * transcript-tail derivation for one refresh. */export async function updateSessionActivity(patch: { status?: SessionStatus waitingFor?: string}): Promise<void> { if (!feature('BG_SESSIONS')) return await updatePidFile({ ...patch, updatedAt: Date.now() })}
/** * Count live concurrent CLI sessions (including this one). * Filters out stale PID files (crashed sessions) and deletes them. * Returns 0 on any error (conservative). */export async function countConcurrentSessions(): Promise<number> { const dir = getSessionsDir() let files: string[] try { files = await readdir(dir) } catch (e) { if (!isFsInaccessible(e)) { logForDebugging(`[concurrentSessions] readdir failed: ${errorMessage(e)}`) } return 0 }
let count = 0 for (const file of files) { // Strict filename guard: only `<pid>.json` is a candidate. parseInt's // lenient prefix-parsing means `2026-03-14_notes.md` would otherwise // parse as PID 2026 and get swept as stale — silent user data loss. // See anthropics/claude-code#34210. if (!/^\d+\.json$/.test(file)) continue const pid = parseInt(file.slice(0, -5), 10) if (pid === process.pid) { count++ continue } if (isProcessRunning(pid)) { count++ } else if (getPlatform() !== 'wsl') { // Stale file from a crashed session — sweep it. Skip on WSL: if // ~/.claude/sessions/ is shared with Windows-native Claude (symlink // or CLAUDE_CONFIG_DIR), a Windows PID won't be probeable from WSL // and we'd falsely delete a live session's file. This is just // telemetry so conservative undercount is acceptable. void unlink(join(dir, file)).catch(() => {}) } } return count}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818import { feature } from 'bun:bundle'import { randomBytes } from 'crypto'import { unwatchFile, watchFile } from 'fs'import memoize from 'lodash-es/memoize.js'import pickBy from 'lodash-es/pickBy.js'import { basename, dirname, join, resolve } from 'path'import { getOriginalCwd, getSessionTrustAccepted } from '../bootstrap/state.js'import { getAutoMemEntrypoint } from '../memdir/paths.js'import { logEvent } from '../services/analytics/index.js'import type { McpServerConfig } from '../services/mcp/types.js'import type { BillingType, ReferralEligibilityResponse,} from '../services/oauth/types.js'import { getCwd } from '../utils/cwd.js'import { registerCleanup } from './cleanupRegistry.js'import { logForDebugging } from './debug.js'import { logForDiagnosticsNoPII } from './diagLogs.js'import { getGlobalClaudeFile } from './env.js'import { getClaudeConfigHomeDir, isEnvTruthy } from './envUtils.js'import { ConfigParseError, getErrnoCode } from './errors.js'import { writeFileSyncAndFlush_DEPRECATED } from './file.js'import { getFsImplementation } from './fsOperations.js'import { findCanonicalGitRoot } from './git.js'import { safeParseJSON } from './json.js'import { stripBOM } from './jsonRead.js'import * as lockfile from './lockfile.js'import { logError } from './log.js'import type { MemoryType } from './memory/types.js'import { normalizePathForConfigKey } from './path.js'import { getEssentialTrafficOnlyReason } from './privacyLevel.js'import { getManagedFilePath } from './settings/managedPath.js'import type { ThemeSetting } from './theme.js'
/* eslint-disable @typescript-eslint/no-require-imports */const teamMemPaths = feature('TEAMMEM') ? (require('../memdir/teamMemPaths.js') as typeof import('../memdir/teamMemPaths.js')) : nullconst ccrAutoConnect = feature('CCR_AUTO_CONNECT') ? (require('../bridge/bridgeEnabled.js') as typeof import('../bridge/bridgeEnabled.js')) : null
/* eslint-enable @typescript-eslint/no-require-imports */import type { ImageDimensions } from './imageResizer.js'import type { ModelOption } from './model/modelOptions.js'import { jsonParse, jsonStringify } from './slowOperations.js'
// Re-entrancy guard: prevents getConfig → logEvent → getGlobalConfig → getConfig// infinite recursion when the config file is corrupted. logEvent's sampling check// reads GrowthBook features from the global config, which calls getConfig again.let insideGetConfig = false
// Image dimension info for coordinate mapping (only set when image was resized)export type PastedContent = { id: number // Sequential numeric ID type: 'text' | 'image' content: string mediaType?: string // e.g., 'image/png', 'image/jpeg' filename?: string // Display name for images in attachment slot dimensions?: ImageDimensions sourcePath?: string // Original file path for images dragged onto the terminal}
export interface SerializedStructuredHistoryEntry { display: string pastedContents?: Record<number, PastedContent> pastedText?: string}export interface HistoryEntry { display: string pastedContents: Record<number, PastedContent>}
export type ReleaseChannel = 'stable' | 'latest'
export type ProjectConfig = { allowedTools: string[] mcpContextUris: string[] mcpServers?: Record<string, McpServerConfig> lastAPIDuration?: number lastAPIDurationWithoutRetries?: number lastToolDuration?: number lastCost?: number lastDuration?: number lastLinesAdded?: number lastLinesRemoved?: number lastTotalInputTokens?: number lastTotalOutputTokens?: number lastTotalCacheCreationInputTokens?: number lastTotalCacheReadInputTokens?: number lastTotalWebSearchRequests?: number lastFpsAverage?: number lastFpsLow1Pct?: number lastSessionId?: string lastModelUsage?: Record< string, { inputTokens: number outputTokens: number cacheReadInputTokens: number cacheCreationInputTokens: number webSearchRequests: number costUSD: number } > lastSessionMetrics?: Record<string, number> exampleFiles?: string[] exampleFilesGeneratedAt?: number
// Trust dialog settings hasTrustDialogAccepted?: boolean
hasCompletedProjectOnboarding?: boolean projectOnboardingSeenCount: number hasClaudeMdExternalIncludesApproved?: boolean hasClaudeMdExternalIncludesWarningShown?: boolean // MCP server approval fields - migrated to settings but kept for backward compatibility enabledMcpjsonServers?: string[] disabledMcpjsonServers?: string[] enableAllProjectMcpServers?: boolean // List of disabled MCP servers (all scopes) - used for enable/disable toggle disabledMcpServers?: string[] // Opt-in list for built-in MCP servers that default to disabled enabledMcpServers?: string[] // Worktree session management activeWorktreeSession?: { originalCwd: string worktreePath: string worktreeName: string originalBranch?: string sessionId: string hookBased?: boolean } /** Spawn mode for `claude remote-control` multi-session. Set by first-run dialog or `w` toggle. */ remoteControlSpawnMode?: 'same-dir' | 'worktree'}
const DEFAULT_PROJECT_CONFIG: ProjectConfig = { allowedTools: [], mcpContextUris: [], mcpServers: {}, enabledMcpjsonServers: [], disabledMcpjsonServers: [], hasTrustDialogAccepted: false, projectOnboardingSeenCount: 0, hasClaudeMdExternalIncludesApproved: false, hasClaudeMdExternalIncludesWarningShown: false,}
export type InstallMethod = 'local' | 'native' | 'global' | 'unknown'
export { EDITOR_MODES, NOTIFICATION_CHANNELS,} from './configConstants.js'
import type { EDITOR_MODES, NOTIFICATION_CHANNELS } from './configConstants.js'
export type NotificationChannel = (typeof NOTIFICATION_CHANNELS)[number]
export type AccountInfo = { accountUuid: string emailAddress: string organizationUuid?: string organizationName?: string | null // added 4/23/2025, not populated for existing users organizationRole?: string | null workspaceRole?: string | null // Populated by /api/oauth/profile displayName?: string hasExtraUsageEnabled?: boolean billingType?: BillingType | null accountCreatedAt?: string subscriptionCreatedAt?: string}
// TODO: 'emacs' is kept for backward compatibility - remove after a few releasesexport type EditorMode = 'emacs' | (typeof EDITOR_MODES)[number]
export type DiffTool = 'terminal' | 'auto'
export type OutputStyle = string
export type GlobalConfig = { /** * @deprecated Use settings.apiKeyHelper instead. */ apiKeyHelper?: string projects?: Record<string, ProjectConfig> numStartups: number installMethod?: InstallMethod autoUpdates?: boolean // Flag to distinguish protection-based disabling from user preference autoUpdatesProtectedForNative?: boolean // Session count when Doctor was last shown doctorShownAtSession?: number userID?: string theme: ThemeSetting hasCompletedOnboarding?: boolean // Tracks the last version that reset onboarding, used with MIN_VERSION_REQUIRING_ONBOARDING_RESET lastOnboardingVersion?: string // Tracks the last version for which release notes were seen, used for managing release notes lastReleaseNotesSeen?: string // Timestamp when changelog was last fetched (content stored in ~/.claude/cache/changelog.md) changelogLastFetched?: number // @deprecated - Migrated to ~/.claude/cache/changelog.md. Keep for migration support. cachedChangelog?: string mcpServers?: Record<string, McpServerConfig> // claude.ai MCP connectors that have successfully connected at least once. // Used to gate "connector unavailable" / "needs auth" startup notifications: // a connector the user has actually used is worth flagging when it breaks, // but an org-configured connector that's been needs-auth since day one is // something the user has demonstrably ignored and shouldn't nag about. claudeAiMcpEverConnected?: string[] preferredNotifChannel: NotificationChannel /** * @deprecated. Use the Notification hook instead (docs/hooks.md). */ customNotifyCommand?: string verbose: boolean customApiKeyResponses?: { approved?: string[] rejected?: string[] } primaryApiKey?: string // Primary API key for the user when no environment variable is set, set via oauth (TODO: rename) hasAcknowledgedCostThreshold?: boolean hasSeenUndercoverAutoNotice?: boolean // ant-only: whether the one-time auto-undercover explainer has been shown hasSeenUltraplanTerms?: boolean // ant-only: whether the one-time CCR terms notice has been shown in the ultraplan launch dialog hasResetAutoModeOptInForDefaultOffer?: boolean // ant-only: one-shot migration guard, re-prompts churned auto-mode users oauthAccount?: AccountInfo iterm2KeyBindingInstalled?: boolean // Legacy - keeping for backward compatibility editorMode?: EditorMode bypassPermissionsModeAccepted?: boolean hasUsedBackslashReturn?: boolean autoCompactEnabled: boolean // Controls whether auto-compact is enabled showTurnDuration: boolean // Controls whether to show turn duration message (e.g., "Cooked for 1m 6s") /** * @deprecated Use settings.env instead. */ env: { [key: string]: string } // Environment variables to set for the CLI hasSeenTasksHint?: boolean // Whether the user has seen the tasks hint hasUsedStash?: boolean // Whether the user has used the stash feature (Ctrl+S) hasUsedBackgroundTask?: boolean // Whether the user has backgrounded a task (Ctrl+B) queuedCommandUpHintCount?: number // Counter for how many times the user has seen the queued command up hint diffTool?: DiffTool // Which tool to use for displaying diffs (terminal or vscode)
// Terminal setup state tracking iterm2SetupInProgress?: boolean iterm2BackupPath?: string // Path to the backup file for iTerm2 preferences appleTerminalBackupPath?: string // Path to the backup file for Terminal.app preferences appleTerminalSetupInProgress?: boolean // Whether Terminal.app setup is currently in progress
// Key binding setup tracking shiftEnterKeyBindingInstalled?: boolean // Whether Shift+Enter key binding is installed (for iTerm2 or VSCode) optionAsMetaKeyInstalled?: boolean // Whether Option as Meta key is installed (for Terminal.app)
// IDE configurations autoConnectIde?: boolean // Whether to automatically connect to IDE on startup if exactly one valid IDE is available autoInstallIdeExtension?: boolean // Whether to automatically install IDE extensions when running from within an IDE
// IDE dialogs hasIdeOnboardingBeenShown?: Record<string, boolean> // Map of terminal name to whether IDE onboarding has been shown ideHintShownCount?: number // Number of times the /ide command hint has been shown hasIdeAutoConnectDialogBeenShown?: boolean // Whether the auto-connect IDE dialog has been shown
tipsHistory: { [tipId: string]: number // Key is tipId, value is the numStartups when tip was last shown }
// /buddy companion soul — bones regenerated from userId on read. See src/buddy/. companion?: import('../buddy/types.js').StoredCompanion companionMuted?: boolean
// Feedback survey tracking feedbackSurveyState?: { lastShownTime?: number }
// Transcript share prompt tracking ("Don't ask again") transcriptShareDismissed?: boolean
// Memory usage tracking memoryUsageCount: number // Number of times user has added to memory
// Sonnet-1M configs hasShownS1MWelcomeV2?: Record<string, boolean> // Whether the Sonnet-1M v2 welcome message has been shown per org // Cache of Sonnet-1M subscriber access per org - key is org ID // hasAccess means "hasAccessAsDefault" but the old name is kept for backward // compatibility. s1mAccessCache?: Record< string, { hasAccess: boolean; hasAccessNotAsDefault?: boolean; timestamp: number } > // Cache of Sonnet-1M PayG access per org - key is org ID // hasAccess means "hasAccessAsDefault" but the old name is kept for backward // compatibility. s1mNonSubscriberAccessCache?: Record< string, { hasAccess: boolean; hasAccessNotAsDefault?: boolean; timestamp: number } >
// Guest passes eligibility cache per org - key is org ID passesEligibilityCache?: Record< string, ReferralEligibilityResponse & { timestamp: number } >
// Grove config cache per account - key is account UUID groveConfigCache?: Record< string, { grove_enabled: boolean; timestamp: number } >
// Guest passes upsell tracking passesUpsellSeenCount?: number // Number of times the guest passes upsell has been shown hasVisitedPasses?: boolean // Whether the user has visited /passes command passesLastSeenRemaining?: number // Last seen remaining_passes count — reset upsell when it increases
// Overage credit grant upsell tracking (keyed by org UUID — multi-org users). // Inlined shape (not import()) because config.ts is in the SDK build surface // and the SDK bundler can't resolve CLI service modules. overageCreditGrantCache?: Record< string, { info: { available: boolean eligible: boolean granted: boolean amount_minor_units: number | null currency: string | null } timestamp: number } > overageCreditUpsellSeenCount?: number // Number of times the overage credit upsell has been shown hasVisitedExtraUsage?: boolean // Whether the user has visited /extra-usage — hides credit upsells
// Voice mode notice tracking voiceNoticeSeenCount?: number // Number of times the voice-mode-available notice has been shown voiceLangHintShownCount?: number // Number of times the /voice dictation-language hint has been shown voiceLangHintLastLanguage?: string // Resolved STT language code when the hint was last shown — reset count when it changes voiceFooterHintSeenCount?: number // Number of sessions the "hold X to speak" footer hint has been shown
// Opus 1M merge notice tracking opus1mMergeNoticeSeenCount?: number // Number of times the opus-1m-merge notice has been shown
// Experiment enrollment notice tracking (keyed by experiment id) experimentNoticesSeenCount?: Record<string, number>
// OpusPlan experiment config hasShownOpusPlanWelcome?: Record<string, boolean> // Whether the OpusPlan welcome message has been shown per org
// Queue usage tracking promptQueueUseCount: number // Number of times use has used the prompt queue
// Btw usage tracking btwUseCount: number // Number of times user has used /btw
// Plan mode usage tracking lastPlanModeUse?: number // Timestamp of last plan mode usage
// Subscription notice tracking subscriptionNoticeCount?: number // Number of times the subscription notice has been shown hasAvailableSubscription?: boolean // Cached result of whether user has a subscription available subscriptionUpsellShownCount?: number // Number of times the subscription upsell has been shown (deprecated) recommendedSubscription?: string // Cached config value from Statsig (deprecated)
// Todo feature configuration todoFeatureEnabled: boolean // Whether the todo feature is enabled showExpandedTodos?: boolean // Whether to show todos expanded, even when empty showSpinnerTree?: boolean // Whether to show the teammate spinner tree instead of pills
// First start time tracking firstStartTime?: string // ISO timestamp when Claude Code was first started on this machine
messageIdleNotifThresholdMs: number // How long the user has to have been idle to get a notification that Claude is done generating
githubActionSetupCount?: number // Number of times the user has set up the GitHub Action slackAppInstallCount?: number // Number of times the user has clicked to install the Slack app
// File checkpointing configuration fileCheckpointingEnabled: boolean
// Terminal progress bar configuration (OSC 9;4) terminalProgressBarEnabled: boolean
// Terminal tab status indicator (OSC 21337). When on, emits a colored // dot + status text to the tab sidebar and drops the spinner prefix // from the title (the dot makes it redundant). showStatusInTerminalTab?: boolean
// Push-notification toggles (set via /config). Default off — explicit opt-in required. taskCompleteNotifEnabled?: boolean inputNeededNotifEnabled?: boolean agentPushNotifEnabled?: boolean
// Claude Code usage tracking claudeCodeFirstTokenDate?: string // ISO timestamp of the user's first Claude Code OAuth token
// Model switch callout tracking (ant-only) modelSwitchCalloutDismissed?: boolean // Whether user chose "Don't show again" modelSwitchCalloutLastShown?: number // Timestamp of last shown (don't show for 24h) modelSwitchCalloutVersion?: string
// Effort callout tracking - shown once for Opus 4.6 users effortCalloutDismissed?: boolean // v1 - legacy, read to suppress v2 for Pro users who already saw it effortCalloutV2Dismissed?: boolean
// Remote callout tracking - shown once before first bridge enable remoteDialogSeen?: boolean
// Cross-process backoff for initReplBridge's oauth_expired_unrefreshable skip. // `expiresAt` is the dedup key — content-addressed, self-clears when /login // replaces the token. `failCount` caps false positives: transient refresh // failures (auth server 5xx, lock errors) get 3 retries before backoff kicks // in, mirroring useReplBridge's MAX_CONSECUTIVE_INIT_FAILURES. Dead-token // accounts cap at 3 config writes; healthy+transient-blip self-heals in ~210s. bridgeOauthDeadExpiresAt?: number bridgeOauthDeadFailCount?: number
// Desktop upsell startup dialog tracking desktopUpsellSeenCount?: number // Total showings (max 3) desktopUpsellDismissed?: boolean // "Don't ask again" picked
// Idle-return dialog tracking idleReturnDismissed?: boolean // "Don't ask again" picked
// Opus 4.5 Pro migration tracking opusProMigrationComplete?: boolean opusProMigrationTimestamp?: number
// Sonnet 4.5 1m migration tracking sonnet1m45MigrationComplete?: boolean
// Opus 4.0/4.1 → current Opus migration (shows one-time notif) legacyOpusMigrationTimestamp?: number
// Sonnet 4.5 → 4.6 migration (pro/max/team premium) sonnet45To46MigrationTimestamp?: number
// Cached statsig gate values cachedStatsigGates: { [gateName: string]: boolean }
// Cached statsig dynamic configs cachedDynamicConfigs?: { [configName: string]: unknown }
// Cached GrowthBook feature values cachedGrowthBookFeatures?: { [featureName: string]: unknown }
// Local GrowthBook overrides (ant-only, set via /config Gates tab). // Checked after env-var overrides but before the real resolved value. growthBookOverrides?: { [featureName: string]: unknown }
// Emergency tip tracking - stores the last shown tip to prevent re-showing lastShownEmergencyTip?: string
// File picker gitignore behavior respectGitignore: boolean // Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected
// Copy command behavior copyFullResponse: boolean // Whether /copy always copies the full response instead of showing the picker
// Fullscreen in-app text selection behavior copyOnSelect?: boolean // Auto-copy to clipboard on mouse-up (undefined → true; lets cmd+c "work" via no-op)
// GitHub repo path mapping for teleport directory switching // Key: "owner/repo" (lowercase), Value: array of absolute paths where repo is cloned githubRepoPaths?: Record<string, string[]>
// Terminal emulator to launch for claude-cli:// deep links. Captured from // TERM_PROGRAM during interactive sessions since the deep link handler runs // headless (LaunchServices/xdg) with no TERM_PROGRAM set. deepLinkTerminal?: string
// iTerm2 it2 CLI setup iterm2It2SetupComplete?: boolean // Whether it2 setup has been verified preferTmuxOverIterm2?: boolean // User preference to always use tmux over iTerm2 split panes
// Skill usage tracking for autocomplete ranking skillUsage?: Record<string, { usageCount: number; lastUsedAt: number }> // Official marketplace auto-install tracking officialMarketplaceAutoInstallAttempted?: boolean // Whether auto-install was attempted officialMarketplaceAutoInstalled?: boolean // Whether auto-install succeeded officialMarketplaceAutoInstallFailReason?: | 'policy_blocked' | 'git_unavailable' | 'gcs_unavailable' | 'unknown' // Reason for failure if applicable officialMarketplaceAutoInstallRetryCount?: number // Number of retry attempts officialMarketplaceAutoInstallLastAttemptTime?: number // Timestamp of last attempt officialMarketplaceAutoInstallNextRetryTime?: number // Earliest time to retry again
// Claude in Chrome settings hasCompletedClaudeInChromeOnboarding?: boolean // Whether Claude in Chrome onboarding has been shown claudeInChromeDefaultEnabled?: boolean // Whether Claude in Chrome is enabled by default (undefined means platform default) cachedChromeExtensionInstalled?: boolean // Cached result of whether Chrome extension is installed
// Chrome extension pairing state (persisted across sessions) chromeExtension?: { pairedDeviceId?: string pairedDeviceName?: string }
// LSP plugin recommendation preferences lspRecommendationDisabled?: boolean // Disable all LSP plugin recommendations lspRecommendationNeverPlugins?: string[] // Plugin IDs to never suggest lspRecommendationIgnoredCount?: number // Track ignored recommendations (stops after 5)
// Claude Code hint protocol state (<claude-code-hint /> tags from CLIs/SDKs). // Nested by hint type so future types (docs, mcp, ...) slot in without new // top-level keys. claudeCodeHints?: { // Plugin IDs the user has already been prompted for. Show-once semantics: // recorded regardless of yes/no response, never re-prompted. Capped at // 100 entries to bound config growth — past that, hints stop entirely. plugin?: string[] // User chose "don't show plugin installation hints again" from the dialog. disabled?: boolean }
// Permission explainer configuration permissionExplainerEnabled?: boolean // Enable Haiku-generated explanations for permission requests (default: true)
// Teammate spawn mode: 'auto' | 'tmux' | 'in-process' teammateMode?: 'auto' | 'tmux' | 'in-process' // How to spawn teammates (default: 'auto') // Model for new teammates when the tool call doesn't pass one. // undefined = hardcoded Opus (backward-compat); null = leader's model; string = model alias/ID. teammateDefaultModel?: string | null
// PR status footer configuration (feature-flagged via GrowthBook) prStatusFooterEnabled?: boolean // Show PR review status in footer (default: true)
// Tmux live panel visibility (ant-only, toggled via Enter on tmux pill) tungstenPanelVisible?: boolean
// Cached org-level fast mode status from the API. // Used to detect cross-session changes and notify users. penguinModeOrgEnabled?: boolean
// Epoch ms when background refreshes last ran (fast mode, quota, passes, client data). // Used with tengu_cicada_nap_ms to throttle API calls startupPrefetchedAt?: number
// Run Remote Control at startup (requires BRIDGE_MODE) // undefined = use default (see getRemoteControlAtStartup() for precedence) remoteControlAtStartup?: boolean
// Cached extra usage disabled reason from the last API response // undefined = no cache, null = extra usage enabled, string = disabled reason. cachedExtraUsageDisabledReason?: string | null
// Auto permissions notification tracking (ant-only) autoPermissionsNotificationCount?: number // Number of times the auto permissions notification has been shown
// Speculation configuration (ant-only) speculationEnabled?: boolean // Whether speculation is enabled (default: true)
// Client data for server-side experiments (fetched during bootstrap). clientDataCache?: Record<string, unknown> | null
// Additional model options for the model picker (fetched during bootstrap). additionalModelOptionsCache?: ModelOption[]
// Disk cache for /api/claude_code/organizations/metrics_enabled. // Org-level settings change rarely; persisting across processes avoids a // cold API call on every `claude -p` invocation. metricsStatusCache?: { enabled: boolean timestamp: number }
// Version of the last-applied migration set. When equal to // CURRENT_MIGRATION_VERSION, runMigrations() skips all sync migrations // (avoiding 11× saveGlobalConfig lock+re-read on every startup). migrationVersion?: number}
/** * Factory for a fresh default GlobalConfig. Used instead of deep-cloning a * shared constant — the nested containers (arrays, records) are all empty, so * a factory gives fresh refs at zero clone cost. */function createDefaultGlobalConfig(): GlobalConfig { return { numStartups: 0, installMethod: undefined, autoUpdates: undefined, theme: 'dark', preferredNotifChannel: 'auto', verbose: false, editorMode: 'normal', autoCompactEnabled: true, showTurnDuration: true, hasSeenTasksHint: false, hasUsedStash: false, hasUsedBackgroundTask: false, queuedCommandUpHintCount: 0, diffTool: 'auto', customApiKeyResponses: { approved: [], rejected: [], }, env: {}, tipsHistory: {}, memoryUsageCount: 0, promptQueueUseCount: 0, btwUseCount: 0, todoFeatureEnabled: true, showExpandedTodos: false, messageIdleNotifThresholdMs: 60000, autoConnectIde: false, autoInstallIdeExtension: true, fileCheckpointingEnabled: true, terminalProgressBarEnabled: true, cachedStatsigGates: {}, cachedDynamicConfigs: {}, cachedGrowthBookFeatures: {}, respectGitignore: true, copyFullResponse: false, }}
export const DEFAULT_GLOBAL_CONFIG: GlobalConfig = createDefaultGlobalConfig()
export const GLOBAL_CONFIG_KEYS = [ 'apiKeyHelper', 'installMethod', 'autoUpdates', 'autoUpdatesProtectedForNative', 'theme', 'verbose', 'preferredNotifChannel', 'shiftEnterKeyBindingInstalled', 'editorMode', 'hasUsedBackslashReturn', 'autoCompactEnabled', 'showTurnDuration', 'diffTool', 'env', 'tipsHistory', 'todoFeatureEnabled', 'showExpandedTodos', 'messageIdleNotifThresholdMs', 'autoConnectIde', 'autoInstallIdeExtension', 'fileCheckpointingEnabled', 'terminalProgressBarEnabled', 'showStatusInTerminalTab', 'taskCompleteNotifEnabled', 'inputNeededNotifEnabled', 'agentPushNotifEnabled', 'respectGitignore', 'claudeInChromeDefaultEnabled', 'hasCompletedClaudeInChromeOnboarding', 'lspRecommendationDisabled', 'lspRecommendationNeverPlugins', 'lspRecommendationIgnoredCount', 'copyFullResponse', 'copyOnSelect', 'permissionExplainerEnabled', 'prStatusFooterEnabled', 'remoteControlAtStartup', 'remoteDialogSeen',] as const
export type GlobalConfigKey = (typeof GLOBAL_CONFIG_KEYS)[number]
export function isGlobalConfigKey(key: string): key is GlobalConfigKey { return GLOBAL_CONFIG_KEYS.includes(key as GlobalConfigKey)}
export const PROJECT_CONFIG_KEYS = [ 'allowedTools', 'hasTrustDialogAccepted', 'hasCompletedProjectOnboarding',] as const
export type ProjectConfigKey = (typeof PROJECT_CONFIG_KEYS)[number]
/** * Check if the user has already accepted the trust dialog for the cwd. * * This function traverses parent directories to check if a parent directory * had approval. Accepting trust for a directory implies trust for child * directories. * * @returns Whether the trust dialog has been accepted (i.e. "should not be shown") */let _trustAccepted = false
export function resetTrustDialogAcceptedCacheForTesting(): void { _trustAccepted = false}
export function checkHasTrustDialogAccepted(): boolean { // Trust only transitions false→true during a session (never the reverse), // so once true we can latch it. false is not cached — it gets re-checked // on every call so that trust dialog acceptance is picked up mid-session. // (lodash memoize doesn't fit here because it would also cache false.) return (_trustAccepted ||= computeTrustDialogAccepted())}
function computeTrustDialogAccepted(): boolean { // Check session-level trust (for home directory case where trust is not persisted) // When running from home dir, trust dialog is shown but acceptance is stored // in memory only. This allows hooks and other features to work during the session. if (getSessionTrustAccepted()) { return true }
const config = getGlobalConfig()
// Always check where trust would be saved (git root or original cwd) // This is the primary location where trust is persisted by saveCurrentProjectConfig const projectPath = getProjectPathForConfig() const projectConfig = config.projects?.[projectPath] if (projectConfig?.hasTrustDialogAccepted) { return true }
// Now check from current working directory and its parents // Normalize paths for consistent JSON key lookup let currentPath = normalizePathForConfigKey(getCwd())
// Traverse all parent directories while (true) { const pathConfig = config.projects?.[currentPath] if (pathConfig?.hasTrustDialogAccepted) { return true }
const parentPath = normalizePathForConfigKey(resolve(currentPath, '..')) // Stop if we've reached the root (when parent is same as current) if (parentPath === currentPath) { break } currentPath = parentPath }
return false}
/** * Check trust for an arbitrary directory (not the session cwd). * Walks up from `dir`, returning true if any ancestor has trust persisted. * Unlike checkHasTrustDialogAccepted, this does NOT consult session trust or * the memoized project path — use when the target dir differs from cwd (e.g. * /assistant installing into a user-typed path). */export function isPathTrusted(dir: string): boolean { const config = getGlobalConfig() let currentPath = normalizePathForConfigKey(resolve(dir)) while (true) { if (config.projects?.[currentPath]?.hasTrustDialogAccepted) return true const parentPath = normalizePathForConfigKey(resolve(currentPath, '..')) if (parentPath === currentPath) return false currentPath = parentPath }}
// We have to put this test code here because Jest doesn't support mocking ES modules :Oconst TEST_GLOBAL_CONFIG_FOR_TESTING: GlobalConfig = { ...DEFAULT_GLOBAL_CONFIG, autoUpdates: false,}const TEST_PROJECT_CONFIG_FOR_TESTING: ProjectConfig = { ...DEFAULT_PROJECT_CONFIG,}
export function isProjectConfigKey(key: string): key is ProjectConfigKey { return PROJECT_CONFIG_KEYS.includes(key as ProjectConfigKey)}
/** * Detect whether writing `fresh` would lose auth/onboarding state that the * in-memory cache still has. This happens when `getConfig` hits a corrupted * or truncated file mid-write (from another process or a non-atomic fallback) * and returns DEFAULT_GLOBAL_CONFIG. Writing that back would permanently * wipe auth. See GH #3117. */function wouldLoseAuthState(fresh: { oauthAccount?: unknown hasCompletedOnboarding?: boolean}): boolean { const cached = globalConfigCache.config if (!cached) return false const lostOauth = cached.oauthAccount !== undefined && fresh.oauthAccount === undefined const lostOnboarding = cached.hasCompletedOnboarding === true && fresh.hasCompletedOnboarding !== true return lostOauth || lostOnboarding}
export function saveGlobalConfig( updater: (currentConfig: GlobalConfig) => GlobalConfig,): void { if (process.env.NODE_ENV === 'test') { const config = updater(TEST_GLOBAL_CONFIG_FOR_TESTING) // Skip if no changes (same reference returned) if (config === TEST_GLOBAL_CONFIG_FOR_TESTING) { return } Object.assign(TEST_GLOBAL_CONFIG_FOR_TESTING, config) return }
let written: GlobalConfig | null = null try { const didWrite = saveConfigWithLock( getGlobalClaudeFile(), createDefaultGlobalConfig, current => { const config = updater(current) // Skip if no changes (same reference returned) if (config === current) { return current } written = { ...config, projects: removeProjectHistory(current.projects), } return written }, ) // Only write-through if we actually wrote. If the auth-loss guard // tripped (or the updater made no changes), the file is untouched and // the cache is still valid -- touching it would corrupt the guard. if (didWrite && written) { writeThroughGlobalConfigCache(written) } } catch (error) { logForDebugging(`Failed to save config with lock: ${error}`, { level: 'error', }) // Fall back to non-locked version on error. This fallback is a race // window: if another process is mid-write (or the file got truncated), // getConfig returns defaults. Refuse to write those over a good cached // config to avoid wiping auth. See GH #3117. const currentConfig = getConfig( getGlobalClaudeFile(), createDefaultGlobalConfig, ) if (wouldLoseAuthState(currentConfig)) { logForDebugging( 'saveGlobalConfig fallback: re-read config is missing auth that cache has; refusing to write. See GH #3117.', { level: 'error' }, ) logEvent('tengu_config_auth_loss_prevented', {}) return } const config = updater(currentConfig) // Skip if no changes (same reference returned) if (config === currentConfig) { return } written = { ...config, projects: removeProjectHistory(currentConfig.projects), } saveConfig(getGlobalClaudeFile(), written, DEFAULT_GLOBAL_CONFIG) writeThroughGlobalConfigCache(written) }}
// Cache for global configlet globalConfigCache: { config: GlobalConfig | null; mtime: number } = { config: null, mtime: 0,}
// Tracking for config file operations (telemetry)let lastReadFileStats: { mtime: number; size: number } | null = nulllet configCacheHits = 0let configCacheMisses = 0// Session-total count of actual disk writes to the global config file.// Exposed for ant-only dev diagnostics (see inc-4552) so anomalous write// rates surface in the UI before they corrupt ~/.claude.json.let globalConfigWriteCount = 0
export function getGlobalConfigWriteCount(): number { return globalConfigWriteCount}
export const CONFIG_WRITE_DISPLAY_THRESHOLD = 20
function reportConfigCacheStats(): void { const total = configCacheHits + configCacheMisses if (total > 0) { logEvent('tengu_config_cache_stats', { cache_hits: configCacheHits, cache_misses: configCacheMisses, hit_rate: configCacheHits / total, }) } configCacheHits = 0 configCacheMisses = 0}
// Register cleanup to report cache stats at session end// eslint-disable-next-line custom-rules/no-top-level-side-effectsregisterCleanup(async () => { reportConfigCacheStats()})
/** * Migrates old autoUpdaterStatus to new installMethod and autoUpdates fields * @internal */function migrateConfigFields(config: GlobalConfig): GlobalConfig { // Already migrated if (config.installMethod !== undefined) { return config }
// autoUpdaterStatus is removed from the type but may exist in old configs const legacy = config as GlobalConfig & { autoUpdaterStatus?: | 'migrated' | 'installed' | 'disabled' | 'enabled' | 'no_permissions' | 'not_configured' }
// Determine install method and auto-update preference from old field let installMethod: InstallMethod = 'unknown' let autoUpdates = config.autoUpdates ?? true // Default to enabled unless explicitly disabled
switch (legacy.autoUpdaterStatus) { case 'migrated': installMethod = 'local' break case 'installed': installMethod = 'native' break case 'disabled': // When disabled, we don't know the install method autoUpdates = false break case 'enabled': case 'no_permissions': case 'not_configured': // These imply global installation installMethod = 'global' break case undefined: // No old status, keep defaults break }
return { ...config, installMethod, autoUpdates, }}
/** * Removes history field from projects (migrated to history.jsonl) * @internal */function removeProjectHistory( projects: Record<string, ProjectConfig> | undefined,): Record<string, ProjectConfig> | undefined { if (!projects) { return projects }
const cleanedProjects: Record<string, ProjectConfig> = {} let needsCleaning = false
for (const [path, projectConfig] of Object.entries(projects)) { // history is removed from the type but may exist in old configs const legacy = projectConfig as ProjectConfig & { history?: unknown } if (legacy.history !== undefined) { needsCleaning = true const { history, ...cleanedConfig } = legacy cleanedProjects[path] = cleanedConfig } else { cleanedProjects[path] = projectConfig } }
return needsCleaning ? cleanedProjects : projects}
// fs.watchFile poll interval for detecting writes from other instances (ms)const CONFIG_FRESHNESS_POLL_MS = 1000let freshnessWatcherStarted = false
// fs.watchFile polls stat on the libuv threadpool and only calls us when mtime// changed — a stalled stat never blocks the main thread.function startGlobalConfigFreshnessWatcher(): void { if (freshnessWatcherStarted || process.env.NODE_ENV === 'test') return freshnessWatcherStarted = true const file = getGlobalClaudeFile() watchFile( file, { interval: CONFIG_FRESHNESS_POLL_MS, persistent: false }, curr => { // Our own writes fire this too — the write-through's Date.now() // overshoot makes cache.mtime > file mtime, so we skip the re-read. // Bun/Node also fire with curr.mtimeMs=0 when the file doesn't exist // (initial callback or deletion) — the <= handles that too. if (curr.mtimeMs <= globalConfigCache.mtime) return void getFsImplementation() .readFile(file, { encoding: 'utf-8' }) .then(content => { // A write-through may have advanced the cache while we were reading; // don't regress to the stale snapshot watchFile stat'd. if (curr.mtimeMs <= globalConfigCache.mtime) return const parsed = safeParseJSON(stripBOM(content)) if (parsed === null || typeof parsed !== 'object') return globalConfigCache = { config: migrateConfigFields({ ...createDefaultGlobalConfig(), ...(parsed as Partial<GlobalConfig>), }), mtime: curr.mtimeMs, } lastReadFileStats = { mtime: curr.mtimeMs, size: curr.size } }) .catch(() => {}) }, ) registerCleanup(async () => { unwatchFile(file) freshnessWatcherStarted = false })}
// Write-through: what we just wrote IS the new config. cache.mtime overshoots// the file's real mtime (Date.now() is recorded after the write) so the// freshness watcher skips re-reading our own write on its next tick.function writeThroughGlobalConfigCache(config: GlobalConfig): void { globalConfigCache = { config, mtime: Date.now() } lastReadFileStats = null}
export function getGlobalConfig(): GlobalConfig { if (process.env.NODE_ENV === 'test') { return TEST_GLOBAL_CONFIG_FOR_TESTING }
// Fast path: pure memory read. After startup, this always hits — our own // writes go write-through and other instances' writes are picked up by the // background freshness watcher (never blocks this path). if (globalConfigCache.config) { configCacheHits++ return globalConfigCache.config }
// Slow path: startup load. Sync I/O here is acceptable because it runs // exactly once, before any UI is rendered. Stat before read so any race // self-corrects (old mtime + new content → watcher re-reads next tick). configCacheMisses++ try { let stats: { mtimeMs: number; size: number } | null = null try { stats = getFsImplementation().statSync(getGlobalClaudeFile()) } catch { // File doesn't exist } const config = migrateConfigFields( getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig), ) globalConfigCache = { config, mtime: stats?.mtimeMs ?? Date.now(), } lastReadFileStats = stats ? { mtime: stats.mtimeMs, size: stats.size } : null startGlobalConfigFreshnessWatcher() return config } catch { // If anything goes wrong, fall back to uncached behavior return migrateConfigFields( getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig), ) }}
/** * Returns the effective value of remoteControlAtStartup. Precedence: * 1. User's explicit config value (always wins — honors opt-out) * 2. CCR auto-connect default (ant-only build, GrowthBook-gated) * 3. false (Remote Control must be explicitly opted into) */export function getRemoteControlAtStartup(): boolean { const explicit = getGlobalConfig().remoteControlAtStartup if (explicit !== undefined) return explicit if (feature('CCR_AUTO_CONNECT')) { if (ccrAutoConnect?.getCcrAutoConnectDefault()) return true } return false}
export function getCustomApiKeyStatus( truncatedApiKey: string,): 'approved' | 'rejected' | 'new' { const config = getGlobalConfig() if (config.customApiKeyResponses?.approved?.includes(truncatedApiKey)) { return 'approved' } if (config.customApiKeyResponses?.rejected?.includes(truncatedApiKey)) { return 'rejected' } return 'new'}
function saveConfig<A extends object>( file: string, config: A, defaultConfig: A,): void { // Ensure the directory exists before writing the config file const dir = dirname(file) const fs = getFsImplementation() // mkdirSync is already recursive in FsOperations implementation fs.mkdirSync(dir)
// Filter out any values that match the defaults const filteredConfig = pickBy( config, (value, key) => jsonStringify(value) !== jsonStringify(defaultConfig[key as keyof A]), ) // Write config file with secure permissions - mode only applies to new files writeFileSyncAndFlush_DEPRECATED( file, jsonStringify(filteredConfig, null, 2), { encoding: 'utf-8', mode: 0o600, }, ) if (file === getGlobalClaudeFile()) { globalConfigWriteCount++ }}
/** * Returns true if a write was performed; false if the write was skipped * (no changes, or auth-loss guard tripped). Callers use this to decide * whether to invalidate the cache -- invalidating after a skipped write * destroys the good cached state the auth-loss guard depends on. */function saveConfigWithLock<A extends object>( file: string, createDefault: () => A, mergeFn: (current: A) => A,): boolean { const defaultConfig = createDefault() const dir = dirname(file) const fs = getFsImplementation()
// Ensure directory exists (mkdirSync is already recursive in FsOperations) fs.mkdirSync(dir)
let release try { const lockFilePath = `${file}.lock` const startTime = Date.now() release = lockfile.lockSync(file, { lockfilePath: lockFilePath, realpath: false, onCompromised: err => { // Default onCompromised throws from a setTimeout callback, which // becomes an unhandled exception. Log instead -- the lock being // stolen (e.g. after a 10s event-loop stall) is recoverable. logForDebugging(`Config lock compromised: ${err}`, { level: 'error' }) }, }) const lockTime = Date.now() - startTime if (lockTime > 100) { logForDebugging( 'Lock acquisition took longer than expected - another Claude instance may be running', ) logEvent('tengu_config_lock_contention', { lock_time_ms: lockTime, }) }
// Check for stale write - file changed since we last read it // Only check for global config file since lastReadFileStats tracks that specific file if (lastReadFileStats && file === getGlobalClaudeFile()) { try { const currentStats = fs.statSync(file) if ( currentStats.mtimeMs !== lastReadFileStats.mtime || currentStats.size !== lastReadFileStats.size ) { logEvent('tengu_config_stale_write', { read_mtime: lastReadFileStats.mtime, write_mtime: currentStats.mtimeMs, read_size: lastReadFileStats.size, write_size: currentStats.size, }) } } catch (e) { const code = getErrnoCode(e) if (code !== 'ENOENT') { throw e } // File doesn't exist yet, no stale check needed } }
// Re-read the current config to get latest state. If the file is // momentarily corrupted (concurrent writes, kill-during-write), this // returns defaults -- we must not write those back over good config. const currentConfig = getConfig(file, createDefault) if (file === getGlobalClaudeFile() && wouldLoseAuthState(currentConfig)) { logForDebugging( 'saveConfigWithLock: re-read config is missing auth that cache has; refusing to write to avoid wiping ~/.claude.json. See GH #3117.', { level: 'error' }, ) logEvent('tengu_config_auth_loss_prevented', {}) return false }
// Apply the merge function to get the updated config const mergedConfig = mergeFn(currentConfig)
// Skip write if no changes (same reference returned) if (mergedConfig === currentConfig) { return false }
// Filter out any values that match the defaults const filteredConfig = pickBy( mergedConfig, (value, key) => jsonStringify(value) !== jsonStringify(defaultConfig[key as keyof A]), )
// Create timestamped backup of existing config before writing // We keep multiple backups to prevent data loss if a reset/corrupted config // overwrites a good backup. Backups are stored in ~/.claude/backups/ to // keep the home directory clean. try { const fileBase = basename(file) const backupDir = getConfigBackupDir()
// Ensure backup directory exists try { fs.mkdirSync(backupDir) } catch (mkdirErr) { const mkdirCode = getErrnoCode(mkdirErr) if (mkdirCode !== 'EEXIST') { throw mkdirErr } }
// Check existing backups first -- skip creating a new one if a recent // backup already exists. During startup, many saveGlobalConfig calls fire // within milliseconds of each other; without this check, each call // creates a new backup file that accumulates on disk. const MIN_BACKUP_INTERVAL_MS = 60_000 const existingBackups = fs .readdirStringSync(backupDir) .filter(f => f.startsWith(`${fileBase}.backup.`)) .sort() .reverse() // Most recent first (timestamps sort lexicographically)
const mostRecentBackup = existingBackups[0] const mostRecentTimestamp = mostRecentBackup ? Number(mostRecentBackup.split('.backup.').pop()) : 0 const shouldCreateBackup = Number.isNaN(mostRecentTimestamp) || Date.now() - mostRecentTimestamp >= MIN_BACKUP_INTERVAL_MS
if (shouldCreateBackup) { const backupPath = join(backupDir, `${fileBase}.backup.${Date.now()}`) fs.copyFileSync(file, backupPath) }
// Clean up old backups, keeping only the 5 most recent const MAX_BACKUPS = 5 // Re-read if we just created one; otherwise reuse the list const backupsForCleanup = shouldCreateBackup ? fs .readdirStringSync(backupDir) .filter(f => f.startsWith(`${fileBase}.backup.`)) .sort() .reverse() : existingBackups
for (const oldBackup of backupsForCleanup.slice(MAX_BACKUPS)) { try { fs.unlinkSync(join(backupDir, oldBackup)) } catch { // Ignore cleanup errors } } } catch (e) { const code = getErrnoCode(e) if (code !== 'ENOENT') { logForDebugging(`Failed to backup config: ${e}`, { level: 'error', }) } // No file to backup or backup failed, continue with write }
// Write config file with secure permissions - mode only applies to new files writeFileSyncAndFlush_DEPRECATED( file, jsonStringify(filteredConfig, null, 2), { encoding: 'utf-8', mode: 0o600, }, ) if (file === getGlobalClaudeFile()) { globalConfigWriteCount++ } return true } finally { if (release) { release() } }}
// Flag to track if config reading is allowedlet configReadingAllowed = false
export function enableConfigs(): void { if (configReadingAllowed) { // Ensure this is idempotent return }
const startTime = Date.now() logForDiagnosticsNoPII('info', 'enable_configs_started')
// Any reads to configuration before this flag is set show an console warning // to prevent us from adding config reading during module initialization configReadingAllowed = true // We only check the global config because currently all the configs share a file getConfig( getGlobalClaudeFile(), createDefaultGlobalConfig, true /* throw on invalid */, )
logForDiagnosticsNoPII('info', 'enable_configs_completed', { duration_ms: Date.now() - startTime, })}
/** * Returns the directory where config backup files are stored. * Uses ~/.claude/backups/ to keep the home directory clean. */function getConfigBackupDir(): string { return join(getClaudeConfigHomeDir(), 'backups')}
/** * Find the most recent backup file for a given config file. * Checks ~/.claude/backups/ first, then falls back to the legacy location * (next to the config file) for backwards compatibility. * Returns the full path to the most recent backup, or null if none exist. */function findMostRecentBackup(file: string): string | null { const fs = getFsImplementation() const fileBase = basename(file) const backupDir = getConfigBackupDir()
// Check the new backup directory first try { const backups = fs .readdirStringSync(backupDir) .filter(f => f.startsWith(`${fileBase}.backup.`)) .sort()
const mostRecent = backups.at(-1) // Timestamps sort lexicographically if (mostRecent) { return join(backupDir, mostRecent) } } catch { // Backup dir doesn't exist yet }
// Fall back to legacy location (next to the config file) const fileDir = dirname(file)
try { const backups = fs .readdirStringSync(fileDir) .filter(f => f.startsWith(`${fileBase}.backup.`)) .sort()
const mostRecent = backups.at(-1) // Timestamps sort lexicographically if (mostRecent) { return join(fileDir, mostRecent) }
// Check for legacy backup file (no timestamp) const legacyBackup = `${file}.backup` try { fs.statSync(legacyBackup) return legacyBackup } catch { // Legacy backup doesn't exist } } catch { // Ignore errors reading directory }
return null}
function getConfig<A>( file: string, createDefault: () => A, throwOnInvalid?: boolean,): A { // Log a warning if config is accessed before it's allowed if (!configReadingAllowed && process.env.NODE_ENV !== 'test') { throw new Error('Config accessed before allowed.') }
const fs = getFsImplementation()
try { const fileContent = fs.readFileSync(file, { encoding: 'utf-8', }) try { // Strip BOM before parsing - PowerShell 5.x adds BOM to UTF-8 files const parsedConfig = jsonParse(stripBOM(fileContent)) return { ...createDefault(), ...parsedConfig, } } catch (error) { // Throw a ConfigParseError with the file path and default config const errorMessage = error instanceof Error ? error.message : String(error) throw new ConfigParseError(errorMessage, file, createDefault()) } } catch (error) { // Handle file not found - check for backup and return default const errCode = getErrnoCode(error) if (errCode === 'ENOENT') { const backupPath = findMostRecentBackup(file) if (backupPath) { process.stderr.write( `\nClaude configuration file not found at: ${file}\n` + `A backup file exists at: ${backupPath}\n` + `You can manually restore it by running: cp "${backupPath}" "${file}"\n\n`, ) } return createDefault() }
// Re-throw ConfigParseError if throwOnInvalid is true if (error instanceof ConfigParseError && throwOnInvalid) { throw error }
// Log config parse errors so users know what happened if (error instanceof ConfigParseError) { logForDebugging( `Config file corrupted, resetting to defaults: ${error.message}`, { level: 'error' }, )
// Guard: logEvent → shouldSampleEvent → getGlobalConfig → getConfig // causes infinite recursion when the config file is corrupted, because // the sampling check reads a GrowthBook feature from global config. // Only log analytics on the outermost call. if (!insideGetConfig) { insideGetConfig = true try { // Log the error for monitoring logError(error)
// Log analytics event for config corruption let hasBackup = false try { fs.statSync(`${file}.backup`) hasBackup = true } catch { // No backup } logEvent('tengu_config_parse_error', { has_backup: hasBackup, }) } finally { insideGetConfig = false } }
process.stderr.write( `\nClaude configuration file at ${file} is corrupted: ${error.message}\n`, )
// Try to backup the corrupted config file (only if not already backed up) const fileBase = basename(file) const corruptedBackupDir = getConfigBackupDir()
// Ensure backup directory exists try { fs.mkdirSync(corruptedBackupDir) } catch (mkdirErr) { const mkdirCode = getErrnoCode(mkdirErr) if (mkdirCode !== 'EEXIST') { throw mkdirErr } }
const existingCorruptedBackups = fs .readdirStringSync(corruptedBackupDir) .filter(f => f.startsWith(`${fileBase}.corrupted.`))
let corruptedBackupPath: string | undefined let alreadyBackedUp = false
// Check if current corrupted content matches any existing backup const currentContent = fs.readFileSync(file, { encoding: 'utf-8' }) for (const backup of existingCorruptedBackups) { try { const backupContent = fs.readFileSync( join(corruptedBackupDir, backup), { encoding: 'utf-8' }, ) if (currentContent === backupContent) { alreadyBackedUp = true break } } catch { // Ignore read errors on backups } }
if (!alreadyBackedUp) { corruptedBackupPath = join( corruptedBackupDir, `${fileBase}.corrupted.${Date.now()}`, ) try { fs.copyFileSync(file, corruptedBackupPath) logForDebugging( `Corrupted config backed up to: ${corruptedBackupPath}`, { level: 'error', }, ) } catch { // Ignore backup errors } }
// Notify user about corrupted config and available backup const backupPath = findMostRecentBackup(file) if (corruptedBackupPath) { process.stderr.write( `The corrupted file has been backed up to: ${corruptedBackupPath}\n`, ) } else if (alreadyBackedUp) { process.stderr.write(`The corrupted file has already been backed up.\n`) }
if (backupPath) { process.stderr.write( `A backup file exists at: ${backupPath}\n` + `You can manually restore it by running: cp "${backupPath}" "${file}"\n\n`, ) } else { process.stderr.write(`\n`) } }
return createDefault() }}
// Memoized function to get the project path for config lookupexport const getProjectPathForConfig = memoize((): string => { const originalCwd = getOriginalCwd() const gitRoot = findCanonicalGitRoot(originalCwd)
if (gitRoot) { // Normalize for consistent JSON keys (forward slashes on all platforms) // This ensures paths like C:\Users\... and C:/Users/... map to the same key return normalizePathForConfigKey(gitRoot) }
// Not in a git repo return normalizePathForConfigKey(resolve(originalCwd))})
export function getCurrentProjectConfig(): ProjectConfig { if (process.env.NODE_ENV === 'test') { return TEST_PROJECT_CONFIG_FOR_TESTING }
const absolutePath = getProjectPathForConfig() const config = getGlobalConfig()
if (!config.projects) { return DEFAULT_PROJECT_CONFIG }
const projectConfig = config.projects[absolutePath] ?? DEFAULT_PROJECT_CONFIG // Not sure how this became a string // TODO: Fix upstream if (typeof projectConfig.allowedTools === 'string') { projectConfig.allowedTools = (safeParseJSON(projectConfig.allowedTools) as string[]) ?? [] }
return projectConfig}
export function saveCurrentProjectConfig( updater: (currentConfig: ProjectConfig) => ProjectConfig,): void { if (process.env.NODE_ENV === 'test') { const config = updater(TEST_PROJECT_CONFIG_FOR_TESTING) // Skip if no changes (same reference returned) if (config === TEST_PROJECT_CONFIG_FOR_TESTING) { return } Object.assign(TEST_PROJECT_CONFIG_FOR_TESTING, config) return } const absolutePath = getProjectPathForConfig()
let written: GlobalConfig | null = null try { const didWrite = saveConfigWithLock( getGlobalClaudeFile(), createDefaultGlobalConfig, current => { const currentProjectConfig = current.projects?.[absolutePath] ?? DEFAULT_PROJECT_CONFIG const newProjectConfig = updater(currentProjectConfig) // Skip if no changes (same reference returned) if (newProjectConfig === currentProjectConfig) { return current } written = { ...current, projects: { ...current.projects, [absolutePath]: newProjectConfig, }, } return written }, ) if (didWrite && written) { writeThroughGlobalConfigCache(written) } } catch (error) { logForDebugging(`Failed to save config with lock: ${error}`, { level: 'error', })
// Same race window as saveGlobalConfig's fallback -- refuse to write // defaults over good cached config. See GH #3117. const config = getConfig(getGlobalClaudeFile(), createDefaultGlobalConfig) if (wouldLoseAuthState(config)) { logForDebugging( 'saveCurrentProjectConfig fallback: re-read config is missing auth that cache has; refusing to write. See GH #3117.', { level: 'error' }, ) logEvent('tengu_config_auth_loss_prevented', {}) return } const currentProjectConfig = config.projects?.[absolutePath] ?? DEFAULT_PROJECT_CONFIG const newProjectConfig = updater(currentProjectConfig) // Skip if no changes (same reference returned) if (newProjectConfig === currentProjectConfig) { return } written = { ...config, projects: { ...config.projects, [absolutePath]: newProjectConfig, }, } saveConfig(getGlobalClaudeFile(), written, DEFAULT_GLOBAL_CONFIG) writeThroughGlobalConfigCache(written) }}
export function isAutoUpdaterDisabled(): boolean { return getAutoUpdaterDisabledReason() !== null}
/** * Returns true if plugin autoupdate should be skipped. * This checks if the auto-updater is disabled AND the FORCE_AUTOUPDATE_PLUGINS * env var is not set to 'true'. The env var allows forcing plugin autoupdate * even when the auto-updater is otherwise disabled. */export function shouldSkipPluginAutoupdate(): boolean { return ( isAutoUpdaterDisabled() && !isEnvTruthy(process.env.FORCE_AUTOUPDATE_PLUGINS) )}
export type AutoUpdaterDisabledReason = | { type: 'development' } | { type: 'env'; envVar: string } | { type: 'config' }
export function formatAutoUpdaterDisabledReason( reason: AutoUpdaterDisabledReason,): string { switch (reason.type) { case 'development': return 'development build' case 'env': return `${reason.envVar} set` case 'config': return 'config' }}
export function getAutoUpdaterDisabledReason(): AutoUpdaterDisabledReason | null { if (process.env.NODE_ENV === 'development') { return { type: 'development' } } if (isEnvTruthy(process.env.DISABLE_AUTOUPDATER)) { return { type: 'env', envVar: 'DISABLE_AUTOUPDATER' } } const essentialTrafficEnvVar = getEssentialTrafficOnlyReason() if (essentialTrafficEnvVar) { return { type: 'env', envVar: essentialTrafficEnvVar } } const config = getGlobalConfig() if ( config.autoUpdates === false && (config.installMethod !== 'native' || config.autoUpdatesProtectedForNative !== true) ) { return { type: 'config' } } return null}
export function getOrCreateUserID(): string { const config = getGlobalConfig() if (config.userID) { return config.userID }
const userID = randomBytes(32).toString('hex') saveGlobalConfig(current => ({ ...current, userID })) return userID}
export function recordFirstStartTime(): void { const config = getGlobalConfig() if (!config.firstStartTime) { const firstStartTime = new Date().toISOString() saveGlobalConfig(current => ({ ...current, firstStartTime: current.firstStartTime ?? firstStartTime, })) }}
export function getMemoryPath(memoryType: MemoryType): string { const cwd = getOriginalCwd()
switch (memoryType) { case 'User': return join(getClaudeConfigHomeDir(), 'CLAUDE.md') case 'Local': return join(cwd, 'CLAUDE.local.md') case 'Project': return join(cwd, 'CLAUDE.md') case 'Managed': return join(getManagedFilePath(), 'CLAUDE.md') case 'AutoMem': return getAutoMemEntrypoint() } // TeamMem is only a valid MemoryType when feature('TEAMMEM') is true if (feature('TEAMMEM')) { return teamMemPaths!.getTeamMemEntrypoint() } return '' // unreachable in external builds where TeamMem is not in MemoryType}
export function getManagedClaudeRulesDir(): string { return join(getManagedFilePath(), '.claude', 'rules')}
export function getUserClaudeRulesDir(): string { return join(getClaudeConfigHomeDir(), 'rules')}
// Exported for testing onlyexport const _getConfigForTesting = getConfigexport const _wouldLoseAuthStateForTesting = wouldLoseAuthStateexport function _setGlobalConfigCacheForTesting( config: GlobalConfig | null,): void { globalConfigCache.config = config globalConfigCache.mtime = config ? Date.now() : 0}123456789101112131415161718192021// These constants are in a separate file to avoid circular dependency issues.// Do NOT add imports to this file - it must remain dependency-free.
export const NOTIFICATION_CHANNELS = [ 'auto', 'iterm2', 'iterm2_with_bell', 'terminal_bell', 'kitty', 'ghostty', 'notifications_disabled',] as const
// Valid editor modes (excludes deprecated 'emacs' which is auto-migrated to 'normal')export const EDITOR_MODES = ['normal', 'vim'] as const
// Valid teammate modes for spawning// 'tmux' = traditional tmux-based teammates// 'in-process' = in-process teammates running in same process// 'auto' = automatically choose based on context (default)export const TEAMMATE_MODES = ['auto', 'tmux', 'in-process'] as const123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051/** * Utility for inserting a block into a content array relative to tool_result * blocks. Used by the API layer to position supplementary content (e.g., * cache editing directives) correctly within user messages. * * Placement rules: * - If tool_result blocks exist: insert after the last one * - Otherwise: insert before the last block * - If the inserted block would be the final element, a text continuation * block is appended (some APIs require the prompt not to end with * non-text content) */
/** * Inserts a block into the content array after the last tool_result block. * Mutates the array in place. * * @param content - The content array to modify * @param block - The block to insert */export function insertBlockAfterToolResults( content: unknown[], block: unknown,): void { // Find position after the last tool_result block let lastToolResultIndex = -1 for (let i = 0; i < content.length; i++) { const item = content[i] if ( item && typeof item === 'object' && 'type' in item && (item as { type: string }).type === 'tool_result' ) { lastToolResultIndex = i } }
if (lastToolResultIndex >= 0) { const insertPos = lastToolResultIndex + 1 content.splice(insertPos, 0, block) // Append a text continuation if the inserted block is now last if (insertPos === content.length - 1) { content.push({ type: 'text', text: '.' }) } } else { // No tool_result blocks — insert before the last block const insertIndex = Math.max(0, content.length - 1) content.splice(insertIndex, 0, block) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reorderedimport { CONTEXT_1M_BETA_HEADER } from '../constants/betas.js'import { getGlobalConfig } from './config.js'import { isEnvTruthy } from './envUtils.js'import { getCanonicalName } from './model/model.js'import { getModelCapability } from './model/modelCapabilities.js'
// Model context window size (200k tokens for all models right now)export const MODEL_CONTEXT_WINDOW_DEFAULT = 200_000
// Maximum output tokens for compact operationsexport const COMPACT_MAX_OUTPUT_TOKENS = 20_000
// Default max output tokensconst MAX_OUTPUT_TOKENS_DEFAULT = 32_000const MAX_OUTPUT_TOKENS_UPPER_LIMIT = 64_000
// Capped default for slot-reservation optimization. BQ p99 output = 4,911// tokens, so 32k/64k defaults over-reserve 8-16× slot capacity. With the cap// enabled, <1% of requests hit the limit; those get one clean retry at 64k// (see query.ts max_output_tokens_escalate). Cap is applied in// claude.ts:getMaxOutputTokensForModel to avoid the growthbook→betas→context// import cycle.export const CAPPED_DEFAULT_MAX_TOKENS = 8_000export const ESCALATED_MAX_TOKENS = 64_000
/** * Check if 1M context is disabled via environment variable. * Used by C4E admins to disable 1M context for HIPAA compliance. */export function is1mContextDisabled(): boolean { return isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_1M_CONTEXT)}
export function has1mContext(model: string): boolean { if (is1mContextDisabled()) { return false } return /\[1m\]/i.test(model)}
// @[MODEL LAUNCH]: Update this pattern if the new model supports 1M contextexport function modelSupports1M(model: string): boolean { if (is1mContextDisabled()) { return false } const canonical = getCanonicalName(model) return canonical.includes('claude-sonnet-4') || canonical.includes('opus-4-6')}
export function getContextWindowForModel( model: string, betas?: string[],): number { // Allow override via environment variable (ant-only) // This takes precedence over all other context window resolution, including 1M detection, // so users can cap the effective context window for local decisions (auto-compact, etc.) // while still using a 1M-capable endpoint. if ( process.env.USER_TYPE === 'ant' && process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS ) { const override = parseInt(process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS, 10) if (!isNaN(override) && override > 0) { return override } }
// [1m] suffix — explicit client-side opt-in, respected over all detection if (has1mContext(model)) { return 1_000_000 }
const cap = getModelCapability(model) if (cap?.max_input_tokens && cap.max_input_tokens >= 100_000) { if ( cap.max_input_tokens > MODEL_CONTEXT_WINDOW_DEFAULT && is1mContextDisabled() ) { return MODEL_CONTEXT_WINDOW_DEFAULT } return cap.max_input_tokens }
if (betas?.includes(CONTEXT_1M_BETA_HEADER) && modelSupports1M(model)) { return 1_000_000 } if (getSonnet1mExpTreatmentEnabled(model)) { return 1_000_000 } if (process.env.USER_TYPE === 'ant') { const antModel = resolveAntModel(model) if (antModel?.contextWindow) { return antModel.contextWindow } } return MODEL_CONTEXT_WINDOW_DEFAULT}
export function getSonnet1mExpTreatmentEnabled(model: string): boolean { if (is1mContextDisabled()) { return false } // Only applies to sonnet 4.6 without an explicit [1m] suffix if (has1mContext(model)) { return false } if (!getCanonicalName(model).includes('sonnet-4-6')) { return false } return getGlobalConfig().clientDataCache?.['coral_reef_sonnet'] === 'true'}
/** * Calculate context window usage percentage from token usage data. * Returns used and remaining percentages, or null values if no usage data. */export function calculateContextPercentages( currentUsage: { input_tokens: number cache_creation_input_tokens: number cache_read_input_tokens: number } | null, contextWindowSize: number,): { used: number | null; remaining: number | null } { if (!currentUsage) { return { used: null, remaining: null } }
const totalInputTokens = currentUsage.input_tokens + currentUsage.cache_creation_input_tokens + currentUsage.cache_read_input_tokens
const usedPercentage = Math.round( (totalInputTokens / contextWindowSize) * 100, ) const clampedUsed = Math.min(100, Math.max(0, usedPercentage))
return { used: clampedUsed, remaining: 100 - clampedUsed, }}
/** * Returns the model's default and upper limit for max output tokens. */export function getModelMaxOutputTokens(model: string): { default: number upperLimit: number} { let defaultTokens: number let upperLimit: number
if (process.env.USER_TYPE === 'ant') { const antModel = resolveAntModel(model.toLowerCase()) if (antModel) { defaultTokens = antModel.defaultMaxTokens ?? MAX_OUTPUT_TOKENS_DEFAULT upperLimit = antModel.upperMaxTokensLimit ?? MAX_OUTPUT_TOKENS_UPPER_LIMIT return { default: defaultTokens, upperLimit } } }
const m = getCanonicalName(model)
if (m.includes('opus-4-6')) { defaultTokens = 64_000 upperLimit = 128_000 } else if (m.includes('sonnet-4-6')) { defaultTokens = 32_000 upperLimit = 128_000 } else if ( m.includes('opus-4-5') || m.includes('sonnet-4') || m.includes('haiku-4') ) { defaultTokens = 32_000 upperLimit = 64_000 } else if (m.includes('opus-4-1') || m.includes('opus-4')) { defaultTokens = 32_000 upperLimit = 32_000 } else if (m.includes('claude-3-opus')) { defaultTokens = 4_096 upperLimit = 4_096 } else if (m.includes('claude-3-sonnet')) { defaultTokens = 8_192 upperLimit = 8_192 } else if (m.includes('claude-3-haiku')) { defaultTokens = 4_096 upperLimit = 4_096 } else if (m.includes('3-5-sonnet') || m.includes('3-5-haiku')) { defaultTokens = 8_192 upperLimit = 8_192 } else if (m.includes('3-7-sonnet')) { defaultTokens = 32_000 upperLimit = 64_000 } else { defaultTokens = MAX_OUTPUT_TOKENS_DEFAULT upperLimit = MAX_OUTPUT_TOKENS_UPPER_LIMIT }
const cap = getModelCapability(model) if (cap?.max_tokens && cap.max_tokens >= 4_096) { upperLimit = cap.max_tokens defaultTokens = Math.min(defaultTokens, upperLimit) }
return { default: defaultTokens, upperLimit }}
/** * Returns the max thinking budget tokens for a given model. The max * thinking tokens should be strictly less than the max output tokens. * * Deprecated since newer models use adaptive thinking rather than a * strict thinking token budget. */export function getMaxThinkingTokensForModel(model: string): number { return getModelMaxOutputTokens(model).upperLimit - 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235import { BASH_TOOL_NAME } from '../tools/BashTool/toolName.js'import { FILE_READ_TOOL_NAME } from '../tools/FileReadTool/prompt.js'import { GREP_TOOL_NAME } from '../tools/GrepTool/prompt.js'import { WEB_FETCH_TOOL_NAME } from '../tools/WebFetchTool/prompt.js'import type { ContextData } from './analyzeContext.js'import { getDisplayPath } from './file.js'import { formatTokens } from './format.js'
// --
export type SuggestionSeverity = 'info' | 'warning'
export type ContextSuggestion = { severity: SuggestionSeverity title: string detail: string /** Estimated tokens that could be saved */ savingsTokens?: number}
// Thresholds for triggering suggestionsconst LARGE_TOOL_RESULT_PERCENT = 15 // tool results > 15% of contextconst LARGE_TOOL_RESULT_TOKENS = 10_000const READ_BLOAT_PERCENT = 5 // Read results > 5% of contextconst NEAR_CAPACITY_PERCENT = 80const MEMORY_HIGH_PERCENT = 5const MEMORY_HIGH_TOKENS = 5_000
// --
export function generateContextSuggestions( data: ContextData,): ContextSuggestion[] { const suggestions: ContextSuggestion[] = []
checkNearCapacity(data, suggestions) checkLargeToolResults(data, suggestions) checkReadResultBloat(data, suggestions) checkMemoryBloat(data, suggestions) checkAutoCompactDisabled(data, suggestions)
// Sort: warnings first, then by savings descending suggestions.sort((a, b) => { if (a.severity !== b.severity) { return a.severity === 'warning' ? -1 : 1 } return (b.savingsTokens ?? 0) - (a.savingsTokens ?? 0) })
return suggestions}
// --
function checkNearCapacity( data: ContextData, suggestions: ContextSuggestion[],): void { if (data.percentage >= NEAR_CAPACITY_PERCENT) { suggestions.push({ severity: 'warning', title: `Context is ${data.percentage}% full`, detail: data.isAutoCompactEnabled ? 'Autocompact will trigger soon, which discards older messages. Use /compact now to control what gets kept.' : 'Autocompact is disabled. Use /compact to free space, or enable autocompact in /config.', }) }}
function checkLargeToolResults( data: ContextData, suggestions: ContextSuggestion[],): void { if (!data.messageBreakdown) return
for (const tool of data.messageBreakdown.toolCallsByType) { const totalToolTokens = tool.callTokens + tool.resultTokens const percent = (totalToolTokens / data.rawMaxTokens) * 100
if ( percent < LARGE_TOOL_RESULT_PERCENT || totalToolTokens < LARGE_TOOL_RESULT_TOKENS ) { continue }
const suggestion = getLargeToolSuggestion( tool.name, totalToolTokens, percent, ) if (suggestion) { suggestions.push(suggestion) } }}
function getLargeToolSuggestion( toolName: string, tokens: number, percent: number,): ContextSuggestion | null { const tokenStr = formatTokens(tokens)
switch (toolName) { case BASH_TOOL_NAME: return { severity: 'warning', title: `Bash results using ${tokenStr} tokens (${percent.toFixed(0)}%)`, detail: 'Pipe output through head, tail, or grep to reduce result size. Avoid cat on large files \u2014 use Read with offset/limit instead.', savingsTokens: Math.floor(tokens * 0.5), } case FILE_READ_TOOL_NAME: return { severity: 'info', title: `Read results using ${tokenStr} tokens (${percent.toFixed(0)}%)`, detail: 'Use offset and limit parameters to read only the sections you need. Avoid re-reading entire files when you only need a few lines.', savingsTokens: Math.floor(tokens * 0.3), } case GREP_TOOL_NAME: return { severity: 'info', title: `Grep results using ${tokenStr} tokens (${percent.toFixed(0)}%)`, detail: 'Add more specific patterns or use the glob or type parameter to narrow file types. Consider Glob for file discovery instead of Grep.', savingsTokens: Math.floor(tokens * 0.3), } case WEB_FETCH_TOOL_NAME: return { severity: 'info', title: `WebFetch results using ${tokenStr} tokens (${percent.toFixed(0)}%)`, detail: 'Web page content can be very large. Consider extracting only the specific information needed.', savingsTokens: Math.floor(tokens * 0.4), } default: if (percent >= 20) { return { severity: 'info', title: `${toolName} using ${tokenStr} tokens (${percent.toFixed(0)}%)`, detail: `This tool is consuming a significant portion of context.`, savingsTokens: Math.floor(tokens * 0.2), } } return null }}
function checkReadResultBloat( data: ContextData, suggestions: ContextSuggestion[],): void { if (!data.messageBreakdown) return
const callsByType = data.messageBreakdown.toolCallsByType const readTool = callsByType.find(t => t.name === FILE_READ_TOOL_NAME) if (!readTool) return
const totalReadTokens = readTool.callTokens + readTool.resultTokens const totalReadPercent = (totalReadTokens / data.rawMaxTokens) * 100 const readPercent = (readTool.resultTokens / data.rawMaxTokens) * 100
// Skip if already covered by checkLargeToolResults (>= 15% band) if ( totalReadPercent >= LARGE_TOOL_RESULT_PERCENT && totalReadTokens >= LARGE_TOOL_RESULT_TOKENS ) { return }
if ( readPercent >= READ_BLOAT_PERCENT && readTool.resultTokens >= LARGE_TOOL_RESULT_TOKENS ) { suggestions.push({ severity: 'info', title: `File reads using ${formatTokens(readTool.resultTokens)} tokens (${readPercent.toFixed(0)}%)`, detail: 'If you are re-reading files, consider referencing earlier reads. Use offset/limit for large files.', savingsTokens: Math.floor(readTool.resultTokens * 0.3), }) }}
function checkMemoryBloat( data: ContextData, suggestions: ContextSuggestion[],): void { const totalMemoryTokens = data.memoryFiles.reduce( (sum, f) => sum + f.tokens, 0, ) const memoryPercent = (totalMemoryTokens / data.rawMaxTokens) * 100
if ( memoryPercent >= MEMORY_HIGH_PERCENT && totalMemoryTokens >= MEMORY_HIGH_TOKENS ) { const largestFiles = [...data.memoryFiles] .sort((a, b) => b.tokens - a.tokens) .slice(0, 3) .map(f => { const name = getDisplayPath(f.path) return `${name} (${formatTokens(f.tokens)})` }) .join(', ')
suggestions.push({ severity: 'info', title: `Memory files using ${formatTokens(totalMemoryTokens)} tokens (${memoryPercent.toFixed(0)}%)`, detail: `Largest: ${largestFiles}. Use /memory to review and prune stale entries.`, savingsTokens: Math.floor(totalMemoryTokens * 0.3), }) }}
function checkAutoCompactDisabled( data: ContextData, suggestions: ContextSuggestion[],): void { if ( !data.isAutoCompactEnabled && data.percentage >= 50 && data.percentage < NEAR_CAPACITY_PERCENT ) { suggestions.push({ severity: 'info', title: 'Autocompact is disabled', detail: 'Without autocompact, you will hit context limits and lose the conversation. Enable it in /config or use /compact manually.', }) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308// Minimal cron expression parsing and next-run calculation.//// Supports the standard 5-field cron subset:// minute hour day-of-month month day-of-week//// Field syntax: wildcard, N, step (star-slash-N), range (N-M), list (N,M,...).// No L, W, ?, or name aliases. All times are interpreted in the process's// local timezone — "0 9 * * *" means 9am wherever the CLI is running.
export type CronFields = { minute: number[] hour: number[] dayOfMonth: number[] month: number[] dayOfWeek: number[]}
type FieldRange = { min: number; max: number }
const FIELD_RANGES: FieldRange[] = [ { min: 0, max: 59 }, // minute { min: 0, max: 23 }, // hour { min: 1, max: 31 }, // dayOfMonth { min: 1, max: 12 }, // month { min: 0, max: 6 }, // dayOfWeek (0=Sunday; 7 accepted as Sunday alias)]
// Parse a single cron field into a sorted array of matching values.// Supports: wildcard, N, star-slash-N (step), N-M (range), and comma-lists.// Returns null if invalid.function expandField(field: string, range: FieldRange): number[] | null { const { min, max } = range const out = new Set<number>()
for (const part of field.split(',')) { // wildcard or star-slash-N const stepMatch = part.match(/^\*(?:\/(\d+))?$/) if (stepMatch) { const step = stepMatch[1] ? parseInt(stepMatch[1], 10) : 1 if (step < 1) return null for (let i = min; i <= max; i += step) out.add(i) continue }
// N-M or N-M/S const rangeMatch = part.match(/^(\d+)-(\d+)(?:\/(\d+))?$/) if (rangeMatch) { const lo = parseInt(rangeMatch[1]!, 10) const hi = parseInt(rangeMatch[2]!, 10) const step = rangeMatch[3] ? parseInt(rangeMatch[3], 10) : 1 // dayOfWeek: accept 7 as Sunday alias in ranges (e.g. 5-7 = Fri,Sat,Sun → [5,6,0]) const isDow = min === 0 && max === 6 const effMax = isDow ? 7 : max if (lo > hi || step < 1 || lo < min || hi > effMax) return null for (let i = lo; i <= hi; i += step) { out.add(isDow && i === 7 ? 0 : i) } continue }
// plain N const singleMatch = part.match(/^\d+$/) if (singleMatch) { let n = parseInt(part, 10) // dayOfWeek: accept 7 as Sunday alias → 0 if (min === 0 && max === 6 && n === 7) n = 0 if (n < min || n > max) return null out.add(n) continue }
return null }
if (out.size === 0) return null return Array.from(out).sort((a, b) => a - b)}
/** * Parse a 5-field cron expression into expanded number arrays. * Returns null if invalid or unsupported syntax. */export function parseCronExpression(expr: string): CronFields | null { const parts = expr.trim().split(/\s+/) if (parts.length !== 5) return null
const expanded: number[][] = [] for (let i = 0; i < 5; i++) { const result = expandField(parts[i]!, FIELD_RANGES[i]!) if (!result) return null expanded.push(result) }
return { minute: expanded[0]!, hour: expanded[1]!, dayOfMonth: expanded[2]!, month: expanded[3]!, dayOfWeek: expanded[4]!, }}
/** * Compute the next Date strictly after `from` that matches the cron fields, * using the process's local timezone. Walks forward minute-by-minute. Bounded * at 366 days; returns null if no match (impossible for valid cron, but * satisfies the type). * * Standard cron semantics: when both dayOfMonth and dayOfWeek are constrained * (neither is the full range), a date matches if EITHER matches. * * DST: fixed-hour crons targeting a spring-forward gap (e.g. `30 2 * * *` * in a US timezone) skip the transition day — the gap hour never appears * in local time, so the hour-set check fails and the loop moves on. * Wildcard-hour crons (`30 * * * *`) fire at the first valid minute after * the gap. Fall-back repeats fire once (the step-forward logic jumps past * the second occurrence). This matches vixie-cron behavior. */export function computeNextCronRun( fields: CronFields, from: Date,): Date | null { const minuteSet = new Set(fields.minute) const hourSet = new Set(fields.hour) const domSet = new Set(fields.dayOfMonth) const monthSet = new Set(fields.month) const dowSet = new Set(fields.dayOfWeek)
// Is the field wildcarded (full range)? const domWild = fields.dayOfMonth.length === 31 const dowWild = fields.dayOfWeek.length === 7
// Round up to the next whole minute (strictly after `from`) const t = new Date(from.getTime()) t.setSeconds(0, 0) t.setMinutes(t.getMinutes() + 1)
const maxIter = 366 * 24 * 60 for (let i = 0; i < maxIter; i++) { const month = t.getMonth() + 1 if (!monthSet.has(month)) { // Jump to start of next month t.setMonth(t.getMonth() + 1, 1) t.setHours(0, 0, 0, 0) continue }
const dom = t.getDate() const dow = t.getDay() // When both dom/dow are constrained, either match is sufficient (OR semantics) const dayMatches = domWild && dowWild ? true : domWild ? dowSet.has(dow) : dowWild ? domSet.has(dom) : domSet.has(dom) || dowSet.has(dow)
if (!dayMatches) { // Jump to start of next day t.setDate(t.getDate() + 1) t.setHours(0, 0, 0, 0) continue }
if (!hourSet.has(t.getHours())) { t.setHours(t.getHours() + 1, 0, 0, 0) continue }
if (!minuteSet.has(t.getMinutes())) { t.setMinutes(t.getMinutes() + 1) continue }
return t }
return null}
// --- cronToHuman ------------------------------------------------------------// Intentionally narrow: covers common patterns; falls through to the raw cron// string for anything else. The `utc` option exists for CCR remote triggers// (agents-platform.tsx), which run on servers and always use UTC cron strings// — that path translates UTC→local for display and needs midnight-crossing// logic for the weekday case. Local scheduled tasks (the default) need neither.
const DAY_NAMES = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',]
function formatLocalTime(minute: number, hour: number): string { // January 1 — no DST gap anywhere. Using `new Date()` (today) would roll // 2am→3am on the one spring-forward day per year. const d = new Date(2000, 0, 1, hour, minute) return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
function formatUtcTimeAsLocal(minute: number, hour: number): string { // Create a date in UTC and format in user's local timezone const d = new Date() d.setUTCHours(hour, minute, 0, 0) return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', timeZoneName: 'short', })}
export function cronToHuman(cron: string, opts?: { utc?: boolean }): string { const utc = opts?.utc ?? false const parts = cron.trim().split(/\s+/) if (parts.length !== 5) return cron
const [minute, hour, dayOfMonth, month, dayOfWeek] = parts as [ string, string, string, string, string, ]
// Every N minutes: step/N * * * * const everyMinMatch = minute.match(/^\*\/(\d+)$/) if ( everyMinMatch && hour === '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*' ) { const n = parseInt(everyMinMatch[1]!, 10) return n === 1 ? 'Every minute' : `Every ${n} minutes` }
// Every hour: 0 * * * * if ( minute.match(/^\d+$/) && hour === '*' && dayOfMonth === '*' && month === '*' && dayOfWeek === '*' ) { const m = parseInt(minute, 10) if (m === 0) return 'Every hour' return `Every hour at :${m.toString().padStart(2, '0')}` }
// Every N hours: 0 step/N * * * const everyHourMatch = hour.match(/^\*\/(\d+)$/) if ( minute.match(/^\d+$/) && everyHourMatch && dayOfMonth === '*' && month === '*' && dayOfWeek === '*' ) { const n = parseInt(everyHourMatch[1]!, 10) const m = parseInt(minute, 10) const suffix = m === 0 ? '' : ` at :${m.toString().padStart(2, '0')}` return n === 1 ? `Every hour${suffix}` : `Every ${n} hours${suffix}` }
// --- Remaining cases reference hour+minute: branch on utc ----------------
if (!minute.match(/^\d+$/) || !hour.match(/^\d+$/)) return cron const m = parseInt(minute, 10) const h = parseInt(hour, 10) const fmtTime = utc ? formatUtcTimeAsLocal : formatLocalTime
// Daily at specific time: M H * * * if (dayOfMonth === '*' && month === '*' && dayOfWeek === '*') { return `Every day at ${fmtTime(m, h)}` }
// Specific day of week: M H * * D if (dayOfMonth === '*' && month === '*' && dayOfWeek.match(/^\d$/)) { const dayIndex = parseInt(dayOfWeek, 10) % 7 // normalize 7 (Sunday alias) -> 0 let dayName: string | undefined if (utc) { // UTC day+time may land on a different local day (midnight crossing). // Compute the actual local weekday by constructing the UTC instant. const ref = new Date() const daysToAdd = (dayIndex - ref.getUTCDay() + 7) % 7 ref.setUTCDate(ref.getUTCDate() + daysToAdd) ref.setUTCHours(h, m, 0, 0) dayName = DAY_NAMES[ref.getDay()] } else { dayName = DAY_NAMES[dayIndex] } if (dayName) return `Every ${dayName} at ${fmtTime(m, h)}` }
// Weekdays: M H * * 1-5 if (dayOfMonth === '*' && month === '*' && dayOfWeek === '1-5') { return `Weekdays at ${fmtTime(m, h)}` }
return cron}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// GrowthBook-backed cron jitter configuration.//// Separated from cronScheduler.ts so the scheduler can be bundled in the// Agent SDK public build without pulling in analytics/growthbook.ts and// its large transitive dependency set (settings/hooks/config cycle).//// Usage:// REPL (useScheduledTasks.ts): pass `getJitterConfig: getCronJitterConfig`// Daemon/SDK: omit getJitterConfig → DEFAULT_CRON_JITTER_CONFIG applies.
import { z } from 'zod/v4'import { getFeatureValue_CACHED_WITH_REFRESH } from '../services/analytics/growthbook.js'import { type CronJitterConfig, DEFAULT_CRON_JITTER_CONFIG,} from './cronTasks.js'import { lazySchema } from './lazySchema.js'
// How often to re-fetch tengu_kairos_cron_config from GrowthBook. Short because// this is an incident lever — when we push a config change to shed :00 load,// we want the fleet to converge within a minute, not on the next process// restart. The underlying call is a synchronous cache read; the refresh just// clears the memoized entry so the next read triggers a background fetch.const JITTER_CONFIG_REFRESH_MS = 60 * 1000
// Upper bounds here are defense-in-depth against fat-fingered GrowthBook// pushes. Like pollConfig.ts, Zod rejects the whole object on any violation// rather than partially trusting it — a config with one bad field falls back// to DEFAULT_CRON_JITTER_CONFIG entirely. oneShotFloorMs shares oneShotMaxMs's// ceiling (floor > max would invert the jitter range) and is cross-checked in// the refine; the shared ceiling keeps the individual bound explicit in the// error path. recurringMaxAgeMs uses .default() so a pre-existing GB config// without the field doesn't get wholesale-rejected — the other fields were// added together at config inception and don't need this.const HALF_HOUR_MS = 30 * 60 * 1000const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000const cronJitterConfigSchema = lazySchema(() => z .object({ recurringFrac: z.number().min(0).max(1), recurringCapMs: z.number().int().min(0).max(HALF_HOUR_MS), oneShotMaxMs: z.number().int().min(0).max(HALF_HOUR_MS), oneShotFloorMs: z.number().int().min(0).max(HALF_HOUR_MS), oneShotMinuteMod: z.number().int().min(1).max(60), recurringMaxAgeMs: z .number() .int() .min(0) .max(THIRTY_DAYS_MS) .default(DEFAULT_CRON_JITTER_CONFIG.recurringMaxAgeMs), }) .refine(c => c.oneShotFloorMs <= c.oneShotMaxMs),)
/** * Read `tengu_kairos_cron_config` from GrowthBook, validate, fall back to * defaults on absent/malformed/out-of-bounds config. Called from check() * every tick via the `getJitterConfig` callback — cheap (synchronous cache * hit). Refresh window: JITTER_CONFIG_REFRESH_MS. * * Exported so ops runbooks can point at a single function when documenting * the lever, and so tests can spy on it without mocking GrowthBook itself. * * Pass this as `getJitterConfig` when calling createCronScheduler in REPL * contexts. Daemon/SDK callers omit getJitterConfig and get defaults. */export function getCronJitterConfig(): CronJitterConfig { const raw = getFeatureValue_CACHED_WITH_REFRESH<unknown>( 'tengu_kairos_cron_config', DEFAULT_CRON_JITTER_CONFIG, JITTER_CONFIG_REFRESH_MS, ) const parsed = cronJitterConfigSchema().safeParse(raw) return parsed.success ? parsed.data : DEFAULT_CRON_JITTER_CONFIG}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565// Non-React scheduler core for .claude/scheduled_tasks.json.// Shared by REPL (via useScheduledTasks) and SDK/-p mode (print.ts).//// Lifecycle: poll getScheduledTasksEnabled() until true (flag flips when// CronCreate runs or a skill on: trigger fires) → load tasks + watch the// file + start a 1s check timer → on fire, call onFire(prompt). stop()// tears everything down.
import type { FSWatcher } from 'chokidar'import { getScheduledTasksEnabled, getSessionCronTasks, removeSessionCronTasks, setScheduledTasksEnabled,} from '../bootstrap/state.js'import { type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, logEvent,} from '../services/analytics/index.js'import { cronToHuman } from './cron.js'import { type CronJitterConfig, type CronTask, DEFAULT_CRON_JITTER_CONFIG, findMissedTasks, getCronFilePath, hasCronTasksSync, jitteredNextCronRunMs, markCronTasksFired, oneShotJitteredNextCronRunMs, readCronTasks, removeCronTasks,} from './cronTasks.js'import { releaseSchedulerLock, tryAcquireSchedulerLock,} from './cronTasksLock.js'import { logForDebugging } from './debug.js'
const CHECK_INTERVAL_MS = 1000const FILE_STABILITY_MS = 300// How often a non-owning session re-probes the scheduler lock. Coarse// because takeover only matters when the owning session has crashed.const LOCK_PROBE_INTERVAL_MS = 5000/** * True when a recurring task was created more than `maxAgeMs` ago and should * be deleted on its next fire. Permanent tasks never age. `maxAgeMs === 0` * means unlimited (never ages out). Sourced from * {@link CronJitterConfig.recurringMaxAgeMs} at call time. * Extracted for testability — the scheduler's check() is buried under * setInterval/chokidar/lock machinery. */export function isRecurringTaskAged( t: CronTask, nowMs: number, maxAgeMs: number,): boolean { if (maxAgeMs === 0) return false return Boolean(t.recurring && !t.permanent && nowMs - t.createdAt >= maxAgeMs)}
type CronSchedulerOptions = { /** Called when a task fires (regular or missed-on-startup). */ onFire: (prompt: string) => void /** While true, firing is deferred to the next tick. */ isLoading: () => boolean /** * When true, bypasses the isLoading gate in check() and auto-enables the * scheduler without waiting for setScheduledTasksEnabled(). The * auto-enable is the load-bearing part — assistant mode has tasks in * scheduled_tasks.json at install time and shouldn't wait on a loader * skill to flip the flag. The isLoading bypass is minor post-#20425 * (assistant mode now idles between turns like a normal REPL). */ assistantMode?: boolean /** * When provided, receives the full CronTask on normal fires (and onFire is * NOT called for that fire). Lets daemon callers see the task id/cron/etc * instead of just the prompt string. */ onFireTask?: (task: CronTask) => void /** * When provided, receives the missed one-shot tasks on initial load (and * onFire is NOT called with the pre-formatted notification). Daemon decides * how to surface them. */ onMissed?: (tasks: CronTask[]) => void /** * Directory containing .claude/scheduled_tasks.json. When provided, the * scheduler never touches bootstrap state: getProjectRoot/getSessionId are * not read, and the getScheduledTasksEnabled() poll is skipped (enable() * runs immediately on start). Required for Agent SDK daemon callers. */ dir?: string /** * Owner key written into the lock file. Defaults to getSessionId(). * Daemon callers must pass a stable per-process UUID since they have no * session. PID remains the liveness probe regardless. */ lockIdentity?: string /** * Returns the cron jitter config to use for this tick. Called once per * check() cycle. REPL callers pass a GrowthBook-backed implementation * (see cronJitterConfig.ts) for live tuning — ops can widen the jitter * window mid-session during a :00 load spike without restarting clients. * Agent SDK daemon callers omit this and get DEFAULT_CRON_JITTER_CONFIG, * which is safe since daemons restart on config change anyway, and the * growthbook.ts → config.ts → commands.ts → REPL chain stays out of * sdk.mjs. */ getJitterConfig?: () => CronJitterConfig /** * Killswitch: polled once per check() tick. When true, check() bails * before firing anything — existing crons stop dead mid-session. CLI * callers inject `() => !isKairosCronEnabled()` so flipping the * tengu_kairos_cron gate off stops already-running schedulers (not just * new ones). Daemon callers omit this, same rationale as getJitterConfig. */ isKilled?: () => boolean /** * Per-task gate applied before any side effect. Tasks returning false are * invisible to this scheduler: never fired, never stamped with * `lastFiredAt`, never deleted, never surfaced as missed, absent from * `getNextFireTime()`. The daemon cron worker uses `t => t.permanent` so * non-permanent tasks in the same scheduled_tasks.json are untouched. */ filter?: (t: CronTask) => boolean}
export type CronScheduler = { start: () => void stop: () => void /** * Epoch ms of the soonest scheduled fire across all loaded tasks, or null * if nothing is scheduled (no tasks, or all tasks already in-flight). * Daemon callers use this to decide whether to tear down an idle agent * subprocess or keep it warm for an imminent fire. */ getNextFireTime: () => number | null}
export function createCronScheduler( options: CronSchedulerOptions,): CronScheduler { const { onFire, isLoading, assistantMode = false, onFireTask, onMissed, dir, lockIdentity, getJitterConfig, isKilled, filter, } = options const lockOpts = dir || lockIdentity ? { dir, lockIdentity } : undefined
// File-backed tasks only. Session tasks (durable: false) are NOT loaded // here — they can be added/removed mid-session with no file event, so // check() reads them fresh from bootstrap state on every tick instead. let tasks: CronTask[] = [] // Per-task next-fire times (epoch ms). const nextFireAt = new Map<string, number>() // Ids we've already enqueued a "missed task" prompt for — prevents // re-asking on every file change before the user answers. const missedAsked = new Set<string>() // Tasks currently enqueued but not yet removed from the file. Prevents // double-fire if the interval ticks again before removeCronTasks lands. const inFlight = new Set<string>()
let enablePoll: ReturnType<typeof setInterval> | null = null let checkTimer: ReturnType<typeof setInterval> | null = null let lockProbeTimer: ReturnType<typeof setInterval> | null = null let watcher: FSWatcher | null = null let stopped = false let isOwner = false
async function load(initial: boolean) { const next = await readCronTasks(dir) if (stopped) return tasks = next
// Only surface missed tasks on initial load. Chokidar-triggered // reloads leave overdue tasks to check() (which anchors from createdAt // and fires immediately). This avoids a misleading "missed while Claude // was not running" prompt for tasks that became overdue mid-session. // // Recurring tasks are NOT surfaced or deleted — check() handles them // correctly (fires on first tick, reschedules forward). Only one-shot // missed tasks need user input (run once now, or discard forever). if (!initial) return
const now = Date.now() const missed = findMissedTasks(next, now).filter( t => !t.recurring && !missedAsked.has(t.id) && (!filter || filter(t)), ) if (missed.length > 0) { for (const t of missed) { missedAsked.add(t.id) // Prevent check() from re-firing the raw prompt while the async // removeCronTasks + chokidar reload chain is in progress. nextFireAt.set(t.id, Infinity) } logEvent('tengu_scheduled_task_missed', { count: missed.length, taskIds: missed .map(t => t.id) .join( ',', ) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, }) if (onMissed) { onMissed(missed) } else { onFire(buildMissedTaskNotification(missed)) } void removeCronTasks( missed.map(t => t.id), dir, ).catch(e => logForDebugging(`[ScheduledTasks] failed to remove missed tasks: ${e}`), ) logForDebugging( `[ScheduledTasks] surfaced ${missed.length} missed one-shot task(s)`, ) } }
function check() { if (isKilled?.()) return if (isLoading() && !assistantMode) return const now = Date.now() const seen = new Set<string>() // File-backed recurring tasks that fired this tick. Batched into one // markCronTasksFired call after the loop so N fires = one write. Session // tasks excluded — they die with the process, no point persisting. const firedFileRecurring: string[] = [] // Read once per tick. REPL callers pass getJitterConfig backed by // GrowthBook so a config push takes effect without restart. Daemon and // SDK callers omit it and get DEFAULT_CRON_JITTER_CONFIG (safe — jitter // is an ops lever for REPL fleet load-shedding, not a daemon concern). const jitterCfg = getJitterConfig?.() ?? DEFAULT_CRON_JITTER_CONFIG
// Shared loop body. `isSession` routes the one-shot cleanup path: // session tasks are removed synchronously from memory, file tasks go // through the async removeCronTasks + chokidar reload. function process(t: CronTask, isSession: boolean) { if (filter && !filter(t)) return seen.add(t.id) if (inFlight.has(t.id)) return
let next = nextFireAt.get(t.id) if (next === undefined) { // First sight — anchor from lastFiredAt (recurring) or createdAt. // Never-fired recurring tasks use createdAt: if isLoading delayed // this tick past the fire time, anchoring from `now` would compute // next-year for pinned crons (`30 14 27 2 *`). Fired-before tasks // use lastFiredAt: the reschedule below writes `now` back to disk, // so on next process spawn first-sight computes the SAME newNext we // set in-memory here. Without this, a daemon child despawning on // idle loses nextFireAt and the next spawn re-anchors from 10-day- // old createdAt → fires every task every cycle. next = t.recurring ? (jitteredNextCronRunMs( t.cron, t.lastFiredAt ?? t.createdAt, t.id, jitterCfg, ) ?? Infinity) : (oneShotJitteredNextCronRunMs( t.cron, t.createdAt, t.id, jitterCfg, ) ?? Infinity) nextFireAt.set(t.id, next) logForDebugging( `[ScheduledTasks] scheduled ${t.id} for ${next === Infinity ? 'never' : new Date(next).toISOString()}`, ) }
if (now < next) return
logForDebugging( `[ScheduledTasks] firing ${t.id}${t.recurring ? ' (recurring)' : ''}`, ) logEvent('tengu_scheduled_task_fire', { recurring: t.recurring ?? false, taskId: t.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, }) if (onFireTask) { onFireTask(t) } else { onFire(t.prompt) }
// Aged-out recurring tasks fall through to the one-shot delete paths // below (session tasks get synchronous removal; file tasks get the // async inFlight/chokidar path). Fires one last time, then is removed. const aged = isRecurringTaskAged(t, now, jitterCfg.recurringMaxAgeMs) if (aged) { const ageHours = Math.floor((now - t.createdAt) / 1000 / 60 / 60) logForDebugging( `[ScheduledTasks] recurring task ${t.id} aged out (${ageHours}h since creation), deleting after final fire`, ) logEvent('tengu_scheduled_task_expired', { taskId: t.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, ageHours, }) }
if (t.recurring && !aged) { // Recurring: reschedule from now (not from next) to avoid rapid // catch-up if the session was blocked. Jitter keeps us off the // exact :00 wall-clock boundary every cycle. const newNext = jitteredNextCronRunMs(t.cron, now, t.id, jitterCfg) ?? Infinity nextFireAt.set(t.id, newNext) // Persist lastFiredAt=now so next process spawn reconstructs this // same newNext on first-sight. Session tasks skip — process-local. if (!isSession) firedFileRecurring.push(t.id) } else if (isSession) { // One-shot (or aged-out recurring) session task: synchronous memory // removal. No inFlight window — the next tick will read a session // store without this id. removeSessionCronTasks([t.id]) nextFireAt.delete(t.id) } else { // One-shot (or aged-out recurring) file task: delete from disk. // inFlight guards against double-fire during the async // removeCronTasks + chokidar reload. inFlight.add(t.id) void removeCronTasks([t.id], dir) .catch(e => logForDebugging( `[ScheduledTasks] failed to remove task ${t.id}: ${e}`, ), ) .finally(() => inFlight.delete(t.id)) nextFireAt.delete(t.id) } }
// File-backed tasks: only when we own the scheduler lock. The lock // exists to stop two Claude sessions in the same cwd from double-firing // the same on-disk task. if (isOwner) { for (const t of tasks) process(t, false) // Batched lastFiredAt write. inFlight guards against double-fire // during the chokidar-triggered reload (same pattern as removeCronTasks // below) — the reload re-seeds `tasks` with the just-written // lastFiredAt, and first-sight on that yields the same newNext we // already set in-memory, so it's idempotent even without inFlight. // Guarding anyway keeps the semantics obvious. if (firedFileRecurring.length > 0) { for (const id of firedFileRecurring) inFlight.add(id) void markCronTasksFired(firedFileRecurring, now, dir) .catch(e => logForDebugging( `[ScheduledTasks] failed to persist lastFiredAt: ${e}`, ), ) .finally(() => { for (const id of firedFileRecurring) inFlight.delete(id) }) } } // Session-only tasks: process-private, the lock does not apply — the // other session cannot see them and there is no double-fire risk. Read // fresh from bootstrap state every tick (no chokidar, no load()). This // is skipped on the daemon path (`dir !== undefined`) which never // touches bootstrap state. if (dir === undefined) { for (const t of getSessionCronTasks()) process(t, true) }
if (seen.size === 0) { // No live tasks this tick — clear the whole schedule so // getNextFireTime() returns null. The eviction loop below is // unreachable here (seen is empty), so stale entries would // otherwise survive indefinitely and keep the daemon agent warm. nextFireAt.clear() return } // Evict schedule entries for tasks no longer present. When !isOwner, // file-task ids aren't in `seen` and get evicted — harmless: they // re-anchor from createdAt on the first owned tick. for (const id of nextFireAt.keys()) { if (!seen.has(id)) nextFireAt.delete(id) } }
async function enable() { if (stopped) return if (enablePoll) { clearInterval(enablePoll) enablePoll = null }
const { default: chokidar } = await import('chokidar') if (stopped) return
// Acquire the per-project scheduler lock. Only the owning session runs // check(). Other sessions probe periodically to take over if the owner // dies. Prevents double-firing when multiple Claudes share a cwd. isOwner = await tryAcquireSchedulerLock(lockOpts).catch(() => false) if (stopped) { if (isOwner) { isOwner = false void releaseSchedulerLock(lockOpts) } return } if (!isOwner) { lockProbeTimer = setInterval(() => { void tryAcquireSchedulerLock(lockOpts) .then(owned => { if (stopped) { if (owned) void releaseSchedulerLock(lockOpts) return } if (owned) { isOwner = true if (lockProbeTimer) { clearInterval(lockProbeTimer) lockProbeTimer = null } } }) .catch(e => logForDebugging(String(e), { level: 'error' })) }, LOCK_PROBE_INTERVAL_MS) lockProbeTimer.unref?.() }
void load(true)
const path = getCronFilePath(dir) watcher = chokidar.watch(path, { persistent: false, ignoreInitial: true, awaitWriteFinish: { stabilityThreshold: FILE_STABILITY_MS }, ignorePermissionErrors: true, }) watcher.on('add', () => void load(false)) watcher.on('change', () => void load(false)) watcher.on('unlink', () => { if (!stopped) { tasks = [] nextFireAt.clear() } })
checkTimer = setInterval(check, CHECK_INTERVAL_MS) // Don't keep the process alive for the scheduler alone — in -p text mode // the process should exit after the single turn even if a cron was created. checkTimer.unref?.() }
return { start() { stopped = false // Daemon path (dir explicitly given): don't touch bootstrap state — // getScheduledTasksEnabled() would read a never-initialized flag. The // daemon is asking to schedule; just enable. if (dir !== undefined) { logForDebugging( `[ScheduledTasks] scheduler start() — dir=${dir}, hasTasks=${hasCronTasksSync(dir)}`, ) void enable() return } logForDebugging( `[ScheduledTasks] scheduler start() — enabled=${getScheduledTasksEnabled()}, hasTasks=${hasCronTasksSync()}`, ) // Auto-enable when scheduled_tasks.json has entries. CronCreateTool // also sets this when a task is created mid-session. if ( !getScheduledTasksEnabled() && (assistantMode || hasCronTasksSync()) ) { setScheduledTasksEnabled(true) } if (getScheduledTasksEnabled()) { void enable() return } enablePoll = setInterval( en => { if (getScheduledTasksEnabled()) void en() }, CHECK_INTERVAL_MS, enable, ) enablePoll.unref?.() }, stop() { stopped = true if (enablePoll) { clearInterval(enablePoll) enablePoll = null } if (checkTimer) { clearInterval(checkTimer) checkTimer = null } if (lockProbeTimer) { clearInterval(lockProbeTimer) lockProbeTimer = null } void watcher?.close() watcher = null if (isOwner) { isOwner = false void releaseSchedulerLock(lockOpts) } }, getNextFireTime() { // nextFireAt uses Infinity for "never" (in-flight one-shots, bad cron // strings). Filter those out so callers can distinguish "soon" from // "nothing pending". let min = Infinity for (const t of nextFireAt.values()) { if (t < min) min = t } return min === Infinity ? null : min }, }}
/** * Build the missed-task notification text. Guidance precedes the task list * and the list is wrapped in a code fence so a multi-line imperative prompt * is not interpreted as immediate instructions to avoid self-inflicted * prompt injection. The full prompt body is preserved — this path DOES * need the model to execute the prompt after user * confirmation, and tasks are already deleted from JSON before the model * sees this notification. */export function buildMissedTaskNotification(missed: CronTask[]): string { const plural = missed.length > 1 const header = `The following one-shot scheduled task${plural ? 's were' : ' was'} missed while Claude was not running. ` + `${plural ? 'They have' : 'It has'} already been removed from .claude/scheduled_tasks.json.\n\n` + `Do NOT execute ${plural ? 'these prompts' : 'this prompt'} yet. ` + `First use the AskUserQuestion tool to ask whether to run ${plural ? 'each one' : 'it'} now. ` + `Only execute if the user confirms.`
const blocks = missed.map(t => { const meta = `[${cronToHuman(t.cron)}, created ${new Date(t.createdAt).toLocaleString()}]` // Use a fence one longer than any backtick run in the prompt so a // prompt containing ``` cannot close the fence early and un-wrap the // trailing text (CommonMark fence-matching rule). const longestRun = (t.prompt.match(/`+/g) ?? []).reduce( (max, run) => Math.max(max, run.length), 0, ) const fence = '`'.repeat(Math.max(3, longestRun + 1)) return `${meta}\n${fence}\n${t.prompt}\n${fence}` })
return `${header}\n\n${blocks.join('\n\n')}`}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458// Scheduled prompts, stored in <project>/.claude/scheduled_tasks.json.//// Tasks come in two flavors:// - One-shot (recurring: false/undefined) — fire once, then auto-delete.// - Recurring (recurring: true) — fire on schedule, reschedule from now,// persist until explicitly deleted via CronDelete or auto-expire after// a configurable limit (DEFAULT_CRON_JITTER_CONFIG.recurringMaxAgeMs).//// File format:// { "tasks": [{ id, cron, prompt, createdAt, recurring?, permanent? }] }
import { randomUUID } from 'crypto'import { readFileSync } from 'fs'import { mkdir, writeFile } from 'fs/promises'import { join } from 'path'import { addSessionCronTask, getProjectRoot, getSessionCronTasks, removeSessionCronTasks,} from '../bootstrap/state.js'import { computeNextCronRun, parseCronExpression } from './cron.js'import { logForDebugging } from './debug.js'import { isFsInaccessible } from './errors.js'import { getFsImplementation } from './fsOperations.js'import { safeParseJSON } from './json.js'import { logError } from './log.js'import { jsonStringify } from './slowOperations.js'
export type CronTask = { id: string /** 5-field cron string (local time) — validated on write, re-validated on read. */ cron: string /** Prompt to enqueue when the task fires. */ prompt: string /** Epoch ms when the task was created. Anchor for missed-task detection. */ createdAt: number /** * Epoch ms of the most recent fire. Written back by the scheduler after * each recurring fire so next-fire computation survives process restarts. * The scheduler anchors first-sight from `lastFiredAt ?? createdAt` — a * never-fired task uses createdAt (correct for pinned crons like * `30 14 27 2 *` whose next-from-now is next year); a fired-before task * reconstructs the same `nextFireAt` the prior process had in memory. * Never set for one-shots (they're deleted on fire). */ lastFiredAt?: number /** When true, the task reschedules after firing instead of being deleted. */ recurring?: boolean /** * When true, the task is exempt from recurringMaxAgeMs auto-expiry. * System escape hatch for assistant mode's built-in tasks (catch-up/ * morning-checkin/dream) — the installer's writeIfMissing() skips existing * files so re-install can't recreate them. Not settable via CronCreateTool; * only written directly to scheduled_tasks.json by src/assistant/install.ts. */ permanent?: boolean /** * Runtime-only flag. false → session-scoped (never written to disk). * File-backed tasks leave this undefined; writeCronTasks strips it so * the on-disk shape stays { id, cron, prompt, createdAt, lastFiredAt?, recurring?, permanent? }. */ durable?: boolean /** * Runtime-only. When set, the task was created by an in-process teammate. * The scheduler routes fires to that teammate's queue instead of the main * REPL's. Never written to disk (teammate crons are always session-only). */ agentId?: string}
type CronFile = { tasks: CronTask[] }
const CRON_FILE_REL = join('.claude', 'scheduled_tasks.json')
/** * Path to the cron file. `dir` defaults to getProjectRoot() — pass it * explicitly from contexts that don't run through main.tsx (e.g. the Agent * SDK daemon, which has no bootstrap state). */export function getCronFilePath(dir?: string): string { return join(dir ?? getProjectRoot(), CRON_FILE_REL)}
/** * Read and parse .claude/scheduled_tasks.json. Returns an empty task list if the file * is missing, empty, or malformed. Tasks with invalid cron strings are * silently dropped (logged at debug level) so a single bad entry never * blocks the whole file. */export async function readCronTasks(dir?: string): Promise<CronTask[]> { const fs = getFsImplementation() let raw: string try { raw = await fs.readFile(getCronFilePath(dir), { encoding: 'utf-8' }) } catch (e: unknown) { if (isFsInaccessible(e)) return [] logError(e) return [] }
const parsed = safeParseJSON(raw, false) if (!parsed || typeof parsed !== 'object') return [] const file = parsed as Partial<CronFile> if (!Array.isArray(file.tasks)) return []
const out: CronTask[] = [] for (const t of file.tasks) { if ( !t || typeof t.id !== 'string' || typeof t.cron !== 'string' || typeof t.prompt !== 'string' || typeof t.createdAt !== 'number' ) { logForDebugging( `[ScheduledTasks] skipping malformed task: ${jsonStringify(t)}`, ) continue } if (!parseCronExpression(t.cron)) { logForDebugging( `[ScheduledTasks] skipping task ${t.id} with invalid cron '${t.cron}'`, ) continue } out.push({ id: t.id, cron: t.cron, prompt: t.prompt, createdAt: t.createdAt, ...(typeof t.lastFiredAt === 'number' ? { lastFiredAt: t.lastFiredAt } : {}), ...(t.recurring ? { recurring: true } : {}), ...(t.permanent ? { permanent: true } : {}), }) } return out}
/** * Sync check for whether the cron file has any valid tasks. Used by * cronScheduler.start() to decide whether to auto-enable. One file read. */export function hasCronTasksSync(dir?: string): boolean { let raw: string try { // eslint-disable-next-line custom-rules/no-sync-fs -- called once from cronScheduler.start() raw = readFileSync(getCronFilePath(dir), 'utf-8') } catch { return false } const parsed = safeParseJSON(raw, false) if (!parsed || typeof parsed !== 'object') return false const tasks = (parsed as Partial<CronFile>).tasks return Array.isArray(tasks) && tasks.length > 0}
/** * Overwrite .claude/scheduled_tasks.json with the given tasks. Creates .claude/ if * missing. Empty task list writes an empty file (rather than deleting) so * the file watcher sees a change event on last-task-removed. */export async function writeCronTasks( tasks: CronTask[], dir?: string,): Promise<void> { const root = dir ?? getProjectRoot() await mkdir(join(root, '.claude'), { recursive: true }) // Strip the runtime-only `durable` flag — everything on disk is durable // by definition, and keeping the flag out means readCronTasks() naturally // yields durable: undefined without having to set it explicitly. const body: CronFile = { tasks: tasks.map(({ durable: _durable, ...rest }) => rest), } await writeFile( getCronFilePath(root), jsonStringify(body, null, 2) + '\n', 'utf-8', )}
/** * Append a task. Returns the generated id. Caller is responsible for having * already validated the cron string (the tool does this via validateInput). * * When `durable` is false the task is held in process memory only * (bootstrap/state.ts) — it fires on schedule this session but is never * written to .claude/scheduled_tasks.json and dies with the process. The * scheduler merges session tasks into its tick loop directly, so no file * change event is needed. */export async function addCronTask( cron: string, prompt: string, recurring: boolean, durable: boolean, agentId?: string,): Promise<string> { // Short ID — 8 hex chars is plenty for MAX_JOBS=50, avoids slice/prefix // juggling between the tool layer (shows short IDs) and disk. const id = randomUUID().slice(0, 8) const task = { id, cron, prompt, createdAt: Date.now(), ...(recurring ? { recurring: true } : {}), } if (!durable) { addSessionCronTask({ ...task, ...(agentId ? { agentId } : {}) }) return id } const tasks = await readCronTasks() tasks.push(task) await writeCronTasks(tasks) return id}
/** * Remove tasks by id. No-op if none match (e.g. another session raced us). * Used for both fire-once cleanup and explicit CronDelete. * * When called with `dir` undefined (REPL path), also sweeps the in-memory * session store — the caller doesn't know which store an id lives in. * Daemon callers pass `dir` explicitly; they have no session, and the * `dir !== undefined` guard keeps this function from touching bootstrap * state on that path (tests enforce this). */export async function removeCronTasks( ids: string[], dir?: string,): Promise<void> { if (ids.length === 0) return // Sweep session store first. If every id was accounted for there, we're // done — skip the file read entirely. removeSessionCronTasks is a no-op // (returns 0) on miss, so pre-existing durable-delete paths fall through // without allocating. if (dir === undefined && removeSessionCronTasks(ids) === ids.length) { return } const idSet = new Set(ids) const tasks = await readCronTasks(dir) const remaining = tasks.filter(t => !idSet.has(t.id)) if (remaining.length === tasks.length) return await writeCronTasks(remaining, dir)}
/** * Stamp `lastFiredAt` on the given recurring tasks and write back. Batched * so N fires in one scheduler tick = one read-modify-write, not N. Only * touches file-backed tasks — session tasks die with the process, no point * persisting their fire time. No-op if none of the ids match (task was * deleted between fire and write — e.g. user ran CronDelete mid-tick). * * Scheduler lock means at most one process calls this; chokidar picks up * the write and triggers a reload which re-seeds `nextFireAt` from the * just-written `lastFiredAt` — idempotent (same computation, same answer). */export async function markCronTasksFired( ids: string[], firedAt: number, dir?: string,): Promise<void> { if (ids.length === 0) return const idSet = new Set(ids) const tasks = await readCronTasks(dir) let changed = false for (const t of tasks) { if (idSet.has(t.id)) { t.lastFiredAt = firedAt changed = true } } if (!changed) return await writeCronTasks(tasks, dir)}
/** * File-backed tasks + session-only tasks, merged. Session tasks get * `durable: false` so callers can distinguish them. File tasks are * returned as-is (durable undefined → truthy). * * Only merges when `dir` is undefined — daemon callers (explicit `dir`) * have no session store to merge with. */export async function listAllCronTasks(dir?: string): Promise<CronTask[]> { const fileTasks = await readCronTasks(dir) if (dir !== undefined) return fileTasks const sessionTasks = getSessionCronTasks().map(t => ({ ...t, durable: false as const, })) return [...fileTasks, ...sessionTasks]}
/** * Next fire time in epoch ms for a cron string, strictly after `fromMs`. * Returns null if invalid or no match in the next 366 days. */export function nextCronRunMs(cron: string, fromMs: number): number | null { const fields = parseCronExpression(cron) if (!fields) return null const next = computeNextCronRun(fields, new Date(fromMs)) return next ? next.getTime() : null}
/** * Cron scheduler tuning knobs. Sourced at runtime from the * `tengu_kairos_cron_config` GrowthBook JSON config (see cronJitterConfig.ts) * so ops can adjust behavior fleet-wide without shipping a client build. * Defaults here preserve the pre-config behavior exactly. */export type CronJitterConfig = { /** Recurring-task forward delay as a fraction of the interval between fires. */ recurringFrac: number /** Upper bound on recurring forward delay regardless of interval length. */ recurringCapMs: number /** One-shot backward lead: maximum ms a task may fire early. */ oneShotMaxMs: number /** * One-shot backward lead: minimum ms a task fires early when the minute-mod * gate matches. 0 = taskIds hashing near zero fire on the exact mark. Raise * this to guarantee nobody lands on the wall-clock boundary. */ oneShotFloorMs: number /** * Jitter fires landing on minutes where `minute % N === 0`. 30 → :00/:30 * (the human-rounding hotspots). 15 → :00/:15/:30/:45. 1 → every minute. */ oneShotMinuteMod: number /** * Recurring tasks auto-expire this many ms after creation (unless marked * `permanent`). Cron is the primary driver of multi-day sessions (p99 * uptime 61min → 53h post-#19931), and unbounded recurrence lets Tier-1 * heap leaks compound indefinitely. The default (7 days) covers "check * my PRs every hour this week" workflows while capping worst-case * session lifetime. Permanent tasks (assistant mode's catch-up/ * morning-checkin/dream) never age out — they can't be recreated if * deleted because install.ts's writeIfMissing() skips existing files. * * `0` = unlimited (tasks never auto-expire). */ recurringMaxAgeMs: number}
export const DEFAULT_CRON_JITTER_CONFIG: CronJitterConfig = { recurringFrac: 0.1, recurringCapMs: 15 * 60 * 1000, oneShotMaxMs: 90 * 1000, oneShotFloorMs: 0, oneShotMinuteMod: 30, recurringMaxAgeMs: 7 * 24 * 60 * 60 * 1000,}
/** * taskId is an 8-hex-char UUID slice (see {@link addCronTask}) → parse as * u32 → [0, 1). Stable across restarts, uniformly distributed across the * fleet. Non-hex ids (hand-edited JSON) fall back to 0 = no jitter. */function jitterFrac(taskId: string): number { const frac = parseInt(taskId.slice(0, 8), 16) / 0x1_0000_0000 return Number.isFinite(frac) ? frac : 0}
/** * Same as {@link nextCronRunMs}, plus a deterministic per-task delay to * avoid a thundering herd when many sessions schedule the same cron string * (e.g. `0 * * * *` → everyone hits inference at :00). * * The delay is proportional to the current gap between fires * ({@link CronJitterConfig.recurringFrac}, capped at * {@link CronJitterConfig.recurringCapMs}) so at defaults an hourly task * spreads across [:00, :06) but a per-minute task only spreads by a few * seconds. * * Only used for recurring tasks. One-shot tasks use * {@link oneShotJitteredNextCronRunMs} (backward jitter, minute-gated). */export function jitteredNextCronRunMs( cron: string, fromMs: number, taskId: string, cfg: CronJitterConfig = DEFAULT_CRON_JITTER_CONFIG,): number | null { const t1 = nextCronRunMs(cron, fromMs) if (t1 === null) return null const t2 = nextCronRunMs(cron, t1) // No second match in the next year (e.g. pinned date) → nothing to // proportion against, and near-certainly not a herd risk. Fire on t1. if (t2 === null) return t1 const jitter = Math.min( jitterFrac(taskId) * cfg.recurringFrac * (t2 - t1), cfg.recurringCapMs, ) return t1 + jitter}
/** * Same as {@link nextCronRunMs}, minus a deterministic per-task lead time * when the fire time lands on a minute boundary matching * {@link CronJitterConfig.oneShotMinuteMod}. * * One-shot tasks are user-pinned ("remind me at 3pm") so delaying them * breaks the contract — but firing slightly early is invisible and spreads * the inference spike from everyone picking the same round wall-clock time. * At defaults (mod 30, max 90 s, floor 0) only :00 and :30 get jitter, * because humans round to the half-hour. * * During an incident, ops can push `tengu_kairos_cron_config` with e.g. * `{oneShotMinuteMod: 15, oneShotMaxMs: 300000, oneShotFloorMs: 30000}` to * spread :00/:15/:30/:45 fires across a [t-5min, t-30s] window — every task * gets at least 30 s of lead, so nobody lands on the exact mark. * * Checks the computed fire time rather than the cron string so * `0 15 * * *`, step expressions, and `0,30 9 * * *` all get jitter * when they land on a matching minute. Clamped to `fromMs` so a task created * inside its own jitter window doesn't fire before it was created. */export function oneShotJitteredNextCronRunMs( cron: string, fromMs: number, taskId: string, cfg: CronJitterConfig = DEFAULT_CRON_JITTER_CONFIG,): number | null { const t1 = nextCronRunMs(cron, fromMs) if (t1 === null) return null // Cron resolution is 1 minute → computed times always have :00 seconds, // so a minute-field check is sufficient to identify the hot marks. // getMinutes() (local), not getUTCMinutes(): cron is evaluated in local // time, and "user picked a round time" means round in *their* TZ. In // half-hour-offset zones (India UTC+5:30) local :00 is UTC :30 — the // UTC check would jitter the wrong marks. if (new Date(t1).getMinutes() % cfg.oneShotMinuteMod !== 0) return t1 // floor + frac * (max - floor) → uniform over [floor, max). With floor=0 // this reduces to the original frac * max. With floor>0, even a taskId // hashing to 0 gets `floor` ms of lead — nobody fires on the exact mark. const lead = cfg.oneShotFloorMs + jitterFrac(taskId) * (cfg.oneShotMaxMs - cfg.oneShotFloorMs) // t1 > fromMs is guaranteed by nextCronRunMs (strictly after), so the // max() only bites when the task was created inside its own lead window. return Math.max(t1 - lead, fromMs)}
/** * A task is "missed" when its next scheduled run (computed from createdAt) * is in the past. Surfaced to the user at startup. Works for both one-shot * and recurring tasks — a recurring task whose window passed while Claude * was down is still "missed". */export function findMissedTasks(tasks: CronTask[], nowMs: number): CronTask[] { return tasks.filter(t => { const next = nextCronRunMs(t.cron, t.createdAt) return next !== null && next < nowMs })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195// Scheduler lease lock for .claude/scheduled_tasks.json.//// When multiple Claude sessions run in the same project directory, only one// should drive the cron scheduler. The first session to acquire this lock// becomes the scheduler; others stay passive and periodically probe the lock.// If the owner dies (PID no longer running), a passive session takes over.//// Pattern mirrors computerUseLock.ts: O_EXCL atomic create, PID liveness// probe, stale-lock recovery, cleanup-on-exit.
import { mkdir, readFile, unlink, writeFile } from 'fs/promises'import { dirname, join } from 'path'import { z } from 'zod/v4'import { getProjectRoot, getSessionId } from '../bootstrap/state.js'import { registerCleanup } from './cleanupRegistry.js'import { logForDebugging } from './debug.js'import { getErrnoCode } from './errors.js'import { isProcessRunning } from './genericProcessUtils.js'import { safeParseJSON } from './json.js'import { lazySchema } from './lazySchema.js'import { jsonStringify } from './slowOperations.js'
const LOCK_FILE_REL = join('.claude', 'scheduled_tasks.lock')
const schedulerLockSchema = lazySchema(() => z.object({ sessionId: z.string(), pid: z.number(), acquiredAt: z.number(), }),)type SchedulerLock = z.infer<ReturnType<typeof schedulerLockSchema>>
/** * Options for out-of-REPL callers (Agent SDK daemon) that don't have * bootstrap state. When omitted, falls back to getProjectRoot() + * getSessionId() as before. lockIdentity should be stable for the lifetime * of one daemon process (e.g. a randomUUID() captured at startup). */export type SchedulerLockOptions = { dir?: string lockIdentity?: string}
let unregisterCleanup: (() => void) | undefined// Suppress repeat "held by X" log lines when polling a live owner.let lastBlockedBy: string | undefined
function getLockPath(dir?: string): string { return join(dir ?? getProjectRoot(), LOCK_FILE_REL)}
async function readLock(dir?: string): Promise<SchedulerLock | undefined> { let raw: string try { raw = await readFile(getLockPath(dir), 'utf8') } catch { return undefined } const result = schedulerLockSchema().safeParse(safeParseJSON(raw, false)) return result.success ? result.data : undefined}
async function tryCreateExclusive( lock: SchedulerLock, dir?: string,): Promise<boolean> { const path = getLockPath(dir) const body = jsonStringify(lock) try { await writeFile(path, body, { flag: 'wx' }) return true } catch (e: unknown) { const code = getErrnoCode(e) if (code === 'EEXIST') return false if (code === 'ENOENT') { // .claude/ doesn't exist yet — create it and retry once. In steady // state the dir already exists (scheduled_tasks.json lives there), // so this path is hit at most once. await mkdir(dirname(path), { recursive: true }) try { await writeFile(path, body, { flag: 'wx' }) return true } catch (retryErr: unknown) { if (getErrnoCode(retryErr) === 'EEXIST') return false throw retryErr } } throw e }}
function registerLockCleanup(opts?: SchedulerLockOptions): void { unregisterCleanup?.() unregisterCleanup = registerCleanup(async () => { await releaseSchedulerLock(opts) })}
/** * Try to acquire the scheduler lock for the current session. * Returns true on success, false if another live session holds it. * * Uses O_EXCL ('wx') for atomic test-and-set. If the file exists: * - Already ours → true (idempotent re-acquire) * - Another live PID → false * - Stale (PID dead / corrupt) → unlink and retry exclusive create once * * If two sessions race to recover a stale lock, only one create succeeds. */export async function tryAcquireSchedulerLock( opts?: SchedulerLockOptions,): Promise<boolean> { const dir = opts?.dir // "sessionId" in the lock file is really just a stable owner key. REPL // uses getSessionId(); daemon callers supply their own UUID. PID remains // the liveness signal regardless. const sessionId = opts?.lockIdentity ?? getSessionId() const lock: SchedulerLock = { sessionId, pid: process.pid, acquiredAt: Date.now(), }
if (await tryCreateExclusive(lock, dir)) { lastBlockedBy = undefined registerLockCleanup(opts) logForDebugging( `[ScheduledTasks] acquired scheduler lock (PID ${process.pid})`, ) return true }
const existing = await readLock(dir)
// Already ours (idempotent). After --resume the session ID is restored // but the process has a new PID — update the lock file so other sessions // see a live PID and don't steal it. if (existing?.sessionId === sessionId) { if (existing.pid !== process.pid) { await writeFile(getLockPath(dir), jsonStringify(lock)) registerLockCleanup(opts) } return true }
// Corrupt or unparseable — treat as stale. // Another live session — blocked. if (existing && isProcessRunning(existing.pid)) { if (lastBlockedBy !== existing.sessionId) { lastBlockedBy = existing.sessionId logForDebugging( `[ScheduledTasks] scheduler lock held by session ${existing.sessionId} (PID ${existing.pid})`, ) } return false }
// Stale — unlink and retry the exclusive create once. if (existing) { logForDebugging( `[ScheduledTasks] recovering stale scheduler lock from PID ${existing.pid}`, ) } await unlink(getLockPath(dir)).catch(() => {}) if (await tryCreateExclusive(lock, dir)) { lastBlockedBy = undefined registerLockCleanup(opts) return true } // Another session won the recovery race. return false}
/** * Release the scheduler lock if the current session owns it. */export async function releaseSchedulerLock( opts?: SchedulerLockOptions,): Promise<void> { unregisterCleanup?.() unregisterCleanup = undefined lastBlockedBy = undefined
const dir = opts?.dir const sessionId = opts?.lockIdentity ?? getSessionId() const existing = await readLock(dir) if (!existing || existing.sessionId !== sessionId) return try { await unlink(getLockPath(dir)) logForDebugging('[ScheduledTasks] released scheduler lock') } catch { // Already gone. }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import { sep } from 'path'import { getOriginalCwd } from '../bootstrap/state.js'import type { LogOption } from '../types/logs.js'import { quote } from './bash/shellQuote.js'import { getSessionIdFromLog } from './sessionStorage.js'
export type CrossProjectResumeResult = | { isCrossProject: false } | { isCrossProject: true isSameRepoWorktree: true projectPath: string } | { isCrossProject: true isSameRepoWorktree: false command: string projectPath: string }
/** * Check if a log is from a different project directory and determine * whether it's a related worktree or a completely different project. * * For same-repo worktrees, we can resume directly without requiring cd. * For different projects, we generate the cd command. */export function checkCrossProjectResume( log: LogOption, showAllProjects: boolean, worktreePaths: string[],): CrossProjectResumeResult { const currentCwd = getOriginalCwd()
if (!showAllProjects || !log.projectPath || log.projectPath === currentCwd) { return { isCrossProject: false } }
// Gate worktree detection to ants only for staged rollout if (process.env.USER_TYPE !== 'ant') { const sessionId = getSessionIdFromLog(log) const command = `cd ${quote([log.projectPath])} && claude --resume ${sessionId}` return { isCrossProject: true, isSameRepoWorktree: false, command, projectPath: log.projectPath, } }
// Check if log.projectPath is under a worktree of the same repo const isSameRepo = worktreePaths.some( wt => log.projectPath === wt || log.projectPath!.startsWith(wt + sep), )
if (isSameRepo) { return { isCrossProject: true, isSameRepoWorktree: true, projectPath: log.projectPath, } }
// Different repo - generate cd command const sessionId = getSessionIdFromLog(log) const command = `cd ${quote([log.projectPath])} && claude --resume ${sessionId}` return { isCrossProject: true, isSameRepoWorktree: false, command, projectPath: log.projectPath, }}12345678910111213// Indirection point for the package.json "browser" field. When bun builds// browser-sdk.js with --target browser, this file is swapped for// crypto.browser.ts — avoiding a ~500KB crypto-browserify polyfill that Bun// would otherwise inline for `import ... from 'crypto'`. Node/bun builds use// this file unchanged.//// NOTE: `export { randomUUID } from 'crypto'` (re-export syntax) breaks under// bun-internal's bytecode compilation — the generated bytecode shows the// import but the binding doesn't link (`ReferenceError: randomUUID is not// defined`). The explicit import-then-export below produces a correct live// binding. See integration-tests-ant-native failure on PR #20957/#21178.import { randomUUID } from 'crypto'export { randomUUID }1234567891011121314151617181920212223242526272829303132import { AsyncLocalStorage } from 'async_hooks'import { getCwdState, getOriginalCwd } from '../bootstrap/state.js'
const cwdOverrideStorage = new AsyncLocalStorage<string>()
/** * Run a function with an overridden working directory for the current async context. * All calls to pwd()/getCwd() within the function (and its async descendants) will * return the overridden cwd instead of the global one. This enables concurrent * agents to each see their own working directory without affecting each other. */export function runWithCwdOverride<T>(cwd: string, fn: () => T): T { return cwdOverrideStorage.run(cwd, fn)}
/** * Get the current working directory */export function pwd(): string { return cwdOverrideStorage.getStore() ?? getCwdState()}
/** * Get the current working directory or the original working directory if the current one is not available */export function getCwd(): string { try { return pwd() } catch { return getOriginalCwd() }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268import { appendFile, mkdir, symlink, unlink } from 'fs/promises'import memoize from 'lodash-es/memoize.js'import { dirname, join } from 'path'import { getSessionId } from 'src/bootstrap/state.js'
import { type BufferedWriter, createBufferedWriter } from './bufferedWriter.js'import { registerCleanup } from './cleanupRegistry.js'import { type DebugFilter, parseDebugFilter, shouldShowDebugMessage,} from './debugFilter.js'import { getClaudeConfigHomeDir, isEnvTruthy } from './envUtils.js'import { getFsImplementation } from './fsOperations.js'import { writeToStderr } from './process.js'import { jsonStringify } from './slowOperations.js'
export type DebugLogLevel = 'verbose' | 'debug' | 'info' | 'warn' | 'error'
const LEVEL_ORDER: Record<DebugLogLevel, number> = { verbose: 0, debug: 1, info: 2, warn: 3, error: 4,}
/** * Minimum log level to include in debug output. Defaults to 'debug', which * filters out 'verbose' messages. Set CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose to * include high-volume diagnostics (e.g. full statusLine command, shell, cwd, * stdout/stderr) that would otherwise drown out useful debug output. */export const getMinDebugLogLevel = memoize((): DebugLogLevel => { const raw = process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim() if (raw && Object.hasOwn(LEVEL_ORDER, raw)) { return raw as DebugLogLevel } return 'debug'})
let runtimeDebugEnabled = false
export const isDebugMode = memoize((): boolean => { return ( runtimeDebugEnabled || isEnvTruthy(process.env.DEBUG) || isEnvTruthy(process.env.DEBUG_SDK) || process.argv.includes('--debug') || process.argv.includes('-d') || isDebugToStdErr() || // Also check for --debug=pattern syntax process.argv.some(arg => arg.startsWith('--debug=')) || // --debug-file implicitly enables debug mode getDebugFilePath() !== null )})
/** * Enables debug logging mid-session (e.g. via /debug). Non-ants don't write * debug logs by default, so this lets them start capturing without restarting * with --debug. Returns true if logging was already active. */export function enableDebugLogging(): boolean { const wasActive = isDebugMode() || process.env.USER_TYPE === 'ant' runtimeDebugEnabled = true isDebugMode.cache.clear?.() return wasActive}
// Extract and parse debug filter from command line arguments// Exported for testing purposesexport const getDebugFilter = memoize((): DebugFilter | null => { // Look for --debug=pattern in argv const debugArg = process.argv.find(arg => arg.startsWith('--debug=')) if (!debugArg) { return null }
// Extract the pattern after the equals sign const filterPattern = debugArg.substring('--debug='.length) return parseDebugFilter(filterPattern)})
export const isDebugToStdErr = memoize((): boolean => { return ( process.argv.includes('--debug-to-stderr') || process.argv.includes('-d2e') )})
export const getDebugFilePath = memoize((): string | null => { for (let i = 0; i < process.argv.length; i++) { const arg = process.argv[i]! if (arg.startsWith('--debug-file=')) { return arg.substring('--debug-file='.length) } if (arg === '--debug-file' && i + 1 < process.argv.length) { return process.argv[i + 1]! } } return null})
function shouldLogDebugMessage(message: string): boolean { if (process.env.NODE_ENV === 'test' && !isDebugToStdErr()) { return false }
// Non-ants only write debug logs when debug mode is active (via --debug at // startup or /debug mid-session). Ants always log for /share, bug reports. if (process.env.USER_TYPE !== 'ant' && !isDebugMode()) { return false }
if ( typeof process === 'undefined' || typeof process.versions === 'undefined' || typeof process.versions.node === 'undefined' ) { return false }
const filter = getDebugFilter() return shouldShowDebugMessage(message, filter)}
let hasFormattedOutput = falseexport function setHasFormattedOutput(value: boolean): void { hasFormattedOutput = value}export function getHasFormattedOutput(): boolean { return hasFormattedOutput}
let debugWriter: BufferedWriter | null = nulllet pendingWrite: Promise<void> = Promise.resolve()
// Module-level so .bind captures only its explicit args, not the// writeFn closure's parent scope (Jarred, #22257).async function appendAsync( needMkdir: boolean, dir: string, path: string, content: string,): Promise<void> { if (needMkdir) { await mkdir(dir, { recursive: true }).catch(() => {}) } await appendFile(path, content) void updateLatestDebugLogSymlink()}
function noop(): void {}
function getDebugWriter(): BufferedWriter { if (!debugWriter) { let ensuredDir: string | null = null debugWriter = createBufferedWriter({ writeFn: content => { const path = getDebugLogPath() const dir = dirname(path) const needMkdir = ensuredDir !== dir ensuredDir = dir if (isDebugMode()) { // immediateMode: must stay sync. Async writes are lost on direct // process.exit() and keep the event loop alive in beforeExit // handlers (infinite loop with Perfetto tracing). See #22257. if (needMkdir) { try { getFsImplementation().mkdirSync(dir) } catch { // Directory already exists } } getFsImplementation().appendFileSync(path, content) void updateLatestDebugLogSymlink() return } // Buffered path (ants without --debug): flushes ~1/sec so chain // depth stays ~1. .bind over a closure so only the bound args are // retained, not this scope. pendingWrite = pendingWrite .then(appendAsync.bind(null, needMkdir, dir, path, content)) .catch(noop) }, flushIntervalMs: 1000, maxBufferSize: 100, immediateMode: isDebugMode(), }) registerCleanup(async () => { debugWriter?.dispose() await pendingWrite }) } return debugWriter}
export async function flushDebugLogs(): Promise<void> { debugWriter?.flush() await pendingWrite}
export function logForDebugging( message: string, { level }: { level: DebugLogLevel } = { level: 'debug', },): void { if (LEVEL_ORDER[level] < LEVEL_ORDER[getMinDebugLogLevel()]) { return } if (!shouldLogDebugMessage(message)) { return }
// Multiline messages break the jsonl output format, so make any multiline messages JSON. if (hasFormattedOutput && message.includes('\n')) { message = jsonStringify(message) } const timestamp = new Date().toISOString() const output = `${timestamp} [${level.toUpperCase()}] ${message.trim()}\n` if (isDebugToStdErr()) { writeToStderr(output) return }
getDebugWriter().write(output)}
export function getDebugLogPath(): string { return ( getDebugFilePath() ?? process.env.CLAUDE_CODE_DEBUG_LOGS_DIR ?? join(getClaudeConfigHomeDir(), 'debug', `${getSessionId()}.txt`) )}
/** * Updates the latest debug log symlink to point to the current debug log file. * Creates or updates a symlink at ~/.claude/debug/latest */const updateLatestDebugLogSymlink = memoize(async (): Promise<void> => { try { const debugLogPath = getDebugLogPath() const debugLogsDir = dirname(debugLogPath) const latestSymlinkPath = join(debugLogsDir, 'latest')
await unlink(latestSymlinkPath).catch(() => {}) await symlink(debugLogPath, latestSymlinkPath) } catch { // Silently fail if symlink creation fails }})
/** * Logs errors for Ants only, always visible in production. */export function logAntError(context: string, error: unknown): void { if (process.env.USER_TYPE !== 'ant') { return }
if (error instanceof Error && error.stack) { logForDebugging(`[ANT-ONLY] ${context} stack trace:\n${error.stack}`, { level: 'error', }) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157import memoize from 'lodash-es/memoize.js'
export type DebugFilter = { include: string[] exclude: string[] isExclusive: boolean}
/** * Parse debug filter string into a filter configuration * Examples: * - "api,hooks" -> include only api and hooks categories * - "!1p,!file" -> exclude logging and file categories * - undefined/empty -> no filtering (show all) */export const parseDebugFilter = memoize( (filterString?: string): DebugFilter | null => { if (!filterString || filterString.trim() === '') { return null }
const filters = filterString .split(',') .map(f => f.trim()) .filter(Boolean)
// If no valid filters remain, return null if (filters.length === 0) { return null }
// Check for mixed inclusive/exclusive filters const hasExclusive = filters.some(f => f.startsWith('!')) const hasInclusive = filters.some(f => !f.startsWith('!'))
if (hasExclusive && hasInclusive) { // For now, we'll treat this as an error case and show all messages // Log error using logForDebugging to avoid console.error lint rule // We'll import and use it later when the circular dependency is resolved // For now, just return null silently return null }
// Clean up filters (remove ! prefix) and normalize const cleanFilters = filters.map(f => f.replace(/^!/, '').toLowerCase())
return { include: hasExclusive ? [] : cleanFilters, exclude: hasExclusive ? cleanFilters : [], isExclusive: hasExclusive, } },)
/** * Extract debug categories from a message * Supports multiple patterns: * - "category: message" -> ["category"] * - "[CATEGORY] message" -> ["category"] * - "MCP server \"name\": message" -> ["mcp", "name"] * - "[ANT-ONLY] 1P event: tengu_timer" -> ["ant-only", "1p"] * * Returns lowercase categories for case-insensitive matching */export function extractDebugCategories(message: string): string[] { const categories: string[] = []
// Pattern 3: MCP server "servername" - Check this first to avoid false positives const mcpMatch = message.match(/^MCP server ["']([^"']+)["']/) if (mcpMatch && mcpMatch[1]) { categories.push('mcp') categories.push(mcpMatch[1].toLowerCase()) } else { // Pattern 1: "category: message" (simple prefix) - only if not MCP pattern const prefixMatch = message.match(/^([^:[]+):/) if (prefixMatch && prefixMatch[1]) { categories.push(prefixMatch[1].trim().toLowerCase()) } }
// Pattern 2: [CATEGORY] at the start const bracketMatch = message.match(/^\[([^\]]+)]/) if (bracketMatch && bracketMatch[1]) { categories.push(bracketMatch[1].trim().toLowerCase()) }
// Pattern 4: Check for additional categories in the message // e.g., "[ANT-ONLY] 1P event: tengu_timer" should match both "ant-only" and "1p" if (message.toLowerCase().includes('1p event:')) { categories.push('1p') }
// Pattern 5: Look for secondary categories after the first pattern // e.g., "AutoUpdaterWrapper: Installation type: development" const secondaryMatch = message.match( /:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/, ) if (secondaryMatch && secondaryMatch[1]) { const secondary = secondaryMatch[1].trim().toLowerCase() // Only add if it's a reasonable category name (not too long, no spaces) if (secondary.length < 30 && !secondary.includes(' ')) { categories.push(secondary) } }
// If no categories found, return empty array (uncategorized) return Array.from(new Set(categories)) // Remove duplicates}
/** * Check if debug message should be shown based on filter * @param categories - Categories extracted from the message * @param filter - Parsed filter configuration * @returns true if message should be shown */export function shouldShowDebugCategories( categories: string[], filter: DebugFilter | null,): boolean { // No filter means show everything if (!filter) { return true }
// If no categories found, handle based on filter mode if (categories.length === 0) { // In exclusive mode, uncategorized messages are excluded by default for security // In inclusive mode, uncategorized messages are excluded (must match a category) return false }
if (filter.isExclusive) { // Exclusive mode: show if none of the categories are in the exclude list return !categories.some(cat => filter.exclude.includes(cat)) } else { // Inclusive mode: show if any of the categories are in the include list return categories.some(cat => filter.include.includes(cat)) }}
/** * Main function to check if a debug message should be shown * Combines extraction and filtering */export function shouldShowDebugMessage( message: string, filter: DebugFilter | null,): boolean { // Fast path: no filter means show everything if (!filter) { return true }
// Only extract categories if we have a filter const categories = extractDebugCategories(message) return shouldShowDebugCategories(categories, filter)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236import { readdir } from 'fs/promises'import { join } from 'path'import { coerce as semverCoerce } from 'semver'import { getSessionId } from '../bootstrap/state.js'import { getCwd } from './cwd.js'import { logForDebugging } from './debug.js'import { execFileNoThrow } from './execFileNoThrow.js'import { pathExists } from './file.js'import { gte as semverGte } from './semver.js'
const MIN_DESKTOP_VERSION = '1.1.2396'
function isDevMode(): boolean { if ((process.env.NODE_ENV as string) === 'development') { return true }
// Local builds from build directories are dev mode even with NODE_ENV=production const pathsToCheck = [process.argv[1] || '', process.execPath || ''] const buildDirs = [ '/build-ant/', '/build-ant-native/', '/build-external/', '/build-external-native/', ]
return pathsToCheck.some(p => buildDirs.some(dir => p.includes(dir)))}
/** * Builds a deep link URL for Claude Desktop to resume a CLI session. * Format: claude://resume?session={sessionId}&cwd={cwd} * In dev mode: claude-dev://resume?session={sessionId}&cwd={cwd} */function buildDesktopDeepLink(sessionId: string): string { const protocol = isDevMode() ? 'claude-dev' : 'claude' const url = new URL(`${protocol}://resume`) url.searchParams.set('session', sessionId) url.searchParams.set('cwd', getCwd()) return url.toString()}
/** * Check if Claude Desktop app is installed. * On macOS, checks for /Applications/Claude.app. * On Linux, checks if xdg-open can handle claude:// protocol. * On Windows, checks if the protocol handler exists. * In dev mode, always returns true (assumes dev Desktop is running). */async function isDesktopInstalled(): Promise<boolean> { // In dev mode, assume the dev Desktop app is running if (isDevMode()) { return true }
const platform = process.platform
if (platform === 'darwin') { // Check for Claude.app in /Applications return pathExists('/Applications/Claude.app') } else if (platform === 'linux') { // Check if xdg-mime can find a handler for claude:// // Note: xdg-mime returns exit code 0 even with no handler, so check stdout too const { code, stdout } = await execFileNoThrow('xdg-mime', [ 'query', 'default', 'x-scheme-handler/claude', ]) return code === 0 && stdout.trim().length > 0 } else if (platform === 'win32') { // On Windows, try to query the registry for the protocol handler const { code } = await execFileNoThrow('reg', [ 'query', 'HKEY_CLASSES_ROOT\\claude', '/ve', ]) return code === 0 }
return false}
/** * Detect the installed Claude Desktop version. * On macOS, reads CFBundleShortVersionString from the app plist. * On Windows, finds the highest app-X.Y.Z directory in the Squirrel install. * Returns null if version cannot be determined. */async function getDesktopVersion(): Promise<string | null> { const platform = process.platform
if (platform === 'darwin') { const { code, stdout } = await execFileNoThrow('defaults', [ 'read', '/Applications/Claude.app/Contents/Info.plist', 'CFBundleShortVersionString', ]) if (code !== 0) { return null } const version = stdout.trim() return version.length > 0 ? version : null } else if (platform === 'win32') { const localAppData = process.env.LOCALAPPDATA if (!localAppData) { return null } const installDir = join(localAppData, 'AnthropicClaude') try { const entries = await readdir(installDir) const versions = entries .filter(e => e.startsWith('app-')) .map(e => e.slice(4)) .filter(v => semverCoerce(v) !== null) .sort((a, b) => { const ca = semverCoerce(a)! const cb = semverCoerce(b)! return ca.compare(cb) }) return versions.length > 0 ? versions[versions.length - 1]! : null } catch { return null } }
return null}
export type DesktopInstallStatus = | { status: 'not-installed' } | { status: 'version-too-old'; version: string } | { status: 'ready'; version: string }
/** * Check Desktop install status including version compatibility. */export async function getDesktopInstallStatus(): Promise<DesktopInstallStatus> { const installed = await isDesktopInstalled() if (!installed) { return { status: 'not-installed' } }
let version: string | null try { version = await getDesktopVersion() } catch { // Best effort — proceed with handoff if version detection fails return { status: 'ready', version: 'unknown' } }
if (!version) { // Can't determine version — assume it's ready (dev mode or unknown install) return { status: 'ready', version: 'unknown' } }
const coerced = semverCoerce(version) if (!coerced || !semverGte(coerced.version, MIN_DESKTOP_VERSION)) { return { status: 'version-too-old', version } }
return { status: 'ready', version }}
/** * Opens a deep link URL using the platform-specific mechanism. * Returns true if the command succeeded, false otherwise. */async function openDeepLink(deepLinkUrl: string): Promise<boolean> { const platform = process.platform logForDebugging(`Opening deep link: ${deepLinkUrl}`)
if (platform === 'darwin') { if (isDevMode()) { // In dev mode, `open` launches a bare Electron binary (without app code) // because setAsDefaultProtocolClient registers just the Electron executable. // Use AppleScript to route the URL to the already-running Electron app. const { code } = await execFileNoThrow('osascript', [ '-e', `tell application "Electron" to open location "${deepLinkUrl}"`, ]) return code === 0 } const { code } = await execFileNoThrow('open', [deepLinkUrl]) return code === 0 } else if (platform === 'linux') { const { code } = await execFileNoThrow('xdg-open', [deepLinkUrl]) return code === 0 } else if (platform === 'win32') { // On Windows, use cmd /c start to open URLs const { code } = await execFileNoThrow('cmd', [ '/c', 'start', '', deepLinkUrl, ]) return code === 0 }
return false}
/** * Build and open a deep link to resume the current session in Claude Desktop. * Returns an object with success status and any error message. */export async function openCurrentSessionInDesktop(): Promise<{ success: boolean error?: string deepLinkUrl?: string}> { const sessionId = getSessionId()
// Check if Desktop is installed const installed = await isDesktopInstalled() if (!installed) { return { success: false, error: 'Claude Desktop is not installed. Install it from https://claude.ai/download', } }
// Build and open the deep link const deepLinkUrl = buildDesktopDeepLink(sessionId) const opened = await openDeepLink(deepLinkUrl)
if (!opened) { return { success: false, error: 'Failed to open Claude Desktop. Please try opening it manually.', deepLinkUrl, } }
return { success: true, deepLinkUrl }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178import { getCwd } from './cwd.js'import { logForDebugging } from './debug.js'import { getRemoteUrl } from './git.js'
export type ParsedRepository = { host: string owner: string name: string}
const repositoryWithHostCache = new Map<string, ParsedRepository | null>()
export function clearRepositoryCaches(): void { repositoryWithHostCache.clear()}
export async function detectCurrentRepository(): Promise<string | null> { const result = await detectCurrentRepositoryWithHost() if (!result) return null // Only return results for github.com to avoid breaking downstream consumers // that assume the result is a github.com repository. // Use detectCurrentRepositoryWithHost() for GHE support. if (result.host !== 'github.com') return null return `${result.owner}/${result.name}`}
/** * Like detectCurrentRepository, but also returns the host (e.g. "github.com" * or a GHE hostname). Callers that need to construct URLs against a specific * GitHub host should use this variant. */export async function detectCurrentRepositoryWithHost(): Promise<ParsedRepository | null> { const cwd = getCwd()
if (repositoryWithHostCache.has(cwd)) { return repositoryWithHostCache.get(cwd) ?? null }
try { const remoteUrl = await getRemoteUrl() logForDebugging(`Git remote URL: ${remoteUrl}`) if (!remoteUrl) { logForDebugging('No git remote URL found') repositoryWithHostCache.set(cwd, null) return null }
const parsed = parseGitRemote(remoteUrl) logForDebugging( `Parsed repository: ${parsed ? `${parsed.host}/${parsed.owner}/${parsed.name}` : null} from URL: ${remoteUrl}`, ) repositoryWithHostCache.set(cwd, parsed) return parsed } catch (error) { logForDebugging(`Error detecting repository: ${error}`) repositoryWithHostCache.set(cwd, null) return null }}
/** * Synchronously returns the cached github.com repository for the current cwd * as "owner/name", or null if it hasn't been resolved yet or the host is not * github.com. Call detectCurrentRepository() first to populate the cache. * * Callers construct github.com URLs, so GHE hosts are filtered out here. */export function getCachedRepository(): string | null { const parsed = repositoryWithHostCache.get(getCwd()) if (!parsed || parsed.host !== 'github.com') return null return `${parsed.owner}/${parsed.name}`}
/** * Parses a git remote URL into host, owner, and name components. * Accepts any host (github.com, GHE instances, etc.). * * Supports: * https://host/owner/repo.git * git@host:owner/repo.git * ssh://git@host/owner/repo.git * git://host/owner/repo.git * https://host/owner/repo (no .git) * * Note: repo names can contain dots (e.g., cc.kurs.web) */export function parseGitRemote(input: string): ParsedRepository | null { const trimmed = input.trim()
// SSH format: git@host:owner/repo.git const sshMatch = trimmed.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/) if (sshMatch?.[1] && sshMatch[2] && sshMatch[3]) { if (!looksLikeRealHostname(sshMatch[1])) return null return { host: sshMatch[1], owner: sshMatch[2], name: sshMatch[3], } }
// URL format: https://host/owner/repo.git, ssh://git@host/owner/repo, git://host/owner/repo const urlMatch = trimmed.match( /^(https?|ssh|git):\/\/(?:[^@]+@)?([^/:]+(?::\d+)?)\/([^/]+)\/([^/]+?)(?:\.git)?$/, ) if (urlMatch?.[1] && urlMatch[2] && urlMatch[3] && urlMatch[4]) { const protocol = urlMatch[1] const hostWithPort = urlMatch[2] const hostWithoutPort = hostWithPort.split(':')[0] ?? '' if (!looksLikeRealHostname(hostWithoutPort)) return null // Only preserve port for HTTPS — SSH/git ports are not usable for constructing // web URLs (e.g. ssh://git@ghe.corp.com:2222 → port 2222 is SSH, not HTTPS). const host = protocol === 'https' || protocol === 'http' ? hostWithPort : hostWithoutPort return { host, owner: urlMatch[3], name: urlMatch[4], } }
return null}
/** * Parses a git remote URL or "owner/repo" string and returns "owner/repo". * Only returns results for github.com hosts — GHE URLs return null. * Use parseGitRemote() for GHE support. * Also accepts plain "owner/repo" strings for backward compatibility. */export function parseGitHubRepository(input: string): string | null { const trimmed = input.trim()
// Try parsing as a full remote URL first. // Only return results for github.com hosts — existing callers (VS Code extension, // bridge) assume this function is GitHub.com-specific. Use parseGitRemote() directly // for GHE support. const parsed = parseGitRemote(trimmed) if (parsed) { if (parsed.host !== 'github.com') return null return `${parsed.owner}/${parsed.name}` }
// If no URL pattern matched, check if it's already in owner/repo format if ( !trimmed.includes('://') && !trimmed.includes('@') && trimmed.includes('/') ) { const parts = trimmed.split('/') if (parts.length === 2 && parts[0] && parts[1]) { // Remove .git extension if present const repo = parts[1].replace(/\.git$/, '') return `${parts[0]}/${repo}` } }
logForDebugging(`Could not parse repository from: ${trimmed}`) return null}
/** * Checks whether a hostname looks like a real domain name rather than an * SSH config alias. A simple dot-check is not enough because aliases like * "github.com-work" still contain a dot. We additionally require that the * last segment (the TLD) is purely alphabetic — real TLDs (com, org, io, net) * never contain hyphens or digits. */function looksLikeRealHostname(host: string): boolean { if (!host.includes('.')) return false const lastSegment = host.split('.').pop() if (!lastSegment) return false // Real TLDs are purely alphabetic (e.g., "com", "org", "io"). // SSH aliases like "github.com-work" have a last segment "com-work" which // contains a hyphen. return /^[a-zA-Z]+$/.test(lastSegment)}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import { dirname } from 'path'import { getFsImplementation } from './fsOperations.js'import { jsonStringify } from './slowOperations.js'
type DiagnosticLogLevel = 'debug' | 'info' | 'warn' | 'error'
type DiagnosticLogEntry = { timestamp: string level: DiagnosticLogLevel event: string data: Record<string, unknown>}
/** * Logs diagnostic information to a logfile. This information is sent * via the environment manager to session-ingress to monitor issues from * within the container. * * *Important* - this function MUST NOT be called with any PII, including * file paths, project names, repo names, prompts, etc. * * @param level Log level. Only used for information, not filtering * @param event A specific event: "started", "mcp_connected", etc. * @param data Optional additional data to log */// sync IO: called from sync contextexport function logForDiagnosticsNoPII( level: DiagnosticLogLevel, event: string, data?: Record<string, unknown>,): void { const logFile = getDiagnosticLogFile() if (!logFile) { return }
const entry: DiagnosticLogEntry = { timestamp: new Date().toISOString(), level, event, data: data ?? {}, }
const fs = getFsImplementation() const line = jsonStringify(entry) + '\n' try { fs.appendFileSync(logFile, line) } catch { // If append fails, try creating the directory first try { fs.mkdirSync(dirname(logFile)) fs.appendFileSync(logFile, line) } catch { // Silently fail if logging is not possible } }}
function getDiagnosticLogFile(): string | undefined { return process.env.CLAUDE_CODE_DIAGNOSTICS_FILE}
/** * Wraps an async function with diagnostic timing logs. * Logs `{event}_started` before execution and `{event}_completed` after with duration_ms. * * @param event Event name prefix (e.g., "git_status" -> logs "git_status_started" and "git_status_completed") * @param fn Async function to execute and time * @param getData Optional function to extract additional data from the result for the completion log * @returns The result of the wrapped function */export async function withDiagnosticsTiming<T>( event: string, fn: () => Promise<T>, getData?: (result: T) => Record<string, unknown>,): Promise<T> { const startTime = Date.now() logForDiagnosticsNoPII('info', `${event}_started`)
try { const result = await fn() const additionalData = getData ? getData(result) : {} logForDiagnosticsNoPII('info', `${event}_completed`, { duration_ms: Date.now() - startTime, ...additionalData, }) return result } catch (error) { logForDiagnosticsNoPII('error', `${event}_failed`, { duration_ms: Date.now() - startTime, }) throw error }}src/components/messageActions.tsxAdded+450
src/components/permissions/FilePermissionDialog/useFilePermissionDialog.tsAdded+212
src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsxAdded+115
src/ink/Ansi.tsxAdded+292
src/ink/root.tsAdded+184
src/ink/stringWidth.tsAdded+222
src/utils/argumentSubstitution.tsAdded+145
src/utils/array.tsAdded+13
src/utils/attribution.tsAdded+393
src/utils/authFileDescriptor.tsAdded+196
src/utils/autoModeDenials.tsAdded+26
src/utils/autoUpdater.tsAdded+561
src/utils/aws.tsAdded+74
src/utils/backgroundHousekeeping.tsAdded+94
src/utils/billing.tsAdded+78
src/utils/binaryCheck.tsAdded+53
src/utils/bundledMode.tsAdded+22
src/utils/caCerts.tsAdded+115
src/utils/classifierApprovals.tsAdded+88
src/utils/classifierApprovalsHook.tsAdded+17
src/utils/claudemd.tsAdded+1479
src/utils/cleanup.tsAdded+602
src/utils/cleanupRegistry.tsAdded+25
src/utils/cliHighlight.tsAdded+54
src/utils/codeIndexing.tsAdded+206
src/utils/collapseBackgroundBashNotifications.tsAdded+84
src/utils/collapseReadSearch.tsAdded+1109
src/utils/collapseTeammateShutdowns.tsAdded+55
src/utils/commandLifecycle.tsAdded+21
src/utils/commitAttribution.tsAdded+961
src/utils/completionCache.tsAdded+166
src/utils/concurrentSessions.tsAdded+204
src/utils/config.tsAdded+1818
src/utils/configConstants.tsAdded+21
src/utils/contentArray.tsAdded+51
src/utils/context.tsAdded+221
src/utils/contextSuggestions.tsAdded+235
src/utils/cron.tsAdded+308
src/utils/cronJitterConfig.tsAdded+75
src/utils/cronScheduler.tsAdded+565
src/utils/cronTasks.tsAdded+458
src/utils/cronTasksLock.tsAdded+195
src/utils/crossProjectResume.tsAdded+75
src/utils/crypto.tsAdded+13
src/utils/cwd.tsAdded+32
src/utils/debug.tsAdded+268
src/utils/debugFilter.tsAdded+157
src/utils/desktopDeepLink.tsAdded+236
src/utils/detectRepository.tsAdded+178
src/utils/diagLogs.tsAdded+94