-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathmain.go
More file actions
1318 lines (1180 loc) · 40.8 KB
/
Copy pathmain.go
File metadata and controls
1318 lines (1180 loc) · 40.8 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
// Bundler downloads Copilot CLI binaries and packages them as a binary file,
// along with a Go source file that embeds the binary and metadata.
//
// Usage:
//
// go run github.com/github/copilot-sdk/go/cmd/bundler [--platform GOOS/GOARCH] [--output DIR] [--cli-version VERSION] [--check-only]
//
// --platform: Target platform using Go conventions (linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64, windows/arm64). Defaults to current platform.
// --output: Output directory for embedded artifacts. Defaults to the current directory.
// --cli-version: CLI version to download. If not specified, automatically detects from the copilot-sdk version in go.mod.
// --check-only: Check that embedded CLI version matches the detected version from package.json without downloading. Exits with error if versions don't match.
package main
import (
"archive/tar"
"compress/gzip"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"go/build"
"go/parser"
"go/token"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/klauspost/compress/zstd"
)
const (
// Keep these URLs centralized so reviewers can verify all outbound calls in one place.
sdkModule = "github.com/github/copilot-sdk/go"
packageJSONURLFmt = "https://raw.githubusercontent.com/github/copilot-sdk/%s/nodejs/package.json"
packageLockURLFmt = "https://raw.githubusercontent.com/github/copilot-sdk/%s/nodejs/package-lock.json"
defaultCLIDownloadBaseURL = "https://github.com/github/copilot-cli/releases/download"
cliDownloadBaseURLEnvironment = "COPILOT_CLI_DOWNLOAD_BASE_URL"
defaultPackageName = "main"
)
// Platform info: release asset platform suffix, binary name
type platformInfo struct {
runtimePlatform string
binaryName string
}
// Map from GOOS/GOARCH to release asset platform info.
var platforms = map[string]platformInfo{
"linux/amd64": {runtimePlatform: "linux-x64", binaryName: "copilot"},
"linux/arm64": {runtimePlatform: "linux-arm64", binaryName: "copilot"},
"darwin/amd64": {runtimePlatform: "darwin-x64", binaryName: "copilot"},
"darwin/arm64": {runtimePlatform: "darwin-arm64", binaryName: "copilot"},
"windows/amd64": {runtimePlatform: "win32-x64", binaryName: "copilot.exe"},
"windows/arm64": {runtimePlatform: "win32-arm64", binaryName: "copilot.exe"},
}
// main is the CLI entry point.
func main() {
platform := flag.String("platform", runtime.GOOS+"/"+runtime.GOARCH, "Target platform as GOOS/GOARCH (e.g. linux/amd64, darwin/arm64), defaults to current platform")
output := flag.String("output", "", "Output directory for embedded artifacts. Defaults to the current directory")
cliVersion := flag.String("cli-version", "", "CLI version to download (auto-detected from go.mod if not specified)")
checkOnly := flag.Bool("check-only", false, "Check that embedded CLI version matches the detected version from go.mod without downloading or updating the embedded files. Exits with error if versions don't match.")
flag.Parse()
// Resolve version first so the default output name can include it.
version := resolveCLIVersion(*cliVersion)
// Resolve platform once to validate input and get the release asset mapping.
goos, goarch, info, err := resolvePlatform(*platform)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
fmt.Fprintf(os.Stderr, "Valid platforms: %s\n", strings.Join(validPlatforms(), ", "))
os.Exit(1)
}
outputPath := filepath.Join(*output, defaultOutputFileName(version, goos, goarch, info.binaryName))
if *checkOnly {
fmt.Printf("Check only: detected CLI version %s from go.mod\n", version)
fmt.Printf("Check only: verifying embedded version for %s\n", *platform)
// Check if existing embedded version matches
if err := checkEmbeddedVersion(version, goos, goarch, *output); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println("Check only: embedded version matches detected version")
return
}
pkgName, err := detectPackageName(*output, goos, goarch)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to detect package name: %v; using package %s\n", err, pkgName)
}
fmt.Printf("Building bundle for %s (CLI version %s)\n", *platform, version)
bundle, err := buildBundle(info, version, outputPath, goos, true)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
var muslBundle bundleArtifacts
if goos == "linux" {
muslInfo := platformInfo{
runtimePlatform: strings.Replace(info.runtimePlatform, "linux-", "linuxmusl-", 1),
binaryName: info.binaryName,
}
muslOutputPath := filepath.Join(*output, defaultOutputFileName(version, "linuxmusl", goarch, info.binaryName))
muslBundle, err = buildBundle(
muslInfo,
version,
muslOutputPath,
goos,
false,
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// Generate the Go file with embed directive
if err := generateGoFile(
goos,
goarch,
bundle.binaryPath,
version,
bundle.binaryHash,
bundle.runtimeArtifactPath,
bundle.runtimeHash,
bundle.wrapperArtifactPath,
bundle.wrapperHash,
bundle.assetsArtifactPath,
bundle.assetsHash,
muslBundle.binaryPath,
muslBundle.binaryHash,
muslBundle.runtimeArtifactPath,
muslBundle.runtimeHash,
muslBundle.wrapperArtifactPath,
muslBundle.wrapperHash,
muslBundle.assetsArtifactPath,
muslBundle.assetsHash,
pkgName,
); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := ensureZstdDependency(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// resolvePlatform validates the platform flag and returns GOOS/GOARCH and mapping info.
func resolvePlatform(platform string) (string, string, platformInfo, error) {
goos, goarch, ok := strings.Cut(platform, "/")
if !ok || goos == "" || goarch == "" {
return "", "", platformInfo{}, fmt.Errorf("invalid platform %q", platform)
}
info, ok := platforms[platform]
if !ok {
return "", "", platformInfo{}, fmt.Errorf("invalid platform %q", platform)
}
return goos, goarch, info, nil
}
// resolveCLIVersion determines the CLI version from the flag or repo metadata.
func resolveCLIVersion(flagValue string) string {
if flagValue != "" {
return flagValue
}
version, err := detectCLIVersion()
if err != nil {
fmt.Fprintf(os.Stderr, "Error detecting CLI version: %v\n", err)
fmt.Fprintln(os.Stderr, "Hint: specify --cli-version explicitly, or run from a Go module that depends on github.com/github/copilot-sdk/go")
os.Exit(1)
}
fmt.Printf("Auto-detected CLI version: %s\n", version)
return version
}
// defaultOutputFileName builds the default bundle filename for a platform.
func defaultOutputFileName(version, goos, goarch, binaryName string) string {
base := strings.TrimSuffix(binaryName, filepath.Ext(binaryName))
ext := filepath.Ext(binaryName)
return fmt.Sprintf("z%s_%s_%s_%s%s.zst", base, version, goos, goarch, ext)
}
// validPlatforms returns valid platform keys for error messages.
func validPlatforms() []string {
result := make([]string, 0, len(platforms))
for p := range platforms {
result = append(result, p)
}
return result
}
// detectPackageName reads package clauses from files that match the target
// platform and build constraints. It returns defaultPackageName with an error
// when detection fails.
func detectPackageName(dir, goos, goarch string) (string, error) {
if dir == "" {
dir = "."
}
entries, err := os.ReadDir(dir)
if err != nil {
return defaultPackageName, fmt.Errorf("failed to read package directory %q: %w", dir, err)
}
buildContext := build.Default
buildContext.GOOS = goos
buildContext.GOARCH = goarch
packageName := ""
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() || !strings.HasSuffix(name, ".go") ||
strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") ||
strings.HasSuffix(name, "_test.go") || strings.HasPrefix(name, "zcopilot_") {
continue
}
matches, err := buildContext.MatchFile(dir, name)
if err != nil {
return defaultPackageName, fmt.Errorf("failed to evaluate build constraints in %q: %w", filepath.Join(dir, name), err)
}
if !matches {
continue
}
path := filepath.Join(dir, name)
file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.PackageClauseOnly)
if err != nil {
return defaultPackageName, fmt.Errorf("failed to parse package clause in %q: %w", path, err)
}
if packageName == "" {
packageName = file.Name.Name
continue
}
if packageName != file.Name.Name {
return defaultPackageName, fmt.Errorf("multiple packages %q and %q found in %q", packageName, file.Name.Name, dir)
}
}
if packageName == "" {
return defaultPackageName, fmt.Errorf("no Go package found in %q", dir)
}
return packageName, nil
}
// detectCLIVersion detects the CLI version by:
// 1. Running "go list -m" to get the copilot-sdk version from the user's go.mod
// 2. Fetching package.json from the SDK repo at that version
// 3. Extracting the pinned Copilot CLI version from it
func detectCLIVersion() (string, error) {
// Get the SDK version from the user's go.mod
sdkVersion, err := getSDKVersion()
if err != nil {
return "", fmt.Errorf("failed to get SDK version: %w", err)
}
fmt.Printf("Found copilot-sdk %s in go.mod\n", sdkVersion)
// Fetch package.json from the SDK repo at that version
cliVersion, err := fetchCLIVersionFromRepo(sdkVersion)
if err != nil {
return "", fmt.Errorf("failed to fetch CLI version: %w", err)
}
return cliVersion, nil
}
// getSDKVersion runs "go list -m" to get the copilot-sdk version from go.mod
func getSDKVersion() (string, error) {
cmd := exec.Command("go", "list", "-m", "-f", "{{.Version}}", sdkModule)
output, err := cmd.Output()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
return "", fmt.Errorf("go list failed: %s", string(exitErr.Stderr))
}
return "", err
}
version := strings.TrimSpace(string(output))
if version == "" {
return "", fmt.Errorf("module %s not found in go.mod", sdkModule)
}
return version, nil
}
// fetchCLIVersionFromRepo fetches package.json from GitHub and extracts the CLI version.
func fetchCLIVersionFromRepo(sdkVersion string) (string, error) {
// Convert Go module version to Git ref
// v0.1.0 -> v0.1.0
// v0.1.0-beta.1 -> v0.1.0-beta.1
// v0.0.0-20240101120000-abcdef123456 -> abcdef123456 (pseudo-version)
gitRef := sdkVersion
// Pseudo-versions end with a 12-character commit hash.
// Format: vX.Y.Z-yyyymmddhhmmss-abcdefabcdef
if idx := strings.LastIndex(sdkVersion, "-"); idx != -1 {
suffix := sdkVersion[idx+1:]
// Use the commit hash when present so we fetch the exact source snapshot.
if len(suffix) == 12 && isHex(suffix) {
gitRef = suffix
}
}
url := fmt.Sprintf(packageJSONURLFmt, gitRef)
fmt.Printf("Fetching %s...\n", url)
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("failed to fetch: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch package.json: %s", resp.Status)
}
var packageJSON struct {
CopilotCLIVersion string `json:"copilotCliVersion"`
}
if err := json.NewDecoder(resp.Body).Decode(&packageJSON); err != nil {
return "", fmt.Errorf("failed to parse package.json: %w", err)
}
if packageJSON.CopilotCLIVersion == "" {
return fetchLegacyCLIVersionFromRepo(gitRef)
}
return packageJSON.CopilotCLIVersion, nil
}
func fetchLegacyCLIVersionFromRepo(gitRef string) (string, error) {
url := fmt.Sprintf(packageLockURLFmt, gitRef)
fmt.Printf("Falling back to %s...\n", url)
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("failed to fetch legacy package-lock.json: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch legacy package-lock.json: %s", resp.Status)
}
var packageLock struct {
Packages map[string]struct {
Version string `json:"version"`
} `json:"packages"`
}
if err := json.NewDecoder(resp.Body).Decode(&packageLock); err != nil {
return "", fmt.Errorf("failed to parse legacy package-lock.json: %w", err)
}
pkg, ok := packageLock.Packages["node_modules/@github/copilot"]
if !ok || pkg.Version == "" {
return "", fmt.Errorf("could not find copilotCliVersion in package.json or @github/copilot in package-lock.json")
}
return pkg.Version, nil
}
// isHex returns true if s contains only hexadecimal characters.
func isHex(s string) bool {
for _, c := range s {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
return false
}
}
return true
}
type bundleArtifacts struct {
binaryPath string
binaryHash []byte
runtimeArtifactPath string
runtimeHash []byte
wrapperArtifactPath string
wrapperHash []byte
assetsArtifactPath string
assetsHash []byte
}
// buildBundle downloads the CLI and native runtime artifacts from one release package.
func buildBundle(info platformInfo, cliVersion, outputPath, goos string, includeLicense bool) (bundleArtifacts, error) {
outputDir := filepath.Dir(outputPath)
if outputDir == "" {
outputDir = "."
}
runtimeArtifactPath := filepath.Join(outputDir, runtimeLibArtifactName(cliVersion, info.runtimePlatform, goos))
wrapperArtifactPath := filepath.Join(outputDir, runtimeWrapperArtifactName(cliVersion, info.runtimePlatform, info.binaryName))
assetsArtifactPath := filepath.Join(outputDir, runtimeAssetsArtifactName(cliVersion, info.runtimePlatform))
requiredPaths := []string{outputPath, runtimeArtifactPath, wrapperArtifactPath, assetsArtifactPath}
if includeLicense {
requiredPaths = append(requiredPaths, licensePathForOutput(outputPath))
}
if filesExist(requiredPaths...) {
// Idempotent output avoids re-downloading in CI or local rebuilds.
fmt.Printf("Output runtime bundle for %s already exists, skipping download\n", info.runtimePlatform)
binaryHash, err := sha256FileFromCompressed(outputPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash existing output: %w", err)
}
runtimeHash, err := sha256FileFromCompressed(runtimeArtifactPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash existing runtime.node: %w", err)
}
wrapperHash, err := sha256FileFromCompressed(wrapperArtifactPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash existing runtime wrapper: %w", err)
}
assetsHash, err := sha256File(assetsArtifactPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash existing runtime assets: %w", err)
}
return bundleArtifacts{outputPath, binaryHash, runtimeArtifactPath, runtimeHash, wrapperArtifactPath, wrapperHash, assetsArtifactPath, assetsHash}, nil
}
// Create temp directory for download
tempDir, err := os.MkdirTemp("", "copilot-bundler-*")
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to create temp dir: %w", err)
}
defer os.RemoveAll(tempDir)
binaryPath, tarballPath, err := downloadCLIBinary(info.runtimePlatform, info.binaryName, cliVersion, tempDir)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to download CLI binary: %w", err)
}
if outputDir != "." {
if err := os.MkdirAll(outputDir, 0755); err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to create output directory: %w", err)
}
}
if includeLicense {
if err := extractCLILicense(tarballPath, outputPath); err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to extract CLI license: %w", err)
}
}
binaryHash, err := sha256File(binaryPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash output binary: %w", err)
}
if err := compressZstdFile(binaryPath, outputPath); err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to write output binary: %w", err)
}
rawLibPath := filepath.Join(tempDir, "runtime.node")
if err := extractFileFromTarball(
tarballPath,
tempDir,
"package/prebuilds/"+info.runtimePlatform+"/runtime.node",
"runtime.node",
); err != nil {
return bundleArtifacts{}, fmt.Errorf("runtime package is missing prebuilds/%s/runtime.node: %w", info.runtimePlatform, err)
}
runtimeHash, err := sha256File(rawLibPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash runtime.node: %w", err)
}
if err := compressZstdFile(rawLibPath, runtimeArtifactPath); err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to write runtime.node: %w", err)
}
wrapperName := runtimeWrapperName(info.binaryName)
rawWrapperPath := filepath.Join(tempDir, wrapperName)
if err := extractFileFromTarball(
tarballPath,
tempDir,
"package/prebuilds/"+info.runtimePlatform+"/"+wrapperName,
wrapperName,
); err != nil {
return bundleArtifacts{}, fmt.Errorf("runtime package is missing prebuilds/%s/%s: %w", info.runtimePlatform, wrapperName, err)
}
wrapperHash, err := sha256File(rawWrapperPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash runtime wrapper: %w", err)
}
if err := compressZstdFile(rawWrapperPath, wrapperArtifactPath); err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to write runtime wrapper: %w", err)
}
if err := createRuntimeAssetsArchive(tarballPath, assetsArtifactPath, info); err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to write runtime assets: %w", err)
}
assetsHash, err := sha256File(assetsArtifactPath)
if err != nil {
return bundleArtifacts{}, fmt.Errorf("failed to hash runtime assets: %w", err)
}
fmt.Printf("Successfully created %s\n", outputPath)
fmt.Printf("Successfully created %s\n", runtimeArtifactPath)
fmt.Printf("Successfully created %s\n", wrapperArtifactPath)
fmt.Printf("Successfully created %s\n", assetsArtifactPath)
return bundleArtifacts{outputPath, binaryHash, runtimeArtifactPath, runtimeHash, wrapperArtifactPath, wrapperHash, assetsArtifactPath, assetsHash}, nil
}
func filesExist(paths ...string) bool {
for _, path := range paths {
if _, err := os.Stat(path); err != nil {
return false
}
}
return true
}
// runtimeLibArtifactName builds the compressed runtime-library artifact filename.
func runtimeLibArtifactName(version, runtimePlatform, goos string) string {
return fmt.Sprintf("zcopilotruntime_%s_%s.%s.zst", version, runtimePlatform, runtimeLibExt(goos))
}
func runtimeWrapperArtifactName(version, runtimePlatform, binaryName string) string {
return fmt.Sprintf("zcopilotruntimewrapper_%s_%s_%s.zst", version, runtimePlatform, runtimeWrapperName(binaryName))
}
func runtimeAssetsArtifactName(version, runtimePlatform string) string {
return fmt.Sprintf("zcopilotruntimeassets_%s_%s.tgz", version, runtimePlatform)
}
func runtimeWrapperName(binaryName string) string {
if filepath.Ext(binaryName) == ".exe" {
return "copilot-runtime.exe"
}
return "copilot-runtime"
}
var hostlessExcludedTopLevel = map[string]bool{
"app.js": true, "assets": true, "changelog.json": true, "copilot": true, "copilot.exe": true,
"foundry-local-sdk": true, "index.js": true, "napi-oop-runtime": true, "LICENSE.md": true,
"npm-loader.js": true, "package.json": true, "pvrecorder": true, "queries": true, "README.md": true,
"sea-loader.js": true, "webview": true,
}
func hostlessRuntimePath(name, runtimePlatform, wrapperName string) (string, bool) {
relative, ok := strings.CutPrefix(name, "package/")
if !ok {
return "", false
}
parts := strings.Split(relative, "/")
topLevel := parts[0]
fileName := parts[len(parts)-1]
if hostlessExcludedTopLevel[topLevel] ||
(strings.HasPrefix(topLevel, "tree-sitter") && strings.HasSuffix(topLevel, ".wasm")) ||
(strings.HasPrefix(topLevel, "voice-") && strings.HasSuffix(topLevel, ".js")) ||
fileName == "cli-native.node" || fileName == "runtime.node" || fileName == wrapperName ||
strings.HasPrefix(fileName, "copilot-runtime-bin") {
return "", false
}
for _, part := range parts {
if part == "mediaremote-adapter" {
return "", false
}
}
if topLevel == "prebuilds" {
if len(parts) < 3 || parts[1] != runtimePlatform {
return "", false
}
return strings.Join(parts[2:], "/"), true
}
return relative, true
}
func createRuntimeAssetsArchive(tarballPath, outputPath string, info platformInfo) error {
sourceFile, err := os.Open(tarballPath)
if err != nil {
return err
}
defer sourceFile.Close()
gzipReader, err := gzip.NewReader(sourceFile)
if err != nil {
return err
}
defer gzipReader.Close()
outputFile, err := os.Create(outputPath)
if err != nil {
return err
}
defer outputFile.Close()
gzipWriter := gzip.NewWriter(outputFile)
tarWriter := tar.NewWriter(gzipWriter)
count := 0
sourceTar := tar.NewReader(gzipReader)
for {
header, err := sourceTar.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if header.Typeflag != tar.TypeReg {
continue
}
destination, include := hostlessRuntimePath(
header.Name,
info.runtimePlatform,
runtimeWrapperName(info.binaryName),
)
if !include {
continue
}
outputHeader := &tar.Header{
Name: destination, Mode: header.Mode, Size: header.Size, Typeflag: tar.TypeReg,
Uid: 0, Gid: 0,
}
if err := tarWriter.WriteHeader(outputHeader); err != nil {
return err
}
if _, err := io.Copy(tarWriter, sourceTar); err != nil {
return err
}
count++
}
if count == 0 {
return fmt.Errorf("runtime package contains no retained assets")
}
if err := tarWriter.Close(); err != nil {
return err
}
return gzipWriter.Close()
}
// runtimeLibExt returns the shared-library extension for the target OS.
func runtimeLibExt(goos string) string {
switch goos {
case "windows":
return "dll"
case "darwin":
return "dylib"
default:
return "so"
}
}
// generateGoFile creates separate source files for normal and in-process builds.
// Both embed the CLI, while only the copilot_inprocess-tagged file embeds the
// native runtime library.
func generateGoFile(
goos,
goarch,
binaryPath,
cliVersion string,
sha256Hash []byte,
runtimeArtifactPath string,
runtimeHash []byte,
wrapperArtifactPath string,
wrapperHash []byte,
assetsArtifactPath string,
assetsHash []byte,
muslBinaryPath string,
muslBinaryHash []byte,
muslRuntimeArtifactPath string,
muslRuntimeHash []byte,
muslWrapperArtifactPath string,
muslWrapperHash []byte,
muslAssetsArtifactPath string,
muslAssetsHash []byte,
pkgName string,
) error {
binaryName := filepath.Base(binaryPath)
licenseName := licenseFileName(binaryName)
hashBase64 := ""
if len(sha256Hash) > 0 {
hashBase64 = base64.StdEncoding.EncodeToString(sha256Hash)
}
outputDir := filepath.Dir(binaryPath)
defaultPath := filepath.Join(outputDir, fmt.Sprintf("zcopilot_%s_%s.go", goos, goarch))
defaultContent := generatedGoFileContent(
"!copilot_inprocess",
pkgName,
binaryName,
licenseName,
cliVersion,
hashBase64,
runtimeArtifactPath,
runtimeHash,
wrapperArtifactPath,
wrapperHash,
assetsArtifactPath,
assetsHash,
muslBinaryPath,
muslBinaryHash,
muslRuntimeArtifactPath,
muslRuntimeHash,
muslWrapperArtifactPath,
muslWrapperHash,
muslAssetsArtifactPath,
muslAssetsHash,
)
if err := os.WriteFile(defaultPath, []byte(defaultContent), 0644); err != nil {
return err
}
inProcessPath := filepath.Join(outputDir, fmt.Sprintf("zcopilot_inprocess_%s_%s.go", goos, goarch))
inProcessContent := generatedGoFileContent(
"copilot_inprocess",
pkgName,
binaryName,
licenseName,
cliVersion,
hashBase64,
runtimeArtifactPath,
runtimeHash,
wrapperArtifactPath,
wrapperHash,
assetsArtifactPath,
assetsHash,
muslBinaryPath,
muslBinaryHash,
muslRuntimeArtifactPath,
muslRuntimeHash,
muslWrapperArtifactPath,
muslWrapperHash,
muslAssetsArtifactPath,
muslAssetsHash,
)
if err := os.WriteFile(inProcessPath, []byte(inProcessContent), 0644); err != nil {
return err
}
fmt.Printf("Generated %s\n", defaultPath)
fmt.Printf("Generated %s\n", inProcessPath)
return nil
}
func generatedGoFileContent(
buildConstraint,
pkgName,
binaryName,
licenseName,
cliVersion,
hashBase64,
runtimeArtifactPath string,
runtimeHash []byte,
wrapperArtifactPath string,
wrapperHash []byte,
assetsArtifactPath string,
assetsHash []byte,
muslBinaryPath string,
muslBinaryHash []byte,
muslRuntimeArtifactPath string,
muslRuntimeHash []byte,
muslWrapperArtifactPath string,
muslWrapperHash []byte,
muslAssetsArtifactPath string,
muslAssetsHash []byte,
) string {
runtimeEmbed := ""
runtimeConfig := ""
runtimeReader := ""
if runtimeArtifactPath != "" && wrapperArtifactPath != "" && assetsArtifactPath != "" {
runtimeArtifactName := filepath.Base(runtimeArtifactPath)
runtimeHashBase64 := base64.StdEncoding.EncodeToString(runtimeHash)
wrapperArtifactName := filepath.Base(wrapperArtifactPath)
wrapperHashBase64 := base64.StdEncoding.EncodeToString(wrapperHash)
assetsArtifactName := filepath.Base(assetsArtifactPath)
assetsHashBase64 := base64.StdEncoding.EncodeToString(assetsHash)
runtimeEmbed = fmt.Sprintf(`
//go:embed %s
var localEmbeddedCopilotRuntimeLib []byte
//go:embed %s
var localEmbeddedCopilotRuntimeExecutable []byte
//go:embed %s
var localEmbeddedCopilotRuntimeAssets []byte
`, runtimeArtifactName, wrapperArtifactName, assetsArtifactName)
runtimeConfig = fmt.Sprintf(`
RuntimeLib: runtimeLibReader(),
RuntimeLibHash: mustDecodeBase64(%q),
RuntimeNode: runtimeLibReader(),
RuntimeNodeHash: mustDecodeBase64(%q),
RuntimeExecutable: runtimeExecutableReader(),
RuntimeExecutableHash: mustDecodeBase64(%q),
RuntimeAssets: bytes.NewReader(localEmbeddedCopilotRuntimeAssets),
RuntimeAssetsHash: mustDecodeBase64(%q),`, runtimeHashBase64, runtimeHashBase64, wrapperHashBase64, assetsHashBase64)
runtimeReader = `
func runtimeLibReader() io.Reader {
r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotRuntimeLib))
if err != nil {
panic("failed to create zstd reader: " + err.Error())
}
return r
}
func runtimeExecutableReader() io.Reader {
r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotRuntimeExecutable))
if err != nil {
panic("failed to create zstd reader: " + err.Error())
}
return r
}
`
}
muslEmbed := ""
muslConfig := ""
muslReaders := ""
if muslBinaryPath != "" && muslRuntimeArtifactPath != "" && muslWrapperArtifactPath != "" && muslAssetsArtifactPath != "" {
muslBinaryName := filepath.Base(muslBinaryPath)
muslBinaryHashBase64 := base64.StdEncoding.EncodeToString(muslBinaryHash)
muslRuntimeName := filepath.Base(muslRuntimeArtifactPath)
muslRuntimeHashBase64 := base64.StdEncoding.EncodeToString(muslRuntimeHash)
muslWrapperName := filepath.Base(muslWrapperArtifactPath)
muslWrapperHashBase64 := base64.StdEncoding.EncodeToString(muslWrapperHash)
muslAssetsName := filepath.Base(muslAssetsArtifactPath)
muslAssetsHashBase64 := base64.StdEncoding.EncodeToString(muslAssetsHash)
muslEmbed = fmt.Sprintf(`
//go:embed %s
var localEmbeddedCopilotCLILinuxMusl []byte
//go:embed %s
var localEmbeddedCopilotRuntimeLibLinuxMusl []byte
//go:embed %s
var localEmbeddedCopilotRuntimeExecutableLinuxMusl []byte
//go:embed %s
var localEmbeddedCopilotRuntimeAssetsLinuxMusl []byte
`, muslBinaryName, muslRuntimeName, muslWrapperName, muslAssetsName)
muslConfig = fmt.Sprintf(`
LinuxMuslCli: linuxMuslCLIReader(),
LinuxMuslCliHash: mustDecodeBase64(%q),
LinuxMuslRuntimeLib: linuxMuslRuntimeLibReader(),
LinuxMuslRuntimeLibHash: mustDecodeBase64(%q),
LinuxMuslRuntimeNode: linuxMuslRuntimeLibReader(),
LinuxMuslRuntimeNodeHash: mustDecodeBase64(%q),
LinuxMuslRuntimeExecutable: linuxMuslRuntimeExecutableReader(),
LinuxMuslRuntimeExecutableHash: mustDecodeBase64(%q),
LinuxMuslRuntimeAssets: bytes.NewReader(localEmbeddedCopilotRuntimeAssetsLinuxMusl),
LinuxMuslRuntimeAssetsHash: mustDecodeBase64(%q),`, muslBinaryHashBase64, muslRuntimeHashBase64, muslRuntimeHashBase64, muslWrapperHashBase64, muslAssetsHashBase64)
muslReaders = `
func linuxMuslCLIReader() io.Reader {
r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotCLILinuxMusl))
if err != nil {
panic("failed to create zstd reader: " + err.Error())
}
return r
}
func linuxMuslRuntimeLibReader() io.Reader {
r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotRuntimeLibLinuxMusl))
if err != nil {
panic("failed to create zstd reader: " + err.Error())
}
return r
}
func linuxMuslRuntimeExecutableReader() io.Reader {
r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotRuntimeExecutableLinuxMusl))
if err != nil {
panic("failed to create zstd reader: " + err.Error())
}
return r
}
`
}
return fmt.Sprintf(`//go:build %s
// Code generated by copilot-sdk bundler; DO NOT EDIT.
package %s
import (
"bytes"
"encoding/base64"
_ "embed"
"io"
"github.com/github/copilot-sdk/go/embeddedcli"
"github.com/klauspost/compress/zstd"
)
//go:embed %s
var localEmbeddedCopilotCLI []byte
//go:embed %s
var localEmbeddedCopilotCLILicense []byte
%s
%s
func init() {
embeddedcli.Setup(embeddedcli.Config{
Cli: cliReader(),
License: localEmbeddedCopilotCLILicense,
Version: %q,
CliHash: mustDecodeBase64(%q),%s%s
})
}
func cliReader() io.Reader {
r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotCLI))
if err != nil {
panic("failed to create zstd reader: " + err.Error())
}
return r
}
%s
%s
func mustDecodeBase64(s string) []byte {
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
panic("failed to decode base64: " + err.Error())
}
return b
}
`, buildConstraint, pkgName, binaryName, licenseName, runtimeEmbed, muslEmbed, cliVersion, hashBase64, runtimeConfig, muslConfig, runtimeReader, muslReaders)
}
var (
releaseChecksumCache = map[string]map[string]string{}
releaseHTTPClient = &http.Client{Timeout: 10 * time.Minute}
)
func cliDownloadBaseURL() string {
if override := strings.TrimRight(os.Getenv(cliDownloadBaseURLEnvironment), "/"); override != "" {
return override
}
return defaultCLIDownloadBaseURL
}
func releaseAssetName(version, runtimePlatform string) string {
return fmt.Sprintf("github-copilot-%s-%s.tgz", version, runtimePlatform)
}
func releaseDownloadURL(version, assetName string) string {
return fmt.Sprintf("%s/v%s/%s", cliDownloadBaseURL(), version, assetName)
}
func parseReleaseChecksums(contents string) map[string]string {
checksums := make(map[string]string)
hashPattern := regexp.MustCompile(`^[0-9a-fA-F]{64}$`)
for _, line := range strings.Split(contents, "\n") {
fields := strings.Fields(line)
if len(fields) != 2 || !hashPattern.MatchString(fields[0]) {
continue
}
checksums[strings.TrimPrefix(fields[1], "*")] = strings.ToLower(fields[0])
}
return checksums
}
func getReleaseChecksum(version, assetName string) (string, error) {
baseURL := cliDownloadBaseURL()
cacheKey := baseURL + "\x00" + version
checksums, ok := releaseChecksumCache[cacheKey]
if !ok {
checksumsURL := fmt.Sprintf("%s/v%s/SHA256SUMS.txt", baseURL, version)
fmt.Printf("Downloading checksums from %s...\n", checksumsURL)
resp, err := releaseHTTPClient.Get(checksumsURL)
if err != nil {
return "", fmt.Errorf("failed to download checksums: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to download checksums: %s", resp.Status)
}
contents, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read checksums: %w", err)
}
checksums = parseReleaseChecksums(string(contents))
releaseChecksumCache[cacheKey] = checksums
}
checksum, ok := checksums[assetName]
if !ok {
return "", fmt.Errorf("SHA256SUMS.txt does not contain %s", assetName)
}
return checksum, nil
}
// downloadCLIBinary downloads the verified release package and extracts the CLI binary. It
// returns the extracted binary path and the downloaded tarball path (retained so
// callers can extract additional files, such as the runtime library).
func downloadCLIBinary(runtimePlatform, binaryName, cliVersion, destDir string) (string, string, error) {
assetName := releaseAssetName(cliVersion, runtimePlatform)
expectedChecksum, err := getReleaseChecksum(cliVersion, assetName)
if err != nil {
return "", "", err
}
tarballURL := releaseDownloadURL(cliVersion, assetName)
fmt.Printf("Downloading from %s...\n", tarballURL)