bloom-launch 0.1.0a1__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.
bloom_cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Bloom Launch structural contract, revision 1."""
bloom_cli/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
bloom_cli/adapters.py ADDED
@@ -0,0 +1,205 @@
1
+ """Minimal scoped native configuration; inspectors supply assessed native controls."""
2
+
3
+ import json
4
+ import os
5
+ import shutil
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+ from .contract import (
10
+ CredentialResolver,
11
+ LaunchError,
12
+ LaunchPlan,
13
+ LaunchRequest,
14
+ QualifiedPath,
15
+ Secret,
16
+ )
17
+ from .controls import agent_name, valid_role, validate_claude_conversation
18
+ from .native import validate_claude_version, validate_opencode_version
19
+
20
+
21
+ class _Adapter:
22
+ harness: str
23
+ protocol: str
24
+
25
+ def __init__(self, resolver: CredentialResolver,
26
+ qualified_paths: tuple[QualifiedPath, ...] = (),
27
+ runtime_parent: Path | None = None):
28
+ self.resolver = resolver
29
+ self.qualified_paths = tuple(qualified_paths)
30
+ self.runtime_parent = runtime_parent
31
+
32
+ def validate(self, request: LaunchRequest) -> None:
33
+ if request.assessment.unresolved:
34
+ raise LaunchError("Native controls unresolved; assess managed policy, login, "
35
+ "providers and extensions before launch")
36
+ self._validate_structure(request)
37
+
38
+ def _validate_structure(self, request: LaunchRequest) -> None:
39
+ """Shared mechanics; ordinary validation additionally requires full assessment."""
40
+ if request.connection.endpoint != request.connection.credential.origin:
41
+ raise LaunchError("Credential reference belongs to a different gateway origin")
42
+ self._validate_version(request.version)
43
+ environment = request.child_environment
44
+ if environment is None:
45
+ raise LaunchError("Preparation requires an owned environment snapshot")
46
+ boolean_controls = ({"CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX",
47
+ "CLAUDE_CODE_USE_FOUNDRY"} if self.harness == "claude" else set())
48
+ text_controls = ({"ANTHROPIC_CUSTOM_HEADERS"} if self.harness == "claude" else
49
+ {"OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "OPENCODE_CONFIG_CONTENT"})
50
+ if (any(environment.get(name, "").lower() not in ("", "0", "false")
51
+ for name in boolean_controls)
52
+ or any(environment.get(name, "") for name in text_controls)):
53
+ raise LaunchError("Native provider/configuration environment controls unresolved")
54
+ if not request.executable.is_absolute() or not request.cwd.is_absolute():
55
+ raise LaunchError("Executable and cwd must be absolute paths")
56
+ if not request.cwd.is_dir():
57
+ raise LaunchError("Launch cwd is not a directory")
58
+ models = {request.baseline_model, *request.role_models.values()}
59
+ if any(not model or any(c.isspace() or ord(c) < 32 for c in model) for model in models):
60
+ raise LaunchError("Use exact nonempty model IDs")
61
+ self._validate_roles(request)
62
+ self._validate_args(request)
63
+
64
+ def _validate_version(self, version):
65
+ raise NotImplementedError
66
+
67
+ def resolve(self, request: LaunchRequest) -> Secret:
68
+ try:
69
+ secret = self.resolver(request.connection)
70
+ if not isinstance(secret, Secret) or not secret.value or any(
71
+ ord(c) < 32 or ord(c) == 127 for c in secret.value
72
+ ):
73
+ raise ValueError
74
+ if any(secret.value in arg for arg in request.passthrough):
75
+ raise ValueError
76
+ return secret
77
+ except Exception:
78
+ raise LaunchError("Credential resolution failed; check the configured source") from None
79
+
80
+ def prepare(self, request: LaunchRequest) -> LaunchPlan:
81
+ request = request.snapshot()
82
+ self.validate(request)
83
+ for role, model in {"main": request.baseline_model, **request.role_models}.items():
84
+ if not any(path.schema_version == 1 and path.harness == self.harness
85
+ and path.version == request.version and path.model == model
86
+ and path.protocol == self.protocol and role in path.roles
87
+ for path in self.qualified_paths):
88
+ raise LaunchError("No qualified path for the exact model/version; use internal "
89
+ "qualification for an authorized candidate")
90
+ return self._prepare_authorized(request, self.resolve(request), "qualified")
91
+
92
+ def _validate_roles(self, request):
93
+ raise NotImplementedError
94
+
95
+ def _validate_args(self, request):
96
+ if self.harness == "claude":
97
+ validate_claude_conversation(request.passthrough, request.version)
98
+ return
99
+ # A deliberately small passthrough grammar: unknown flags may affect connection or roles.
100
+ if (self.harness == "opencode" and request.passthrough
101
+ and request.passthrough[0] != "run"):
102
+ raise LaunchError("Unresolved passthrough invocation; use interactive or run mode")
103
+ values = {"--format", "--title"}
104
+ args = iter(request.passthrough)
105
+ for arg in args:
106
+ if arg == "--":
107
+ raise LaunchError("Unresolved passthrough separator would hide scoped settings")
108
+ if arg == "--agent" and self.harness == "opencode":
109
+ name = next(args, "")
110
+ if not agent_name(name) or "agent:" + name not in request.role_models:
111
+ raise LaunchError("Unresolved passthrough agent choice")
112
+ elif arg in values:
113
+ value = next(args, "")
114
+ if not value or value.startswith("-"):
115
+ raise LaunchError("Missing or ambiguous passthrough option value")
116
+ elif arg.startswith("-"):
117
+ raise LaunchError("Unresolved passthrough control; supply resolved models/roles")
118
+
119
+ def _plan(self, request, updates, removals, artifacts, qualification, argv=None):
120
+ return LaunchPlan(
121
+ executable=request.executable,
122
+ argv=tuple(request.passthrough if argv is None else argv),
123
+ cwd=request.cwd, version=request.version, baseline_model=request.baseline_model,
124
+ role_models=dict(request.role_models), environment_updates=updates,
125
+ environment_removals=frozenset(removals), owned_artifacts=tuple(artifacts),
126
+ child_environment=(dict(request.child_environment)
127
+ if request.child_environment is not None else None),
128
+ qualification=qualification,
129
+ )
130
+
131
+
132
+ class ClaudeAdapter(_Adapter):
133
+ harness = "claude"
134
+ protocol = "anthropic-messages"
135
+
136
+ def _validate_version(self, version):
137
+ validate_claude_version(version)
138
+
139
+ def _validate_roles(self, request):
140
+ if set(request.role_models) - {"haiku", "sonnet", "opus", "subagent"}:
141
+ raise LaunchError("Unresolved Claude role choice")
142
+
143
+ def _prepare_authorized(self, request, secret, qualification):
144
+ directory = None
145
+ try:
146
+ directory = Path(tempfile.mkdtemp(prefix="bloom-launch-", dir=self.runtime_parent))
147
+ directory.chmod(0o700)
148
+ env = {
149
+ "ANTHROPIC_BASE_URL": request.connection.endpoint,
150
+ "ANTHROPIC_AUTH_TOKEN": secret.value,
151
+ "ANTHROPIC_API_KEY": "",
152
+ "ANTHROPIC_MODEL": request.baseline_model,
153
+ "CLAUDE_CODE_GATEWAY_HINT_HEADERS": "1",
154
+ }
155
+ for role, model in request.role_models.items():
156
+ name = ("CLAUDE_CODE_SUBAGENT_MODEL" if role == "subagent"
157
+ else f"ANTHROPIC_DEFAULT_{role.upper()}_MODEL")
158
+ env[name] = model
159
+ path = directory / "settings.json"
160
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
161
+ with os.fdopen(fd, "w") as stream:
162
+ os.fchmod(stream.fileno(), 0o600)
163
+ json.dump({"env": env, "apiKeyHelper": ""}, stream)
164
+ return self._plan(
165
+ request, {}, {"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"}, (directory,),
166
+ qualification, (*request.passthrough, "--settings", str(path)),
167
+ )
168
+ except BaseException as error:
169
+ if directory is not None:
170
+ shutil.rmtree(directory)
171
+ if not isinstance(error, Exception):
172
+ raise
173
+ raise LaunchError("Could not prepare protected Claude session settings") from None
174
+
175
+
176
+ class OpenCodeAdapter(_Adapter):
177
+ harness = "opencode"
178
+ protocol = "openai-chat-completions"
179
+
180
+ def _validate_version(self, version):
181
+ validate_opencode_version(version)
182
+
183
+ def _validate_roles(self, request):
184
+ if any(not valid_role("opencode", role) for role in request.role_models):
185
+ raise LaunchError("Unresolved OpenCode role choice")
186
+ if "small" not in request.role_models:
187
+ raise LaunchError("OpenCode requires an explicit compatible small model")
188
+
189
+ def _prepare_authorized(self, request, secret, qualification):
190
+ models = {request.baseline_model, *request.role_models.values()}
191
+ config = {
192
+ "model": "bloom/" + request.baseline_model,
193
+ "small_model": "bloom/" + request.role_models["small"],
194
+ "provider": {"bloom": {
195
+ "name": "Bloom", "npm": "@ai-sdk/openai-compatible",
196
+ "options": {"baseURL": request.connection.endpoint + "/v1", "apiKey": secret.value},
197
+ "models": {model: {"name": model} for model in sorted(models)},
198
+ }},
199
+ }
200
+ agents = {role[6:]: {"model": "bloom/" + model}
201
+ for role, model in request.role_models.items() if role.startswith("agent:")}
202
+ if agents:
203
+ config["agent"] = agents
204
+ return self._plan(request, {"OPENCODE_CONFIG_CONTENT": json.dumps(config)}, (), (),
205
+ qualification)
@@ -0,0 +1,50 @@
1
+ """Invocation-owned authenticated grants, never a configuration-supplied allowlist."""
2
+
3
+ from collections.abc import Callable, Iterable
4
+ from dataclasses import dataclass, field
5
+
6
+ from .contract import LaunchConnection, LaunchError, Secret
7
+ from .credentials import normalize_origin
8
+ from .discovery import discover_permitted
9
+
10
+ DiscoveryTransport = Callable[[LaunchConnection, Secret], Iterable[str]]
11
+
12
+
13
+ @dataclass(frozen=True, init=False)
14
+ class DiscoveryAuthorization:
15
+ """Construct only by discovery. Python composition may inject a trusted transport."""
16
+
17
+ origin: str
18
+ _secret: Secret = field(repr=False)
19
+ _value: str = field(repr=False)
20
+ _grants: frozenset[str] = field(repr=False)
21
+
22
+ def __init__(self, connection: LaunchConnection, secret: Secret, *,
23
+ transport: DiscoveryTransport = discover_permitted) -> None:
24
+ origin = normalize_origin(connection.endpoint)
25
+ if origin != normalize_origin(connection.credential.origin):
26
+ raise LaunchError("Discovery authorization binding changed; retry with --config")
27
+ object.__setattr__(self, "origin", origin)
28
+ object.__setattr__(self, "_secret", secret)
29
+ object.__setattr__(self, "_value", secret.value)
30
+ object.__setattr__(self, "_grants", frozenset(transport(connection, secret)))
31
+ self.authorize(connection, secret)
32
+ if not self._grants:
33
+ raise LaunchError("No permitted model IDs; check gateway access or retry with --config")
34
+ # Validate the complete immutable snapshot before any consumer can print
35
+ # or filter it. Encoding checks scalar validity without changing the IDs.
36
+ try:
37
+ for model in self._grants:
38
+ model.encode("utf-8")
39
+ except UnicodeEncodeError:
40
+ raise LaunchError("Invalid discovery content; expected valid Unicode model IDs; "
41
+ "retry with --config") from None
42
+ if any(self._value in model for model in self._grants):
43
+ raise LaunchError("Unsafe discovery content; retry with --config")
44
+
45
+ def authorize(self, connection: LaunchConnection, secret: Secret) -> frozenset[str]:
46
+ if (normalize_origin(connection.endpoint) != self.origin
47
+ or normalize_origin(connection.credential.origin) != self.origin
48
+ or secret is not self._secret or secret.value != self._value):
49
+ raise LaunchError("Discovery authorization binding changed; retry with --config")
50
+ return self._grants