-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatcher.py
More file actions
370 lines (303 loc) · 13.7 KB
/
patcher.py
File metadata and controls
370 lines (303 loc) · 13.7 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
#!/usr/bin/env python3
"""
patcher.py - Patch Claude Code's spinner messages in its compiled ELF binary.
Replaces the built-in spinner/progress messages with custom ones from messages.json.
Works by finding and patching V8 snapshot regions in the binary.
"""
import argparse
import json
import os
import shutil
import struct
import subprocess
import sys
from pathlib import Path
# Binary format constants
TYPE_TAG = b'\x09\x00\x00\x00'
SEPARATOR = b'\x10\x00\x00\x00\x00\x00\x00\x00'
ANCHOR_STRING = b'Accomplishing'
ANCHOR_PATTERN = TYPE_TAG + struct.pack('<I', len(ANCHOR_STRING)) + ANCHOR_STRING
BACKUP_DIR = Path.home() / '.brainrot-spinners' / 'backup'
ORIGINAL_MESSAGES = [
"Accomplishing", "Actioning", "Actualizing", "Architecting", "Baking",
"Beaming", "Beboppin'", "Befuddling", "Billowing", "Blanching",
"Bloviating", "Boogieing", "Boondoggling", "Booping", "Bootstrapping",
"Brewing", "Bunning", "Burrowing", "Calculating", "Canoodling",
"Caramelizing", "Cascading", "Catapulting", "Cerebrating", "Channeling",
"Channelling", "Choreographing", "Churning", "Clauding", "Coalescing",
"Cogitating", "Combobulating", "Composing", "Computing", "Concocting",
"Considering", "Contemplating", "Cooking", "Crafting", "Creating",
"Crunching", "Crystallizing", "Cultivating", "Deciphering", "Deliberating",
"Determining", "Dilly-dallying", "Discombobulating", "Doing", "Doodling",
"Drizzling", "Ebbing", "Effecting", "Elucidating", "Embellishing",
"Enchanting", "Envisioning", "Evaporating", "Fermenting", "Fiddle-faddling",
"Finagling", "Flamb", "Flibbertigibbeting", "Flowing", "Flummoxing",
"Fluttering", "Forging", "Forming", "Frolicking", "Frosting",
"Gallivanting", "Galloping", "Garnishing", "Generating", "Gesticulating",
"Germinating", "Gitifying", "Grooving", "Gusting", "Harmonizing",
"Hashing", "Hatching", "Herding", "Honking", "Hullaballooing",
"Hyperspacing", "Ideating", "Imagining", "Improvising", "Incubating",
"Inferring", "Infusing", "Ionizing", "Jitterbugging", "Julienning",
"Kneading", "Leavening", "Levitating", "Lollygagging", "Manifesting",
"Marinating", "Meandering", "Metamorphosing", "Misting", "Moonwalking",
"Moseying", "Mulling", "Mustering", "Musing", "Nebulizing",
"Nesting", "Newspapering", "Noodling", "Nucleating", "Orbiting",
"Orchestrating", "Osmosing", "Perambulating", "Percolating", "Perusing",
"Philosophising", "Photosynthesizing", "Pollinating", "Pondering",
"Pontificating", "Pouncing", "Precipitating", "Prestidigitating",
"Processing", "Proofing", "Propagating", "Puttering", "Puzzling",
"Quantumizing", "Razzle-dazzling", "Razzmatazzing", "Recombobulating",
"Reticulating", "Roosting", "Ruminating", "Saut", "Scampering",
"Schlepping", "Scurrying", "Seasoning", "Shenaniganing", "Shimmying",
"Simmering", "Skedaddling", "Sketching", "Slithering", "Smooshing",
"Sock-hopping", "Spelunking", "Spinning", "Sprouting", "Stewing",
"Sublimating", "Swirling", "Swooping", "Symbioting", "Synthesizing",
"Tempering", "Thinking", "Thundering", "Tinkering", "Tomfoolering",
"Topsy-turvying", "Transfiguring", "Transmuting", "Twisting", "Undulating",
"Unfurling", "Unravelling", "Vibing", "Waddling", "Wandering",
"Warping", "Whatchamacalliting", "Whirlpooling", "Whirring", "Whisking",
"Wibbling", "Working", "Wrangling", "Zesting", "Zigzagging",
]
def pad_size(string_len):
"""Calculate the padded size for string data (aligned to 16-byte boundary)."""
if string_len == 0:
return 0
return ((string_len + 15) // 16) * 16
def find_anchor_offsets(data):
"""Find all offsets where the anchor pattern (Accomplishing entry) starts."""
offsets = []
start = 0
while True:
idx = data.find(ANCHOR_PATTERN, start)
if idx == -1:
break
offsets.append(idx)
start = idx + 1
return offsets
def parse_region(data, offset):
"""Parse a message region starting at offset. Returns list of (offset, original_string, allocated_size) tuples."""
entries = []
pos = offset
while pos + 8 <= len(data):
# Check type tag
tag = data[pos:pos + 4]
if tag != TYPE_TAG:
break
# Read string length
str_len = struct.unpack_from('<I', data, pos + 4)[0]
# Sanity check: string length shouldn't be absurdly large
if str_len > 1024:
break
# Calculate allocated size (padded to 16 bytes)
alloc_size = pad_size(str_len)
# Check we have enough data
if pos + 8 + alloc_size + 8 > len(data):
break
# Read the string
string_data = data[pos + 8:pos + 8 + str_len].decode('ascii', errors='replace')
# Verify separator after padded string data
sep = data[pos + 8 + alloc_size:pos + 8 + alloc_size + 8]
if sep != SEPARATOR:
break
entries.append((pos, string_data, alloc_size))
# Move to next entry: tag(4) + len(4) + padded_string(alloc_size) + separator(8)
pos += 4 + 4 + alloc_size + 8
return entries
def load_messages(messages_path):
"""Load replacement messages from JSON file."""
with open(messages_path, 'r') as f:
data = json.load(f)
return data['messages']
def auto_detect_binary():
"""Try to auto-detect the Claude binary path."""
# Try the known path first
known_path = Path.home() / '.local' / 'share' / 'claude' / 'versions' / '2.1.70'
if known_path.exists():
return str(known_path)
# Try which claude + readlink
try:
result = subprocess.run(['which', 'claude'], capture_output=True, text=True)
if result.returncode == 0:
claude_path = result.stdout.strip()
real_path = os.path.realpath(claude_path)
if os.path.exists(real_path):
return real_path
except Exception:
pass
return None
def do_dry_run(binary_path, messages_path):
"""Find message regions and print proposed replacements without modifying anything."""
if binary_path is None:
binary_path = auto_detect_binary()
if binary_path is None:
print("ERROR: Could not auto-detect Claude binary. Specify path with --dry-run PATH")
sys.exit(1)
print(f"Binary: {binary_path}")
print(f"Size: {os.path.getsize(binary_path):,} bytes")
print()
replacement_msgs = load_messages(messages_path)
print(f"Loaded {len(replacement_msgs)} replacement messages from {messages_path}")
print()
with open(binary_path, 'rb') as f:
data = f.read()
anchors = find_anchor_offsets(data)
print(f"Found {len(anchors)} message region(s) at offsets: {[hex(o) for o in anchors]}")
print()
for region_idx, anchor_offset in enumerate(anchors):
entries = parse_region(data, anchor_offset)
print(f"--- Region {region_idx + 1} at offset {hex(anchor_offset)} ({len(entries)} entries) ---")
for i, (offset, original, alloc_size) in enumerate(entries):
replacement = replacement_msgs[i % len(replacement_msgs)]
fits = len(replacement) <= alloc_size
status = "OK" if fits else f"TOO LONG ({len(replacement)} > {alloc_size})"
if not fits:
# Find a shorter replacement that fits
for j in range(len(replacement_msgs)):
candidate = replacement_msgs[(i + j) % len(replacement_msgs)]
if len(candidate) <= alloc_size:
replacement = candidate
status = f"OK (alt #{(i+j) % len(replacement_msgs)})"
break
else:
replacement = original
status = "SKIP (no fit)"
print(f" [{i:3d}] {original:30s} -> {replacement:30s} [alloc={alloc_size:2d}] {status}")
print()
print("Dry run complete. No changes were made.")
def do_patch(binary_path, messages_path):
"""Patch the binary with replacement messages."""
if not os.path.exists(binary_path):
print(f"ERROR: Binary not found: {binary_path}")
sys.exit(1)
replacement_msgs = load_messages(messages_path)
print(f"Loaded {len(replacement_msgs)} replacement messages from {messages_path}")
# Create backup
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
version = "unknown"
# Try to extract version from path
parts = Path(binary_path).parts
for i, part in enumerate(parts):
if part == 'versions' and i + 1 < len(parts):
version = parts[i + 1]
break
backup_name = f"claude-{version}.backup"
backup_path = BACKUP_DIR / backup_name
if not backup_path.exists():
print(f"Backing up to {backup_path}")
shutil.copy2(binary_path, backup_path)
else:
print(f"Backup already exists at {backup_path}")
# Read binary
with open(binary_path, 'rb') as f:
data = bytearray(f.read())
print(f"Binary size: {len(data):,} bytes")
anchors = find_anchor_offsets(data)
print(f"Found {len(anchors)} message region(s)")
total_replaced = 0
total_skipped = 0
for region_idx, anchor_offset in enumerate(anchors):
entries = parse_region(bytes(data), anchor_offset)
print(f" Region {region_idx + 1} at {hex(anchor_offset)}: {len(entries)} entries")
for i, (offset, original, alloc_size) in enumerate(entries):
replacement = replacement_msgs[i % len(replacement_msgs)]
# If it doesn't fit, try to find one that does
if len(replacement) > alloc_size:
found = False
for j in range(len(replacement_msgs)):
candidate = replacement_msgs[(i + j) % len(replacement_msgs)]
if len(candidate) <= alloc_size:
replacement = candidate
found = True
break
if not found:
total_skipped += 1
continue
# Write new length
new_len = len(replacement)
struct.pack_into('<I', data, offset + 4, new_len)
# Write new string + null padding
new_bytes = replacement.encode('ascii')
for k in range(alloc_size):
if k < len(new_bytes):
data[offset + 8 + k] = new_bytes[k]
else:
data[offset + 8 + k] = 0
total_replaced += 1
# Write patched binary (use temp file + rename to handle "text file busy")
import tempfile
tmp_path = binary_path + '.patching'
with open(tmp_path, 'wb') as f:
f.write(data)
# Preserve permissions
shutil.copymode(binary_path, tmp_path)
os.replace(tmp_path, binary_path)
print()
print(f"Patched {total_replaced} messages across {len(anchors)} region(s)")
if total_skipped:
print(f"Skipped {total_skipped} entries (no replacement fit)")
# Show a sample
print()
print("Sample replacements:")
sample_entries = parse_region(bytes(data), anchors[0])
for i, (offset, msg, alloc) in enumerate(sample_entries[:5]):
print(f" {ORIGINAL_MESSAGES[i]:25s} -> {msg}")
def do_restore(binary_path):
"""Restore the binary from backup."""
if not os.path.exists(binary_path):
print(f"ERROR: Binary not found: {binary_path}")
sys.exit(1)
version = "unknown"
parts = Path(binary_path).parts
for i, part in enumerate(parts):
if part == 'versions' and i + 1 < len(parts):
version = parts[i + 1]
break
backup_name = f"claude-{version}.backup"
backup_path = BACKUP_DIR / backup_name
if not backup_path.exists():
print(f"ERROR: No backup found at {backup_path}")
print("Available backups:")
if BACKUP_DIR.exists():
for f in BACKUP_DIR.iterdir():
print(f" {f}")
else:
print(" (none)")
sys.exit(1)
print(f"Restoring from {backup_path}")
shutil.copy2(backup_path, binary_path)
print("Restore complete.")
def do_list(messages_path):
"""List replacement messages from JSON file."""
msgs = load_messages(messages_path)
print(f"Replacement messages ({len(msgs)} total):")
print()
for i, msg in enumerate(msgs):
print(f" [{i:2d}] {msg}")
def main():
parser = argparse.ArgumentParser(
description='Patch Claude Code spinner messages with custom replacements.'
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--patch', metavar='BINARY_PATH',
help='Patch the binary at BINARY_PATH with custom messages')
group.add_argument('--restore', metavar='BINARY_PATH',
help='Restore the binary at BINARY_PATH from backup')
group.add_argument('--dry-run', metavar='BINARY_PATH', nargs='?', const='__auto__',
help='Show what would be changed without modifying (auto-detects binary if not specified)')
group.add_argument('--list', action='store_true',
help='List replacement messages from messages.json')
parser.add_argument('--messages', metavar='MESSAGES_JSON',
default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'messages.json'),
help='Path to messages.json (default: messages.json next to this script)')
args = parser.parse_args()
if args.patch:
do_patch(args.patch, args.messages)
elif args.restore:
do_restore(args.restore)
elif args.dry_run is not None:
binary_path = None if args.dry_run == '__auto__' else args.dry_run
do_dry_run(binary_path, args.messages)
elif args.list:
do_list(args.messages)
if __name__ == '__main__':
main()