-
Notifications
You must be signed in to change notification settings - Fork 289
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·2135 lines (1939 loc) · 94.7 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·2135 lines (1939 loc) · 94.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
#!/bin/bash
set -e
# ─────────────────────────────────────────────────────────
# ClawGod Installer
#
# Downloads Claude Code from npm, applies patches, replaces claude command
#
# 用法:
# curl -fsSL https://raw.githubusercontent.com/0Chencc/clawgod/main/install.sh | bash
# # 或
# bash install.sh [--version 2.1.89] [--no-upgrade]
# ─────────────────────────────────────────────────────────
CLAWGOD_DIR="$HOME/.clawgod"
BIN_DIR="$HOME/.local/bin"
VERSION="${CLAWGOD_VERSION:-latest}"
NO_UPGRADE="${CLAWGOD_NO_UPGRADE:-}"
LEAN_OFF="${CLAWGOD_LEAN_OFF:-}"
LEAN_ON="${CLAWGOD_LEAN_ON:-}"
LEAN_MAX="${CLAWGOD_LEAN_MAX:-}"
CLAWGOD_SELF_VERSION="0.0.0-dev" # injected by release workflow from git tag
# Parse args
while [[ $# -gt 0 ]]; do
case $1 in
--version) VERSION="$2"; shift 2 ;;
--no-upgrade) NO_UPGRADE=1; shift ;;
--uninstall) UNINSTALL=1; shift ;;
--lean-off) LEAN_OFF=1; shift ;;
--lean-on) LEAN_ON=1; shift ;;
--lean-max) LEAN_MAX=1; shift ;;
*) shift ;;
esac
done
# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
DIM='\033[2m'
BOLD='\033[1m'
NC='\033[0m'
info() { echo -e " ${GREEN}✓${NC} $1"; }
warn() { echo -e " ${RED}✗${NC} $1"; }
dim() { echo -e " ${DIM}$1${NC}"; }
echo ""
echo -e "${BOLD} ClawGod Installer${NC}"
echo ""
# ─── Uninstall ─────────────────────────────────────────
if [ "$UNINSTALL" = "1" ]; then
CLAUDE_BIN=$(command -v claude 2>/dev/null || true)
for DIR in "${CLAUDE_BIN:+$(dirname "$CLAUDE_BIN")}" "$BIN_DIR"; do
[ -z "$DIR" ] && continue
if [ -e "$DIR/claude.orig" ]; then
# Has backup — restore it
mv "$DIR/claude.orig" "$DIR/claude"
info "Original claude restored ($DIR/claude)"
elif [ -f "$DIR/claude" ] && grep -q "clawgod" "$DIR/claude" 2>/dev/null; then
# Our launcher, no backup — remove it (otherwise it points to deleted cli.js)
rm -f "$DIR/claude"
info "Removed ClawGod launcher ($DIR/claude)"
fi
# Always remove the explicit clawgod alias if it's ours
if [ -f "$DIR/clawgod" ] && grep -q "clawgod" "$DIR/clawgod" 2>/dev/null; then
rm -f "$DIR/clawgod"
info "Removed ClawGod alias ($DIR/clawgod)"
fi
done
rm -rf "$CLAWGOD_DIR/node_modules" "$CLAWGOD_DIR/vendor" "$CLAWGOD_DIR/bun-runtime" "$CLAWGOD_DIR/cli.original.js" "$CLAWGOD_DIR/cli.original.js.bak" "$CLAWGOD_DIR/cli.original.cjs" "$CLAWGOD_DIR/cli.original.cjs.bak" "$CLAWGOD_DIR/cli.js" "$CLAWGOD_DIR/cli.cjs" "$CLAWGOD_DIR/patch.mjs" "$CLAWGOD_DIR/patch.js" "$CLAWGOD_DIR/extract-natives.mjs" "$CLAWGOD_DIR/post-process.mjs" "$CLAWGOD_DIR/repatch.mjs" "$CLAWGOD_DIR/.source-version"
hash -r 2>/dev/null
info "ClawGod uninstalled"
echo ""
warn " Restart your terminal or run: hash -r"
echo ""
exit 0
fi
# ─── Prerequisites ─────────────────────────────────────
if ! command -v node &>/dev/null; then
warn "Node.js is required (>= 18) for the patcher. Install from https://nodejs.org"
exit 1
fi
NODE_VERSION=$(node -e "console.log(process.versions.node.split('.')[0])")
if [ "$NODE_VERSION" -lt 18 ]; then
warn "Node.js >= 18 required (found v$NODE_VERSION)"
exit 1
fi
# ─── Ensure Bun (runtime that executes the patched cli.js) ─────────────
BUN_BIN=""
if command -v bun &>/dev/null; then
BUN_BIN=$(command -v bun)
elif [ -x "$HOME/.bun/bin/bun" ]; then
BUN_BIN="$HOME/.bun/bin/bun"
else
dim "Installing Bun (required runtime for v2.1.113+ cli.js) ..."
curl -fsSL https://bun.sh/install | bash >/dev/null 2>&1 || true
BUN_BIN="$HOME/.bun/bin/bun"
if [ ! -x "$BUN_BIN" ]; then
warn "Bun installation failed. Install manually: https://bun.sh/install"
exit 1
fi
fi
info "Bun: $($BUN_BIN --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.
# Bump MIN_BUN_VERSION when Anthropic moves the embedded Bun forward
# again (track via 'bun upgrade --canary' on a runner + smoke test).
MIN_BUN_VERSION="1.3.14"
BUN_VERSION_RAW=$($BUN_BIN --version 2>/dev/null | head -1)
BUN_VERSION_NUM=$(echo "$BUN_VERSION_RAW" | sed 's/-.*//')
if [ -z "$BUN_VERSION_NUM" ] \
|| [ "$(printf '%s\n%s\n' "$BUN_VERSION_NUM" "$MIN_BUN_VERSION" | sort -V | head -1)" != "$MIN_BUN_VERSION" ]; then
warn ""
warn "Bun ${BUN_VERSION_RAW:-<unknown>} is below the required minimum ($MIN_BUN_VERSION)."
warn ""
warn " Anthropic builds claude-code with Bun's canary channel. Older Bun"
warn " panics on cli.original.cjs with 'Expected CommonJS module to have"
warn " a function wrapper'. This is a hard requirement, not a warning."
warn ""
warn " Upgrade with one of:"
warn " bun upgrade --canary (if installed via curl/install.sh)"
warn " brew upgrade bun (homebrew)"
warn " scoop uninstall bun && \\ (scoop — shim blocks self-replace)"
warn " irm https://bun.sh/install.ps1 | iex && bun upgrade --canary"
warn ""
warn " Then re-run this installer."
exit 1
fi
# ─── ripgrep prerequisite (search/grep tool) ──────────────────────────
# Without rg the Grep tool inside Claude Code fails. Bun-bundled ripgrep
# is only reachable from inside the standalone executable; running the
# extracted cli.js under Bun runtime means we depend on system rg.
# This is a hard prerequisite — refuse to install otherwise.
if ! command -v rg &>/dev/null; then
warn "ripgrep (rg) is required but not found in PATH."
warn " Claude Code's Grep tool will not function without it."
warn ""
case "$(uname -s)" in
Darwin) warn " Install: brew install ripgrep" ;;
Linux) warn " Install: apt install ripgrep | dnf install ripgrep | pacman -S ripgrep" ;;
*) warn " Install: https://github.com/BurntSushi/ripgrep#installation" ;;
esac
warn ""
warn " Re-run this script after installing rg."
exit 1
fi
info "ripgrep: $(rg --version | head -1)"
# ─── Handle --no-upgrade (skip download, re-patch only) ──────────────
mkdir -p "$CLAWGOD_DIR" "$BIN_DIR"
if [ "$NO_UPGRADE" = "1" ]; then
if [ ! -f "$CLAWGOD_DIR/cli.original.cjs" ]; then
warn "--no-upgrade requires an existing installation."
warn "Run a full install first (without --no-upgrade)."
exit 1
fi
if [ -f "$CLAWGOD_DIR/cli.original.cjs.bak" ]; then
cp "$CLAWGOD_DIR/cli.original.cjs.bak" "$CLAWGOD_DIR/cli.original.cjs"
info "Restored clean cli.original.cjs from backup"
fi
info "Skipping download (--no-upgrade)"
else
# ─── Locate native Bun binary (cli.js source) ──────────────────────────
# v2.1.113+ ships a Bun standalone executable as the only canonical form.
# We extract cli.js text from this binary, patch it, then run via Bun
# runtime. Source: npm registry (@anthropic-ai/claude-code-<platform>).
# Local binary detection is intentionally skipped — see policy note below.
mkdir -p "$CLAWGOD_DIR" "$BIN_DIR"
NATIVE_BIN=""
NATIVE_BIN_LABEL=""
NATIVE_BIN_TMPDIR=""
# Detection policy: ALWAYS pull from the npm registry @latest.
#
# Earlier versions of this script also probed local `node_modules` roots
# (npm-global, bun-global) before falling back to the registry. That was
# a stale-source trap: once clawgod is installed it patches out
# `claude update`, so users never re-run `npm install -g` / `bun add -g`.
# Both directories freeze at whatever version was on disk the day clawgod
# was first installed, and `claude update` (which is now redirected here)
# would re-detect that 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, and npm's HTTP cache keeps repeats fast.
# Detect platform suffix (used by the npm fetch below)
case "$(uname -s)" in
Darwin) os="darwin" ;;
Linux) os="linux" ;;
*) os="" ;;
esac
case "$(uname -m)" in
arm64|aarch64) arch="arm64" ;;
x86_64|amd64) arch="x64" ;;
*) arch="" ;;
esac
if [ "$os" = "linux" ] && (ldd /bin/ls 2>/dev/null | grep -q musl); then
PLATFORM="${os}-${arch}-musl"
else
PLATFORM="${os}-${arch}"
fi
# Pull the Bun standalone binary from the npm registry. Anthropic publishes
# per-platform packages (e.g. claude-code-darwin-arm64); their tarball ships
# the binary directly under package/.
if [ -z "$NATIVE_BIN" ]; then
if ! command -v npm &>/dev/null; then
warn "No native Claude Code binary found locally, and npm is not installed."
warn " Either install the official binary first:"
warn " curl -fsSL https://claude.ai/install.sh | bash"
warn " or install npm so we can fetch it from the registry."
exit 1
fi
if [ -z "$os" ] || [ -z "$arch" ]; then
warn "Unsupported platform: $(uname -s) $(uname -m)"
exit 1
fi
NPM_PKG="@anthropic-ai/claude-code-${PLATFORM}"
dim "Fetching $NPM_PKG@$VERSION from npm registry ..."
NATIVE_BIN_TMPDIR=$(mktemp -d)
if ( cd "$NATIVE_BIN_TMPDIR" && npm pack "$NPM_PKG@$VERSION" --silent >/dev/null 2>&1 ); then
TARBALL=$(ls "$NATIVE_BIN_TMPDIR"/*.tgz 2>/dev/null | head -1)
if [ -n "$TARBALL" ]; then
( cd "$NATIVE_BIN_TMPDIR" && tar xzf "$TARBALL" )
cand="$NATIVE_BIN_TMPDIR/package/claude"
if [ -f "$cand" ]; then
sz=$(stat -f%z "$cand" 2>/dev/null || stat -c%s "$cand" 2>/dev/null || echo 0)
if [ "$sz" -gt 10000000 ]; then
NATIVE_BIN="$cand"
NATIVE_BIN_LABEL=$(node -e "console.log(require('$NATIVE_BIN_TMPDIR/package/package.json').version)" 2>/dev/null || echo "npm-latest")
fi
fi
fi
fi
if [ -z "$NATIVE_BIN" ]; then
rm -rf "$NATIVE_BIN_TMPDIR"
warn "Failed to download $NPM_PKG from npm."
warn " Install the official Claude Code binary manually:"
warn " curl -fsSL https://claude.ai/install.sh | bash"
exit 1
fi
info "Downloaded $NPM_PKG@$NATIVE_BIN_LABEL"
fi
if [ -z "$NATIVE_BIN" ]; then
warn "Native Claude Code binary not found"
warn "Install the official binary first:"
warn " curl -fsSL https://claude.ai/install.sh | bash"
warn "Then re-run this script."
exit 1
fi
# Write extractor to a temp file (used both for cli.js and .node modules)
cat > "$CLAWGOD_DIR/extract-natives.mjs" << 'EXTRACTOR_EOF'
#!/usr/bin/env node
/**
* ClawGod Bun section extractor
*
* Parses the .bun (PE/ELF) or __BUN,__bun (Mach-O) section embedded in a
* Bun standalone executable, walks the module graph, and extracts:
* - the entry-point module → <out>/cli.original.js
* - every loader=napi module → <out>/vendor/<name>/<arch>-<os>/<name>.node
*
* Everything else is dropped (e.g. auto-generated *.js napi shims aren't
* needed because cli.js already inlines the require('/$bunfs/root/X.node')
* calls that post-process.mjs rewrites to the vendor lookup).
*
* Adapted from /home/kaiju/code/python/parse-bun/main.js (which itself
* implements the format documented in docs/bun-section-format.md). Lazy
* Bun.file reads were replaced with readFileSync so the script runs under
* the existing `node` invocation in install.sh / install.ps1.
*
* Usage:
* node extract-natives.mjs <binary-path> <output-dir>
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { join, basename } from 'node:path';
// ─── Format constants ────────────────────────────────────────────────
const TRAILER = Buffer.from('\n---- Bun! ----\n');
const BUN_SECTION_NAME = '.bun';
const OFFSET_STRUCT_SIZE = 32;
const MODULE_RECORD_SIZE = 52;
// loader id → name (subset; only `napi` is acted on, rest informational)
const LOADERS = {
0:'jsx', 1:'js', 2:'ts', 3:'tsx', 4:'css', 5:'file', 6:'json', 7:'jsonc',
8:'toml', 9:'wasm', 10:'napi', 11:'base64', 12:'dataurl', 13:'text',
14:'bunsh', 15:'sqlite', 16:'sqlite_embedded', 17:'html', 18:'yaml',
19:'json5', 20:'md',
};
// ELF
const ELF_MAGIC_LE = 0x464c457f; // "\x7fELF" LE u32
const ELF_EI_CLASS = 0x04;
const ELF_EI_DATA = 0x05;
const ELF_CLASS_64 = 0x02;
const ELF_DATA_LE = 0x01;
const ELF_E_MACHINE = 0x12; // u16
const ELF_EHDR_SIZE = 0x40;
const ELF64_E_SHOFF = 0x28;
const ELF64_E_SHENTSIZE = 0x3a;
const ELF64_E_SHNUM = 0x3c;
const ELF64_E_SHSTRNDX = 0x3e;
const ELF64_SH_NAME = 0x00;
const ELF64_SH_OFFSET = 0x18;
const ELF64_SH_SIZE = 0x20;
const EM_X86_64 = 0x3e;
const EM_AARCH64 = 0xb7;
// Mach-O (thin LE 64-bit; fat / 32-bit / BE rejected with clear message)
const MH_MAGIC_64 = 0xfeedfacf;
const MH_CIGAM_64 = 0xcffaedfe;
const MH_MAGIC = 0xfeedface;
const MH_CIGAM = 0xcefaedfe;
const MACH_CPUTYPE_OFF = 0x04; // u32
const MACH_NCMDS_OFF = 0x10;
const MACH_SIZEOFCMDS_OFF = 0x14;
const MACH_HDR_SIZE_64 = 0x20;
const LC_SEGMENT_64 = 0x19;
const LC_CMDSIZE_OFF = 0x04;
const LC_SEGNAME_OFF = 0x08;
const LC_SEGNAME_LEN = 0x10;
const SEG64_NSECTS_OFF = 0x40;
const SEG64_SECTS_OFF = 0x48;
const SECT64_ENTRY_SIZE = 0x50;
const SECT64_SIZE_OFF = 0x28;
const SECT64_OFFSET_OFF = 0x30;
const CPU_TYPE_X86_64 = 0x01000007;
const CPU_TYPE_ARM64 = 0x0100000c;
// PE
const PE_OFFSET_PTR = 0x3c;
const PE_MACHINE_OFF = 0x04; // relative to PE sig
const PE_NUM_SECTIONS_OFF = 0x06;
const PE_OPT_HDR_SIZE_OFF = 0x14;
const PE_COFF_HDR_SIZE = 0x18;
const PE_OPT_MAGIC_OFF = 0x18;
const PE_OPT_MAGIC_PE32P = 0x20b;
const PE_SECTION_ENTRY_SIZE = 0x28;
const PE_SECT_RAW_SIZE_OFF = 0x10;
const PE_SECT_RAW_OFF_OFF = 0x14;
const PE_SECT_NAME_LEN = 0x08;
const IMAGE_MACHINE_AMD64 = 0x8664;
const IMAGE_MACHINE_ARM64 = 0xaa64;
// ─── Helpers ─────────────────────────────────────────────────────────
function die(msg) { throw new Error(`error: ${msg}`); }
function readU64LE(buf, off, what) {
const v = buf.readBigUInt64LE(off);
if (v > BigInt(Number.MAX_SAFE_INTEGER)) die(`${what} exceeds JS safe integer: ${v}`);
return Number(v);
}
function checkedSlice(buf, off, size, what) {
if (off < 0 || size < 0 || off + size > buf.length) {
die(`${what} out of bounds: offset=${off} size=${size} buf=${buf.length}`);
}
return buf.subarray(off, off + size);
}
function decodeName(buf) {
return buf.toString('utf8').replace(/\u0000+$/u, '');
}
// ─── Section locators (per format) ───────────────────────────────────
function findSectionElf(buf) {
if (buf.length < ELF_EHDR_SIZE) die('ELF too small');
if (buf[ELF_EI_CLASS] !== ELF_CLASS_64) die('ELF: only 64-bit supported');
if (buf[ELF_EI_DATA] !== ELF_DATA_LE) die('ELF: only little-endian supported');
const eMachine = buf.readUInt16LE(ELF_E_MACHINE);
const arch = eMachine === EM_X86_64 ? 'x64'
: eMachine === EM_AARCH64 ? 'arm64'
: die(`ELF: unsupported e_machine 0x${eMachine.toString(16)}`);
const shoff = readU64LE(buf, ELF64_E_SHOFF, 'ELF e_shoff');
const shentsize = buf.readUInt16LE(ELF64_E_SHENTSIZE);
const shnum = buf.readUInt16LE(ELF64_E_SHNUM);
const shstrndx = buf.readUInt16LE(ELF64_E_SHSTRNDX);
if (shstrndx >= shnum) die('ELF e_shstrndx out of range');
const shstrEntry = buf.subarray(shoff + shstrndx * shentsize, shoff + (shstrndx + 1) * shentsize);
const shstrOffset = readU64LE(shstrEntry, ELF64_SH_OFFSET, 'shstrtab offset');
const shstrSize = readU64LE(shstrEntry, ELF64_SH_SIZE, 'shstrtab size');
const shstr = checkedSlice(buf, shstrOffset, shstrSize, 'shstrtab');
let match = null;
for (let i = 0; i < shnum; i++) {
const entry = buf.subarray(shoff + i * shentsize, shoff + (i + 1) * shentsize);
const nameIdx = entry.readUInt32LE(ELF64_SH_NAME);
if (nameIdx >= shstr.length) continue;
let nameEnd = nameIdx;
while (nameEnd < shstr.length && shstr[nameEnd] !== 0) nameEnd++;
if (shstr.toString('ascii', nameIdx, nameEnd) !== BUN_SECTION_NAME) continue;
if (match) die('ELF has multiple .bun sections');
const rawOffset = readU64LE(entry, ELF64_SH_OFFSET, '.bun sh_offset');
const rawSize = readU64LE(entry, ELF64_SH_SIZE, '.bun sh_size');
if (rawOffset + rawSize > buf.length) die('.bun out of file bounds');
match = { format: 'ELF', os: 'linux', arch, rawOffset, rawSize };
}
if (!match) die('ELF has no .bun section');
return match;
}
function findSectionMacho(buf) {
if (buf.length < MACH_HDR_SIZE_64) die('Mach-O too small');
const cputype = buf.readUInt32LE(MACH_CPUTYPE_OFF);
const arch = cputype === CPU_TYPE_X86_64 ? 'x64'
: cputype === CPU_TYPE_ARM64 ? 'arm64'
: die(`Mach-O: unsupported cputype 0x${cputype.toString(16)}`);
const ncmds = buf.readUInt32LE(MACH_NCMDS_OFF);
const sizeofcmds = buf.readUInt32LE(MACH_SIZEOFCMDS_OFF);
if (sizeofcmds === 0 || MACH_HDR_SIZE_64 + sizeofcmds > buf.length) die('Mach-O sizeofcmds invalid');
const cmds = buf.subarray(MACH_HDR_SIZE_64, MACH_HDR_SIZE_64 + sizeofcmds);
let match = null;
let off = 0;
for (let i = 0; i < ncmds; i++) {
if (off + 8 > sizeofcmds) die(`Mach-O LC ${i} truncated`);
const cmd = cmds.readUInt32LE(off);
const cmdsize = cmds.readUInt32LE(off + LC_CMDSIZE_OFF);
if (cmdsize < 8 || off + cmdsize > sizeofcmds) die(`Mach-O LC ${i} cmdsize invalid: ${cmdsize}`);
if (cmd === LC_SEGMENT_64) {
const segname = cmds.toString('ascii', off + LC_SEGNAME_OFF, off + LC_SEGNAME_OFF + LC_SEGNAME_LEN).replace(/\0+$/, '');
if (segname === '__BUN') {
const nsects = cmds.readUInt32LE(off + SEG64_NSECTS_OFF);
if (SEG64_SECTS_OFF + nsects * SECT64_ENTRY_SIZE > cmdsize) die(`Mach-O LC_SEGMENT_64(__BUN) sections exceed cmdsize`);
for (let j = 0; j < nsects; j++) {
const s = off + SEG64_SECTS_OFF + j * SECT64_ENTRY_SIZE;
const sectname = cmds.toString('ascii', s, s + LC_SEGNAME_LEN).replace(/\0+$/, '');
if (sectname === '__bun') {
const rawSize = readU64LE(cmds, s + SECT64_SIZE_OFF, '__bun size');
const rawOffset = cmds.readUInt32LE(s + SECT64_OFFSET_OFF);
if (rawOffset + rawSize > buf.length) die('__bun out of file bounds');
if (match) die('Mach-O has multiple __BUN,__bun sections');
match = { format: 'Mach-O', os: 'darwin', arch, rawOffset, rawSize };
}
}
}
}
off += cmdsize;
}
if (!match) die('Mach-O has no __BUN,__bun section');
return match;
}
function findSectionPe(buf) {
if (buf.length < 0x40) die('PE too small');
if (buf.toString('ascii', 0, 2) !== 'MZ') die('PE missing MZ header');
const peOff = buf.readUInt32LE(PE_OFFSET_PTR);
if (buf.toString('ascii', peOff, peOff + 4) !== 'PE\0\0') die('PE missing PE signature');
const machine = buf.readUInt16LE(peOff + PE_MACHINE_OFF);
const arch = machine === IMAGE_MACHINE_AMD64 ? 'x64'
: machine === IMAGE_MACHINE_ARM64 ? 'arm64'
: die(`PE: unsupported machine 0x${machine.toString(16)}`);
const optMagic = buf.readUInt16LE(peOff + PE_OPT_MAGIC_OFF);
if (optMagic !== PE_OPT_MAGIC_PE32P) die(`PE: only 64-bit (PE32+) supported, got 0x${optMagic.toString(16)}`);
const numSect = buf.readUInt16LE(peOff + PE_NUM_SECTIONS_OFF);
const optHdrSize = buf.readUInt16LE(peOff + PE_OPT_HDR_SIZE_OFF);
const sectTable = peOff + PE_COFF_HDR_SIZE + optHdrSize;
let match = null;
for (let i = 0; i < numSect; i++) {
const entry = sectTable + i * PE_SECTION_ENTRY_SIZE;
const rawNm = buf.subarray(entry, entry + PE_SECT_NAME_LEN);
const nul = rawNm.indexOf(0);
const name = rawNm.subarray(0, nul === -1 ? rawNm.length : nul).toString('ascii');
if (name !== BUN_SECTION_NAME) continue;
if (match) die('PE has multiple .bun sections');
const rawSize = buf.readUInt32LE(entry + PE_SECT_RAW_SIZE_OFF);
const rawOffset = buf.readUInt32LE(entry + PE_SECT_RAW_OFF_OFF);
if (rawOffset + rawSize > buf.length) die('.bun out of file bounds');
match = { format: 'PE', os: 'win32', arch, rawOffset, rawSize };
}
if (!match) die('PE has no .bun section');
return match;
}
function findBunSection(buf) {
if (buf.length < 4) die('file too small');
const magic = buf.readUInt32LE(0);
if (magic === ELF_MAGIC_LE) return findSectionElf(buf);
if (magic === MH_MAGIC_64) return findSectionMacho(buf);
if (magic === MH_CIGAM_64 || magic === MH_CIGAM) die('Mach-O: only little-endian supported');
if (magic === MH_MAGIC) die('Mach-O: only 64-bit supported');
return findSectionPe(buf);
}
// ─── Payload + module records ────────────────────────────────────────
function parsePayload(sectionData) {
if (sectionData.length < 8) die('.bun too small for length prefix');
const payloadSize = readU64LE(sectionData, 0, '.bun payload length');
if (payloadSize + 8 > sectionData.length) die('.bun payload exceeds raw section');
const payload = sectionData.subarray(8, 8 + payloadSize);
if (payload.length < OFFSET_STRUCT_SIZE + TRAILER.length) die('.bun payload too small');
if (!payload.subarray(payload.length - TRAILER.length).equals(TRAILER)) die('.bun trailer mismatch');
return payload;
}
function parseOffsets(payload) {
const start = payload.length - TRAILER.length - OFFSET_STRUCT_SIZE;
return {
modules_offset: payload.readUInt32LE(start + 8),
modules_size: payload.readUInt32LE(start + 12),
entry_point_id: payload.readUInt32LE(start + 16),
};
}
function parseModules(payload, offsets) {
if (offsets.modules_size % MODULE_RECORD_SIZE !== 0) {
die(`modules table size not a multiple of ${MODULE_RECORD_SIZE}: ${offsets.modules_size}`);
}
const count = offsets.modules_size / MODULE_RECORD_SIZE;
if (offsets.entry_point_id >= count) die(`entry_point_id ${offsets.entry_point_id} >= ${count}`);
const table = checkedSlice(payload, offsets.modules_offset, offsets.modules_size, 'modules table');
const out = [];
for (let i = 0; i < count; i++) {
const rec = table.subarray(i * MODULE_RECORD_SIZE, (i + 1) * MODULE_RECORD_SIZE);
const nameOff = rec.readUInt32LE(0);
const nameSize = rec.readUInt32LE(4);
const contentOff = rec.readUInt32LE(8);
const contentSize= rec.readUInt32LE(12);
const loaderId = rec.readUInt8(49);
const name = decodeName(checkedSlice(payload, nameOff, nameSize, `module[${i}].name`));
const content = checkedSlice(payload, contentOff, contentSize, `module[${i}].content`);
out.push({
index: i,
entry: i === offsets.entry_point_id,
name,
content,
loader: LOADERS[loaderId] ?? `unknown(${loaderId})`,
});
}
return out;
}
// ─── Output dispatch ─────────────────────────────────────────────────
function napiBasename(name) {
// Bun records may use either '/' (POSIX builds) or '\\' (PE) as separator;
// always normalize so basename grabs the right tail.
const flat = name.replaceAll('\\', '/');
const tail = flat.split('/').pop() ?? '';
return tail.replace(/\.node$/i, '');
}
// ─── Main ────────────────────────────────────────────────────────────
function main() {
const [,, binaryPath, outputDir] = process.argv;
if (!binaryPath || !outputDir) {
console.error('Usage: extract-natives.mjs <binary-path> <output-dir>');
process.exit(1);
}
if (!existsSync(binaryPath)) {
console.error(`Binary not found: ${binaryPath}`);
process.exit(1);
}
const buf = readFileSync(binaryPath);
console.log(`Size: ${(buf.length / 1024 / 1024).toFixed(1)} MB`);
const section = findBunSection(buf);
console.log(`Format: ${section.format} (${section.arch}-${section.os})`);
const sectionData = checkedSlice(buf, section.rawOffset, section.rawSize, '.bun section');
const payload = parsePayload(sectionData);
const offsets = parseOffsets(payload);
const modules = parseModules(payload, offsets);
console.log(`Modules: ${modules.length} (entry id=${offsets.entry_point_id})`);
mkdirSync(outputDir, { recursive: true });
let cliCount = 0, napiCount = 0, dropped = 0;
for (const m of modules) {
if (m.entry) {
const out = join(outputDir, 'cli.original.js');
writeFileSync(out, m.content);
console.log(` cli.js ${(m.content.length / 1024 / 1024).toFixed(2)} MB → ${out} (${m.name})`);
cliCount++;
} else if (m.loader === 'napi') {
const base = napiBasename(m.name);
if (!base) { console.warn(` skip napi ${m.name}: empty basename`); dropped++; continue; }
const dir = join(outputDir, 'vendor', base, `${section.arch}-${section.os}`);
mkdirSync(dir, { recursive: true });
const out = join(dir, `${base}.node`);
writeFileSync(out, m.content);
console.log(` napi ${(m.content.length / 1024).toFixed(0).padStart(5)} KB → ${out}`);
napiCount++;
} else {
dropped++;
}
}
console.log(`Extracted: ${cliCount} cli.js + ${napiCount} napi (${dropped} dropped)`);
if (cliCount !== 1) {
console.error(`error: expected exactly 1 entry-point, got ${cliCount}`);
process.exit(2);
}
}
main();
EXTRACTOR_EOF
# ─── Extract cli.js + native modules from Bun binary ──────────
# Note: extract-natives.mjs and post-process.mjs are kept around (NOT deleted)
# so the wrapper's drift detector can re-run them when the user upgrades
# their native Claude binary.
# Single extractor pass: writes cli.original.js to $CLAWGOD_DIR and creates
# vendor/<name>/<arch>-<os>/<name>.node for every napi module in one go.
rm -rf "$CLAWGOD_DIR/vendor" "$CLAWGOD_DIR/cli.original.js" 2>/dev/null
dim "Extracting cli.js + napi modules from $(echo "$NATIVE_BIN_LABEL") ..."
if ! node "$CLAWGOD_DIR/extract-natives.mjs" "$NATIVE_BIN" "$CLAWGOD_DIR" 2>&1 | while IFS= read -r line; do echo " $line"; done; then
err "Failed to extract from native binary"
exit 1
fi
[ -f "$CLAWGOD_DIR/cli.original.js" ] || { err "cli.js missing after extraction"; exit 1; }
# ─── Post-process cli.js for Bun runtime ──────────────────────
# 0. Strip leading @bun pragma comments so Bun recognises the CJS wrapper
# 1. Rewrite /$bunfs/root/X.node paths to point at extracted vendor modules
# 2. Rewrite build-time /home/runner/.../*.ts URLs (used by ripgrep,
# sandbox, computer-use, etc. for asset resolution) to __filename so
# relative resolutions land near our cli.original.cjs
# 3. Wrap the Bun-cjs IIFE with an actual invocation so `require()` runs it
# 4. Save as .cjs (Bun + CJS module wrapper)
dim "Rewriting bunfs paths and IIFE invocation ..."
cat > "$CLAWGOD_DIR/post-process.mjs" << 'POSTPROC_EOF'
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');
// Strip leading @bun pragma comments (e.g. "// @bun @bytecode @bun-cjs\n")
// Bun requires the file to start directly with "(function" to recognize
// the CommonJS wrapper; any preceding comment breaks that detection.
code = code.replace(/^(?:\/\/[^\n]*\n)+/, '');
// (1) bunfs .node module paths → runtime vendor lookup
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')}))`,
);
// (2) build-time fileURLToPath() leaks → use cli.cjs's own __filename
code = code.replace(
/[\w$]+\.fileURLToPath\("file:\/\/\/home\/runner\/work\/claude-cli-internal\/claude-cli-internal\/[^"]*"\)/g,
() => '__filename',
);
// (3) make the outer (function(...){...}) actually run
code = code.replace(/\}\)\s*$/, '})(exports, require, module, __filename, __dirname)');
writeFileSync(dst, code);
unlinkSync(src);
console.log(`cli.original.cjs: ${code.length} bytes`);
POSTPROC_EOF
node "$CLAWGOD_DIR/post-process.mjs" 2>&1 | while IFS= read -r line; do echo " $line"; done
[ -f "$CLAWGOD_DIR/cli.original.cjs" ] || { err "Post-process failed"; exit 1; }
# Stamp the source version so the wrapper can detect drift on next launch
echo "$NATIVE_BIN_LABEL" > "$CLAWGOD_DIR/.source-version"
# If we pulled the binary from npm into a tmpdir, clean it up now —
# extraction is done, drift detection only consults ~/.local/share/claude/versions/.
if [ -n "$NATIVE_BIN_TMPDIR" ]; then
rm -rf "$NATIVE_BIN_TMPDIR"
fi
info "cli.original.cjs ready ($NATIVE_BIN_LABEL)"
fi # end --no-upgrade skip
# ─── Write re-patch helper (used by wrapper on version drift) ─────────
cat > "$CLAWGOD_DIR/repatch.mjs" << 'REPATCH_EOF'
#!/usr/bin/env bun
// Re-extract + post-process + patch the user's currently-installed
// native Claude binary. Invoked by cli.cjs when it detects that
// .source-version no longer matches the latest binary in versions/.
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);
}
rmSync(join(here, 'vendor'), { recursive: true, force: true });
rmSync(join(here, 'cli.original.js'), { force: 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', [extractor, nativeBin, here]);
run('post-process', [postProc]);
run('patcher', [patcher]);
writeFileSync(join(here, '.source-version'), basename(nativeBin) + '\n');
console.log(`[clawgod] re-patched to ${basename(nativeBin)}`);
REPATCH_EOF
chmod +x "$CLAWGOD_DIR/repatch.mjs"
info "Re-patch helper installed (repatch.mjs)"
# ─── Write OpenAI-compatible proxy ────────────────────────────
cat > "$CLAWGOD_DIR/openai-proxy.cjs" << 'PROXY_EOF'
'use strict';
// Anthropic Messages API <-> OpenAI Chat Completions API translation proxy
// Allows Claude Code to use xAI/Grok and other OpenAI-compatible APIs
function translateSystem(system) {
if (!system) return [];
if (typeof system === 'string') return [{ role: 'system', content: system }];
if (Array.isArray(system)) {
var text = system.filter(function (b) { return b.type === 'text'; }).map(function (b) { return b.text; }).join('\n');
return text ? [{ role: 'system', content: text }] : [];
}
return [];
}
function translateMessages(msgs) {
var out = [];
for (var i = 0; i < msgs.length; i++) {
var msg = msgs[i];
if (msg.role === 'user') {
if (typeof msg.content === 'string') { out.push({ role: 'user', content: msg.content }); continue; }
if (!Array.isArray(msg.content)) continue;
var toolResults = [], otherBlocks = [];
for (var j = 0; j < msg.content.length; j++) {
if (msg.content[j].type === 'tool_result') toolResults.push(msg.content[j]);
else otherBlocks.push(msg.content[j]);
}
for (var k = 0; k < toolResults.length; k++) {
var tr = toolResults[k], content = '';
if (typeof tr.content === 'string') content = tr.content;
else if (Array.isArray(tr.content)) content = tr.content.filter(function (b) { return b.type === 'text'; }).map(function (b) { return b.text; }).join('\n');
if (tr.is_error) content = '[ERROR] ' + content;
out.push({ role: 'tool', tool_call_id: tr.tool_use_id, content: content || '' });
}
if (otherBlocks.length > 0) {
var parts = [];
for (var l = 0; l < otherBlocks.length; l++) {
var block = otherBlocks[l];
if (block.type === 'text') parts.push({ type: 'text', text: block.text });
else if (block.type === 'image') {
var url = block.source.type === 'base64' ? 'data:' + block.source.media_type + ';base64,' + block.source.data : block.source.url;
parts.push({ type: 'image_url', image_url: { url: url } });
}
}
if (parts.length === 1 && parts[0].type === 'text') out.push({ role: 'user', content: parts[0].text });
else if (parts.length > 0) out.push({ role: 'user', content: parts });
}
} else if (msg.role === 'assistant') {
if (typeof msg.content === 'string') { out.push({ role: 'assistant', content: msg.content }); continue; }
if (!Array.isArray(msg.content)) continue;
var textContent = '', toolCalls = [];
for (var m = 0; m < msg.content.length; m++) {
var b = msg.content[m];
if (b.type === 'text') textContent += b.text;
else if (b.type === 'tool_use') toolCalls.push({ id: b.id, type: 'function', function: { name: b.name, arguments: typeof b.input === 'string' ? b.input : JSON.stringify(b.input) } });
}
var assistantMsg = { role: 'assistant', content: textContent || null };
if (toolCalls.length > 0) assistantMsg.tool_calls = toolCalls;
out.push(assistantMsg);
}
}
return out;
}
function translateTools(tools) {
if (!tools || tools.length === 0) return undefined;
return tools.map(function (t) {
return { type: 'function', function: { name: t.name, description: t.description || '', parameters: t.input_schema || { type: 'object', properties: {} } } };
});
}
function stripCacheControl(obj) {
if (!obj || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(stripCacheControl);
var out = {};
for (var key in obj) { if (key === 'cache_control') continue; out[key] = stripCacheControl(obj[key]); }
return out;
}
function translateRequest(body) {
var cleaned = stripCacheControl(body);
var systemMsgs = translateSystem(cleaned.system);
var userMsgs = translateMessages(cleaned.messages || []);
var openaiBody = { model: cleaned.model, messages: systemMsgs.concat(userMsgs), stream: !!cleaned.stream };
if (cleaned.max_tokens) openaiBody.max_tokens = cleaned.max_tokens;
if (cleaned.temperature !== undefined) openaiBody.temperature = cleaned.temperature;
if (cleaned.top_p !== undefined) openaiBody.top_p = cleaned.top_p;
if (cleaned.stop_sequences) openaiBody.stop = cleaned.stop_sequences;
var tools = translateTools(cleaned.tools);
if (tools) openaiBody.tools = tools;
if (cleaned.stream) openaiBody.stream_options = { include_usage: true };
return openaiBody;
}
function mapFinishReason(reason) {
if (reason === 'stop') return 'end_turn';
if (reason === 'tool_calls') return 'tool_use';
if (reason === 'length') return 'max_tokens';
return 'end_turn';
}
function translateResponse(openaiResp, requestModel) {
var choice = openaiResp.choices && openaiResp.choices[0];
if (!choice) return { id: 'msg_proxy_error', type: 'message', role: 'assistant', content: [{ type: 'text', text: 'No response from upstream API' }], model: requestModel, stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } };
var content = [];
if (choice.message.content) content.push({ type: 'text', text: choice.message.content });
if (choice.message.tool_calls) {
for (var i = 0; i < choice.message.tool_calls.length; i++) {
var tc = choice.message.tool_calls[i], input = {};
try { input = JSON.parse(tc.function.arguments || '{}'); } catch (e) {}
content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input: input });
}
}
if (content.length === 0) content.push({ type: 'text', text: '' });
return { id: openaiResp.id || ('msg_' + Date.now()), type: 'message', role: 'assistant', content: content, model: requestModel || openaiResp.model, stop_reason: mapFinishReason(choice.finish_reason), stop_sequence: null, usage: { input_tokens: (openaiResp.usage && openaiResp.usage.prompt_tokens) || 0, output_tokens: (openaiResp.usage && openaiResp.usage.completion_tokens) || 0 } };
}
function sse(event, data) { return 'event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n'; }
function createStreamTranslator(requestModel) {
var state = { model: requestModel, blockIndex: 0, sentStart: false, inText: false, tcBufs: {}, inTok: 0, outTok: 0, msgId: 'msg_' + Date.now() };
return function (chunk) {
var events = [];
if (!state.sentStart) {
state.sentStart = true;
if (chunk.id) state.msgId = chunk.id;
events.push(sse('message_start', { type: 'message_start', message: { id: state.msgId, type: 'message', role: 'assistant', content: [], model: state.model || chunk.model, stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } }));
events.push(sse('ping', { type: 'ping' }));
}
var choice = chunk.choices && chunk.choices[0];
if (!choice) { if (chunk.usage) { state.inTok = chunk.usage.prompt_tokens || 0; state.outTok = chunk.usage.completion_tokens || 0; } return events; }
var delta = choice.delta || {};
if (delta.content) {
if (!state.inText) { state.inText = true; events.push(sse('content_block_start', { type: 'content_block_start', index: state.blockIndex, content_block: { type: 'text', text: '' } })); }
events.push(sse('content_block_delta', { type: 'content_block_delta', index: state.blockIndex, delta: { type: 'text_delta', text: delta.content } }));
}
if (delta.tool_calls) {
if (state.inText) { events.push(sse('content_block_stop', { type: 'content_block_stop', index: state.blockIndex })); state.blockIndex++; state.inText = false; }
for (var i = 0; i < delta.tool_calls.length; i++) {
var tc = delta.tool_calls[i], idx = tc.index;
if (!state.tcBufs[idx]) {
var tcId = tc.id || ('toolu_' + Date.now() + '_' + idx), tcName = (tc.function && tc.function.name) || '';
state.tcBufs[idx] = { id: tcId, name: tcName, bi: state.blockIndex };
events.push(sse('content_block_start', { type: 'content_block_start', index: state.blockIndex, content_block: { type: 'tool_use', id: tcId, name: tcName, input: {} } }));
state.blockIndex++;
}
var buf = state.tcBufs[idx];
if (tc.function && tc.function.name) buf.name = tc.function.name;
if (tc.function && tc.function.arguments) {
events.push(sse('content_block_delta', { type: 'content_block_delta', index: buf.bi, delta: { type: 'input_json_delta', partial_json: tc.function.arguments } }));
}
}
}
if (choice.finish_reason) {
if (state.inText) { events.push(sse('content_block_stop', { type: 'content_block_stop', index: state.blockIndex })); state.inText = false; }
for (var key in state.tcBufs) events.push(sse('content_block_stop', { type: 'content_block_stop', index: state.tcBufs[key].bi }));
events.push(sse('message_delta', { type: 'message_delta', delta: { stop_reason: mapFinishReason(choice.finish_reason), stop_sequence: null }, usage: { output_tokens: state.outTok } }));
events.push(sse('message_stop', { type: 'message_stop' }));
}
return events;
};
}
function parseSSELines(text) {
var chunks = [], lines = text.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (!line.startsWith('data: ')) continue;
var payload = line.substring(6);
if (payload === '[DONE]') { chunks.push(null); continue; }
try { chunks.push(JSON.parse(payload)); } catch (e) {}
}
return chunks;
}
function startProxy(config) {
var upstreamURL = (config.baseURL || 'https://api.x.ai/v1').replace(/\/+$/, '');
var upstreamKey = config.apiKey;
var server = Bun.serve({
port: 0, hostname: '127.0.0.1', idleTimeout: 255,
fetch: async function (req) {
var url = new URL(req.url);
if (req.method === 'GET' && url.pathname === '/health') return new Response('ok');
if (req.method !== 'POST' || !url.pathname.endsWith('/messages'))
return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'Content-Type': 'application/json' } });
var body;
try { body = await req.json(); } catch (e) {
return new Response(JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: 'Invalid JSON' } }), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
var requestModel = body.model || config.model || '';
var isStream = !!body.stream;
var openaiBody;
try { openaiBody = translateRequest(body); } catch (e) {
return new Response(JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: 'Translation error: ' + e.message } }), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
var upstreamResp;
try {
upstreamResp = await fetch(upstreamURL + '/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + upstreamKey },
body: JSON.stringify(openaiBody),
});
} catch (e) {
return new Response(JSON.stringify({ type: 'error', error: { type: 'api_error', message: 'Upstream connection failed: ' + e.message } }), { status: 502, headers: { 'Content-Type': 'application/json' } });
}
if (!upstreamResp.ok && !isStream) {
var errText = await upstreamResp.text().catch(function () { return ''; });
var errBody; try { errBody = JSON.parse(errText); } catch (e) { errBody = null; }
return new Response(JSON.stringify({ type: 'error', error: { type: upstreamResp.status === 429 ? 'rate_limit_error' : 'api_error', message: (errBody && errBody.error && errBody.error.message) || errText || ('HTTP ' + upstreamResp.status) } }), { status: upstreamResp.status, headers: { 'Content-Type': 'application/json' } });
}
if (!isStream) {
var result; try { result = await upstreamResp.json(); } catch (e) {
return new Response(JSON.stringify({ type: 'error', error: { type: 'api_error', message: 'Invalid upstream response' } }), { status: 502, headers: { 'Content-Type': 'application/json' } });
}
return new Response(JSON.stringify(translateResponse(result, requestModel)), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
var translator = createStreamTranslator(requestModel);
var upstreamBody = upstreamResp.body;
var readable = new ReadableStream({
async start(controller) {
var encoder = new TextEncoder(), decoder = new TextDecoder(), buffer = '';
try {
var reader = upstreamBody.getReader();
while (true) {
var r = await reader.read();
if (r.done) break;
buffer += decoder.decode(r.value, { stream: true });
var boundary = buffer.lastIndexOf('\n');
if (boundary === -1) continue;
var complete = buffer.substring(0, boundary + 1);
buffer = buffer.substring(boundary + 1);
var chunks = parseSSELines(complete);
for (var ci = 0; ci < chunks.length; ci++) {