-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathindex.ts
More file actions
949 lines (896 loc) · 31.1 KB
/
Copy pathindex.ts
File metadata and controls
949 lines (896 loc) · 31.1 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
import * as fs from 'node:fs/promises';
import * as fsSync from 'node:fs';
import * as path from 'node:path';
import {
CONFIG_DIR,
NATIVE_BINARY_BACKUP_FILE,
updateConfigFile,
} from '../config';
import { ClaudeCodeInstallationInfo, TweakccConfig } from '../types';
import { debug, replaceFileBreakingHardLinks } from '../utils';
import {
extractClaudeJsFromNativeInstallation,
repackNativeInstallation,
} from '../nativeInstallationLoader';
import { DEFAULT_SETTINGS } from '../defaultSettings';
// Notes to patch-writers:
//
// - Always use [$\w]+ instead of \w+ to match identifiers (variable/function names), because at
// least in Node.js's regex engine, \w+ does not include $, so ABC$, which is a perfectly valid
// identifier, would not be matched. The way cli.js is minified, $ frequently appears in global
// identifiers.
//
// - When starting a regular expression with an identifier name, for example if you're matching a
// string of the form "someVarName = ...", make sure to put some kind of word boundary at the
// beginning, e.g. `,` `;` `}` or `{`. This can **SIGNIFICANTLY** speed up matching, easily
// bringing a 1.5s search down to 30ms. **DO NOT** use `\b`, because it doesn't properly treat
// `$`, which appears in identifiers often, as a word character, so `\b[$\w]+` will NOT match `,$=`.
//
import { writeShowMoreItemsInSelectMenus } from './showMoreItemsInSelectMenus';
import { writeThemes } from './themes';
import { writeContextLimit } from './contextLimit';
import { writeInputBoxBorder } from './inputBorderBox';
import { writeThinkerFormat } from './thinkerFormat';
import { writeThinkerSymbolMirrorOption } from './thinkerMirrorOption';
import { writeThinkerSymbolChars } from './thinkerSymbolChars';
import { writeThinkerSymbolSpeed } from './thinkerSymbolSpeed';
import { writeThinkerSymbolWidthLocation } from './thinkerSymbolWidth';
import { writeThinkingVerbs } from './thinkingVerbs';
import { writeUserMessageDisplay } from './userMessageDisplay';
import { writeInputPatternHighlighters } from './inputPatternHighlighters';
import { writeVerboseProperty } from './verboseProperty';
import { writeModelCustomizations } from './modelSelector';
import { writeOpusplan1m } from './opusplan1m';
import { writeThinkingVisibility } from './thinkingVisibility';
import { writeSubagentModels } from './subagentModels';
import { writePatchesAppliedIndication } from './patchesAppliedIndication';
import { applySystemPrompts } from './systemPrompts';
import { writeFixLspSupport } from './fixLspSupport';
import { writeToolsets } from './toolsets';
import { writeTableFormat } from './tableFormat';
import { writeConversationTitle } from './conversationTitle';
import { writeHideStartupBanner } from './hideStartupBanner';
import { writeHideCtrlGToEdit } from './hideCtrlGToEdit';
import { writeHideStartupClawd } from './hideStartupClawd';
import { writeIncreaseFileReadLimit } from './increaseFileReadLimit';
import { writeSuppressLineNumbers } from './suppressLineNumbers';
import { writeSuppressRateLimitOptions } from './suppressRateLimitOptions';
import { writeSessionMemory } from './sessionMemory';
import { writeRememberSkill } from './rememberSkill';
import { writeThinkingBlockStyling } from './thinkingBlockStyling';
import { writeMcpNonBlocking, writeMcpBatchSize } from './mcpStartup';
import { writeStatuslineUpdateThrottle } from './statuslineUpdateThrottle';
import { writeTokenCountRounding } from './tokenCountRounding';
import { writeAgentsMd } from './agentsMd';
import { writeAutoAcceptPlanMode } from './autoAcceptPlanMode';
import { writeAllowBypassPermsInSudo } from './allowBypassPermsInSudo';
import { writeSuppressNativeInstallerWarning } from './suppressNativeInstallerWarning';
import { writeScrollEscapeSequenceFilter } from './scrollEscapeSequenceFilter';
import { writeWorktreeMode } from './worktreeMode';
import { writeAllowCustomAgentModels } from './allowCustomAgentModels';
import { writeVoiceMode } from './voiceMode';
import { writeChannelsMode } from './channelsMode';
import { writeSessionColor } from './sessionColor';
import {
restoreNativeBinaryFromBackup,
restoreClijsFromBackup,
} from '../installationBackup';
import { compareVersions } from '../systemPromptSync';
export { showDiff, showPositionalDiff, globalReplace } from './patchDiffing';
export {
findChalkVar,
getModuleLoaderFunction,
getReactModuleNameNonBun,
getReactModuleFunctionBun,
getReactVar,
clearReactVarCache,
findRequireFunc,
getRequireFuncName,
clearRequireFuncNameCache,
findTextComponent,
findBoxComponent,
} from './helpers';
export interface LocationResult {
startIndex: number;
endIndex: number;
identifiers?: string[];
}
export interface ModificationEdit {
startIndex: number;
endIndex: number;
newContent: string;
}
// =============================================================================
// Patch Group and Result Types
// =============================================================================
export enum PatchGroup {
SYSTEM_PROMPTS = 'System Prompts',
ALWAYS_APPLIED = 'Always Applied',
MISC_CONFIGURABLE = 'Misc Configurable',
FEATURES = 'Features',
}
export interface PatchResult {
id: string;
name: string;
group: PatchGroup;
applied: boolean;
failed?: boolean;
skipped?: boolean;
details?: string;
description?: string;
}
export interface ApplyCustomizationResult {
config: TweakccConfig;
results: PatchResult[];
}
// =============================================================================
// Patch Definitions (Single Source of Truth)
// =============================================================================
/**
* All patch definitions with their metadata.
* This is the single source of truth for patch IDs, names, groups, and descriptions.
*/
const PATCH_DEFINITIONS = [
// Always Applied
{
id: 'verbose-property',
name: 'Verbose property',
group: PatchGroup.ALWAYS_APPLIED,
description: 'Token counter will show (2s · ↓ 169 tokens · thinking)',
},
{
id: 'opusplan1m',
name: 'Opusplan[1m] support',
group: PatchGroup.ALWAYS_APPLIED,
description:
'Use the "Opus Plan 1M" model: Opus for planning, Sonnet 1M context for building',
},
{
id: 'thinking-block-styling',
name: 'Thinking block styling',
group: PatchGroup.ALWAYS_APPLIED,
description: 'Restore dim/gray + italic styling for thinking blocks',
},
{
id: 'fix-lsp-support',
name: 'Fix LSP support',
group: PatchGroup.ALWAYS_APPLIED,
description: 'Enable/fix nascent LSP support',
},
{
id: 'statusline-update-throttle',
name: `Statusline update throttling correction`,
group: PatchGroup.ALWAYS_APPLIED,
description: `Statusline updates will be properly throttled instead of queued (or debounced)`,
},
{
id: 'session-color',
name: 'Session color from env',
group: PatchGroup.ALWAYS_APPLIED,
description:
'Set session prompt bar color via TWEAKCC_SESSION_COLOR env var',
},
// Misc Configurable
{
id: 'model-customizations',
name: 'Model customizations',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Access all Claude models with /model, not just latest 3',
},
{
id: 'show-more-items-in-select-menus',
name: 'Show more items in select menus',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Show 25 items in select menus instead of default 5',
},
{
id: 'context-limit',
name: 'Context limit',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Override the 200K context limit via CLAUDE_CODE_CONTEXT_LIMIT env var (set before launching CC)',
},
{
id: 'patches-applied-indication',
name: 'Patches applied indication',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Show "tweakcc patches applied" and tweakcc version inside CC',
},
{
id: 'table-format',
name: 'Table format',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Tables generated by Claude will be rendered more compactly',
},
{
id: 'themes',
name: 'Themes',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Your custom themes will be available via /theme',
},
{
id: 'thinking-verbs',
name: 'Thinking verbs',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Your custom list of thinking verbs will be cycled through',
},
{
id: 'thinker-format',
name: 'Thinker format',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Your custom format string that thinking verbs are wrapped in will be applied',
},
{
id: 'thinker-symbol-chars',
name: 'Thinker symbol chars',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Your custom thinking spinner will be rendered',
},
{
id: 'thinker-symbol-speed',
name: 'Thinker symbol speed',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'The thinking spinner will play at a custom FPS',
},
{
id: 'thinker-symbol-width',
name: 'Thinker symbol width',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'The thinking spinner will be in a box of custom width',
},
{
id: 'thinker-symbol-mirror',
name: 'Thinker symbol mirror',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'The thinking spinner will reverse or restart when it finishes',
},
{
id: 'input-box-border',
name: 'Input box border',
group: PatchGroup.MISC_CONFIGURABLE,
description:
"Your custom styles to the main input box's border will be applied",
},
{
id: 'subagent-models',
name: 'Subagent models',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Use custom models for Plan, Explore, and General subagents',
},
{
id: 'thinking-visibility',
name: 'Thinking block visibility',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Thinking blocks outputted by the model will show without Ctrl+O',
},
{
id: 'hide-startup-banner',
name: 'Hide startup banner',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'CC\'s startup banner with "Clawd" and release notes will be hidden',
},
{
id: 'hide-ctrl-g-to-edit',
name: 'Hide Ctrl+G to edit',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Note about using Ctrl+G to edit prompt will be hidden',
},
{
id: 'hide-startup-clawd',
name: 'Hide startup Clawd',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'The "Clawd" icon on startup will be hidden for a cleaner look',
},
{
id: 'increase-file-read-limit',
name: 'Increase file read limit',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Max tokens Claude can read from a file at once will be increased',
},
{
id: 'suppress-line-numbers',
name: 'Suppress line numbers',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'"1→" "2→" etc. prefixes for each line of Read output will be omitted',
},
{
id: 'suppress-rate-limit-options',
name: 'Suppress rate limit options',
group: PatchGroup.MISC_CONFIGURABLE,
description:
"/rate-limit-options won't be injected when limits are reached",
},
{
id: 'token-count-rounding',
name: 'Token count rounding',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Round displayed token counts to the nearest multiple of chosen value',
},
{
id: 'remember-skill',
name: 'Remember skill',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Register the built-in "/remember" skill to review session memories and update CLAUDE.local.md',
},
{
id: 'agents-md',
name: 'AGENTS.md (and others)',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Support AGENTS.md and others in addition to CLAUDE.md',
},
{
id: 'auto-accept-plan-mode',
name: 'Auto-accept plan mode',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Automatically accept plans without the "Ready to code?" confirmation prompt',
},
{
id: 'allow-sudo-bypass-permissions',
name: 'Allow bypassing permissions with --dangerously-skip-permissions in sudo',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Allow bypassing permissions with --dangerously-skip-permissions even when running with root/sudo privileges',
},
{
id: 'suppress-native-installer-warning',
name: 'Suppress native installer warning',
group: PatchGroup.MISC_CONFIGURABLE,
description: 'Suppress the native installer warning message at startup',
},
{
id: 'filter-scroll-escape-sequences',
name: 'Filter scroll escape sequences',
group: PatchGroup.MISC_CONFIGURABLE,
description:
'Filter out terminal escape sequences that cause unwanted scrolling',
},
// Features
{
id: 'allow-custom-agent-models',
name: 'Allow custom agent models',
group: PatchGroup.FEATURES,
description:
'Allow arbitrary model names in custom agent frontmatter (e.g. gemini-2.5-flash)',
},
{
id: 'worktree-mode',
name: 'Worktree mode',
group: PatchGroup.FEATURES,
description:
'Enable the EnterWorktree tool for isolated git worktree sessions',
},
{
id: 'session-memory',
name: 'Session memory',
group: PatchGroup.FEATURES,
description:
'Enable session memory (auto-extraction + past session search)',
},
{
id: 'toolsets',
name: 'Toolsets',
group: PatchGroup.FEATURES,
description: 'Custom toolsets will be registered',
},
{
id: 'mcp-non-blocking',
name: 'MCP non-blocking',
group: PatchGroup.FEATURES,
description: 'If you have MCP servers, CC startup will be much faster',
},
{
id: 'mcp-batch-size',
name: 'MCP batch size',
group: PatchGroup.FEATURES,
description: 'Change the number of MCP servers started in parallel',
},
{
id: 'user-message-display',
name: 'User message display',
group: PatchGroup.FEATURES,
description: 'User messages in the chat history will be styled',
},
{
id: 'input-pattern-highlighters',
name: 'Input pattern highlighters',
group: PatchGroup.FEATURES,
description: 'Custom input highlighters will be registered',
},
{
id: 'conversation-title',
name: 'Conversation title',
group: PatchGroup.FEATURES,
description: '/title command will be created & enabled',
},
{
id: 'voice-mode',
name: 'Voice mode',
group: PatchGroup.FEATURES,
description:
'Enable /voice command for speech-to-text input (hold Space to record)',
},
{
id: 'channels-mode',
name: 'Channels mode',
group: PatchGroup.FEATURES,
description:
'Enable MCP channel notifications (--channels without allowlist or dev flag)',
},
] as const;
/** Union type of all valid patch IDs */
export type PatchId = (typeof PATCH_DEFINITIONS)[number]['id'];
/** Patch definition interface (derived from PATCH_DEFINITIONS) */
export interface PatchDefinition {
id: PatchId;
name: string;
group: PatchGroup;
description: string;
}
/**
* Returns the list of all available patches with their IDs, names, groups, and descriptions.
* Used by --list-patches flag.
*/
export const getAllPatchDefinitions = (): PatchDefinition[] => {
return [...PATCH_DEFINITIONS];
};
/** Patch implementation with function and optional condition */
interface PatchImplementation {
fn: (content: string) => string | null;
condition?: boolean;
}
// =============================================================================
// Legacy types (for backward compatibility with patchesAppliedIndication)
// =============================================================================
export interface PatchApplied {
newContent: string;
items: string[];
}
// =============================================================================
// Helper Functions
// =============================================================================
export const escapeIdent = (ident: string): string => {
return ident.replace(/\$/g, '\\$');
};
/**
* Apply patches to content using the implementations map, tracking results.
* @param patchFilter - Optional list of patch IDs to apply (if provided, only matching patches are applied)
*/
const applyPatchImplementations = (
content: string,
implementations: Record<PatchId, PatchImplementation>,
patchFilter?: string[] | null
): { content: string; results: PatchResult[] } => {
const results: PatchResult[] = [];
// Process patches in the order defined in PATCH_DEFINITIONS
for (const def of PATCH_DEFINITIONS) {
const impl = implementations[def.id];
// Skip patches not in the filter (if filter is provided)
if (patchFilter && !patchFilter.includes(def.id)) {
results.push({
id: def.id,
name: def.name,
group: def.group,
applied: false,
skipped: true,
description: def.description,
});
continue;
}
// Skip patches where condition is explicitly false, but record them as skipped
if (impl.condition === false) {
results.push({
id: def.id,
name: def.name,
group: def.group,
applied: false,
skipped: true,
description: def.description,
});
continue;
}
debug(`Applying patch: ${def.name}`);
const result = impl.fn(content);
const failed = result === null;
const applied = !failed && result !== content;
if (!failed) {
content = result;
}
results.push({
id: def.id,
name: def.name,
group: def.group,
applied,
failed,
description: def.description,
});
}
return { content, results };
};
// =============================================================================
// Main Apply Function
// =============================================================================
export const applyCustomization = async (
config: TweakccConfig,
ccInstInfo: ClaudeCodeInstallationInfo,
patchFilter?: string[] | null
): Promise<ApplyCustomizationResult> => {
let content: string;
if (ccInstInfo.nativeInstallationPath) {
// For native installations: restore the binary, then extract to memory
await restoreNativeBinaryFromBackup(ccInstInfo);
// Extract from backup if it exists, otherwise from the native installation
let backupExists = false;
try {
await fs.stat(NATIVE_BINARY_BACKUP_FILE);
backupExists = true;
} catch {
// Backup doesn't exist, extract from native installation
}
const pathToExtractFrom = backupExists
? NATIVE_BINARY_BACKUP_FILE
: ccInstInfo.nativeInstallationPath;
debug(
`Extracting claude.js from ${backupExists ? 'backup' : 'native installation'}: ${pathToExtractFrom}`
);
const claudeJsBuffer =
await extractClaudeJsFromNativeInstallation(pathToExtractFrom);
if (!claudeJsBuffer) {
throw new Error('Failed to extract claude.js from native installation');
}
// Save original extracted JS for debugging
const origPath = path.join(CONFIG_DIR, 'native-claudejs-orig.js');
fsSync.writeFileSync(origPath, claudeJsBuffer);
debug(`Saved original extracted JS from native to: ${origPath}`);
content = claudeJsBuffer.toString('utf8');
} else {
// For NPM installations: restore cli.js from backup, then read it
await restoreClijsFromBackup(ccInstInfo);
if (!ccInstInfo.cliPath) {
throw new Error('cliPath is required for NPM installations');
}
content = await fs.readFile(ccInstInfo.cliPath, { encoding: 'utf8' });
}
// Collect all patch results
const allResults: PatchResult[] = [];
// ==========================================================================
// Apply system prompt customizations (has its own result format)
// ==========================================================================
const systemPromptsResult = await applySystemPrompts(
content,
ccInstInfo.version,
undefined, // escapeNonAscii - auto-detect
patchFilter
);
content = systemPromptsResult.newContent;
// Sort system prompt results alphabetically by name before adding
const sortedSystemPromptResults = [...systemPromptsResult.results].sort(
(a, b) => a.name.localeCompare(b.name)
);
allResults.push(...sortedSystemPromptResults);
// Legacy items array for patchesAppliedIndication (backward compatibility)
// Escape ANSI codes so they render properly when injected into cli.js
const escapeForCliJs = (str: string): string =>
str.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$');
const legacyItems: string[] = sortedSystemPromptResults
.filter(r => r.applied && r.details)
.map(r => escapeForCliJs(`${r.name}: ${r.details}`));
// Extract config values that are used multiple times or need pre-computation
const tableFormat = config.settings.misc?.tableFormat ?? 'default';
const showTweakccVersion = config.settings.misc?.showTweakccVersion ?? true;
const showPatchesApplied = config.settings.misc?.showPatchesApplied ?? true;
// ==========================================================================
// Define patch implementations (keyed by PatchId)
// ==========================================================================
// Keep model list customization and select-menu size behavior in sync.
// Disabling model customizations should restore both selectors to vanilla CC behavior.
const modelCustomizationsEnabled =
config.settings.misc?.enableModelCustomizations ?? true;
const patchImplementations: Record<PatchId, PatchImplementation> = {
// Always Applied
'verbose-property': {
fn: c => writeVerboseProperty(c),
},
'context-limit': {
fn: c => writeContextLimit(c),
condition: !!config.settings.misc?.enableContextLimitOverride,
},
opusplan1m: {
fn: c => writeOpusplan1m(c),
},
'thinking-block-styling': {
fn: c => writeThinkingBlockStyling(c),
condition:
ccInstInfo.version == null ||
compareVersions(ccInstInfo.version, '2.1.26') < 0,
},
'fix-lsp-support': {
fn: c => writeFixLspSupport(c),
},
'statusline-update-throttle': {
fn: c =>
writeStatuslineUpdateThrottle(
c,
config.settings.misc?.statuslineThrottleMs ?? 300,
config.settings.misc?.statuslineUseFixedInterval ?? false
),
condition: config.settings.misc?.statuslineThrottleMs != null,
},
// Misc Configurable
'patches-applied-indication': {
fn: c =>
writePatchesAppliedIndication(
c,
'4.0.11',
legacyItems,
showTweakccVersion,
showPatchesApplied
),
},
'model-customizations': {
fn: c => writeModelCustomizations(c),
condition: modelCustomizationsEnabled,
},
'show-more-items-in-select-menus': {
fn: c => writeShowMoreItemsInSelectMenus(c, 25),
condition: modelCustomizationsEnabled,
},
'table-format': {
fn: c => writeTableFormat(c, tableFormat),
condition: tableFormat !== 'default',
},
themes: {
fn: c => writeThemes(c, config.settings.themes!),
condition: !!(
config.settings.themes &&
config.settings.themes.length > 0 &&
JSON.stringify(config.settings.themes) !==
JSON.stringify(DEFAULT_SETTINGS.themes)
),
},
'thinking-verbs': {
fn: c => writeThinkingVerbs(c, config.settings.thinkingVerbs!.verbs),
condition: !!config.settings.thinkingVerbs,
},
'thinker-format': {
fn: c => writeThinkerFormat(c, config.settings.thinkingVerbs!.format),
condition: !!config.settings.thinkingVerbs,
},
'thinker-symbol-chars': {
fn: c => writeThinkerSymbolChars(c, config.settings.thinkingStyle.phases),
condition:
JSON.stringify(config.settings.thinkingStyle.phases) !==
JSON.stringify(DEFAULT_SETTINGS.thinkingStyle.phases),
},
'thinker-symbol-speed': {
fn: c =>
writeThinkerSymbolSpeed(
c,
config.settings.thinkingStyle.updateInterval
),
condition:
config.settings.thinkingStyle.updateInterval !==
DEFAULT_SETTINGS.thinkingStyle.updateInterval &&
(ccInstInfo.version == null ||
compareVersions(ccInstInfo.version, '2.1.27') < 0),
},
'thinker-symbol-width': {
fn: c =>
writeThinkerSymbolWidthLocation(
c,
Math.max(...config.settings.thinkingStyle.phases.map(p => p.length)) +
1
),
condition:
JSON.stringify(config.settings.thinkingStyle.phases) !==
JSON.stringify(DEFAULT_SETTINGS.thinkingStyle.phases),
},
'thinker-symbol-mirror': {
fn: c =>
writeThinkerSymbolMirrorOption(
c,
config.settings.thinkingStyle.reverseMirror
),
condition:
config.settings.thinkingStyle.reverseMirror !==
DEFAULT_SETTINGS.thinkingStyle.reverseMirror,
},
'input-box-border': {
fn: c => writeInputBoxBorder(c, config.settings.inputBox!.removeBorder),
condition: !!(
config.settings.inputBox &&
typeof config.settings.inputBox.removeBorder === 'boolean'
),
},
'subagent-models': {
fn: c => writeSubagentModels(c, config.settings.subagentModels!),
condition: !!config.settings.subagentModels,
},
'thinking-visibility': {
fn: c => writeThinkingVisibility(c),
condition: config.settings.misc?.expandThinkingBlocks ?? true,
},
'hide-startup-banner': {
fn: c => writeHideStartupBanner(c),
condition: !!config.settings.misc?.hideStartupBanner,
},
'hide-ctrl-g-to-edit': {
fn: c => writeHideCtrlGToEdit(c),
condition: !!config.settings.misc?.hideCtrlGToEdit,
},
'hide-startup-clawd': {
fn: c => writeHideStartupClawd(c),
condition: !!config.settings.misc?.hideStartupClawd,
},
'increase-file-read-limit': {
fn: c => writeIncreaseFileReadLimit(c),
condition: !!config.settings.misc?.increaseFileReadLimit,
},
'suppress-line-numbers': {
fn: c => writeSuppressLineNumbers(c),
condition: !!config.settings.misc?.suppressLineNumbers,
},
'suppress-rate-limit-options': {
fn: c => writeSuppressRateLimitOptions(c),
condition: !!config.settings.misc?.suppressRateLimitOptions,
},
'token-count-rounding': {
fn: c =>
writeTokenCountRounding(c, config.settings.misc!.tokenCountRounding!),
condition: !!config.settings.misc?.tokenCountRounding,
},
'remember-skill': {
fn: c => writeRememberSkill(c),
condition:
!!config.settings.misc?.enableRememberSkill &&
!!ccInstInfo.version &&
compareVersions(ccInstInfo.version, '2.1.42') < 0,
},
'agents-md': {
fn: c => writeAgentsMd(c, config.settings.claudeMdAltNames!),
condition: !!(
config.settings.claudeMdAltNames &&
config.settings.claudeMdAltNames.length > 0
),
},
'auto-accept-plan-mode': {
fn: c => writeAutoAcceptPlanMode(c),
condition: !!config.settings.misc?.autoAcceptPlanMode,
},
'allow-sudo-bypass-permissions': {
fn: c => writeAllowBypassPermsInSudo(c),
condition: !!config.settings.misc?.allowBypassPermissionsInSudo,
},
'suppress-native-installer-warning': {
fn: c => writeSuppressNativeInstallerWarning(c),
condition: !!config.settings.misc?.suppressNativeInstallerWarning,
},
'filter-scroll-escape-sequences': {
fn: c => writeScrollEscapeSequenceFilter(c),
condition: !!config.settings.misc?.filterScrollEscapeSequences,
},
// Features
'allow-custom-agent-models': {
fn: c => writeAllowCustomAgentModels(c),
condition: !!config.settings.misc?.allowCustomAgentModels,
},
'worktree-mode': {
fn: c => writeWorktreeMode(c),
condition:
!!config.settings.misc?.enableWorktreeMode &&
!!ccInstInfo.version &&
compareVersions(ccInstInfo.version, '2.1.51') < 0,
},
'session-memory': {
fn: c => writeSessionMemory(c),
condition: !!config.settings.misc?.enableSessionMemory,
},
toolsets: {
fn: c =>
writeToolsets(
c,
config.settings.toolsets!,
config.settings.defaultToolset,
config.settings.planModeToolset
),
condition: !!(
config.settings.toolsets && config.settings.toolsets.length > 0
),
},
'mcp-non-blocking': {
fn: c => writeMcpNonBlocking(c),
condition: !!config.settings.misc?.mcpConnectionNonBlocking,
},
'mcp-batch-size': {
fn: c => writeMcpBatchSize(c, config.settings.misc!.mcpServerBatchSize!),
condition: !!config.settings.misc?.mcpServerBatchSize,
},
'user-message-display': {
fn: c => writeUserMessageDisplay(c, config.settings.userMessageDisplay!),
condition: !!config.settings.userMessageDisplay,
},
'input-pattern-highlighters': {
fn: c =>
writeInputPatternHighlighters(
c,
config.settings.inputPatternHighlighters!
),
condition: !!(
config.settings.inputPatternHighlighters &&
config.settings.inputPatternHighlighters.length > 0
),
},
'conversation-title': {
fn: c => writeConversationTitle(c),
condition:
(config.settings.misc?.enableConversationTitle ?? true) &&
!!(
ccInstInfo.version &&
compareVersions(ccInstInfo.version, '2.0.64') < 0
),
},
'voice-mode': {
fn: c =>
writeVoiceMode(
c,
config.settings.misc?.enableVoiceConciseOutput ?? true
),
condition: !!config.settings.misc?.enableVoiceMode,
},
'channels-mode': {
fn: c => writeChannelsMode(c),
condition: !!config.settings.misc?.enableChannelsMode,
},
'session-color': {
fn: c => writeSessionColor(c),
},
};
// ==========================================================================
// Apply all patches
// ==========================================================================
const { content: patchedContent, results: patchResults } =
applyPatchImplementations(content, patchImplementations, patchFilter);
content = patchedContent;
allResults.push(...patchResults);
// ==========================================================================
// Write the modified content back
// ==========================================================================
if (ccInstInfo.nativeInstallationPath) {
// For native installations: repack the modified claude.js back into the binary
debug(
`Repacking modified claude.js into native installation: ${ccInstInfo.nativeInstallationPath}`
);
// Save patched JS for debugging
const patchedPath = path.join(CONFIG_DIR, 'native-claudejs-patched.js');
fsSync.writeFileSync(patchedPath, content, 'utf8');
debug(`Saved patched JS from native to: ${patchedPath}`);
const modifiedBuffer = Buffer.from(content, 'utf8');
await repackNativeInstallation(
ccInstInfo.nativeInstallationPath,
modifiedBuffer,
ccInstInfo.nativeInstallationPath
);
} else {
// For NPM installations: replace the cli.js file
if (!ccInstInfo.cliPath) {
throw new Error('cliPath is required for NPM installations');
}
await replaceFileBreakingHardLinks(ccInstInfo.cliPath, content, 'patch');
}
const updatedConfig = await updateConfigFile(cfg => {
cfg.changesApplied = true;
});
return {
config: updatedConfig,
results: allResults,
};
};