microsoft-copilot-sdk 1.0.29.dev42910103371__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,644 @@
1
+ """Download and cache the Copilot CLI runtime package.
2
+
3
+ The platform-specific GitHub release package contains the out-of-process runtime
4
+ wrapper, native runtime library, and runtime assets, but omits the legacy SEA
5
+ ``copilot[.exe]``. Its bytes are downloaded and verified, then the filtered hostless
6
+ bundle is materialized directly into the SDK's existing cache layout. ``download_cli``
7
+ preserves the historical CLI filename by creating a compatibility alias from the
8
+ runtime wrapper inside the complete materialized bundle:
9
+
10
+ - Linux: ~/.cache/copilot-sdk/cli/{version}/prebuilds/{platform}/copilot
11
+ - macOS: ~/Library/Caches/copilot-sdk/cli/{version}/prebuilds/{platform}/copilot
12
+ - Windows: %LOCALAPPDATA%/copilot-sdk/cli/{version}/prebuilds/{platform}/copilot.exe
13
+
14
+ Environment variables:
15
+ - COPILOT_CLI_EXTRACT_DIR: Override the runtime bundle cache root.
16
+ - COPILOT_SKIP_CLI_DOWNLOAD: Set to "1" or "true" to disable auto-download.
17
+ - COPILOT_CLI_DOWNLOAD_BASE_URL: Override the GitHub Releases base URL.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import errno
23
+ import hashlib
24
+ import io
25
+ import os
26
+ import re
27
+ import stat
28
+ import sys
29
+ import tarfile
30
+ import tempfile
31
+ import time
32
+ from collections.abc import Generator
33
+ from contextlib import contextmanager
34
+ from http.client import IncompleteRead
35
+ from pathlib import Path, PurePosixPath
36
+ from urllib.error import HTTPError, URLError
37
+ from urllib.request import urlopen
38
+
39
+ from ._cli_version import (
40
+ CLI_VERSION,
41
+ get_checksums_url,
42
+ get_cli_binary_name,
43
+ get_download_url,
44
+ get_release_asset_name,
45
+ get_runtime_platform,
46
+ )
47
+
48
+ _CACHE_DIR_NAME = "copilot-sdk"
49
+ _MAX_RETRIES = 3
50
+ _RETRIABLE_DOWNLOAD_ERRORS = (HTTPError, URLError, IncompleteRead)
51
+ _HOSTLESS_ASSETS_MARKER = ".hostless-runtime-assets-v2"
52
+
53
+
54
+ def _sanitize_version(version: str) -> str:
55
+ """Sanitize version string for use as a directory name.
56
+
57
+ Replaces any character not in [a-zA-Z0-9._-] with underscore.
58
+ Matches the Rust SDK's sanitization logic.
59
+ """
60
+ return re.sub(r"[^a-zA-Z0-9._\-]", "_", version)
61
+
62
+
63
+ def get_cache_dir(version: str | None = None) -> Path:
64
+ """Return the cache directory for runtime bundles.
65
+
66
+ Args:
67
+ version: CLI version string. If None, returns the root cache dir.
68
+ """
69
+ # COPILOT_CLI_EXTRACT_DIR overrides the entire version-specific directory.
70
+ extract_override = os.environ.get("COPILOT_CLI_EXTRACT_DIR")
71
+ if extract_override:
72
+ return Path(extract_override)
73
+
74
+ if sys.platform == "darwin":
75
+ root = Path.home() / "Library" / "Caches" / _CACHE_DIR_NAME
76
+ elif sys.platform == "win32":
77
+ local_app_data = os.environ.get("LOCALAPPDATA")
78
+ if local_app_data:
79
+ root = Path(local_app_data) / _CACHE_DIR_NAME
80
+ else:
81
+ root = Path.home() / "AppData" / "Local" / _CACHE_DIR_NAME
82
+ else:
83
+ xdg = os.environ.get("XDG_CACHE_HOME")
84
+ if xdg:
85
+ root = Path(xdg) / _CACHE_DIR_NAME
86
+ else:
87
+ root = Path.home() / ".cache" / _CACHE_DIR_NAME
88
+
89
+ if version:
90
+ return root / "cli" / _sanitize_version(version)
91
+ return root / "cli"
92
+
93
+
94
+ def get_cached_cli_path(version: str | None = None) -> str | None:
95
+ """Return the cached compatibility entrypoint for a complete runtime bundle.
96
+
97
+ Args:
98
+ version: CLI version. Defaults to the pinned CLI_VERSION.
99
+
100
+ Returns:
101
+ Path to the binary, or None if not cached.
102
+ """
103
+ ver = version or CLI_VERSION
104
+ if not ver:
105
+ return None
106
+
107
+ try:
108
+ runtime_platform = get_runtime_platform()
109
+ except RuntimeError:
110
+ return None
111
+ binary_name = get_cli_binary_name()
112
+ wrapper_name = "copilot-runtime.exe" if sys.platform == "win32" else "copilot-runtime"
113
+ pair_dir = get_cache_dir(ver) / "prebuilds" / runtime_platform
114
+ binary_path = pair_dir / binary_name
115
+ required = (
116
+ binary_path,
117
+ pair_dir / wrapper_name,
118
+ pair_dir / "runtime.node",
119
+ pair_dir / _HOSTLESS_ASSETS_MARKER,
120
+ )
121
+
122
+ try:
123
+ if all(path.is_file() and path.stat().st_size > 0 for path in required):
124
+ return str(binary_path)
125
+ except FileNotFoundError:
126
+ # A concurrent repair can remove the bundle during this probe; treat it as a miss.
127
+ pass
128
+ return None
129
+
130
+
131
+ def _should_skip_download() -> bool:
132
+ """Check if auto-download is disabled via environment variable."""
133
+ val = os.environ.get("COPILOT_SKIP_CLI_DOWNLOAD", "").lower()
134
+ return val in ("1", "true", "yes")
135
+
136
+
137
+ def _fetch_checksums(version: str) -> dict[str, str]:
138
+ """Fetch and parse the SHA256SUMS.txt file.
139
+
140
+ Returns a dict mapping filename → sha256 hex digest.
141
+ """
142
+ url = get_checksums_url(version)
143
+ try:
144
+ text = _fetch_url_bytes(url, timeout=30).decode("utf-8")
145
+ except (RuntimeError, UnicodeDecodeError) as exc:
146
+ raise RuntimeError(
147
+ f"Failed to download checksums from {url}: {exc}\n\n"
148
+ "If you are in an offline or firewalled environment, set "
149
+ "COPILOT_CLI_PATH to point to a manually-installed binary."
150
+ ) from exc
151
+
152
+ checksums: dict[str, str] = {}
153
+ for line in text.strip().splitlines():
154
+ parts = line.split()
155
+ if len(parts) == 2 and re.fullmatch(r"[a-fA-F0-9]{64}", parts[0]):
156
+ digest, filename = parts
157
+ # Some formats use *filename (binary mode indicator)
158
+ checksums[filename.lstrip("*")] = digest.lower()
159
+ return checksums
160
+
161
+
162
+ def _verify_checksum(data: bytes, expected_hash: str, filename: str) -> None:
163
+ """Verify SHA-256 checksum of downloaded data."""
164
+ actual = hashlib.sha256(data).hexdigest()
165
+ if actual != expected_hash:
166
+ raise RuntimeError(
167
+ f"Checksum mismatch for {filename}:\n expected: {expected_hash}\n actual: {actual}"
168
+ )
169
+
170
+
171
+ def _fetch_verified_release_package(version: str, runtime_platform: str) -> bytes:
172
+ """Download and verify the unified platform release package."""
173
+ asset_name = get_release_asset_name(version, runtime_platform)
174
+ expected_hash = _fetch_checksums(version).get(asset_name)
175
+ if not expected_hash:
176
+ raise RuntimeError(f"SHA256SUMS.txt does not contain {asset_name}.")
177
+ url = get_download_url(version, asset_name)
178
+ data = _fetch_url_bytes(url, timeout=600)
179
+ _verify_checksum(data, expected_hash, asset_name)
180
+ return data
181
+
182
+
183
+ def _runtime_bundle_is_complete(pair_dir: Path, wrapper_name: str) -> bool:
184
+ required = (
185
+ pair_dir / wrapper_name,
186
+ pair_dir / "runtime.node",
187
+ pair_dir / _HOSTLESS_ASSETS_MARKER,
188
+ )
189
+ try:
190
+ return all(path.is_file() and path.stat().st_size > 0 for path in required)
191
+ except FileNotFoundError:
192
+ # A concurrent repair can remove an incomplete bundle during this probe.
193
+ return False
194
+
195
+
196
+ @contextmanager
197
+ def _runtime_bundle_lock(pair_dir: Path) -> Generator[None, None, None]:
198
+ """Serialize installers that share ``pair_dir``, when the cache allows it.
199
+
200
+ The lock is advisory. Where it cannot be taken (a missing, unreadable or
201
+ read-only parent, an existing lock this user cannot write, or a filesystem
202
+ such as NFS that rejects the lock), installers proceed unlocked, as they
203
+ did before the lock existed.
204
+ """
205
+ if sys.platform != "win32":
206
+ import fcntl
207
+
208
+ # The parent survives bundle replacement and needs no writable lock file,
209
+ # even when another user populated the cache with a restrictive umask.
210
+ try:
211
+ lock_fd = os.open(pair_dir.parent, os.O_RDONLY)
212
+ except OSError:
213
+ yield
214
+ return
215
+ locked = False
216
+ try:
217
+ try:
218
+ fcntl.flock(lock_fd, fcntl.LOCK_EX)
219
+ locked = True
220
+ except OSError:
221
+ pass
222
+ yield
223
+ finally:
224
+ if locked:
225
+ fcntl.flock(lock_fd, fcntl.LOCK_UN)
226
+ os.close(lock_fd)
227
+ return
228
+
229
+ import msvcrt
230
+
231
+ # Keep the Windows lock outside the replaceable tree, and never unlink its inode.
232
+ lock_path = pair_dir.parent / f".runtime-bundle.{pair_dir.name}.lock"
233
+ try:
234
+ lock = lock_path.open("a+b")
235
+ except OSError:
236
+ yield
237
+ return
238
+ with lock:
239
+ if lock.tell() == 0:
240
+ lock.write(b"\0")
241
+ lock.flush()
242
+ lock.seek(0)
243
+ # LK_LOCK gives up after ten attempts; repairs can take longer.
244
+ while True:
245
+ try:
246
+ msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
247
+ break
248
+ except OSError as exc:
249
+ if exc.errno != errno.EACCES:
250
+ raise
251
+ time.sleep(1)
252
+ try:
253
+ yield
254
+ finally:
255
+ lock.seek(0)
256
+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
257
+
258
+
259
+ def download_cli(version: str | None = None, *, force: bool = False) -> str:
260
+ """Provision a complete runtime bundle with a ``copilot[.exe]`` alias.
261
+
262
+ Args:
263
+ version: CLI version to download. Defaults to the pinned CLI_VERSION.
264
+ force: If True, re-download even if already cached.
265
+
266
+ Returns:
267
+ Path to the compatibility entrypoint adjacent to the complete runtime bundle.
268
+
269
+ Raises:
270
+ RuntimeError: If the version is not set, download fails, or
271
+ checksum verification fails.
272
+ """
273
+ ver = version or CLI_VERSION
274
+ if not ver:
275
+ raise RuntimeError(
276
+ "No CLI version pinned. This is a development install — "
277
+ "set COPILOT_CLI_PATH or install a published wheel."
278
+ )
279
+
280
+ binary_name = get_cli_binary_name()
281
+
282
+ if not force:
283
+ cached = get_cached_cli_path(ver)
284
+ if cached is not None:
285
+ return cached
286
+
287
+ wrapper_path = Path(ensure_runtime_wrapper(ver, force=force))
288
+ binary_path = wrapper_path.with_name(binary_name)
289
+ with _runtime_bundle_lock(wrapper_path.parent):
290
+ if not force:
291
+ cached = get_cached_cli_path(ver)
292
+ if cached is not None:
293
+ return cached
294
+ fd, temp_name = tempfile.mkstemp(dir=wrapper_path.parent, prefix=".cli-")
295
+ try:
296
+ with os.fdopen(fd, "wb") as destination:
297
+ destination.write(wrapper_path.read_bytes())
298
+ staged = Path(temp_name)
299
+ if sys.platform != "win32":
300
+ staged.chmod(staged.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
301
+ os.replace(staged, binary_path)
302
+ except OSError:
303
+ try:
304
+ os.unlink(temp_name)
305
+ except OSError:
306
+ pass
307
+ if not force:
308
+ cached = get_cached_cli_path(ver)
309
+ if cached is not None:
310
+ return cached
311
+ raise
312
+
313
+ return str(binary_path)
314
+
315
+
316
+ def _fetch_url_bytes(url: str, *, timeout: int) -> bytes:
317
+ """Download bytes from ``url`` with retries."""
318
+ last_exc: Exception | None = None
319
+ for attempt in range(_MAX_RETRIES):
320
+ try:
321
+ with urlopen(url, timeout=timeout) as response:
322
+ return response.read()
323
+ except _RETRIABLE_DOWNLOAD_ERRORS as exc:
324
+ last_exc = exc
325
+ if attempt < _MAX_RETRIES - 1:
326
+ time.sleep(2**attempt)
327
+ raise RuntimeError(f"Failed to download from {url}: {last_exc}") from last_exc
328
+
329
+
330
+ _HOSTLESS_EXCLUDED_TOP_LEVEL = {
331
+ "app.js",
332
+ "assets",
333
+ "changelog.json",
334
+ "cli-main.js",
335
+ "copilot",
336
+ "copilot.exe",
337
+ "copilot-sdk",
338
+ "foundry-local-sdk",
339
+ "index.js",
340
+ "LICENSE.md",
341
+ "napi-oop-runtime",
342
+ "npm-loader.js",
343
+ "package.json",
344
+ "preloads",
345
+ "pvrecorder",
346
+ "queries",
347
+ "README.md",
348
+ "sdk",
349
+ "sea-loader.js",
350
+ "webview",
351
+ }
352
+
353
+
354
+ def _hostless_runtime_path(member_name: str, runtime_platform: str) -> Path | None:
355
+ if "\\" in member_name:
356
+ raise RuntimeError(f"Unsafe runtime package path: {member_name}")
357
+ parts = PurePosixPath(member_name).parts
358
+ if not parts or parts[0] != "package" or len(parts) < 2:
359
+ return None
360
+ relative = parts[1:]
361
+ top_level = relative[0]
362
+ file_name = relative[-1]
363
+ if (
364
+ top_level in _HOSTLESS_EXCLUDED_TOP_LEVEL
365
+ or (top_level.startswith("tree-sitter") and top_level.endswith(".wasm"))
366
+ or (top_level.startswith("voice-") and top_level.endswith(".js"))
367
+ or file_name == "cli-native.node"
368
+ or "mediaremote-adapter" in relative
369
+ or file_name.startswith("copilot-runtime-bin")
370
+ ):
371
+ return None
372
+ if top_level == "prebuilds":
373
+ if len(relative) < 3 or relative[1] != runtime_platform:
374
+ return None
375
+ relative = relative[2:]
376
+ destination = Path(*relative)
377
+ if destination.is_absolute() or ".." in destination.parts:
378
+ raise RuntimeError(f"Unsafe runtime package path: {member_name}")
379
+ return destination
380
+
381
+
382
+ def _materialize_runtime_bundle(data: bytes, runtime_platform: str, destination: Path) -> None:
383
+ """Extract the hostless runtime tree, retaining unknown package assets by default."""
384
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
385
+ for member in archive:
386
+ relative = _hostless_runtime_path(member.name, runtime_platform)
387
+ if relative is None or member.isdir():
388
+ continue
389
+ if not member.isfile():
390
+ raise RuntimeError(f"Unsupported runtime package entry: {member.name}")
391
+ extracted = archive.extractfile(member)
392
+ if extracted is None:
393
+ raise RuntimeError(f"Failed to read runtime package entry: {member.name}")
394
+ target = destination / relative
395
+ target.parent.mkdir(parents=True, exist_ok=True)
396
+ target.write_bytes(extracted.read())
397
+ if sys.platform != "win32":
398
+ target.chmod(member.mode & 0o777)
399
+
400
+
401
+ def ensure_runtime_wrapper(version: str | None = None, force: bool = False) -> str:
402
+ """Provision the runtime pair and retained assets from the release package."""
403
+ ver = version or CLI_VERSION
404
+ if not ver:
405
+ raise RuntimeError("No runtime version is pinned.")
406
+ runtime_platform = get_runtime_platform()
407
+ wrapper_name = "copilot-runtime.exe" if sys.platform == "win32" else "copilot-runtime"
408
+ pair_dir = get_cache_dir(ver) / "prebuilds" / runtime_platform
409
+ wrapper_path = pair_dir / wrapper_name
410
+ runtime_path = pair_dir / "runtime.node"
411
+ assets_marker = pair_dir / _HOSTLESS_ASSETS_MARKER
412
+
413
+ if _runtime_bundle_is_complete(pair_dir, wrapper_name) and not force:
414
+ return str(wrapper_path)
415
+ with _runtime_bundle_lock(pair_dir):
416
+ if _runtime_bundle_is_complete(pair_dir, wrapper_name) and not force:
417
+ return str(wrapper_path)
418
+ wrapper_exists = wrapper_path.is_file() and wrapper_path.stat().st_size > 0
419
+ runtime_exists = runtime_path.is_file() and runtime_path.stat().st_size > 0
420
+ if not force and wrapper_exists != runtime_exists:
421
+ raise RuntimeError(
422
+ f"Incomplete Copilot runtime bundle in {pair_dir}: "
423
+ f"{wrapper_name} and runtime.node are required."
424
+ )
425
+ if _should_skip_download():
426
+ raise RuntimeError(
427
+ f"Copilot runtime bundle is not cached in {pair_dir} "
428
+ "and automatic downloads are disabled."
429
+ )
430
+
431
+ data = _fetch_verified_release_package(ver, runtime_platform)
432
+ import shutil
433
+
434
+ pair_dir.parent.mkdir(parents=True, exist_ok=True)
435
+ staging_dir = Path(tempfile.mkdtemp(dir=pair_dir.parent, prefix=".runtime-bundle-"))
436
+ try:
437
+ _materialize_runtime_bundle(data, runtime_platform, staging_dir)
438
+ staged_wrapper = staging_dir / wrapper_name
439
+ staged_runtime = staging_dir / "runtime.node"
440
+ if (
441
+ not staged_wrapper.is_file()
442
+ or staged_wrapper.stat().st_size == 0
443
+ or not staged_runtime.is_file()
444
+ or staged_runtime.stat().st_size == 0
445
+ ):
446
+ raise RuntimeError("Copilot runtime wrapper and runtime.node must both be non-empty.")
447
+ if sys.platform != "win32":
448
+ staged_wrapper.chmod(
449
+ staged_wrapper.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
450
+ )
451
+ (staging_dir / assets_marker.name).write_text("1\n", encoding="ascii")
452
+ with _runtime_bundle_lock(pair_dir):
453
+ if _runtime_bundle_is_complete(pair_dir, wrapper_name) and not force:
454
+ return str(wrapper_path)
455
+ try:
456
+ if pair_dir.exists():
457
+ shutil.rmtree(pair_dir)
458
+ staging_dir.replace(pair_dir)
459
+ except OSError:
460
+ if _runtime_bundle_is_complete(pair_dir, wrapper_name):
461
+ return str(wrapper_path)
462
+ raise
463
+ finally:
464
+ if staging_dir.exists():
465
+ shutil.rmtree(staging_dir, ignore_errors=True)
466
+
467
+ return str(wrapper_path)
468
+
469
+
470
+ def ensure_runtime_library(cli_path: str, version: str | None = None) -> str | None:
471
+ """Ensure the native in-process (FFI) runtime library sits next to ``cli_path``.
472
+
473
+ The canonical staged bundle contains ``prebuilds/<platform>/runtime.node``.
474
+ This helper reuses that verified library and copies it next to the CLI binary
475
+ under its natural platform name (``libcopilot_runtime.so`` / ``.dylib`` /
476
+ ``copilot_runtime.dll``).
477
+
478
+ Copying the library next to an external CLI is opt-in — this is only invoked when
479
+ the in-process transport is selected (lazy) or via
480
+ ``python -m copilot download-runtime --in-process`` (explicit). The default stdio
481
+ path leaves the library in the canonical staged bundle.
482
+
483
+ Returns the absolute path to the library, or None if it could not be provisioned
484
+ (e.g. download disabled or unsupported platform). Raises RuntimeError on
485
+ download/verification failure.
486
+ """
487
+ # Import lazily to avoid a hard dependency for stdio-only users.
488
+ from ._ffi_runtime_host import _natural_library_name, resolve_library_path
489
+
490
+ # Already present (bundled prebuilds layout in dev, or a prior download)?
491
+ existing = resolve_library_path(cli_path)
492
+ if existing is not None:
493
+ return existing
494
+
495
+ ver = version or CLI_VERSION
496
+ if not ver:
497
+ return None
498
+
499
+ try:
500
+ runtime_platform = get_runtime_platform()
501
+ except RuntimeError:
502
+ return None
503
+
504
+ cli_dir = Path(cli_path).resolve().parent
505
+ lib_path = cli_dir / _natural_library_name()
506
+ if lib_path.exists():
507
+ return str(lib_path)
508
+
509
+ pair_dir = get_cache_dir(ver) / "prebuilds" / runtime_platform
510
+ wrapper_name = "copilot-runtime.exe" if sys.platform == "win32" else "copilot-runtime"
511
+ if _should_skip_download() and not _runtime_bundle_is_complete(pair_dir, wrapper_name):
512
+ return None
513
+ wrapper_path = Path(ensure_runtime_wrapper(ver))
514
+ canonical_runtime = wrapper_path.with_name("runtime.node")
515
+
516
+ # Write atomically next to the CLI so concurrent starts don't observe a partial
517
+ # library. A rename within the same directory is atomic on POSIX and Windows.
518
+ import shutil
519
+
520
+ cli_dir.mkdir(parents=True, exist_ok=True)
521
+ fd, tmp_name = tempfile.mkstemp(dir=cli_dir, prefix=".runtime-lib-")
522
+ try:
523
+ with os.fdopen(fd, "wb") as out, canonical_runtime.open("rb") as source:
524
+ shutil.copyfileobj(source, out)
525
+ os.replace(tmp_name, lib_path)
526
+ except OSError:
527
+ try:
528
+ os.unlink(tmp_name)
529
+ except OSError:
530
+ # Best-effort cleanup of the temp file; ignore if it's already gone or
531
+ # can't be removed (the OS reclaims it, and it doesn't affect correctness).
532
+ pass
533
+ if lib_path.exists():
534
+ return str(lib_path)
535
+ raise
536
+
537
+ return str(lib_path)
538
+
539
+
540
+ def get_or_download_cli(version: str | None = None) -> str | None:
541
+ """Get the cached CLI binary, downloading it if necessary.
542
+
543
+ Returns None if:
544
+ - No version is pinned (dev install)
545
+ - Auto-download is disabled via COPILOT_SKIP_CLI_DOWNLOAD
546
+ - The platform is unsupported
547
+
548
+ Raises RuntimeError on download/verification failures.
549
+ """
550
+ ver = version or CLI_VERSION
551
+ if not ver:
552
+ return None
553
+
554
+ # Check cache first
555
+ cached = get_cached_cli_path(ver)
556
+ if cached:
557
+ return cached
558
+
559
+ # Check platform support before attempting download
560
+ try:
561
+ runtime_platform = get_runtime_platform()
562
+ except RuntimeError:
563
+ return None
564
+
565
+ if _should_skip_download():
566
+ pair_dir = get_cache_dir(ver) / "prebuilds" / runtime_platform
567
+ wrapper_name = "copilot-runtime.exe" if sys.platform == "win32" else "copilot-runtime"
568
+ if not _runtime_bundle_is_complete(pair_dir, wrapper_name):
569
+ return None
570
+
571
+ # Download
572
+ return download_cli(ver)
573
+
574
+
575
+ def main() -> None:
576
+ """CLI entry point for `python -m copilot download-runtime`."""
577
+ import argparse
578
+
579
+ parser = argparse.ArgumentParser(
580
+ prog="python -m copilot",
581
+ description="Copilot SDK utilities",
582
+ )
583
+ subparsers = parser.add_subparsers(dest="command")
584
+
585
+ # download-runtime subcommand
586
+ dl_parser = subparsers.add_parser(
587
+ "download-runtime",
588
+ help="Download the Copilot runtime",
589
+ )
590
+ dl_parser.add_argument(
591
+ "--force",
592
+ action="store_true",
593
+ help="Re-download even if already cached",
594
+ )
595
+ dl_parser.add_argument(
596
+ "--version",
597
+ help="Runtime version to download (default: pinned version)",
598
+ )
599
+ dl_parser.add_argument(
600
+ "--in-process",
601
+ action="store_true",
602
+ help=(
603
+ "Also download the native in-process (FFI) runtime library "
604
+ "(prebuilds/<platform>/runtime.node) and place it next to the CLI. "
605
+ "Only needed for the experimental in-process transport."
606
+ ),
607
+ )
608
+
609
+ args = parser.parse_args()
610
+
611
+ if args.command == "download-runtime":
612
+ ver = args.version or CLI_VERSION
613
+ if not ver:
614
+ print(
615
+ "Error: No runtime version pinned (development install). "
616
+ "Use --version to specify a version.",
617
+ file=sys.stderr,
618
+ )
619
+ sys.exit(1)
620
+
621
+ print(f"Downloading Copilot runtime v{ver}...")
622
+ try:
623
+ if args.in_process:
624
+ path = download_cli(ver, force=args.force)
625
+ else:
626
+ path = ensure_runtime_wrapper(ver, force=args.force)
627
+ print(f"Runtime cached at: {path}")
628
+ if args.in_process:
629
+ print("Downloading in-process (FFI) runtime library...")
630
+ lib_path = ensure_runtime_library(path, ver)
631
+ if lib_path:
632
+ print(f"Runtime library cached at: {lib_path}")
633
+ else:
634
+ print(
635
+ "Warning: could not provision the in-process runtime library "
636
+ "(download disabled or unsupported platform).",
637
+ file=sys.stderr,
638
+ )
639
+ except RuntimeError as exc:
640
+ print(f"Error: {exc}", file=sys.stderr)
641
+ sys.exit(1)
642
+ else:
643
+ parser.print_help()
644
+ sys.exit(1)