forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.ts
More file actions
1015 lines (925 loc) · 31.4 KB
/
Copy pathsettings.ts
File metadata and controls
1015 lines (925 loc) · 31.4 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 mergeWith from 'lodash-es/mergeWith.js'
import { dirname, join, resolve } from 'path'
import { z } from 'zod/v4'
import {
getFlagSettingsInline,
getFlagSettingsPath,
getOriginalCwd,
getUseCoworkPlugins,
} from '../../bootstrap/state.js'
import { getRemoteManagedSettingsSyncFromCache } from '../../services/remoteManagedSettings/syncCacheState.js'
import { uniq } from '../array.js'
import { logForDebugging } from '../debug.js'
import { logForDiagnosticsNoPII } from '../diagLogs.js'
import { getClaudeConfigHomeDir, isEnvTruthy } from '../envUtils.js'
import { getErrnoCode, isENOENT } from '../errors.js'
import { writeFileSyncAndFlush_DEPRECATED } from '../file.js'
import { readFileSync } from '../fileRead.js'
import { getFsImplementation, safeResolvePath } from '../fsOperations.js'
import { addFileGlobRuleToGitignore } from '../git/gitignore.js'
import { safeParseJSON } from '../json.js'
import { logError } from '../log.js'
import { getPlatform } from '../platform.js'
import { clone, jsonStringify } from '../slowOperations.js'
import { profileCheckpoint } from '../startupProfiler.js'
import {
type EditableSettingSource,
getEnabledSettingSources,
type SettingSource,
} from './constants.js'
import { markInternalWrite } from './internalWrites.js'
import {
getManagedFilePath,
getManagedSettingsDropInDir,
} from './managedPath.js'
import { getHkcuSettings, getMdmSettings } from './mdm/settings.js'
import {
getCachedParsedFile,
getCachedSettingsForSource,
getPluginSettingsBase,
getSessionSettingsCache,
resetSettingsCache,
setCachedParsedFile,
setCachedSettingsForSource,
setSessionSettingsCache,
} from './settingsCache.js'
import { type SettingsJson, SettingsSchema } from './types.js'
import {
filterInvalidPermissionRules,
formatZodError,
type SettingsWithErrors,
type ValidationError,
} from './validation.js'
/**
* Get the path to the managed settings file based on the current platform
*/
function getManagedSettingsFilePath(): string {
return join(getManagedFilePath(), 'managed-settings.json')
}
/**
* Load file-based managed settings: managed-settings.json + managed-settings.d/*.json.
*
* managed-settings.json is merged first (lowest precedence / base), then drop-in
* files are sorted alphabetically and merged on top (higher precedence, later
* files win). This matches the systemd/sudoers drop-in convention: the base
* file provides defaults, drop-ins customize. Separate teams can ship
* independent policy fragments (e.g. 10-otel.json, 20-security.json) without
* coordinating edits to a single admin-owned file.
*
* Exported for testing.
*/
export function loadManagedFileSettings(): {
settings: SettingsJson | null
errors: ValidationError[]
} {
const errors: ValidationError[] = []
let merged: SettingsJson = {}
let found = false
const { settings, errors: baseErrors } = parseSettingsFile(
getManagedSettingsFilePath(),
)
errors.push(...baseErrors)
if (settings && Object.keys(settings).length > 0) {
merged = mergeWith(merged, settings, settingsMergeCustomizer)
found = true
}
const dropInDir = getManagedSettingsDropInDir()
try {
const entries = getFsImplementation()
.readdirSync(dropInDir)
.filter(
d =>
(d.isFile() || d.isSymbolicLink()) &&
d.name.endsWith('.json') &&
!d.name.startsWith('.'),
)
.map(d => d.name)
.sort()
for (const name of entries) {
const { settings, errors: fileErrors } = parseSettingsFile(
join(dropInDir, name),
)
errors.push(...fileErrors)
if (settings && Object.keys(settings).length > 0) {
merged = mergeWith(merged, settings, settingsMergeCustomizer)
found = true
}
}
} catch (e) {
const code = getErrnoCode(e)
if (code !== 'ENOENT' && code !== 'ENOTDIR') {
logError(e)
}
}
return { settings: found ? merged : null, errors }
}
/**
* Check which file-based managed settings sources are present.
* Used by /status to show "(file)", "(drop-ins)", or "(file + drop-ins)".
*/
export function getManagedFileSettingsPresence(): {
hasBase: boolean
hasDropIns: boolean
} {
const { settings: base } = parseSettingsFile(getManagedSettingsFilePath())
const hasBase = !!base && Object.keys(base).length > 0
let hasDropIns = false
const dropInDir = getManagedSettingsDropInDir()
try {
hasDropIns = getFsImplementation()
.readdirSync(dropInDir)
.some(
d =>
(d.isFile() || d.isSymbolicLink()) &&
d.name.endsWith('.json') &&
!d.name.startsWith('.'),
)
} catch {
// dir doesn't exist
}
return { hasBase, hasDropIns }
}
/**
* Handles file system errors appropriately
* @param error The error to handle
* @param path The file path that caused the error
*/
function handleFileSystemError(error: unknown, path: string): void {
if (
typeof error === 'object' &&
error &&
'code' in error &&
error.code === 'ENOENT'
) {
logForDebugging(
`Broken symlink or missing file encountered for settings.json at path: ${path}`,
)
} else {
logError(error)
}
}
/**
* Parses a settings file into a structured format
* @param path The path to the permissions file
* @param source The source of the settings (optional, for error reporting)
* @returns Parsed settings data and validation errors
*/
export function parseSettingsFile(path: string): {
settings: SettingsJson | null
errors: ValidationError[]
} {
const cached = getCachedParsedFile(path)
if (cached) {
// Clone so callers (e.g. mergeWith in getSettingsForSourceUncached,
// updateSettingsForSource) can't mutate the cached entry.
return {
settings: cached.settings ? clone(cached.settings) : null,
errors: cached.errors,
}
}
const result = parseSettingsFileUncached(path)
setCachedParsedFile(path, result)
// Clone the first return too — the caller may mutate before
// another caller reads the same cache entry.
return {
settings: result.settings ? clone(result.settings) : null,
errors: result.errors,
}
}
function parseSettingsFileUncached(path: string): {
settings: SettingsJson | null
errors: ValidationError[]
} {
try {
const { resolvedPath } = safeResolvePath(getFsImplementation(), path)
const content = readFileSync(resolvedPath)
if (content.trim() === '') {
return { settings: {}, errors: [] }
}
const data = safeParseJSON(content, false)
// Filter invalid permission rules before schema validation so one bad
// rule doesn't cause the entire settings file to be rejected.
const ruleWarnings = filterInvalidPermissionRules(data, path)
const result = SettingsSchema().safeParse(data)
if (!result.success) {
const errors = formatZodError(result.error, path)
return { settings: null, errors: [...ruleWarnings, ...errors] }
}
return { settings: result.data, errors: ruleWarnings }
} catch (error) {
handleFileSystemError(error, path)
return { settings: null, errors: [] }
}
}
/**
* Get the absolute path to the associated file root for a given settings source
* (e.g. for $PROJ_DIR/.claude/settings.json, returns $PROJ_DIR)
* @param source The source of the settings
* @returns The root path of the settings file
*/
export function getSettingsRootPathForSource(source: SettingSource): string {
switch (source) {
case 'userSettings':
return resolve(getClaudeConfigHomeDir())
case 'policySettings':
case 'projectSettings':
case 'localSettings': {
return resolve(getOriginalCwd())
}
case 'flagSettings': {
const path = getFlagSettingsPath()
return path ? dirname(resolve(path)) : resolve(getOriginalCwd())
}
}
}
/**
* Get the user settings filename based on cowork mode.
* Returns 'cowork_settings.json' when in cowork mode, 'settings.json' otherwise.
*
* Priority:
* 1. Session state (set by CLI flag --cowork)
* 2. Environment variable CLAUDE_CODE_USE_COWORK_PLUGINS
* 3. Default: 'settings.json'
*/
function getUserSettingsFilePath(): string {
if (
getUseCoworkPlugins() ||
isEnvTruthy(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)
) {
return 'cowork_settings.json'
}
return 'settings.json'
}
export function getSettingsFilePathForSource(
source: SettingSource,
): string | undefined {
switch (source) {
case 'userSettings':
return join(
getSettingsRootPathForSource(source),
getUserSettingsFilePath(),
)
case 'projectSettings':
case 'localSettings': {
return join(
getSettingsRootPathForSource(source),
getRelativeSettingsFilePathForSource(source),
)
}
case 'policySettings':
return getManagedSettingsFilePath()
case 'flagSettings': {
return getFlagSettingsPath()
}
}
}
export function getRelativeSettingsFilePathForSource(
source: 'projectSettings' | 'localSettings',
): string {
switch (source) {
case 'projectSettings':
return join('.claude', 'settings.json')
case 'localSettings':
return join('.claude', 'settings.local.json')
}
}
export function getSettingsForSource(
source: SettingSource,
): SettingsJson | null {
const cached = getCachedSettingsForSource(source)
if (cached !== undefined) return cached
const result = getSettingsForSourceUncached(source)
setCachedSettingsForSource(source, result)
return result
}
function getSettingsForSourceUncached(
source: SettingSource,
): SettingsJson | null {
// For policySettings: first source wins (remote > HKLM/plist > file > HKCU)
if (source === 'policySettings') {
const remoteSettings = getRemoteManagedSettingsSyncFromCache()
if (remoteSettings && Object.keys(remoteSettings).length > 0) {
return remoteSettings
}
const mdmResult = getMdmSettings()
if (Object.keys(mdmResult.settings).length > 0) {
return mdmResult.settings
}
const { settings: fileSettings } = loadManagedFileSettings()
if (fileSettings) {
return fileSettings
}
const hkcu = getHkcuSettings()
if (Object.keys(hkcu.settings).length > 0) {
return hkcu.settings
}
return null
}
const settingsFilePath = getSettingsFilePathForSource(source)
const { settings: fileSettings } = settingsFilePath
? parseSettingsFile(settingsFilePath)
: { settings: null }
// For flagSettings, merge in any inline settings set via the SDK
if (source === 'flagSettings') {
const inlineSettings = getFlagSettingsInline()
if (inlineSettings) {
const parsed = SettingsSchema().safeParse(inlineSettings)
if (parsed.success) {
return mergeWith(
fileSettings || {},
parsed.data,
settingsMergeCustomizer,
) as SettingsJson
}
}
}
return fileSettings
}
/**
* Get the origin of the highest-priority active policy settings source.
* Uses "first source wins" — returns the first source that has content.
* Priority: remote > plist/hklm > file (managed-settings.json) > hkcu
*/
export function getPolicySettingsOrigin():
| 'remote'
| 'plist'
| 'hklm'
| 'file'
| 'hkcu'
| null {
// 1. Remote (highest)
const remoteSettings = getRemoteManagedSettingsSyncFromCache()
if (remoteSettings && Object.keys(remoteSettings).length > 0) {
return 'remote'
}
// 2. Admin-only MDM (HKLM / macOS plist)
const mdmResult = getMdmSettings()
if (Object.keys(mdmResult.settings).length > 0) {
return getPlatform() === 'macos' ? 'plist' : 'hklm'
}
// 3. managed-settings.json + managed-settings.d/ (file-based, requires admin)
const { settings: fileSettings } = loadManagedFileSettings()
if (fileSettings) {
return 'file'
}
// 4. HKCU (lowest — user-writable)
const hkcu = getHkcuSettings()
if (Object.keys(hkcu.settings).length > 0) {
return 'hkcu'
}
return null
}
/**
* Merges `settings` into the existing settings for `source` using lodash mergeWith.
*
* To delete a key from a record field (e.g. enabledPlugins, extraKnownMarketplaces),
* set it to `undefined` — do NOT use `delete`. mergeWith only detects deletion when
* the key is present with an explicit `undefined` value.
*/
export function updateSettingsForSource(
source: EditableSettingSource,
settings: SettingsJson,
): { error: Error | null } {
if (
(source as unknown) === 'policySettings' ||
(source as unknown) === 'flagSettings'
) {
return { error: null }
}
// Create the folder if needed
const filePath = getSettingsFilePathForSource(source)
if (!filePath) {
return { error: null }
}
try {
getFsImplementation().mkdirSync(dirname(filePath))
// Try to get existing settings with validation. Bypass the per-source
// cache — mergeWith below mutates its target (including nested refs),
// and mutating the cached object would leak unpersisted state if the
// write fails before resetSettingsCache().
let existingSettings = getSettingsForSourceUncached(source)
// If validation failed, check if file exists with a JSON syntax error
if (!existingSettings) {
let content: string | null = null
try {
content = readFileSync(filePath)
} catch (e) {
if (!isENOENT(e)) {
throw e
}
// File doesn't exist — fall through to merge with empty settings
}
if (content !== null) {
const rawData = safeParseJSON(content)
if (rawData === null) {
// JSON syntax error - return validation error instead of overwriting
// safeParseJSON will already log the error, so we'll just return the error here
return {
error: new Error(
`Invalid JSON syntax in settings file at ${filePath}`,
),
}
}
if (rawData && typeof rawData === 'object') {
existingSettings = rawData as SettingsJson
logForDebugging(
`Using raw settings from ${filePath} due to validation failure`,
)
}
}
}
const updatedSettings = mergeWith(
existingSettings || {},
settings,
(
_objValue: unknown,
srcValue: unknown,
key: string | number | symbol,
object: Record<string | number | symbol, unknown>,
) => {
// Handle undefined as deletion
if (srcValue === undefined && object && typeof key === 'string') {
delete object[key]
return undefined
}
// For arrays, always replace with the provided array
// This puts the responsibility on the caller to compute the desired final state
if (Array.isArray(srcValue)) {
return srcValue
}
// For non-arrays, let lodash handle the default merge behavior
return undefined
},
)
// Mark this as an internal write before writing the file
markInternalWrite(filePath)
writeFileSyncAndFlush_DEPRECATED(
filePath,
jsonStringify(updatedSettings, null, 2) + '\n',
)
// Invalidate the session cache since settings have been updated
resetSettingsCache()
if (source === 'localSettings') {
// Okay to add to gitignore async without awaiting
void addFileGlobRuleToGitignore(
getRelativeSettingsFilePathForSource('localSettings'),
getOriginalCwd(),
)
}
} catch (e) {
const error = new Error(
`Failed to read raw settings from ${filePath}: ${e}`,
)
logError(error)
return { error }
}
return { error: null }
}
/**
* Custom merge function for arrays - concatenate and deduplicate
*/
function mergeArrays<T>(targetArray: T[], sourceArray: T[]): T[] {
return uniq([...targetArray, ...sourceArray])
}
/**
* Custom merge function for lodash mergeWith when merging settings.
* Arrays are concatenated and deduplicated; other values use default lodash merge behavior.
* Exported for testing.
*/
export function settingsMergeCustomizer(
objValue: unknown,
srcValue: unknown,
): unknown {
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
return mergeArrays(objValue, srcValue)
}
// Return undefined to let lodash handle default merge behavior
return undefined
}
/**
* Get a list of setting keys from managed settings for logging purposes.
* For certain nested settings (permissions, sandbox, hooks), expands to show
* one level of nesting (e.g., "permissions.allow"). For other settings,
* returns only the top-level key.
*
* @param settings The settings object to extract keys from
* @returns Sorted array of key paths
*/
export function getManagedSettingsKeysForLogging(
settings: SettingsJson,
): string[] {
// Use .strip() to get only valid schema keys
const validSettings = SettingsSchema().strip().parse(settings) as Record<
string,
unknown
>
const keysToExpand = ['permissions', 'sandbox', 'hooks']
const allKeys: string[] = []
// Define valid nested keys for each nested setting we expand
const validNestedKeys: Record<string, Set<string>> = {
permissions: new Set([
'allow',
'deny',
'ask',
'defaultMode',
'disableBypassPermissionsMode',
...(feature('TRANSCRIPT_CLASSIFIER') ? ['disableAutoMode'] : []),
'additionalDirectories',
]),
sandbox: new Set([
'enabled',
'failIfUnavailable',
'allowUnsandboxedCommands',
'network',
'filesystem',
'ignoreViolations',
'excludedCommands',
'autoAllowBashIfSandboxed',
'enableWeakerNestedSandbox',
'enableWeakerNetworkIsolation',
'ripgrep',
]),
// For hooks, we use z.record with enum keys, so we validate separately
hooks: new Set([
'PreToolUse',
'PostToolUse',
'Notification',
'UserPromptSubmit',
'SessionStart',
'SessionEnd',
'Stop',
'SubagentStop',
'PreCompact',
'PostCompact',
'TeammateIdle',
'TaskCreated',
'TaskCompleted',
]),
}
for (const key of Object.keys(validSettings)) {
if (
keysToExpand.includes(key) &&
validSettings[key] &&
typeof validSettings[key] === 'object'
) {
// Expand nested keys for these special settings (one level deep only)
const nestedObj = validSettings[key] as Record<string, unknown>
const validKeys = validNestedKeys[key]
if (validKeys) {
for (const nestedKey of Object.keys(nestedObj)) {
// Only include known valid nested keys
if (validKeys.has(nestedKey)) {
allKeys.push(`${key}.${nestedKey}`)
}
}
}
} else {
// For other settings, just use the top-level key
allKeys.push(key)
}
}
return allKeys.sort()
}
// Flag to prevent infinite recursion when loading settings
let isLoadingSettings = false
/**
* Load settings from disk without using cache
* This is the original implementation that actually reads from files
*/
function loadSettingsFromDisk(): SettingsWithErrors {
// Prevent recursive calls to loadSettingsFromDisk
if (isLoadingSettings) {
return { settings: {}, errors: [] }
}
const startTime = Date.now()
profileCheckpoint('loadSettingsFromDisk_start')
logForDiagnosticsNoPII('info', 'settings_load_started')
isLoadingSettings = true
try {
// Start with plugin settings as the lowest priority base.
// All file-based sources (user, project, local, flag, policy) override these.
// Plugin settings only contain allowlisted keys (e.g., agent) that are valid SettingsJson fields.
const pluginSettings = getPluginSettingsBase()
let mergedSettings: SettingsJson = {}
if (pluginSettings) {
mergedSettings = mergeWith(
mergedSettings,
pluginSettings,
settingsMergeCustomizer,
)
}
const allErrors: ValidationError[] = []
const seenErrors = new Set<string>()
const seenFiles = new Set<string>()
// Merge settings from each source in priority order with deep merging
for (const source of getEnabledSettingSources()) {
// policySettings: "first source wins" — use the highest-priority source
// that has content. Priority: remote > HKLM/plist > managed-settings.json > HKCU
if (source === 'policySettings') {
let policySettings: SettingsJson | null = null
const policyErrors: ValidationError[] = []
// 1. Remote (highest priority)
const remoteSettings = getRemoteManagedSettingsSyncFromCache()
if (remoteSettings && Object.keys(remoteSettings).length > 0) {
const result = SettingsSchema().safeParse(remoteSettings)
if (result.success) {
policySettings = result.data
} else {
// Remote exists but is invalid — surface errors even as we fall through
policyErrors.push(
...formatZodError(result.error, 'remote managed settings'),
)
}
}
// 2. Admin-only MDM (HKLM / macOS plist)
if (!policySettings) {
const mdmResult = getMdmSettings()
if (Object.keys(mdmResult.settings).length > 0) {
policySettings = mdmResult.settings
}
policyErrors.push(...mdmResult.errors)
}
// 3. managed-settings.json + managed-settings.d/ (file-based, requires admin)
if (!policySettings) {
const { settings, errors } = loadManagedFileSettings()
if (settings) {
policySettings = settings
}
policyErrors.push(...errors)
}
// 4. HKCU (lowest — user-writable, only if nothing above exists)
if (!policySettings) {
const hkcu = getHkcuSettings()
if (Object.keys(hkcu.settings).length > 0) {
policySettings = hkcu.settings
}
policyErrors.push(...hkcu.errors)
}
// Merge the winning policy source into the settings chain
if (policySettings) {
mergedSettings = mergeWith(
mergedSettings,
policySettings,
settingsMergeCustomizer,
)
}
for (const error of policyErrors) {
const errorKey = `${error.file}:${error.path}:${error.message}`
if (!seenErrors.has(errorKey)) {
seenErrors.add(errorKey)
allErrors.push(error)
}
}
continue
}
const filePath = getSettingsFilePathForSource(source)
if (filePath) {
const resolvedPath = resolve(filePath)
// Skip if we've already loaded this file from another source
if (!seenFiles.has(resolvedPath)) {
seenFiles.add(resolvedPath)
const { settings, errors } = parseSettingsFile(filePath)
// Add unique errors (deduplication)
for (const error of errors) {
const errorKey = `${error.file}:${error.path}:${error.message}`
if (!seenErrors.has(errorKey)) {
seenErrors.add(errorKey)
allErrors.push(error)
}
}
if (settings) {
mergedSettings = mergeWith(
mergedSettings,
settings,
settingsMergeCustomizer,
)
}
}
}
// For flagSettings, also merge any inline settings set via the SDK
if (source === 'flagSettings') {
const inlineSettings = getFlagSettingsInline()
if (inlineSettings) {
const parsed = SettingsSchema().safeParse(inlineSettings)
if (parsed.success) {
mergedSettings = mergeWith(
mergedSettings,
parsed.data,
settingsMergeCustomizer,
)
}
}
}
}
logForDiagnosticsNoPII('info', 'settings_load_completed', {
duration_ms: Date.now() - startTime,
source_count: seenFiles.size,
error_count: allErrors.length,
})
return { settings: mergedSettings, errors: allErrors }
} finally {
isLoadingSettings = false
}
}
/**
* Get merged settings from all sources in priority order
* Settings are merged from lowest to highest priority:
* userSettings -> projectSettings -> localSettings -> policySettings
*
* This function returns a snapshot of settings at the time of call.
* For React components, prefer using useSettings() hook for reactive updates
* when settings change on disk.
*
* Uses session-level caching to avoid repeated file I/O.
* Cache is invalidated when settings files change via resetSettingsCache().
*
* @returns Merged settings from all available sources (always returns at least empty object)
*/
export function getInitialSettings(): SettingsJson {
const { settings } = getSettingsWithErrors()
return settings || {}
}
/**
* @deprecated Use getInitialSettings() instead. This alias exists for backwards compatibility.
*/
export const getSettings_DEPRECATED = getInitialSettings
export type SettingsWithSources = {
effective: SettingsJson
/** Ordered low-to-high priority — later entries override earlier ones. */
sources: Array<{ source: SettingSource; settings: SettingsJson }>
}
/**
* Get the effective merged settings alongside the raw per-source settings,
* in merge-priority order. Only includes sources that are enabled and have
* non-empty content.
*
* Always reads fresh from disk — resets the session cache so that `effective`
* and `sources` are consistent even if the change detector hasn't fired yet.
*/
export function getSettingsWithSources(): SettingsWithSources {
// Reset both caches so getSettingsForSource (per-source cache) and
// getInitialSettings (session cache) agree on the current disk state.
resetSettingsCache()
const sources: SettingsWithSources['sources'] = []
for (const source of getEnabledSettingSources()) {
const settings = getSettingsForSource(source)
if (settings && Object.keys(settings).length > 0) {
sources.push({ source, settings })
}
}
return { effective: getInitialSettings(), sources }
}
/**
* Get merged settings and validation errors from all sources
* This function now uses session-level caching to avoid repeated file I/O.
* Settings changes require Claude Code restart, so cache is valid for entire session.
* @returns Merged settings and all validation errors encountered
*/
export function getSettingsWithErrors(): SettingsWithErrors {
// Use cached result if available
const cached = getSessionSettingsCache()
if (cached !== null) {
return cached
}
// Load from disk and cache the result
const result = loadSettingsFromDisk()
profileCheckpoint('loadSettingsFromDisk_end')
setSessionSettingsCache(result)
return result
}
/**
* Check if any raw settings file contains a specific key, regardless of validation.
* This is useful for detecting user intent even when settings validation fails.
* For example, if a user set cleanupPeriodDays but has validation errors elsewhere,
* we can detect they explicitly configured cleanup and skip cleanup rather than
* falling back to defaults.
*/
/**
* Returns true if any trusted settings source has accepted the bypass
* permissions mode dialog. projectSettings is intentionally excluded —
* a malicious project could otherwise auto-bypass the dialog (RCE risk).
*/
export function hasSkipDangerousModePermissionPrompt(): boolean {
return !!(
getSettingsForSource('userSettings')?.skipDangerousModePermissionPrompt ||
getSettingsForSource('localSettings')?.skipDangerousModePermissionPrompt ||
getSettingsForSource('flagSettings')?.skipDangerousModePermissionPrompt ||
getSettingsForSource('policySettings')?.skipDangerousModePermissionPrompt
)
}
/**
* Returns true if any trusted settings source has accepted the auto
* mode opt-in dialog. projectSettings is intentionally excluded —
* a malicious project could otherwise auto-bypass the dialog (RCE risk).
*/
export function hasAutoModeOptIn(): boolean {
if (feature('TRANSCRIPT_CLASSIFIER')) {
const user = getSettingsForSource('userSettings')?.skipAutoPermissionPrompt
const local =
getSettingsForSource('localSettings')?.skipAutoPermissionPrompt
const flag = getSettingsForSource('flagSettings')?.skipAutoPermissionPrompt
const policy =
getSettingsForSource('policySettings')?.skipAutoPermissionPrompt
const result = !!(user || local || flag || policy)
logForDebugging(
`[auto-mode] hasAutoModeOptIn=${result} skipAutoPermissionPrompt: user=${user} local=${local} flag=${flag} policy=${policy}`,
)
return result
}
return false
}
/**
* Returns whether plan mode should use auto mode semantics. Default true
* (opt-out). Returns false if any trusted source explicitly sets false.
* projectSettings is excluded so a malicious project can't control this.
*/
export function getUseAutoModeDuringPlan(): boolean {
if (feature('TRANSCRIPT_CLASSIFIER')) {
return (
getSettingsForSource('policySettings')?.useAutoModeDuringPlan !== false &&
getSettingsForSource('flagSettings')?.useAutoModeDuringPlan !== false &&
getSettingsForSource('userSettings')?.useAutoModeDuringPlan !== false &&
getSettingsForSource('localSettings')?.useAutoModeDuringPlan !== false
)
}
return true
}
/**
* Returns the merged autoMode config from trusted settings sources.
* Only available when TRANSCRIPT_CLASSIFIER is active; returns undefined otherwise.
* projectSettings is intentionally excluded — a malicious project could
* otherwise inject classifier allow/deny rules (RCE risk).
*/
export function getAutoModeConfig():
| { allow?: string[]; soft_deny?: string[]; environment?: string[] }
| undefined {
if (feature('TRANSCRIPT_CLASSIFIER')) {
const schema = z.object({
allow: z.array(z.string()).optional(),
soft_deny: z.array(z.string()).optional(),
deny: z.array(z.string()).optional(),
environment: z.array(z.string()).optional(),
})
const allow: string[] = []
const soft_deny: string[] = []
const environment: string[] = []
for (const source of [
'userSettings',
'localSettings',
'flagSettings',
'policySettings',
] as const) {
const settings = getSettingsForSource(source)
if (!settings) continue
const result = schema.safeParse(
(settings as Record<string, unknown>).autoMode,
)
if (result.success) {
if (result.data.allow) allow.push(...result.data.allow)
if (result.data.soft_deny) soft_deny.push(...result.data.soft_deny)
if (process.env.USER_TYPE === 'ant') {
if (result.data.deny) soft_deny.push(...result.data.deny)
}
if (result.data.environment)
environment.push(...result.data.environment)
}
}
if (allow.length > 0 || soft_deny.length > 0 || environment.length > 0) {
return {
...(allow.length > 0 && { allow }),
...(soft_deny.length > 0 && { soft_deny }),
...(environment.length > 0 && { environment }),
}
}
}
return undefined
}
export function rawSettingsContainsKey(key: string): boolean {
for (const source of getEnabledSettingSources()) {
// Skip policySettings - we only care about user-configured settings
if (source === 'policySettings') {
continue
}
const filePath = getSettingsFilePathForSource(source)
if (!filePath) {
continue
}
try {
const { resolvedPath } = safeResolvePath(getFsImplementation(), filePath)
const content = readFileSync(resolvedPath)
if (!content.trim()) {
continue