@simplexai/localmodels-linux-x64 0.1.0-dev.38 → 0.1.0-dev.40
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +81 -73
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +4 -0
- package/modules/localmodels/auth_proxy.py +74 -16
- package/modules/localmodels/bifrost_config.py +19 -0
- package/modules/localmodels/budget.py +27 -18
- package/modules/localmodels/catalog.json +18 -6
- package/modules/localmodels/chat_template.py +35 -0
- package/modules/localmodels/cli_parser.py +26 -3
- package/modules/localmodels/deploy.py +44 -10
- package/modules/localmodels/deploy_steps.py +6 -3
- package/modules/localmodels/download-mirrors.json +52 -4
- package/modules/localmodels/engines-b11583.json +20 -4
- package/modules/localmodels/engines-b12167.json +5 -1
- package/modules/localmodels/engines-strata-0.1.47.json +5 -1
- package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
- package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
- package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
- package/modules/localmodels/engines-whisper-b5454.json +5 -1
- package/modules/localmodels/engines.json +55 -11
- package/modules/localmodels/frontend.py +5 -2
- package/modules/localmodels/gateway.py +2 -0
- package/modules/localmodels/gateway_bifrost.py +3 -0
- package/modules/localmodels/gateway_home.py +132 -0
- package/modules/localmodels/guard.py +15 -6
- package/modules/localmodels/harness.py +104 -37
- package/modules/localmodels/harness_gateway.py +9 -3
- package/modules/localmodels/harness_probe.py +5 -1
- package/modules/localmodels/hf_repo.py +15 -8
- package/modules/localmodels/library_gateway.py +28 -15
- package/modules/localmodels/library_jobs.py +7 -1
- package/modules/localmodels/library_serve.py +5 -0
- package/modules/localmodels/metal.py +29 -12
- package/modules/localmodels/metal_probe.py +16 -6
- package/modules/localmodels/npm_signatures.py +131 -0
- package/modules/localmodels/npm_transport.py +26 -10
- package/modules/localmodels/probe.py +4 -0
- package/modules/localmodels/process_identity.py +21 -5
- package/modules/localmodels/region.py +244 -0
- package/modules/localmodels/remote_ops.py +69 -13
- package/modules/localmodels/remote_ops_download.py +217 -10
- package/modules/localmodels/remote_ops_prepare.py +61 -8
- package/modules/localmodels/remote_ops_remove.py +15 -0
- package/modules/localmodels/remote_ops_service.py +10 -0
- package/modules/localmodels/runtime-lock.json +13 -13
- package/modules/localmodels/runtime_args.py +4 -2
- package/modules/localmodels/runtime_cli.py +76 -74
- package/modules/localmodels/runtime_discovery.py +58 -0
- package/modules/localmodels/runtime_install.py +103 -7
- package/modules/localmodels/runtime_io.py +64 -7
- package/modules/localmodels/runtime_pi.py +122 -0
- package/modules/localmodels/runtime_process.py +101 -15
- package/modules/localmodels/runtime_releases.py +51 -71
- package/modules/localmodels/service_deployment.py +5 -3
- package/modules/localmodels/service_probe.py +146 -31
- package/modules/localmodels/setup_inspection.py +110 -14
- package/modules/localmodels/setup_text.py +13 -0
- package/modules/localmodels/slot_cache.py +467 -0
- package/modules/localmodels/source_byok.py +484 -0
- package/modules/localmodels/source_byok_probe.py +275 -0
- package/modules/localmodels/source_cli.py +426 -0
- package/modules/localmodels/stack_args.py +2 -1
- package/modules/localmodels/stack_binding.py +125 -5
- package/modules/localmodels/stack_capacity.py +3 -3
- package/modules/localmodels/stack_down.py +22 -7
- package/modules/localmodels/stack_events.py +62 -0
- package/modules/localmodels/stack_hardware.py +20 -17
- package/modules/localmodels/stack_lifecycle.py +12 -3
- package/modules/localmodels/stack_rollback.py +9 -4
- package/modules/localmodels/stack_up.py +27 -20
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/tools.json +1365 -14
- package/modules/localmodels/transport.py +2 -0
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +78 -70
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""BYOK upstream validation, live probing, Bifrost mounting and isolated client profiles."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import copy
|
|
7
|
+
import ipaddress
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import urllib.parse
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Literal, TypedDict
|
|
14
|
+
|
|
15
|
+
from localmodels import (
|
|
16
|
+
bifrost_config,
|
|
17
|
+
bifrost_datasheet,
|
|
18
|
+
bifrost_models,
|
|
19
|
+
bifrost_provider,
|
|
20
|
+
gateway_bifrost,
|
|
21
|
+
harness,
|
|
22
|
+
hosts,
|
|
23
|
+
library_gateway,
|
|
24
|
+
runtime_io,
|
|
25
|
+
)
|
|
26
|
+
from localmodels.probe import HostFacts
|
|
27
|
+
|
|
28
|
+
Protocol = Literal["openai-chat", "openai-responses", "anthropic"]
|
|
29
|
+
Mode = Literal["local", "subscription", "byok"]
|
|
30
|
+
Runtime = Literal["claude", "codex", "pi"]
|
|
31
|
+
|
|
32
|
+
PROTOCOLS: tuple[Protocol, ...] = ("openai-chat", "openai-responses", "anthropic")
|
|
33
|
+
# The order the wire formats are tried for each Runtime: its own format first, so Bifrost
|
|
34
|
+
# forwards the Runtime's requests without translating them.
|
|
35
|
+
PROTOCOL_ORDER: dict[Runtime, tuple[Protocol, ...]] = {
|
|
36
|
+
"claude": ("anthropic", "openai-responses", "openai-chat"),
|
|
37
|
+
"codex": ("openai-responses", "openai-chat", "anthropic"),
|
|
38
|
+
"pi": ("openai-chat", "openai-responses", "anthropic"),
|
|
39
|
+
}
|
|
40
|
+
MODES: tuple[Mode, ...] = ("local", "subscription", "byok")
|
|
41
|
+
RUNTIMES: tuple[Runtime, ...] = ("claude", "codex", "pi")
|
|
42
|
+
|
|
43
|
+
BYOK_PROVIDER = bifrost_config.BYOK_PROVIDER
|
|
44
|
+
BYOK_MODEL = BYOK_PROVIDER
|
|
45
|
+
BYOK_PI_MODEL = f"{gateway_bifrost.PI_PROVIDER}/{BYOK_MODEL}"
|
|
46
|
+
DEFAULT_CONTEXT_WINDOW = bifrost_models.DEFAULT_CONTEXT
|
|
47
|
+
MAX_CONTEXT_WINDOW = 2_147_483_647
|
|
48
|
+
MODEL_ID_PATTERN = re.compile(r"^[-a-zA-Z0-9_./:@]{1,256}$")
|
|
49
|
+
|
|
50
|
+
CREDENTIALS_SCHEMA = "localmodels.byok-credentials/v1"
|
|
51
|
+
SOURCE_SCHEMA = "localmodels.model-source/v1"
|
|
52
|
+
STATUS_SCHEMA = "localmodels.model-source-status/v1"
|
|
53
|
+
CHECK_SCHEMA = "localmodels.byok-check/v1"
|
|
54
|
+
MODELS_SCHEMA = "localmodels.byok-models/v1"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ByokEndpoint(TypedDict):
|
|
58
|
+
base_url: str
|
|
59
|
+
api_key: str
|
|
60
|
+
model_id: str
|
|
61
|
+
context_window: int
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ByokCredentials(TypedDict):
|
|
65
|
+
schema: str
|
|
66
|
+
protocol: Protocol
|
|
67
|
+
# As entered, and the address that answered ``protocol``, which can add or drop the
|
|
68
|
+
# /anthropic of a gateway serving both API families.
|
|
69
|
+
base_url: str
|
|
70
|
+
upstream_url: str
|
|
71
|
+
api_key: str
|
|
72
|
+
model_id: str
|
|
73
|
+
context_window: int
|
|
74
|
+
key_saved: bool
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ByokSummary(TypedDict):
|
|
78
|
+
configured: bool
|
|
79
|
+
protocol: Protocol | None
|
|
80
|
+
base_url: str | None
|
|
81
|
+
model_id: str | None
|
|
82
|
+
context_window: int | None
|
|
83
|
+
key_saved: bool
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class SourceState(TypedDict):
|
|
87
|
+
schema: str
|
|
88
|
+
mode: Mode
|
|
89
|
+
runtime: Runtime
|
|
90
|
+
runtime_model: str
|
|
91
|
+
# The BYOK model ID as entered, which the Computer shows in place of the gateway route.
|
|
92
|
+
model_label: str | None
|
|
93
|
+
gateway_url: str | None
|
|
94
|
+
environment: dict[str, str]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class ByokError(ValueError):
|
|
98
|
+
"""Structured BYOK failure with a closed error code and CLI exit status."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, code: str, message: str, *, exit_code: int = 1) -> None:
|
|
101
|
+
super().__init__(message)
|
|
102
|
+
self.code = code
|
|
103
|
+
self.exit_code = exit_code
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _credentials_path() -> Path:
|
|
107
|
+
return hosts.state_dir().resolve() / "byok.json"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _source_path() -> Path:
|
|
111
|
+
return hosts.state_dir().resolve() / "model-source.json"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def byok_home() -> Path:
|
|
115
|
+
"""Isolated client configuration root for BYOK, separate from native and stack profiles."""
|
|
116
|
+
return hosts.state_dir().resolve() / "byok-home"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _is_tailscale(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
|
120
|
+
return isinstance(address, ipaddress.IPv4Address) and address in ipaddress.ip_network(
|
|
121
|
+
"100.64.0.0/10"
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _classify_host(hostname: str) -> bool:
|
|
126
|
+
"""Return whether ``hostname`` is loopback or private LAN; reject metadata/link-local hosts."""
|
|
127
|
+
lowered = hostname.lower().rstrip(".")
|
|
128
|
+
if not lowered:
|
|
129
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Endpoint URL requires a hostname.", exit_code=2)
|
|
130
|
+
try:
|
|
131
|
+
address = ipaddress.ip_address(lowered)
|
|
132
|
+
except ValueError:
|
|
133
|
+
if lowered == "metadata.google.internal":
|
|
134
|
+
raise ByokError(
|
|
135
|
+
"BYOK_INVALID_CONFIG", "Metadata endpoints are not allowed.", exit_code=2
|
|
136
|
+
) from None
|
|
137
|
+
return lowered == "localhost" or lowered.endswith(".local") or "." not in lowered
|
|
138
|
+
if address.is_link_local or address.is_multicast or address.is_unspecified:
|
|
139
|
+
raise ByokError(
|
|
140
|
+
"BYOK_INVALID_CONFIG",
|
|
141
|
+
"Link-local, multicast and unspecified addresses are not allowed.",
|
|
142
|
+
exit_code=2,
|
|
143
|
+
)
|
|
144
|
+
return bool(address.is_loopback or address.is_private or _is_tailscale(address))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def validate_url(raw: object) -> tuple[str, bool]:
|
|
148
|
+
"""Validate an upstream endpoint URL and report whether it targets loopback or private LAN."""
|
|
149
|
+
if not isinstance(raw, str) or not raw.strip() or len(raw) > 2048:
|
|
150
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Endpoint URL is required.", exit_code=2)
|
|
151
|
+
value = raw.strip().rstrip("/")
|
|
152
|
+
parsed = urllib.parse.urlsplit(value)
|
|
153
|
+
try:
|
|
154
|
+
port = parsed.port
|
|
155
|
+
except ValueError as exc:
|
|
156
|
+
raise ByokError(
|
|
157
|
+
"BYOK_INVALID_CONFIG", "Endpoint URL port is invalid.", exit_code=2
|
|
158
|
+
) from exc
|
|
159
|
+
if (
|
|
160
|
+
parsed.scheme not in ("http", "https")
|
|
161
|
+
or not parsed.hostname
|
|
162
|
+
or parsed.username is not None
|
|
163
|
+
or parsed.password is not None
|
|
164
|
+
or parsed.query
|
|
165
|
+
or parsed.fragment
|
|
166
|
+
or (port is not None and not 1 <= port <= 65535)
|
|
167
|
+
):
|
|
168
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Endpoint URL format is invalid.", exit_code=2)
|
|
169
|
+
private = _classify_host(parsed.hostname)
|
|
170
|
+
if parsed.scheme == "http" and not private:
|
|
171
|
+
raise ByokError(
|
|
172
|
+
"BYOK_INVALID_CONFIG",
|
|
173
|
+
"Plain HTTP is allowed only for localhost and private network endpoints.",
|
|
174
|
+
exit_code=2,
|
|
175
|
+
)
|
|
176
|
+
return value, private
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def load_credentials() -> ByokCredentials | None:
|
|
180
|
+
"""Read saved BYOK credentials from private state, or None when absent."""
|
|
181
|
+
path = _credentials_path()
|
|
182
|
+
if not path.exists() and not path.is_symlink():
|
|
183
|
+
return None
|
|
184
|
+
runtime_io.private_permissions(path)
|
|
185
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
186
|
+
if not isinstance(raw, dict) or raw.get("schema") != CREDENTIALS_SCHEMA:
|
|
187
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK credentials are invalid.")
|
|
188
|
+
protocol = raw.get("protocol")
|
|
189
|
+
if protocol not in PROTOCOLS:
|
|
190
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK protocol is invalid.")
|
|
191
|
+
url, _ = validate_url(raw.get("base_url"))
|
|
192
|
+
upstream, _ = validate_url(raw.get("upstream_url"))
|
|
193
|
+
model_id = str(raw.get("model_id") or "")
|
|
194
|
+
if not MODEL_ID_PATTERN.fullmatch(model_id):
|
|
195
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK model ID is invalid.")
|
|
196
|
+
key = raw.get("api_key", "")
|
|
197
|
+
if not isinstance(key, str):
|
|
198
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK key is invalid.")
|
|
199
|
+
window = int(raw.get("context_window") or DEFAULT_CONTEXT_WINDOW)
|
|
200
|
+
return {
|
|
201
|
+
"schema": CREDENTIALS_SCHEMA,
|
|
202
|
+
"protocol": protocol,
|
|
203
|
+
"base_url": url,
|
|
204
|
+
"upstream_url": upstream,
|
|
205
|
+
"api_key": key,
|
|
206
|
+
"model_id": model_id,
|
|
207
|
+
"context_window": window if 1 <= window <= MAX_CONTEXT_WINDOW else DEFAULT_CONTEXT_WINDOW,
|
|
208
|
+
"key_saved": bool(key),
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def save_credentials(creds: ByokCredentials) -> None:
|
|
213
|
+
"""Persist BYOK credentials in a 0600 private file."""
|
|
214
|
+
state = hosts.state_dir().resolve()
|
|
215
|
+
runtime_io.private_directory(state)
|
|
216
|
+
runtime_io.write_private_json(_credentials_path(), creds)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def credentials_summary(creds: ByokCredentials | None = None) -> ByokSummary:
|
|
220
|
+
"""Redacted BYOK metadata safe to expose across RPC and UI boundaries."""
|
|
221
|
+
loaded = creds if creds is not None else load_credentials()
|
|
222
|
+
if loaded is None:
|
|
223
|
+
return {
|
|
224
|
+
"configured": False,
|
|
225
|
+
"protocol": None,
|
|
226
|
+
"base_url": None,
|
|
227
|
+
"model_id": None,
|
|
228
|
+
"context_window": None,
|
|
229
|
+
"key_saved": False,
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
"configured": True,
|
|
233
|
+
"protocol": loaded["protocol"],
|
|
234
|
+
"base_url": loaded["base_url"],
|
|
235
|
+
"model_id": loaded["model_id"],
|
|
236
|
+
"context_window": loaded["context_window"],
|
|
237
|
+
"key_saved": loaded["key_saved"],
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _resolve_key(payload: dict[str, Any], saved: ByokCredentials | None, private: bool) -> str:
|
|
242
|
+
raw_key = payload.get("apiKey")
|
|
243
|
+
if isinstance(raw_key, str) and raw_key != "":
|
|
244
|
+
if len(raw_key) > 4096 or any(ord(c) <= 32 or ord(c) == 127 for c in raw_key):
|
|
245
|
+
raise ByokError("BYOK_INVALID_CONFIG", "API key format is invalid.", exit_code=2)
|
|
246
|
+
return raw_key
|
|
247
|
+
if raw_key is None and saved is not None and saved["key_saved"]:
|
|
248
|
+
return saved["api_key"]
|
|
249
|
+
if raw_key == "" and saved is not None and saved["key_saved"] and payload.get("reuseSavedKey"):
|
|
250
|
+
return saved["api_key"]
|
|
251
|
+
if private and (raw_key == "" or raw_key is None):
|
|
252
|
+
return ""
|
|
253
|
+
raise ByokError("BYOK_INVALID_CONFIG", "An API key is required for this endpoint.", exit_code=2)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def resolve_endpoint(
|
|
257
|
+
payload: dict[str, Any] | None, *, require_input: bool = False, require_model: bool = True
|
|
258
|
+
) -> ByokEndpoint:
|
|
259
|
+
"""Validate incoming BYOK input, falling back to saved credentials when omitted.
|
|
260
|
+
|
|
261
|
+
Listing models needs only the address and key, so ``require_model`` false allows no
|
|
262
|
+
model ID.
|
|
263
|
+
"""
|
|
264
|
+
saved = load_credentials()
|
|
265
|
+
if not payload:
|
|
266
|
+
if require_input or saved is None:
|
|
267
|
+
raise ByokError("BYOK_INVALID_CONFIG", "BYOK configuration is required.", exit_code=2)
|
|
268
|
+
return {
|
|
269
|
+
"base_url": saved["base_url"],
|
|
270
|
+
"api_key": saved["api_key"],
|
|
271
|
+
"model_id": saved["model_id"],
|
|
272
|
+
"context_window": saved["context_window"],
|
|
273
|
+
}
|
|
274
|
+
allowed = {"baseUrl", "apiKey", "modelId", "contextWindow", "reuseSavedKey"}
|
|
275
|
+
if not isinstance(payload, dict) or set(payload) - allowed:
|
|
276
|
+
raise ByokError(
|
|
277
|
+
"BYOK_INVALID_CONFIG", "BYOK configuration fields are invalid.", exit_code=2
|
|
278
|
+
)
|
|
279
|
+
base_raw = payload.get("baseUrl") or (saved["base_url"] if saved else "")
|
|
280
|
+
base_url, private = validate_url(base_raw)
|
|
281
|
+
model_raw = payload.get("modelId") or (saved["model_id"] if saved and require_model else "")
|
|
282
|
+
if not isinstance(model_raw, str) or (
|
|
283
|
+
(require_model or model_raw) and not MODEL_ID_PATTERN.fullmatch(model_raw.strip())
|
|
284
|
+
):
|
|
285
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Model ID is invalid.", exit_code=2)
|
|
286
|
+
window_raw = payload.get("contextWindow")
|
|
287
|
+
if window_raw is None:
|
|
288
|
+
window = saved["context_window"] if saved else DEFAULT_CONTEXT_WINDOW
|
|
289
|
+
elif type(window_raw) is int and 1 <= window_raw <= MAX_CONTEXT_WINDOW:
|
|
290
|
+
window = window_raw
|
|
291
|
+
else:
|
|
292
|
+
raise ByokError(
|
|
293
|
+
"BYOK_INVALID_CONFIG", "Context window must be a positive integer.", exit_code=2
|
|
294
|
+
)
|
|
295
|
+
return {
|
|
296
|
+
"base_url": base_url,
|
|
297
|
+
"api_key": _resolve_key(payload, saved, private),
|
|
298
|
+
"model_id": model_raw.strip(),
|
|
299
|
+
"context_window": window,
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def render_byok_provider(creds: ByokCredentials) -> dict[str, Any]:
|
|
304
|
+
"""Render the Bifrost provider entry for ``localmodels-byok``."""
|
|
305
|
+
key = creds["api_key"] or gateway_bifrost.CALLER_KEY
|
|
306
|
+
model = creds["model_id"]
|
|
307
|
+
entry = bifrost_provider.render("llm", creds["upstream_url"], model, key, BYOK_PROVIDER)
|
|
308
|
+
first = entry["keys"][0]
|
|
309
|
+
first["models"] = [model] if model == BYOK_MODEL else [model, BYOK_MODEL]
|
|
310
|
+
first["aliases"] = {BYOK_MODEL: model}
|
|
311
|
+
custom = entry["custom_provider_config"]
|
|
312
|
+
if creds["protocol"] == "anthropic":
|
|
313
|
+
custom["base_provider_type"] = "anthropic"
|
|
314
|
+
custom.pop("allowed_requests", None)
|
|
315
|
+
elif creds["protocol"] == "openai-responses":
|
|
316
|
+
custom["allowed_requests"] = {
|
|
317
|
+
"list_models": True,
|
|
318
|
+
"responses": True,
|
|
319
|
+
"responses_stream": True,
|
|
320
|
+
}
|
|
321
|
+
return entry
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _write_codex_profile(root: Path, addr: str, facts: bifrost_models.LlmFacts) -> str:
|
|
325
|
+
codex_dir = root / ".codex"
|
|
326
|
+
runtime_io.private_directory(codex_dir)
|
|
327
|
+
catalog_path = codex_dir / "localmodels-models.json"
|
|
328
|
+
catalog_doc = bifrost_models.codex_catalog(facts, BYOK_MODEL)
|
|
329
|
+
runtime_io.write_private_json(catalog_path, catalog_doc)
|
|
330
|
+
config_toml = "\n".join(
|
|
331
|
+
[
|
|
332
|
+
f'model = "{BYOK_MODEL}"',
|
|
333
|
+
f'model_provider = "{gateway_bifrost.PI_PROVIDER}"',
|
|
334
|
+
f"model_catalog_json = {json.dumps(str(catalog_path))}",
|
|
335
|
+
"",
|
|
336
|
+
f"[model_providers.{gateway_bifrost.PI_PROVIDER}]",
|
|
337
|
+
'name = "localmodels (Bifrost BYOK)"',
|
|
338
|
+
f'base_url = "http://{addr}/v1"',
|
|
339
|
+
'wire_api = "responses"',
|
|
340
|
+
"requires_openai_auth = false",
|
|
341
|
+
"",
|
|
342
|
+
]
|
|
343
|
+
)
|
|
344
|
+
target = codex_dir / "config.toml"
|
|
345
|
+
tmp = codex_dir / ".config.toml.tmp"
|
|
346
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
347
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
348
|
+
handle.write(config_toml)
|
|
349
|
+
os.replace(tmp, target)
|
|
350
|
+
runtime_io.private_permissions(target, created=True)
|
|
351
|
+
return str(codex_dir)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _write_claude_profile(root: Path, addr: str, context: int) -> str:
|
|
355
|
+
claude_dir = root / ".claude"
|
|
356
|
+
runtime_io.private_directory(claude_dir)
|
|
357
|
+
settings = {"env": bifrost_models.claude_env(BYOK_MODEL, f"http://{addr}", context)}
|
|
358
|
+
runtime_io.write_private_json(claude_dir / "settings.json", settings)
|
|
359
|
+
return str(claude_dir)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _write_pi_profile(root: Path, addr: str, facts: bifrost_models.LlmFacts) -> str:
|
|
363
|
+
pi_dir = root / ".pi" / "agent"
|
|
364
|
+
runtime_io.private_directory(pi_dir)
|
|
365
|
+
models_doc = {
|
|
366
|
+
"providers": {
|
|
367
|
+
gateway_bifrost.PI_PROVIDER: bifrost_models.pi_provider(
|
|
368
|
+
facts, BYOK_MODEL, f"http://{addr}"
|
|
369
|
+
)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
settings_doc = {
|
|
373
|
+
"defaultProvider": gateway_bifrost.PI_PROVIDER,
|
|
374
|
+
"defaultModel": BYOK_MODEL,
|
|
375
|
+
}
|
|
376
|
+
runtime_io.write_private_json(pi_dir / "models.json", models_doc)
|
|
377
|
+
runtime_io.write_private_json(pi_dir / "settings.json", settings_doc)
|
|
378
|
+
return str(pi_dir)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def write_byok_profiles(addr: str, creds: ByokCredentials) -> dict[str, str]:
|
|
382
|
+
"""Write isolated Codex, Claude Code and Pi profiles pointed at Bifrost's BYOK route."""
|
|
383
|
+
root = byok_home()
|
|
384
|
+
runtime_io.private_directory(root)
|
|
385
|
+
facts: bifrost_models.LlmFacts = {
|
|
386
|
+
"display": creds["model_id"],
|
|
387
|
+
"context": creds["context_window"],
|
|
388
|
+
"efforts": ["low", "medium", "high"],
|
|
389
|
+
"defaultEffort": "medium",
|
|
390
|
+
}
|
|
391
|
+
return {
|
|
392
|
+
"CODEX_HOME": _write_codex_profile(root, addr, facts),
|
|
393
|
+
"CLAUDE_CONFIG_DIR": _write_claude_profile(root, addr, creds["context_window"]),
|
|
394
|
+
"PI_CODING_AGENT_DIR": _write_pi_profile(root, addr, facts),
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def mount_byok(creds: ByokCredentials, facts: HostFacts) -> tuple[str, dict[str, str]]:
|
|
399
|
+
"""Mount ``localmodels-byok`` onto owned Bifrost and generate isolated client profiles."""
|
|
400
|
+
with library_gateway.gateway_locked():
|
|
401
|
+
try:
|
|
402
|
+
record = library_gateway.ensure_instance(facts)
|
|
403
|
+
if record is None:
|
|
404
|
+
raise ByokError("BYOK_GATEWAY_FAILED", "Bifrost gateway could not be prepared.")
|
|
405
|
+
app = Path(record["app_dir"])
|
|
406
|
+
config = gateway_bifrost.read_config(app)
|
|
407
|
+
before, before_sheet = copy.deepcopy(config), library_gateway.read_sheet(app)
|
|
408
|
+
providers = config.setdefault("providers", {})
|
|
409
|
+
providers[BYOK_PROVIDER] = render_byok_provider(creds)
|
|
410
|
+
governance = config.setdefault("governance", {})
|
|
411
|
+
rules = [
|
|
412
|
+
r
|
|
413
|
+
for r in (governance.get("routing_rules") or [])
|
|
414
|
+
if r.get("id") != bifrost_config.BYOK_RULE
|
|
415
|
+
]
|
|
416
|
+
rules.append(bifrost_config.byok_rule(creds["model_id"]))
|
|
417
|
+
governance["routing_rules"] = rules
|
|
418
|
+
names = (
|
|
419
|
+
[creds["model_id"]]
|
|
420
|
+
if creds["model_id"] == BYOK_MODEL
|
|
421
|
+
else [creds["model_id"], BYOK_MODEL]
|
|
422
|
+
)
|
|
423
|
+
prefix = f"{BYOK_PROVIDER}/"
|
|
424
|
+
kept_sheet = {k: v for k, v in before_sheet.items() if not k.startswith(prefix)}
|
|
425
|
+
sheet = (
|
|
426
|
+
kept_sheet
|
|
427
|
+
| bifrost_datasheet.sheets(BYOK_PROVIDER, names, creds["context_window"])[
|
|
428
|
+
bifrost_datasheet.DATASHEET
|
|
429
|
+
]
|
|
430
|
+
)
|
|
431
|
+
library_gateway.apply_config(record, config, sheet)
|
|
432
|
+
try:
|
|
433
|
+
expected = f"{BYOK_PROVIDER}/{BYOK_MODEL}"
|
|
434
|
+
if expected not in bifrost_models.listed(record["addr"]):
|
|
435
|
+
raise ByokError("BYOK_GATEWAY_FAILED", f"Bifrost did not list {expected}.")
|
|
436
|
+
except BaseException:
|
|
437
|
+
with contextlib.suppress(Exception):
|
|
438
|
+
library_gateway.apply_config(record, before, before_sheet)
|
|
439
|
+
raise
|
|
440
|
+
env = write_byok_profiles(record["addr"], creds)
|
|
441
|
+
return f"http://{record['addr']}", env
|
|
442
|
+
except ByokError:
|
|
443
|
+
raise
|
|
444
|
+
except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
|
|
445
|
+
raise ByokError("BYOK_GATEWAY_FAILED", str(exc)) from None
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def runtime_model_for_byok(runtime: Runtime) -> str:
|
|
449
|
+
"""Return the model identifier each Runtime uses for the Bifrost BYOK route."""
|
|
450
|
+
return BYOK_PI_MODEL if runtime == "pi" else BYOK_MODEL
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def load_source_state() -> SourceState | None:
|
|
454
|
+
"""Read the persisted active model-source state, or None when not yet written."""
|
|
455
|
+
path = _source_path()
|
|
456
|
+
if not path.exists() and not path.is_symlink():
|
|
457
|
+
return None
|
|
458
|
+
runtime_io.private_permissions(path)
|
|
459
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
460
|
+
if (
|
|
461
|
+
not isinstance(raw, dict)
|
|
462
|
+
or raw.get("schema") != SOURCE_SCHEMA
|
|
463
|
+
or raw.get("mode") not in MODES
|
|
464
|
+
or raw.get("runtime") not in RUNTIMES
|
|
465
|
+
):
|
|
466
|
+
return None
|
|
467
|
+
env = raw.get("environment")
|
|
468
|
+
return {
|
|
469
|
+
"schema": SOURCE_SCHEMA,
|
|
470
|
+
"mode": raw["mode"],
|
|
471
|
+
"runtime": raw["runtime"],
|
|
472
|
+
"runtime_model": str(raw.get("runtime_model") or ""),
|
|
473
|
+
"model_label": str(raw["model_label"]) if raw.get("model_label") else None,
|
|
474
|
+
"gateway_url": str(raw["gateway_url"]) if raw.get("gateway_url") else None,
|
|
475
|
+
"environment": {str(k): str(v) for k, v in env.items()} if isinstance(env, dict) else {},
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def save_source_state(state: SourceState) -> SourceState:
|
|
480
|
+
"""Atomically write the active model-source state."""
|
|
481
|
+
root = hosts.state_dir().resolve()
|
|
482
|
+
runtime_io.private_directory(root)
|
|
483
|
+
runtime_io.write_private_json(_source_path(), state)
|
|
484
|
+
return state
|