forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.ts
More file actions
1817 lines (1607 loc) · 62 KB
/
config.ts
File metadata and controls
1817 lines (1607 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { 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'))
: null
const 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 releases
export 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 :O
const 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 config
let globalConfigCache: { config: GlobalConfig | null; mtime: number } = {
config: null,
mtime: 0,
}
// Tracking for config file operations (telemetry)
let lastReadFileStats: { mtime: number; size: number } | null = null
let configCacheHits = 0
let 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-effects
registerCleanup(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 = 1000
let 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()