commensa 0.1.0rc2__tar.gz

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,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: commensa
3
+ Version: 0.1.0rc2
4
+ Summary: Verified installer and stable command router for Commensa
5
+ Author: Commensa LLC
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://commensa.ai/
8
+ Project-URL: Documentation, https://commensa.ai/docs
9
+ Project-URL: Installation, https://commensa.ai/install
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Operating System :: Microsoft :: Windows :: Windows 11
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Software Development :: Quality Assurance
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Commensa bootstrap
22
+
23
+ This small public package installs verified Commensa releases and keeps one
24
+ stable `commensa` command in front of them. It does not contain the private
25
+ Report, Cockpit, Project X-Ray, commensa me tracking, or Commensa Manager
26
+ runtimes.
27
+
28
+ Install the free Core:
29
+
30
+ ```bash
31
+ pipx install commensa
32
+ commensa install core
33
+ ```
34
+
35
+ After purchasing an entitled product on `commensa.ai`, install the matching
36
+ capability. Commensa privately asks first for the secure access link in the
37
+ delivery email, then for the activation key. Neither belongs in a shell command.
38
+
39
+ ```bash
40
+ commensa install report
41
+ commensa install cockpit
42
+ commensa install xray
43
+ commensa install me
44
+ ```
45
+
46
+ For example, a new Report customer can use one shell line:
47
+
48
+ ```bash
49
+ pipx install commensa && commensa install report
50
+ ```
51
+
52
+ Approved Manager beta operators can install Manager into selected AI
53
+ interfaces:
54
+
55
+ ```bash
56
+ commensa install manager --interface codex --interface claude-code
57
+ ```
58
+
59
+ Normal product commands continue through the verified local runtime:
60
+
61
+ ```bash
62
+ commensa capabilities --json
63
+ commensa privacy --json
64
+ commensa doctor --json
65
+ ```
66
+
67
+ ## Current platform boundary
68
+
69
+ The release candidate supports the same command-line installation flow on
70
+ macOS, Linux, and native Windows 11. On Windows, `pipx` supplies the isolated
71
+ Python runtime and Commensa creates managed `.cmd` launchers; PowerShell or
72
+ Command Prompt can run the same `commensa install ...` commands. WSL remains a
73
+ separate Linux route.
74
+
75
+ The Windows route has automated contract coverage but still requires its first
76
+ acceptance pass on a physical Windows 11 x64 host before it can be described as
77
+ host-verified. It is not the separately signed Windows desktop installer.
78
+
79
+ Signed native installers remain the intended nontechnical customer route. This
80
+ package is the interim cross-platform command-line route.
@@ -0,0 +1,60 @@
1
+ # Commensa bootstrap
2
+
3
+ This small public package installs verified Commensa releases and keeps one
4
+ stable `commensa` command in front of them. It does not contain the private
5
+ Report, Cockpit, Project X-Ray, commensa me tracking, or Commensa Manager
6
+ runtimes.
7
+
8
+ Install the free Core:
9
+
10
+ ```bash
11
+ pipx install commensa
12
+ commensa install core
13
+ ```
14
+
15
+ After purchasing an entitled product on `commensa.ai`, install the matching
16
+ capability. Commensa privately asks first for the secure access link in the
17
+ delivery email, then for the activation key. Neither belongs in a shell command.
18
+
19
+ ```bash
20
+ commensa install report
21
+ commensa install cockpit
22
+ commensa install xray
23
+ commensa install me
24
+ ```
25
+
26
+ For example, a new Report customer can use one shell line:
27
+
28
+ ```bash
29
+ pipx install commensa && commensa install report
30
+ ```
31
+
32
+ Approved Manager beta operators can install Manager into selected AI
33
+ interfaces:
34
+
35
+ ```bash
36
+ commensa install manager --interface codex --interface claude-code
37
+ ```
38
+
39
+ Normal product commands continue through the verified local runtime:
40
+
41
+ ```bash
42
+ commensa capabilities --json
43
+ commensa privacy --json
44
+ commensa doctor --json
45
+ ```
46
+
47
+ ## Current platform boundary
48
+
49
+ The release candidate supports the same command-line installation flow on
50
+ macOS, Linux, and native Windows 11. On Windows, `pipx` supplies the isolated
51
+ Python runtime and Commensa creates managed `.cmd` launchers; PowerShell or
52
+ Command Prompt can run the same `commensa install ...` commands. WSL remains a
53
+ separate Linux route.
54
+
55
+ The Windows route has automated contract coverage but still requires its first
56
+ acceptance pass on a physical Windows 11 x64 host before it can be described as
57
+ host-verified. It is not the separately signed Windows desktop installer.
58
+
59
+ Signed native installers remain the intended nontechnical customer route. This
60
+ package is the interim cross-platform command-line route.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "commensa"
7
+ version = "0.1.0rc2"
8
+ description = "Verified installer and stable command router for Commensa"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = []
12
+ authors = [{name = "Commensa LLC"}]
13
+ license = "LicenseRef-Proprietary"
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Operating System :: MacOS",
18
+ "Operating System :: Microsoft :: Windows :: Windows 11",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Topic :: Software Development :: Quality Assurance",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://commensa.ai/"
27
+ Documentation = "https://commensa.ai/docs"
28
+ Installation = "https://commensa.ai/install"
29
+
30
+ [project.scripts]
31
+ commensa = "commensa_bootstrap.cli:main"
32
+
33
+ [tool.setuptools]
34
+ package-dir = {"" = "src"}
35
+ packages = ["commensa_bootstrap"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: commensa
3
+ Version: 0.1.0rc2
4
+ Summary: Verified installer and stable command router for Commensa
5
+ Author: Commensa LLC
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://commensa.ai/
8
+ Project-URL: Documentation, https://commensa.ai/docs
9
+ Project-URL: Installation, https://commensa.ai/install
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Operating System :: Microsoft :: Windows :: Windows 11
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Software Development :: Quality Assurance
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Commensa bootstrap
22
+
23
+ This small public package installs verified Commensa releases and keeps one
24
+ stable `commensa` command in front of them. It does not contain the private
25
+ Report, Cockpit, Project X-Ray, commensa me tracking, or Commensa Manager
26
+ runtimes.
27
+
28
+ Install the free Core:
29
+
30
+ ```bash
31
+ pipx install commensa
32
+ commensa install core
33
+ ```
34
+
35
+ After purchasing an entitled product on `commensa.ai`, install the matching
36
+ capability. Commensa privately asks first for the secure access link in the
37
+ delivery email, then for the activation key. Neither belongs in a shell command.
38
+
39
+ ```bash
40
+ commensa install report
41
+ commensa install cockpit
42
+ commensa install xray
43
+ commensa install me
44
+ ```
45
+
46
+ For example, a new Report customer can use one shell line:
47
+
48
+ ```bash
49
+ pipx install commensa && commensa install report
50
+ ```
51
+
52
+ Approved Manager beta operators can install Manager into selected AI
53
+ interfaces:
54
+
55
+ ```bash
56
+ commensa install manager --interface codex --interface claude-code
57
+ ```
58
+
59
+ Normal product commands continue through the verified local runtime:
60
+
61
+ ```bash
62
+ commensa capabilities --json
63
+ commensa privacy --json
64
+ commensa doctor --json
65
+ ```
66
+
67
+ ## Current platform boundary
68
+
69
+ The release candidate supports the same command-line installation flow on
70
+ macOS, Linux, and native Windows 11. On Windows, `pipx` supplies the isolated
71
+ Python runtime and Commensa creates managed `.cmd` launchers; PowerShell or
72
+ Command Prompt can run the same `commensa install ...` commands. WSL remains a
73
+ separate Linux route.
74
+
75
+ The Windows route has automated contract coverage but still requires its first
76
+ acceptance pass on a physical Windows 11 x64 host before it can be described as
77
+ host-verified. It is not the separately signed Windows desktop installer.
78
+
79
+ Signed native installers remain the intended nontechnical customer route. This
80
+ package is the interim cross-platform command-line route.
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/commensa.egg-info/PKG-INFO
4
+ src/commensa.egg-info/SOURCES.txt
5
+ src/commensa.egg-info/dependency_links.txt
6
+ src/commensa.egg-info/entry_points.txt
7
+ src/commensa.egg-info/top_level.txt
8
+ src/commensa_bootstrap/__init__.py
9
+ src/commensa_bootstrap/cli.py
10
+ src/commensa_bootstrap/errors.py
11
+ src/commensa_bootstrap/install.py
12
+ src/commensa_bootstrap/runtime.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ commensa = commensa_bootstrap.cli:main
@@ -0,0 +1 @@
1
+ commensa_bootstrap
@@ -0,0 +1,3 @@
1
+ """Public Commensa installer and stable command router."""
2
+
3
+ __version__ = "0.1.0rc2"
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from . import __version__
7
+ from .errors import BootstrapError
8
+ from .install import PAID_TARGETS, connect, install
9
+ from .runtime import forward
10
+
11
+
12
+ INSTALL_TARGETS = ("core", *PAID_TARGETS, "manager")
13
+ INTERFACES = ("codex", "claude-code", "cursor")
14
+
15
+
16
+ def build_parser() -> argparse.ArgumentParser:
17
+ parser = argparse.ArgumentParser(
18
+ prog="commensa",
19
+ description="Install and run verified Commensa products.",
20
+ )
21
+ parser.add_argument("--version", action="version", version=f"Commensa bootstrap {__version__}")
22
+ sub = parser.add_subparsers(dest="bootstrap_command")
23
+ install_parser = sub.add_parser("install", help="install an entitled Commensa capability")
24
+ install_parser.add_argument("target", choices=INSTALL_TARGETS)
25
+ install_parser.add_argument(
26
+ "--interface",
27
+ action="append",
28
+ choices=INTERFACES,
29
+ default=[],
30
+ help="AI interface for Manager; repeat to install more than one",
31
+ )
32
+ connect_parser = sub.add_parser("connect", help="connect an installed runtime to an AI host")
33
+ connect_parser.add_argument("host", choices=INTERFACES)
34
+ return parser
35
+
36
+
37
+ def main(argv: list[str] | None = None) -> int:
38
+ arguments = list(sys.argv[1:] if argv is None else argv)
39
+ if not arguments:
40
+ build_parser().print_help()
41
+ return 0
42
+ if arguments[0] not in {"install", "connect", "-h", "--help", "--version"}:
43
+ try:
44
+ return forward(arguments)
45
+ except BootstrapError as exc:
46
+ print(f"Commensa: {exc}", file=sys.stderr)
47
+ return 4
48
+ parser = build_parser()
49
+ args = parser.parse_args(arguments)
50
+ if args.bootstrap_command is None:
51
+ return 0
52
+ try:
53
+ if args.bootstrap_command == "install":
54
+ if args.interface and args.target != "manager":
55
+ raise BootstrapError("--interface applies only to Commensa Manager.")
56
+ install(args.target, interfaces=tuple(dict.fromkeys(args.interface)))
57
+ print(f"Commensa {args.target} installation and verification completed.")
58
+ else:
59
+ connect(args.host)
60
+ print(f"Commensa connection to {args.host} completed.")
61
+ return 0
62
+ except BootstrapError as exc:
63
+ print(f"Commensa: {exc}", file=sys.stderr)
64
+ return 1
65
+ except KeyboardInterrupt:
66
+ print("Commensa: cancelled.", file=sys.stderr)
67
+ return 7
68
+
69
+
70
+ if __name__ == "__main__":
71
+ raise SystemExit(main())
@@ -0,0 +1,3 @@
1
+ class BootstrapError(RuntimeError):
2
+ """A bounded, user-actionable bootstrap failure."""
3
+
@@ -0,0 +1,416 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import getpass
6
+ import json
7
+ import os
8
+ import platform
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import urllib.parse
14
+ import urllib.error
15
+ import urllib.request
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Sequence
19
+
20
+ from .errors import BootstrapError
21
+ from .runtime import command_invocation, default_data_home, managed_bin, runtime_command
22
+
23
+
24
+ MAX_INSTALLER_BYTES = 512 * 1024
25
+ MAX_ADAPTER_BYTES = 25 * 1024 * 1024
26
+ MAX_RELEASE_BYTES = 500 * 1024 * 1024
27
+ MAX_MANIFEST_BYTES = 32 * 1024
28
+ USER_AGENT = "Commensa-PyPI-Bootstrap/0.1.0rc2"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class InstallerSource:
33
+ url: str
34
+ sha256: str
35
+
36
+
37
+ INSTALLERS = {
38
+ "core": InstallerSource(
39
+ "https://commensa.ai/dl/install_core.py",
40
+ "7cf4874a58ec33baca149cfa67ebdf07f466c6db82c675409986ebfcd9900b17",
41
+ ),
42
+ "paid": InstallerSource(
43
+ "https://commensa.ai/downloads/install_product.py",
44
+ "d8c53a1cc0f897a28c7696a60ef8b4ad3f092d16c94658777b75f845f8095f7e",
45
+ ),
46
+ "manager": InstallerSource(
47
+ "https://commensa.ai/downloads/install_manager.py",
48
+ "59081156470cb59b156fa323ca4aa86b69727ae1efb15d370d5caf1ef5b581a7",
49
+ ),
50
+ }
51
+
52
+ CODEX_ADAPTER = InstallerSource(
53
+ "https://commensa.ai/dl/adapters/commensa-codex.zip",
54
+ "7188ce681249f51cc295657c807b89b97cdfe34ceed4ac35a7f06860641e9c74",
55
+ )
56
+
57
+ RELEASE_MANIFESTS = {
58
+ "paid": "https://commensa.ai/downloads/release-manifest.json",
59
+ "manager": "https://commensa.ai/downloads/manager-manifest.json",
60
+ }
61
+
62
+ PAID_TARGETS = {
63
+ "xray": "xray_project",
64
+ "report": "run_report",
65
+ "cockpit": "open_cockpit",
66
+ "me": "track_me",
67
+ }
68
+
69
+
70
+ def _validate_source(source: InstallerSource) -> None:
71
+ try:
72
+ parsed = urllib.parse.urlsplit(source.url)
73
+ port = parsed.port
74
+ except ValueError as exc:
75
+ raise BootstrapError("Bootstrap download URL is invalid.") from exc
76
+ if (
77
+ parsed.scheme != "https"
78
+ or parsed.hostname != "commensa.ai"
79
+ or parsed.username
80
+ or parsed.password
81
+ or port
82
+ ):
83
+ raise BootstrapError("Bootstrap downloads must use the Commensa HTTPS origin.")
84
+ if not re.fullmatch(r"[0-9a-f]{64}", source.sha256):
85
+ raise BootstrapError("Bootstrap source has an invalid pinned SHA-256 value.")
86
+
87
+
88
+ def parse_access_link(link: str, *, target: str) -> tuple[str, str]:
89
+ try:
90
+ parsed = urllib.parse.urlsplit(link.strip())
91
+ port = parsed.port
92
+ except ValueError as exc:
93
+ raise BootstrapError("The secure Commensa access link is invalid.") from exc
94
+ if (
95
+ parsed.scheme != "https"
96
+ or parsed.hostname != "commensa.ai"
97
+ or parsed.username
98
+ or parsed.password
99
+ or port
100
+ ):
101
+ raise BootstrapError("Use the secure https://commensa.ai access link from your delivery email.")
102
+ allowed_paths = {"/thanks"}
103
+ allowed_grants = ("session_id",)
104
+ if target == "manager":
105
+ allowed_paths.add("/manager-access")
106
+ allowed_grants = ("session_id", "beta_token")
107
+ if parsed.path not in allowed_paths:
108
+ raise BootstrapError("The secure access link has an unexpected Commensa path.")
109
+ query = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)
110
+ present = [(name, query[name]) for name in allowed_grants if name in query]
111
+ if len(present) != 1 or len(present[0][1]) != 1:
112
+ raise BootstrapError("The secure access link is missing one valid delivery grant.")
113
+ name, values = present[0]
114
+ value = values[0]
115
+ if not re.fullmatch(r"[A-Za-z0-9_-]{8,512}", value):
116
+ raise BootstrapError("The secure access link contains an invalid delivery grant.")
117
+ return name, value
118
+
119
+
120
+ def authorized_url(url: str, grant: tuple[str, str]) -> str:
121
+ try:
122
+ parsed = urllib.parse.urlsplit(url)
123
+ port = parsed.port
124
+ except ValueError as exc:
125
+ raise BootstrapError("Entitled download URL is invalid.") from exc
126
+ if (
127
+ parsed.scheme != "https"
128
+ or parsed.hostname != "commensa.ai"
129
+ or parsed.username
130
+ or parsed.password
131
+ or port
132
+ or parsed.query
133
+ ):
134
+ raise BootstrapError("Entitled downloads must use a clean Commensa HTTPS URL.")
135
+ name, value = grant
136
+ if name not in {"session_id", "beta_token"}:
137
+ raise BootstrapError("Unknown Commensa delivery grant type.")
138
+ return urllib.parse.urlunsplit(
139
+ (parsed.scheme, parsed.netloc, parsed.path, urllib.parse.urlencode({name: value}), "")
140
+ )
141
+
142
+
143
+ def download_verified(
144
+ source: InstallerSource,
145
+ destination: Path,
146
+ *,
147
+ maximum_bytes: int = MAX_INSTALLER_BYTES,
148
+ ) -> None:
149
+ _validate_source(source)
150
+ request = urllib.request.Request(
151
+ source.url,
152
+ headers={"accept": "application/octet-stream", "user-agent": USER_AGENT},
153
+ )
154
+ destination.parent.mkdir(parents=True, exist_ok=True)
155
+ temporary = destination.with_name(f".{destination.name}.download")
156
+ digest = hashlib.sha256()
157
+ total = 0
158
+ try:
159
+ try:
160
+ with urllib.request.urlopen(request, timeout=30) as response, temporary.open("wb") as handle:
161
+ while True:
162
+ chunk = response.read(64 * 1024)
163
+ if not chunk:
164
+ break
165
+ total += len(chunk)
166
+ if total > maximum_bytes:
167
+ raise BootstrapError("Verified download exceeds its size limit.")
168
+ digest.update(chunk)
169
+ handle.write(chunk)
170
+ handle.flush()
171
+ os.fsync(handle.fileno())
172
+ except (urllib.error.URLError, TimeoutError):
173
+ raise BootstrapError(
174
+ "The Commensa download could not be authorized or reached. "
175
+ "Reopen the secure access link or check the network, then try again."
176
+ ) from None
177
+ if not hmac.compare_digest(digest.hexdigest(), source.sha256):
178
+ raise BootstrapError("Downloaded Commensa installer did not match its pinned SHA-256 value.")
179
+ os.replace(temporary, destination)
180
+ finally:
181
+ try:
182
+ temporary.unlink()
183
+ except FileNotFoundError:
184
+ pass
185
+
186
+
187
+ def _installer_kind(target: str) -> str:
188
+ if target == "core":
189
+ return "core"
190
+ if target == "manager":
191
+ return "manager"
192
+ if target in PAID_TARGETS:
193
+ return "paid"
194
+ raise BootstrapError(f"Unknown Commensa install target: {target}")
195
+
196
+
197
+ def build_installer_command(
198
+ target: str,
199
+ script: Path,
200
+ data_home: Path,
201
+ *,
202
+ interfaces: Sequence[str],
203
+ archive: Path | None = None,
204
+ archive_sha256: str | None = None,
205
+ version: str | None = None,
206
+ ) -> list[str]:
207
+ kind = _installer_kind(target)
208
+ command = [
209
+ sys.executable,
210
+ str(script),
211
+ "--python-executable",
212
+ sys.executable,
213
+ "--install-root",
214
+ str(data_home),
215
+ "--bin-dir",
216
+ str(managed_bin(data_home)),
217
+ ]
218
+ if kind == "manager":
219
+ for interface in interfaces:
220
+ command.extend(["--platform", interface])
221
+ if archive is not None:
222
+ if not archive_sha256 or not version:
223
+ raise BootstrapError("A local release archive requires its exact hash and version.")
224
+ command.extend(
225
+ [
226
+ "--archive",
227
+ str(archive),
228
+ "--sha256",
229
+ archive_sha256,
230
+ "--version",
231
+ version,
232
+ ]
233
+ )
234
+ return command
235
+
236
+
237
+ def _fetch_entitled_release(
238
+ kind: str,
239
+ grant: tuple[str, str],
240
+ directory: Path,
241
+ ) -> tuple[Path, str, str]:
242
+ manifest_url = authorized_url(RELEASE_MANIFESTS[kind], grant)
243
+ request = urllib.request.Request(
244
+ manifest_url,
245
+ headers={"accept": "application/json", "user-agent": USER_AGENT},
246
+ )
247
+ try:
248
+ with urllib.request.urlopen(request, timeout=30) as response:
249
+ raw = response.read(MAX_MANIFEST_BYTES + 1)
250
+ except (urllib.error.URLError, TimeoutError):
251
+ raise BootstrapError(
252
+ "The entitled release manifest could not be authorized or reached. "
253
+ "Reopen the secure access link, then try again."
254
+ ) from None
255
+ if len(raw) > MAX_MANIFEST_BYTES:
256
+ raise BootstrapError("Commensa release manifest exceeds its size limit.")
257
+ try:
258
+ manifest = json.loads(raw.decode("utf-8"))
259
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
260
+ raise BootstrapError("Commensa release manifest is not valid JSON.") from exc
261
+ if not isinstance(manifest, dict) or manifest.get("schema_version") != "1":
262
+ raise BootstrapError("Commensa release manifest schema is unsupported.")
263
+ for field in ("archive", "sha256", "version"):
264
+ if not isinstance(manifest.get(field), str):
265
+ raise BootstrapError(f"Commensa release manifest is missing {field}.")
266
+ if not re.fullmatch(r"[0-9a-f]{64}", manifest["sha256"]):
267
+ raise BootstrapError("Commensa release manifest has an invalid archive hash.")
268
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,39}", manifest["version"]):
269
+ raise BootstrapError("Commensa release manifest has an invalid version.")
270
+ archive_base = urllib.parse.urljoin(RELEASE_MANIFESTS[kind], manifest["archive"])
271
+ try:
272
+ archive_parsed = urllib.parse.urlsplit(archive_base)
273
+ archive_port = archive_parsed.port
274
+ except ValueError as exc:
275
+ raise BootstrapError("Commensa release archive URL is invalid.") from exc
276
+ if (
277
+ archive_parsed.scheme != "https"
278
+ or archive_parsed.hostname != "commensa.ai"
279
+ or archive_parsed.username
280
+ or archive_parsed.password
281
+ or archive_port
282
+ ):
283
+ raise BootstrapError("Commensa release archive is outside the approved origin.")
284
+ archive = directory / Path(archive_parsed.path).name
285
+ download_verified(
286
+ InstallerSource(authorized_url(archive_base, grant), manifest["sha256"]),
287
+ archive,
288
+ maximum_bytes=MAX_RELEASE_BYTES,
289
+ )
290
+ return archive, manifest["sha256"], manifest["version"]
291
+
292
+
293
+ def _read_json_command(command: list[str]) -> dict:
294
+ completed = subprocess.run(command, check=False, capture_output=True, text=True)
295
+ if completed.returncode not in {0, 8}:
296
+ raise BootstrapError("Commensa installed, but its verification command failed.")
297
+ try:
298
+ result = json.loads(completed.stdout)
299
+ except json.JSONDecodeError as exc:
300
+ raise BootstrapError("Commensa installed, but verification returned invalid output.") from exc
301
+ if not isinstance(result, dict):
302
+ raise BootstrapError("Commensa verification returned an invalid response.")
303
+ return result
304
+
305
+
306
+ def _verify_install(target: str, data_home: Path, system: str) -> None:
307
+ manager = target == "manager"
308
+ command = runtime_command(data_home=data_home, manager=manager, system=system)
309
+ if not command.is_file():
310
+ raise BootstrapError("Installer completed without creating the managed Commensa runtime command.")
311
+ if manager:
312
+ result = _read_json_command(
313
+ command_invocation(command, ["doctor", "--json"], system=system)
314
+ )
315
+ if result.get("status") not in {"ok", "needs_attention"}:
316
+ raise BootstrapError("Commensa Manager did not return a valid post-install status.")
317
+ return
318
+ result = _read_json_command(
319
+ command_invocation(command, ["capabilities", "--json"], system=system)
320
+ )
321
+ if result.get("status") != "ok" or not isinstance(result.get("capabilities"), dict):
322
+ raise BootstrapError("Commensa did not return its installed capability catalog.")
323
+ capability = PAID_TARGETS.get(target)
324
+ if capability and result["capabilities"].get(capability, {}).get("status") not in {
325
+ "available",
326
+ "offline_grace",
327
+ }:
328
+ raise BootstrapError(
329
+ f"The runtime installed, but this access key does not currently grant {target}."
330
+ )
331
+
332
+
333
+ def install(
334
+ target: str,
335
+ *,
336
+ data_home: Path | None = None,
337
+ interfaces: Sequence[str] = (),
338
+ system: str | None = None,
339
+ access_link: str | None = None,
340
+ ) -> None:
341
+ system = system or platform.system()
342
+ if system not in {"Darwin", "Linux", "Windows"}:
343
+ raise BootstrapError(f"This Commensa bootstrap has not been accepted on {system}.")
344
+ kind = _installer_kind(target)
345
+ source = INSTALLERS[kind]
346
+ root = data_home or default_data_home(system)
347
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
348
+ try:
349
+ os.chmod(root, 0o700)
350
+ except OSError:
351
+ pass
352
+ with tempfile.TemporaryDirectory(prefix=".bootstrap-", dir=root) as raw:
353
+ script = Path(raw) / f"install_{kind}.py"
354
+ archive = None
355
+ archive_sha256 = None
356
+ version = None
357
+ if kind == "core":
358
+ download_verified(source, script)
359
+ else:
360
+ link = access_link or getpass.getpass(
361
+ "Secure Commensa access link from your delivery email: "
362
+ )
363
+ grant = parse_access_link(link, target=target)
364
+ download_verified(
365
+ InstallerSource(authorized_url(source.url, grant), source.sha256),
366
+ script,
367
+ )
368
+ archive, archive_sha256, version = _fetch_entitled_release(
369
+ kind, grant, Path(raw)
370
+ )
371
+ command = build_installer_command(
372
+ target,
373
+ script,
374
+ root,
375
+ interfaces=interfaces,
376
+ archive=archive,
377
+ archive_sha256=archive_sha256,
378
+ version=version,
379
+ )
380
+ completed = subprocess.run(command, check=False)
381
+ if completed.returncode != 0:
382
+ raise BootstrapError(f"The verified Commensa {target} installer did not complete.")
383
+ _verify_install(target, root, system)
384
+
385
+
386
+ def connect(host: str, *, data_home: Path | None = None, system: str | None = None) -> None:
387
+ system = system or platform.system()
388
+ root = data_home or default_data_home(system)
389
+ if host != "codex":
390
+ raise BootstrapError(
391
+ f"Automated {host} connection is not yet an accepted PyPI route. "
392
+ "Use https://commensa.ai/install for the current instructions."
393
+ )
394
+ command = runtime_command(data_home=root, system=system)
395
+ if not command.is_file():
396
+ raise BootstrapError("Install Commensa Core before connecting Codex.")
397
+ with tempfile.TemporaryDirectory(prefix=".adapter-", dir=root) as raw:
398
+ archive = Path(raw) / "commensa-codex.zip"
399
+ download_verified(CODEX_ADAPTER, archive, maximum_bytes=MAX_ADAPTER_BYTES)
400
+ completed = subprocess.run(
401
+ command_invocation(
402
+ command,
403
+ [
404
+ "integrate",
405
+ "codex",
406
+ "--archive",
407
+ str(archive),
408
+ "--sha256",
409
+ CODEX_ADAPTER.sha256,
410
+ ],
411
+ system=system,
412
+ ),
413
+ check=False,
414
+ )
415
+ if completed.returncode != 0:
416
+ raise BootstrapError("The verified Codex connection needs attention.")
@@ -0,0 +1,81 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import subprocess
6
+ from pathlib import Path
7
+ from typing import Sequence
8
+
9
+ from .errors import BootstrapError
10
+
11
+
12
+ def default_data_home(system: str | None = None) -> Path:
13
+ system = system or platform.system()
14
+ configured = os.environ.get("COMMENSA_HOME")
15
+ if configured:
16
+ return Path(configured).expanduser()
17
+ if system == "Windows":
18
+ local = os.environ.get("LOCALAPPDATA")
19
+ if local:
20
+ return Path(local) / "Commensa"
21
+ return Path.home() / ".commensa"
22
+
23
+
24
+ def managed_bin(data_home: Path) -> Path:
25
+ return data_home.expanduser() / "bootstrap" / "bin"
26
+
27
+
28
+ def runtime_command(
29
+ *,
30
+ data_home: Path,
31
+ manager: bool = False,
32
+ system: str | None = None,
33
+ ) -> Path:
34
+ system = system or platform.system()
35
+ name = "commensa-manager" if manager else "commensa"
36
+ if system == "Windows":
37
+ name += ".cmd"
38
+ return managed_bin(data_home) / name
39
+
40
+
41
+ def command_invocation(
42
+ command: Path,
43
+ arguments: Sequence[str],
44
+ *,
45
+ system: str | None = None,
46
+ ) -> list[str]:
47
+ system = system or platform.system()
48
+ if system == "Windows":
49
+ return [
50
+ os.environ.get("COMSPEC", "cmd.exe"),
51
+ "/d",
52
+ "/s",
53
+ "/c",
54
+ str(command),
55
+ *arguments,
56
+ ]
57
+ return [str(command), *arguments]
58
+
59
+
60
+ def forward(
61
+ arguments: Sequence[str],
62
+ *,
63
+ data_home: Path | None = None,
64
+ system: str | None = None,
65
+ ) -> int:
66
+ data_home = data_home or default_data_home(system)
67
+ args = list(arguments)
68
+ manager = bool(args and args[0] == "manager")
69
+ if manager:
70
+ args = args[1:]
71
+ command = runtime_command(data_home=data_home, manager=manager, system=system)
72
+ if not command.is_file():
73
+ target = "manager" if manager else "core"
74
+ raise BootstrapError(
75
+ f"The verified Commensa {target} runtime is not installed. "
76
+ f"Run: commensa install {target}"
77
+ )
78
+ return subprocess.run(
79
+ command_invocation(command, args, system=system),
80
+ check=False,
81
+ ).returncode