-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathinstall.ps1
More file actions
1397 lines (1210 loc) · 53.7 KB
/
install.ps1
File metadata and controls
1397 lines (1210 loc) · 53.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
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
#Requires -Version 5.1
<#
.SYNOPSIS
ClawGod Installer for Windows
.DESCRIPTION
Downloads Claude Code from npm, applies feature unlock patches,
and replaces the 'claude' command with the patched version.
.EXAMPLE
irm clawgod.0chen.cc/install.ps1 | iex
# or
.\install.ps1
.\install.ps1 -Version 2.1.89
.\install.ps1 -Uninstall
#>
param(
[string]$Version = "latest",
[switch]$Uninstall,
[switch]$DryRun
)
$ErrorActionPreference = "Stop"
$ClawDir = Join-Path $env:USERPROFILE ".clawgod"
$BinDir = Join-Path $env:USERPROFILE ".local\bin"
# ─── Colors ───────────────────────────────────────────
function Write-OK($msg) { Write-Host " ✓ $msg" -ForegroundColor Green }
function Write-Err($msg) { Write-Host " ✗ $msg" -ForegroundColor Red }
function Write-Warn($msg) { Write-Host " ! $msg" -ForegroundColor Yellow }
function Write-Dim($msg) { Write-Host " $msg" -ForegroundColor DarkGray }
Write-Host ""
Write-Host " ClawGod Installer" -ForegroundColor White -NoNewline
Write-Host " (Windows)" -ForegroundColor DarkGray
Write-Host ""
# ─── Uninstall ────────────────────────────────────────
if ($Uninstall) {
# Restore original claude
$claudeOrig = Join-Path $BinDir "claude.orig.cmd"
$claudeCmd = Join-Path $BinDir "claude.cmd"
if (Test-Path $claudeOrig) {
Move-Item -Force $claudeOrig $claudeCmd
Write-OK "Original claude restored"
}
# Also check for .exe backup
$claudeExeOrig = Join-Path $BinDir "claude.orig.exe"
$claudeExe = Join-Path $BinDir "claude.exe"
if (Test-Path $claudeExeOrig) {
Move-Item -Force $claudeExeOrig $claudeExe
Write-OK "Original claude.exe restored"
}
# Remove explicit clawgod alias
$clawgodCmd = Join-Path $BinDir "clawgod.cmd"
if (Test-Path $clawgodCmd) {
Remove-Item -Force $clawgodCmd
Write-OK "Removed clawgod alias"
}
foreach ($f in @("cli.js","cli.cjs","cli.original.js","cli.original.cjs","cli.original.js.bak","cli.original.cjs.bak","patch.js","patch.mjs","extract-natives.mjs","post-process.mjs","repatch.mjs",".source-version","node_modules","bun-runtime")) {
$p = Join-Path $ClawDir $f
if (Test-Path $p) { Remove-Item -Recurse -Force $p }
}
Write-OK "ClawGod uninstalled"
Write-Host ""
exit 0
}
# ─── Prerequisites ────────────────────────────────────
try { $null = Get-Command node -ErrorAction Stop }
catch {
Write-Err "Node.js is required (>= 18) for the patcher. Install from https://nodejs.org"
exit 1
}
$nodeVer = [int](node -e "console.log(process.versions.node.split('.')[0])")
if ($nodeVer -lt 18) {
Write-Err "Node.js >= 18 required (found v$nodeVer)"
exit 1
}
# ─── Ensure Bun (runtime that executes the patched cli.js) ────────────
$BunBin = $null
try { $BunBin = (Get-Command bun -ErrorAction Stop).Source } catch {}
if (-not $BunBin) {
$homeBun = Join-Path $env:USERPROFILE ".bun\bin\bun.exe"
if (Test-Path $homeBun) { $BunBin = $homeBun }
}
if (-not $BunBin) {
Write-Dim "Installing Bun (required runtime for v2.1.113+ cli.js) ..."
try {
Invoke-Expression "$(Invoke-RestMethod https://bun.sh/install.ps1)" 2>$null | Out-Null
} catch {}
$BunBin = Join-Path $env:USERPROFILE ".bun\bin\bun.exe"
if (-not (Test-Path $BunBin)) {
Write-Err "Bun installation failed. Install manually: https://bun.sh/install"
exit 1
}
}
Write-OK "Bun: $(& $BunBin --version)"
# ─── Bun version pre-flight ───────────────────────────────────────────
# Anthropic builds the native binary with Bun's canary channel; stable
# bun.sh trails by one version. Bun < 1.3.14 panics on cli.original.cjs
# with "Expected CommonJS module to have a function wrapper". Refuse
# early — no npm download / no patch / no late sanity surprise where
# PowerShell's NativeCommandError display buries the friendly message.
# Bump $MinBunVersion when Anthropic moves the embedded Bun forward
# again.
$MinBunVersion = '1.3.14'
$BunVersionRaw = ''
try {
$bunOut = & $BunBin --version 2>$null | Select-Object -First 1
if ($bunOut) { $BunVersionRaw = "$bunOut".Trim() }
} catch {}
$BunVersionNum = ($BunVersionRaw -split '-')[0]
$BunVersionOk = $false
try {
if ($BunVersionNum) {
$BunVersionOk = ([version]$BunVersionNum) -ge ([version]$MinBunVersion)
}
} catch {}
if (-not $BunVersionOk) {
Write-Host ""
Write-Err "Bun $BunVersionRaw is below the required minimum ($MinBunVersion)."
Write-Err ""
Write-Err " Anthropic builds claude-code with Bun's canary channel. Older Bun"
Write-Err " panics on cli.original.cjs with 'Expected CommonJS module to have"
Write-Err " a function wrapper'. This is a hard requirement, not a warning."
Write-Err ""
Write-Err " Upgrade with one of:"
Write-Err " bun upgrade --canary"
Write-Err " powershell -c ""iex & {`$(irm https://bun.sh/install.ps1)} -Version canary"""
Write-Err ""
Write-Err " If your bun is from scoop (the binary is behind a shim and refuses"
Write-Err " to self-replace, so 'bun upgrade' silently hangs):"
Write-Err " scoop uninstall bun"
Write-Err " irm https://bun.sh/install.ps1 | iex"
Write-Err " bun upgrade --canary"
Write-Err ""
Write-Err " Then re-run this installer."
exit 1
}
# ─── ripgrep prerequisite (search/grep tool) ──────────────────────────
# Hard prerequisite — without rg the Grep tool inside Claude Code fails.
try {
$rgPath = (Get-Command rg -ErrorAction Stop).Source
Write-OK "ripgrep: $rgPath"
}
catch {
Write-Err "ripgrep (rg) is required but not found in PATH."
Write-Err " Claude Code's Grep tool will not function without it."
Write-Err ""
Write-Err " Install: winget install BurntSushi.ripgrep.MSVC"
Write-Err " or: scoop install ripgrep"
Write-Err " or: choco install ripgrep"
Write-Err ""
Write-Err " Re-run this script after installing rg."
exit 1
}
# ─── Locate native Bun binary (cli.js source) ──────────────────────────
# Source: npm registry (@anthropic-ai/claude-code-win32-<arch>).
# Local binary detection is intentionally skipped — see policy note below.
New-Item -ItemType Directory -Force -Path $ClawDir | Out-Null
New-Item -ItemType Directory -Force -Path $BinDir | Out-Null
$NativeBin = $null
$NativeBinLabel = $null
$NativeBinTmpDir = $null
# Detect platform suffix
if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64" -or $env:PROCESSOR_ARCHITEW6432 -eq "ARM64") {
$arch = "arm64"
} else {
$arch = "x64"
}
$platformSuffix = "win32-$arch"
# Detection policy: ALWAYS pull from the npm registry @latest.
#
# Earlier versions of this script also probed local install directories
# (versions/, claude.orig, npm-global, bun-global) before falling back to
# the registry. Every one of those is a stale-source trap: clawgod patches
# out `claude update`, so users never re-run the underlying installers,
# and those directories freeze at whatever version was on disk the day
# clawgod was first installed. `claude update` (which is now redirected
# here) would re-detect the frozen binary forever — never reaching the
# registry. See INCIDENT_LOG 2026-04-29 entry. The fix is to skip local
# detection entirely; the npm tarball is ~60-90 MB compressed, fetched
# once per upgrade.
# npm registry — pull the platform tarball directly via Node.
# Avoids depending on `npm` and `tar` being on PATH (older Windows 10
# builds lack tar.exe; some PowerShell shims mangle `& npm`). Node is
# already a hard prerequisite for the patcher, so reuse it.
if (-not $NativeBin) {
$npmPkg = "@anthropic-ai/claude-code-$platformSuffix"
Write-Dim "Fetching $npmPkg@latest from npm registry ..."
$NativeBinTmpDir = Join-Path $env:TEMP "clawgod-binary-$([Guid]::NewGuid().ToString('N'))"
New-Item -ItemType Directory -Force -Path $NativeBinTmpDir | Out-Null
$fetchScript = Join-Path $NativeBinTmpDir "fetch.mjs"
@'
// Download a scoped npm tarball (no npm CLI dependency) and extract it
// using Node's built-in zlib + a minimal POSIX tar parser.
import { request as httpsRequest } from 'node:https';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { gunzipSync } from 'node:zlib';
const [, , pkgSpec, outDir] = process.argv;
const last = pkgSpec.lastIndexOf('@');
const pkg = last > 0 ? pkgSpec.slice(0, last) : pkgSpec;
const ver = last > 0 ? pkgSpec.slice(last + 1) : 'latest';
function get(url) {
return new Promise((resolve, reject) => {
httpsRequest(url, { method: 'GET' }, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
return get(res.headers.location).then(resolve, reject);
}
if (res.statusCode !== 200) {
return reject(new Error(`HTTP ${res.statusCode} for ${url}`));
}
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
}).on('error', reject).end();
});
}
const metaBuf = await get(`https://registry.npmjs.org/${pkg}/${ver}`);
const meta = JSON.parse(metaBuf.toString('utf8'));
console.log(`Resolved ${pkg}@${meta.version}`);
const tgz = await get(meta.dist.tarball);
console.log(`Downloaded ${(tgz.length / 1024 / 1024).toFixed(1)} MB`);
const buf = gunzipSync(tgz);
mkdirSync(outDir, { recursive: true });
let off = 0, files = 0;
while (off + 512 <= buf.length) {
const name = buf.slice(off, off + 100).toString('utf8').replace(/\0+$/, '');
if (!name) break;
const sizeOct = buf.slice(off + 124, off + 136).toString('utf8').replace(/[\0\s]+$/, '');
const size = parseInt(sizeOct, 8) || 0;
const typeflag = String.fromCharCode(buf[off + 156]);
off += 512;
if (typeflag === '0' || typeflag === '\0') {
const dest = join(outDir, name);
mkdirSync(dirname(dest), { recursive: true });
writeFileSync(dest, buf.slice(off, off + size));
files++;
}
off += Math.ceil(size / 512) * 512;
}
console.log(`Extracted ${files} files`);
console.log(`VERSION=${meta.version}`);
'@ | Set-Content $fetchScript -Encoding UTF8
$output = & node $fetchScript "$npmPkg@latest" $NativeBinTmpDir 2>&1
$exitCode = $LASTEXITCODE
$output | ForEach-Object { Write-Host " $_" }
Remove-Item -Force $fetchScript -ErrorAction SilentlyContinue
if ($exitCode -ne 0) {
Remove-Item -Recurse -Force $NativeBinTmpDir -ErrorAction SilentlyContinue
Write-Err "Fetch failed (node exit $exitCode). Install the official binary manually:"
Write-Err " irm https://claude.ai/install.ps1 | iex"
exit 1
}
$cand = Join-Path $NativeBinTmpDir "package\claude.exe"
if ((Test-Path $cand) -and (Get-Item $cand).Length -gt 10MB) {
$NativeBin = $cand
# Pull the version line printed by fetch.mjs ("VERSION=2.1.x")
$verLine = $output | Where-Object { $_ -match '^VERSION=' } | Select-Object -First 1
if ($verLine) { $NativeBinLabel = ($verLine -replace '^VERSION=', '').Trim() }
else { $NativeBinLabel = "npm-latest" }
} else {
Remove-Item -Recurse -Force $NativeBinTmpDir -ErrorAction SilentlyContinue
Write-Err "Tarball downloaded but expected package\claude.exe was missing or too small."
Write-Err " Tempdir kept for inspection: $NativeBinTmpDir"
exit 1
}
Write-OK "Downloaded $npmPkg@$NativeBinLabel"
}
if (-not $NativeBin) {
Write-Err "Native Claude Code binary not found"
Write-Err "Install the official binary first:"
Write-Err " irm https://claude.ai/install.ps1 | iex"
Write-Err "Then re-run this script."
exit 1
}
# Always write the extractor (used for cli.js and/or .node modules)
$extractorPath = Join-Path $ClawDir "extract-natives.mjs"
@'
#!/usr/bin/env node
/**
* ClawGod native module extractor
*
* Extracts embedded .node NAPI modules from a Bun single-file executable
* (the official Claude Code native binary).
*
* Supports:
* - Mach-O (macOS) — arm64 + x86_64 thin binaries
* - ELF (Linux) — arm64 + x86_64
* - PE (Windows) — x86_64 + arm64
*
* Usage:
* node extract-natives.mjs <binary-path> <output-dir>
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from 'fs';
import { join, basename } from 'path';
// ─── Mach-O constants ────────────────────────────────────────────────
const MH_MAGIC_64 = 0xfeedfacf; // little-endian 64-bit
const LC_SEGMENT_64 = 0x19;
const LC_ID_DYLIB = 0x0d;
const MH_DYLIB = 6;
const CPU_TYPE_X86_64 = 0x01000007;
const CPU_TYPE_ARM64 = 0x0100000c;
// ─── ELF constants ───────────────────────────────────────────────────
const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46]); // 7f 'E' 'L' 'F'
const ET_DYN = 3; // shared object
const EM_X86_64 = 62;
const EM_AARCH64 = 183;
// ─── PE constants ────────────────────────────────────────────────────
const MZ_MAGIC = Buffer.from([0x4d, 0x5a]); // "MZ"
const PE_MAGIC = Buffer.from([0x50, 0x45, 0, 0]); // "PE\0\0"
const IMAGE_FILE_MACHINE_AMD64 = 0x8664;
const IMAGE_FILE_MACHINE_ARM64 = 0xaa64;
const IMAGE_FILE_DLL = 0x2000;
// ─── Helpers ─────────────────────────────────────────────────────────
function archName(format, cputype) {
if (format === 'macho') {
if (cputype === CPU_TYPE_ARM64) return 'arm64';
if (cputype === CPU_TYPE_X86_64) return 'x64';
}
if (format === 'elf') {
if (cputype === EM_AARCH64) return 'arm64';
if (cputype === EM_X86_64) return 'x64';
}
if (format === 'pe') {
if (cputype === IMAGE_FILE_MACHINE_ARM64) return 'arm64';
if (cputype === IMAGE_FILE_MACHINE_AMD64) return 'x64';
}
return null;
}
function platformSuffix(format, arch) {
const os = format === 'macho' ? 'darwin' : format === 'elf' ? 'linux' : 'win32';
return `${arch}-${os}`;
}
// ─── Mach-O parser ───────────────────────────────────────────────────
function parseMachODylib(buf, off) {
const magic = buf.readUInt32LE(off);
if (magic !== MH_MAGIC_64) return null;
const cputype = buf.readUInt32LE(off + 4);
if (cputype !== CPU_TYPE_ARM64 && cputype !== CPU_TYPE_X86_64) return null;
const filetype = buf.readUInt32LE(off + 12);
if (filetype !== MH_DYLIB) return null;
const ncmds = buf.readUInt32LE(off + 16);
if (ncmds === 0 || ncmds > 500) return null;
let totalFileEnd = 0;
let installName = null;
let cmdOff = off + 32;
for (let i = 0; i < ncmds; i++) {
if (cmdOff + 8 > buf.length) return null;
const cmd = buf.readUInt32LE(cmdOff);
const cmdsize = buf.readUInt32LE(cmdOff + 4);
if (cmdsize === 0 || cmdsize > 65536) return null;
if (cmd === LC_SEGMENT_64) {
const fileoff = Number(buf.readBigUInt64LE(cmdOff + 40));
const filesize = Number(buf.readBigUInt64LE(cmdOff + 48));
const end = fileoff + filesize;
if (end > totalFileEnd) totalFileEnd = end;
} else if (cmd === LC_ID_DYLIB) {
// dylib_command: uint32 cmd, cmdsize, str_offset, timestamp, version...
// then name string at cmdOff + str_offset
const strOff = buf.readUInt32LE(cmdOff + 8);
const nameStart = cmdOff + strOff;
const nameEnd = buf.indexOf(0, nameStart);
if (nameEnd !== -1 && nameEnd - nameStart < 1024) {
installName = buf.slice(nameStart, nameEnd).toString('utf8');
}
}
cmdOff += cmdsize;
}
if (totalFileEnd === 0) return null;
return {
offset: off,
size: totalFileEnd,
arch: archName('macho', cputype),
installName,
};
}
function extractMachODylibs(buf) {
const dylibs = [];
// Magic bytes for fast indexOf scan: cf fa ed fe (MH_MAGIC_64 LE)
const magicBytes = Buffer.from([0xcf, 0xfa, 0xed, 0xfe]);
let off = 1; // skip the main binary at offset 0
while ((off = buf.indexOf(magicBytes, off)) !== -1) {
const info = parseMachODylib(buf, off);
if (info && off + info.size <= buf.length) {
dylibs.push(info);
off += info.size; // skip past this dylib
} else {
off += 4;
}
}
return dylibs;
}
// ─── ELF parser ──────────────────────────────────────────────────────
function parseELFSharedObject(buf, off) {
if (buf.length - off < 64) return null;
if (!buf.slice(off, off + 4).equals(ELF_MAGIC)) return null;
const eiClass = buf.readUInt8(off + 4); // 1=32-bit, 2=64-bit
if (eiClass !== 2) return null;
const eiData = buf.readUInt8(off + 5); // 1=LE, 2=BE
if (eiData !== 1) return null; // only LE supported
const eType = buf.readUInt16LE(off + 16);
if (eType !== ET_DYN) return null;
const eMachine = buf.readUInt16LE(off + 18);
if (eMachine !== EM_X86_64 && eMachine !== EM_AARCH64) return null;
// ELF64 header layout:
// e_shoff (section header offset): off + 40 (u64)
// e_shentsize: off + 58 (u16)
// e_shnum: off + 60 (u16)
const shoff = Number(buf.readBigUInt64LE(off + 40));
const shentsize = buf.readUInt16LE(off + 58);
const shnum = buf.readUInt16LE(off + 60);
if (shentsize !== 64 || shnum === 0 || shnum > 1000) return null;
// Total size = shoff + shnum * shentsize (the section header table is at the end)
const totalSize = shoff + shnum * shentsize;
if (totalSize > buf.length - off) return null;
return {
offset: off,
size: totalSize,
arch: archName('elf', eMachine),
installName: null, // ELF soname requires dynamic section walk; we'll rely on adjacent strings
};
}
function extractELFSharedObjects(buf) {
const sos = [];
// Scan for ELF magic; ELF headers are rare in data so 4-byte alignment is fine
for (let off = 4; off < buf.length - 64; off += 4) {
if (buf.readUInt8(off) !== 0x7f) continue;
const info = parseELFSharedObject(buf, off);
if (!info) continue;
if (off + info.size > buf.length) continue;
sos.push(info);
}
return sos;
}
// ─── PE parser ───────────────────────────────────────────────────────
function parsePEDll(buf, off) {
if (buf.length - off < 1024) return null;
if (!buf.slice(off, off + 2).equals(MZ_MAGIC)) return null;
// PE header offset at MZ + 0x3c (e_lfanew)
const peOff = buf.readUInt32LE(off + 0x3c);
if (peOff > 4096) return null; // sanity
if (off + peOff + 24 > buf.length) return null;
if (!buf.slice(off + peOff, off + peOff + 4).equals(PE_MAGIC)) return null;
const machine = buf.readUInt16LE(off + peOff + 4);
if (machine !== IMAGE_FILE_MACHINE_AMD64 && machine !== IMAGE_FILE_MACHINE_ARM64) return null;
const numberOfSections = buf.readUInt16LE(off + peOff + 6);
const sizeOfOptionalHeader = buf.readUInt16LE(off + peOff + 20);
const characteristics = buf.readUInt16LE(off + peOff + 22);
if (!(characteristics & IMAGE_FILE_DLL)) return null;
// Walk sections to find the max (PointerToRawData + SizeOfRawData)
const sectionHeaderOff = off + peOff + 24 + sizeOfOptionalHeader;
let totalSize = sectionHeaderOff - off; // header area minimum
for (let i = 0; i < numberOfSections; i++) {
const secOff = sectionHeaderOff + i * 40;
if (secOff + 40 > buf.length) return null;
const sizeOfRawData = buf.readUInt32LE(secOff + 16);
const pointerToRawData = buf.readUInt32LE(secOff + 20);
const end = pointerToRawData + sizeOfRawData;
if (end > totalSize) totalSize = end;
}
if (totalSize === 0 || totalSize > 50 * 1024 * 1024) return null;
return {
offset: off,
size: totalSize,
arch: archName('pe', machine),
installName: null,
};
}
function extractPEDlls(buf) {
const dlls = [];
for (let off = 0; off < buf.length - 1024; off++) {
if (buf.readUInt8(off) !== 0x4d) continue;
if (buf.readUInt8(off + 1) !== 0x5a) continue;
const info = parsePEDll(buf, off);
if (!info) continue;
if (off + info.size > buf.length) continue;
dlls.push(info);
}
return dlls;
}
// ─── Main dispatch ───────────────────────────────────────────────────
function detectFormat(buf) {
if (buf.readUInt32LE(0) === MH_MAGIC_64) return 'macho';
if (buf.slice(0, 4).equals(ELF_MAGIC)) return 'elf';
if (buf.slice(0, 2).equals(MZ_MAGIC)) return 'pe';
return null;
}
// Names to look for from install names / nearby strings
const KNOWN_MODULES = [
'image-processor',
'audio-capture',
'computer-use-input',
'computer-use-swift',
'url-handler',
];
function identifyDylib(buf, dylib) {
// 1. Try install name (most reliable)
if (dylib.installName) {
const base = basename(dylib.installName).replace(/\.(node|dylib|so|dll)$/, '');
for (const m of KNOWN_MODULES) {
if (base === m) return m;
// Handle variants like "libcomputer_use_input.dylib"
if (base === `lib${m.replace(/-/g, '_')}`) return m;
if (base === `lib${m.replace(/-/g, '')}`) return m;
if (base.toLowerCase().includes(m.replace(/-/g, ''))) return m;
}
}
// 2. Scan the dylib body for known module name strings
const body = buf.slice(dylib.offset, dylib.offset + dylib.size);
for (const m of KNOWN_MODULES) {
if (body.indexOf(Buffer.from(m)) !== -1) return m;
}
return null;
}
// ─── cli.js text extraction (Bun standalone) ─────────────────────────
// Two anchors: bunfs path (primary, Mach-O/ELF) and cli_after_main_complete
// (fallback, used when Windows PE builds omit the bunfs path string).
const CLI_PATH_MARKER = Buffer.from('file:///$bunfs/root/src/entrypoints/cli.js');
const CLI_FN_MARKER = Buffer.from('(function(exports, require, module');
const CLI_TAIL_MARKER = Buffer.from('cli_after_main_complete")}');
const CLI_END_MARKER = Buffer.from(');})');
function extractCliJs(buf) {
let fnStart = -1;
const pathOff = buf.indexOf(CLI_PATH_MARKER);
if (pathOff !== -1) {
const candidate = buf.indexOf(CLI_FN_MARKER, pathOff);
if (candidate !== -1 && candidate - pathOff <= 1024) fnStart = candidate;
}
if (fnStart === -1) {
const tailMark = buf.indexOf(CLI_TAIL_MARKER);
if (tailMark === -1) return null;
const candidate = buf.lastIndexOf(CLI_FN_MARKER, tailMark);
if (candidate === -1 || tailMark - candidate < 1024 * 1024) return null;
fnStart = candidate;
}
const tailFromFn = buf.indexOf(CLI_TAIL_MARKER, fnStart);
if (tailFromFn === -1) return null;
const ending = buf.indexOf(CLI_END_MARKER, tailFromFn);
if (ending === -1 || ending - tailFromFn > 4096) return null;
return buf.slice(fnStart, ending + CLI_END_MARKER.length).toString('utf8');
}
function main() {
const [, , binaryPath, outputDir, ...rest] = process.argv;
const wantCliJs = rest.includes('--cli-js');
if (!binaryPath || !outputDir) {
console.error('Usage: extract-natives.mjs <binary-path> <output-dir> [--cli-js]');
process.exit(1);
}
if (!existsSync(binaryPath)) {
console.error(`Binary not found: ${binaryPath}`);
process.exit(1);
}
const stat = statSync(binaryPath);
if (stat.size < 10 * 1024 * 1024) {
console.error(`Binary too small (${stat.size} bytes) — not a native Claude Code binary`);
process.exit(1);
}
const buf = readFileSync(binaryPath);
const format = detectFormat(buf);
if (!format) {
console.error('Unknown binary format (expected Mach-O / ELF / PE)');
process.exit(1);
}
console.log(`Format: ${format}`);
console.log(`Size: ${(buf.length / 1024 / 1024).toFixed(1)} MB`);
if (wantCliJs) {
const js = extractCliJs(buf);
if (!js) {
console.error('Could not locate cli.js payload in binary (markers missing).');
process.exit(2);
}
mkdirSync(outputDir, { recursive: true });
const out = join(outputDir, 'cli.original.js');
writeFileSync(out, js);
console.log(` cli.js ${(js.length / 1024 / 1024).toFixed(2)} MB -> ${out}`);
return;
}
let libs = [];
if (format === 'macho') libs = extractMachODylibs(buf);
else if (format === 'elf') libs = extractELFSharedObjects(buf);
else if (format === 'pe') libs = extractPEDlls(buf);
// Skip the first (main binary itself)
libs = libs.filter(l => l.offset !== 0);
console.log(`Found: ${libs.length} embedded native libraries`);
console.log();
mkdirSync(outputDir, { recursive: true });
const summary = { extracted: [], skipped: [] };
for (const lib of libs) {
const name = identifyDylib(buf, lib);
if (!name) {
summary.skipped.push({ ...lib, reason: 'unidentified' });
continue;
}
const platform = platformSuffix(format, lib.arch);
const targetDir = join(outputDir, name, platform);
mkdirSync(targetDir, { recursive: true });
const targetFile = join(targetDir, `${name}.node`);
const data = buf.slice(lib.offset, lib.offset + lib.size);
writeFileSync(targetFile, data);
console.log(` ✓ ${name.padEnd(20)} ${lib.arch.padEnd(6)} ${(lib.size / 1024).toFixed(0).padStart(5)} KB → ${targetFile}`);
summary.extracted.push({ name, platform, size: lib.size });
}
console.log();
console.log(`Extracted ${summary.extracted.length}, skipped ${summary.skipped.length}`);
if (summary.skipped.length > 0) {
console.log('\nSkipped (unidentified):');
for (const s of summary.skipped) {
console.log(` offset=${s.offset} arch=${s.arch} size=${(s.size / 1024).toFixed(0)}KB`);
}
}
}
main();
'@ | Set-Content $extractorPath -Encoding UTF8
# ─── Extract cli.js + native modules from Bun binary ──────────
$VendorDir = Join-Path $ClawDir "vendor"
if (Test-Path $VendorDir) { Remove-Item -Recurse -Force $VendorDir }
New-Item -ItemType Directory -Force -Path $VendorDir | Out-Null
$dstCli = Join-Path $ClawDir "cli.original.js"
Write-Dim "Extracting cli.js from $NativeBinLabel ..."
& node $extractorPath $NativeBin $ClawDir --cli-js 2>&1 | ForEach-Object { Write-Host " $_" }
if (-not (Test-Path $dstCli)) {
Write-Err "Failed to extract cli.js from native binary"
exit 1
}
Write-Dim "Extracting native modules from $NativeBinLabel ..."
& node $extractorPath $NativeBin $VendorDir 2>&1 | ForEach-Object { Write-Host " $_" }
# Note: keep extractorPath around — repatch.mjs uses it on version drift
# ─── Post-process cli.js for Bun runtime ──────────────────────
Write-Dim "Rewriting bunfs paths and IIFE invocation ..."
$postProc = Join-Path $ClawDir "post-process.mjs"
@'
import { readFileSync, writeFileSync, unlinkSync } from 'fs';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const here = dirname(fileURLToPath(import.meta.url));
const src = `${here}/cli.original.js`;
const dst = `${here}/cli.original.cjs`;
let code = readFileSync(src, 'utf8');
code = code.replace(
/require\(['"](\/\$bunfs\/root\/([\w-]+)\.node)['"]\)/g,
(m, _full, name) =>
`require(require('path').join(__dirname,'vendor',${JSON.stringify(name)},\`\${process.arch==='arm64'?'arm64':'x64'}-\${process.platform==='darwin'?'darwin':process.platform==='linux'?'linux':'win32'}\`,${JSON.stringify(name + '.node')}))`,
);
code = code.replace(
/[\w$]+\.fileURLToPath\("file:\/\/\/home\/runner\/work\/claude-cli-internal\/claude-cli-internal\/[^"]*"\)/g,
() => '__filename',
);
code = code.replace(/\}\)\s*$/, '})(exports, require, module, __filename, __dirname)');
writeFileSync(dst, code);
unlinkSync(src);
console.log(`cli.original.cjs: ${code.length} bytes`);
'@ | Set-Content $postProc -Encoding UTF8
& node $postProc 2>&1 | ForEach-Object { Write-Host " $_" }
if (-not (Test-Path (Join-Path $ClawDir "cli.original.cjs"))) {
Write-Err "Post-process failed"
exit 1
}
# Stamp source version so wrapper can detect drift on next launch
Set-Content -Path (Join-Path $ClawDir ".source-version") -Value $NativeBinLabel -Encoding ASCII
# If we pulled the binary from npm into a tmpdir, clean up — extraction
# is done; drift detection only consults %USERPROFILE%\.local\share\claude\versions\.
if ($NativeBinTmpDir -and (Test-Path $NativeBinTmpDir)) {
Remove-Item -Recurse -Force $NativeBinTmpDir -ErrorAction SilentlyContinue
}
Write-OK "cli.original.cjs ready ($NativeBinLabel)"
# ─── Write re-patch helper (used by wrapper on version drift) ─────────
@'
#!/usr/bin/env bun
import { spawnSync } from 'child_process';
import { writeFileSync, existsSync, mkdirSync, rmSync } from 'fs';
import { dirname, join, basename } from 'path';
import { fileURLToPath } from 'url';
const here = dirname(fileURLToPath(import.meta.url));
const nativeBin = process.argv[2];
if (!nativeBin || !existsSync(nativeBin)) {
console.error('repatch: native binary path required and must exist');
process.exit(1);
}
const vendor = join(here, 'vendor');
rmSync(vendor, { recursive: true, force: true });
mkdirSync(vendor, { recursive: true });
const runtime = process.execPath;
function run(label, args) {
const r = spawnSync(runtime, args, { cwd: here, stdio: 'inherit' });
if (r.status !== 0) {
console.error(`repatch: ${label} failed (exit ${r.status})`);
process.exit(1);
}
}
const extractor = join(here, 'extract-natives.mjs');
const postProc = join(here, 'post-process.mjs');
const patcher = join(here, 'patch.mjs');
run('extract cli.js', [extractor, nativeBin, here, '--cli-js']);
run('extract natives', [extractor, nativeBin, vendor]);
run('post-process', [postProc]);
run('patcher', [patcher]);
writeFileSync(join(here, '.source-version'), basename(nativeBin) + '\n');
console.log(`[clawgod] re-patched to ${basename(nativeBin)}`);
'@ | Set-Content (Join-Path $ClawDir "repatch.mjs") -Encoding UTF8
Write-OK "Re-patch helper installed (repatch.mjs)"
# ─── Write wrapper (cli.cjs, runs under Bun) ──────────────────
@'
#!/usr/bin/env bun
const { readFileSync, existsSync, mkdirSync, writeFileSync, readdirSync, statSync, renameSync } = require('fs');
const { join, basename } = require('path');
const { homedir } = require('os');
const { spawnSync } = require('child_process');
const clawgodDir = join(homedir(), '.clawgod');
// Note: drift detection removed — see install.sh wrapper for full notes.
// `versions/` either doesn't exist (Windows) or doesn't grow on healthy
// clawgod installs (we patch out `claude update`), so the check could only
// retract a fresh install.ps1 / install.sh upgrade. `claude update` →
// install.sh redirect is the single source of truth for version upgrades.
// One-time migration: earlier wrapper versions set CLAUDE_CONFIG_DIR=~/.clawgod,
// which made Claude Code read/write ~/.clawgod/.claude.json instead of the
// native ~/.claude.json (the file holding MCP config, project history, session
// index). Move it back transparently on first run after upgrade.
const nativeClaudeJson = join(homedir(), '.claude.json');
const strayClaudeJson = join(clawgodDir, '.claude.json');
if (existsSync(strayClaudeJson) && !existsSync(nativeClaudeJson)) {
try { renameSync(strayClaudeJson, nativeClaudeJson); } catch {}
}
const providerDir = clawgodDir;
const configFile = join(providerDir, 'provider.json');
const defaultConfig = {
apiKey: '',
baseURL: 'https://api.anthropic.com',
model: '',
smallModel: '',
timeoutMs: 3000000,
};
let config = { ...defaultConfig };
if (existsSync(configFile)) {
try {
const raw = JSON.parse(readFileSync(configFile, 'utf8'));
config = { ...defaultConfig, ...raw };
} catch {}
} else {
mkdirSync(providerDir, { recursive: true });
writeFileSync(configFile, JSON.stringify(defaultConfig, null, 2) + '\n');
}
const hasProviderApiKey = !!config.apiKey;
if (hasProviderApiKey) {
process.env.ANTHROPIC_API_KEY = config.apiKey;
if (config.baseURL) process.env.ANTHROPIC_BASE_URL = config.baseURL;
if (config.model) process.env.ANTHROPIC_MODEL = config.model;
if (config.smallModel) process.env.ANTHROPIC_SMALL_FAST_MODEL = config.smallModel;
if (config.baseURL && !/anthropic\.com/i.test(config.baseURL)) {
process.env.ANTHROPIC_AUTH_TOKEN ??= config.apiKey;
}
} else if (config.baseURL && config.baseURL !== defaultConfig.baseURL) {
process.env.ANTHROPIC_BASE_URL ??= config.baseURL;
}
if (config.timeoutMs) {
process.env.API_TIMEOUT_MS ??= String(config.timeoutMs);
}
process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC ??= '1';
process.env.DISABLE_INSTALLATION_CHECKS ??= '1';
process.env.USE_BUILTIN_RIPGREP ??= '1';
const featuresFile = join(providerDir, 'features.json');
if (!process.env.CLAUDE_INTERNAL_FC_OVERRIDES && existsSync(featuresFile)) {
try {
const raw = readFileSync(featuresFile, 'utf8');
JSON.parse(raw);
process.env.CLAUDE_INTERNAL_FC_OVERRIDES = raw;
} catch {}
}
require('./cli.original.cjs');
'@ | Set-Content (Join-Path $ClawDir "cli.cjs") -Encoding UTF8
Write-OK "Wrapper created (cli.cjs)"
# ─── Write universal patcher ──────────────────────────
# (Same Node.js patcher as bash version — extract from install.sh or inline)
$patcherUrl = "https://raw.githubusercontent.com/0Chencc/clawgod/main/patcher.mjs"
# Inline the patcher to avoid extra download
$patcherCode = @'
#!/usr/bin/env node
/**
* ClawGod Universal Patcher
*/
import { readFileSync, writeFileSync, existsSync, copyFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const TARGET = join(__dirname, 'cli.original.cjs');
const BACKUP = TARGET + '.bak';
const patches = [
{
name: 'USER_TYPE → ant',
pattern: /function ([\w$]+)\(\)\{return"external"\}/g,
replacer: (m, fn) => `function ${fn}(){return"ant"}`,
sentinel: 'return"external"',
},
{
name: 'GrowthBook env overrides',
pattern: /function ([\w$]+)\(\)\{if\(!([\w$]+)\)\2=!0;return ([\w$]+)\}/g,
replacer: (m, fn, flag, val) =>
`function ${fn}(){if(!${flag}){${flag}=!0;try{let e=process.env.CLAUDE_INTERNAL_FC_OVERRIDES;if(e)${val}=JSON.parse(e)}catch(e){}}return ${val}}`,
unique: true,
},
{
name: 'GrowthBook config overrides',
pattern: /function ([\w$]+)\(\)\{return\}(function)/g,
replacer: (m, fn, next) =>
`function ${fn}(){try{return j8().growthBookOverrides??null}catch{return null}}${next}`,
selectIndex: 0,
validate: (match, code) => {
const pos = code.indexOf(match);
const nearby = code.substring(Math.max(0, pos - 500), pos + 500);
return nearby.includes('growthBook') || nearby.includes('GrowthBook') || nearby.includes('FeatureValue');
},
},
{
name: 'Agent Teams always enabled',
pattern: /function ([\w$]+)\(\)\{if\(![\w$]+\(process\.env\.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS\)&&![\w$]+\(\)\)return!1;if\(![\w$]+\("tengu_amber_flint",!0\)\)return!1;return!0\}/g,
replacer: (m, fn) => `function ${fn}(){return!0}`,
},
{
name: 'Computer Use subscription bypass',
pattern: /function ([\w$]+)\(\)\{let [\w$]+=[\w$]+\(\);return [\w$]+==="max"\|\|[\w$]+==="pro"\}/g,
replacer: (m, fn) => `function ${fn}(){return!0}`,
},
{
name: 'Computer Use default enabled',
pattern: /([\w$]+=)\{enabled:!1,pixelValidation/g,
replacer: (m, prefix) => `${prefix}{enabled:!0,pixelValidation`,
},
{
// v2.1.92+: name:"ultraplan",get description(){...},argumentHint:"<prompt>",isEnabled:()=>fnRef()
// Older : name:"ultraplan",description:`...`,argumentHint:"<prompt>",isEnabled:()=>!1
name: 'Ultraplan enable',
pattern: /(name:"ultraplan",[\s\S]{1,500}?argumentHint:"<prompt>",isEnabled:\(\)=>)(?:!1|[\w$]+\(\))/g,
replacer: (m, prefix) => `${prefix}!0`,
sentinel: 'name:"ultraplan"',
},
{
name: 'Ultrareview enable',
pattern: /function ([\w$]+)\(\)\{return [\w$]+\("tengu_review_bughunter_config",null\)(\?\.enabled===!0)?\}/g,
replacer: (m, fn) => `function ${fn}(){return{enabled:!0}}`,
sentinel: '"tengu_review_bughunter_config"',
},
{
name: 'Logo + brand color → green (RGB dark)',
pattern: /clawd_body:"rgb\(215,119,87\)"/g,
replacer: () => 'clawd_body:"rgb(34,197,94)"',