@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,275 @@
|
|
|
1
|
+
"""BYOK endpoint probing: the wire format and address an endpoint answers, and its models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, TypedDict
|
|
10
|
+
|
|
11
|
+
from localmodels import bifrost_provider
|
|
12
|
+
from localmodels.source_byok import (
|
|
13
|
+
CREDENTIALS_SCHEMA,
|
|
14
|
+
MAX_CONTEXT_WINDOW,
|
|
15
|
+
PROTOCOL_ORDER,
|
|
16
|
+
ByokCredentials,
|
|
17
|
+
ByokEndpoint,
|
|
18
|
+
ByokError,
|
|
19
|
+
Protocol,
|
|
20
|
+
Runtime,
|
|
21
|
+
validate_url,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
MAX_PROBE_BYTES = 1 << 20
|
|
25
|
+
MAX_LISTED_MODELS = 1000
|
|
26
|
+
# Gateways that serve both API families often put OpenAI under /v1 and Anthropic under
|
|
27
|
+
# /anthropic on one host, so a format missing at the entered URL is also tried there.
|
|
28
|
+
ANTHROPIC_SUFFIX = "/anthropic"
|
|
29
|
+
# The list field each wire format's reply carries, which tells a real reply from a page
|
|
30
|
+
# that answers any path.
|
|
31
|
+
_REPLY_FIELD: dict[Protocol, str] = {
|
|
32
|
+
"openai-chat": "choices",
|
|
33
|
+
"openai-responses": "output",
|
|
34
|
+
"anthropic": "content",
|
|
35
|
+
}
|
|
36
|
+
# Which failure explains a refused endpoint best when nothing answered.
|
|
37
|
+
_FAILURE_RANK = ("BYOK_AUTH_FAILED", "BYOK_MODEL_NOT_FOUND", "BYOK_UPSTREAM_REJECTED")
|
|
38
|
+
_WINDOW_FIELDS = ("context_length", "context_window", "max_input_tokens")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ByokModel(TypedDict):
|
|
42
|
+
id: str
|
|
43
|
+
name: str | None
|
|
44
|
+
context_window: int | None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
48
|
+
def redirect_request(
|
|
49
|
+
self, _req: Any, _fp: Any, _code: int, _msg: str, _headers: Any, _newurl: str
|
|
50
|
+
) -> None:
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _alternate(root: str) -> str:
|
|
55
|
+
"""The other half of the /v1 and /anthropic layout."""
|
|
56
|
+
if root.endswith(ANTHROPIC_SUFFIX):
|
|
57
|
+
return root.removesuffix(ANTHROPIC_SUFFIX)
|
|
58
|
+
return root + ANTHROPIC_SUFFIX
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _roots(base_url: str, protocol: Protocol) -> list[str]:
|
|
62
|
+
"""Where ``protocol`` may be served: the entered URL first, then the alternate when the
|
|
63
|
+
entered URL names the other API family."""
|
|
64
|
+
root = bifrost_provider.origin(base_url)
|
|
65
|
+
if root.endswith(ANTHROPIC_SUFFIX) == (protocol == "anthropic"):
|
|
66
|
+
return [root]
|
|
67
|
+
return [root, _alternate(root)]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _headers(protocol: Protocol, api_key: str) -> dict[str, str]:
|
|
71
|
+
headers = {"Accept": "application/json", "Content-Type": "application/json"}
|
|
72
|
+
if protocol == "anthropic":
|
|
73
|
+
headers["anthropic-version"] = "2023-06-01"
|
|
74
|
+
if api_key:
|
|
75
|
+
headers["x-api-key"] = api_key
|
|
76
|
+
elif api_key:
|
|
77
|
+
headers["Authorization"] = f"Bearer {api_key}"
|
|
78
|
+
return headers
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _call(
|
|
82
|
+
url: str, headers: dict[str, str], private: bool, timeout: float, body: Any = None
|
|
83
|
+
) -> Any:
|
|
84
|
+
"""One request without redirects; the parsed JSON reply, or a ByokError naming why not."""
|
|
85
|
+
handlers: list[urllib.request.BaseHandler] = [_NoRedirect()]
|
|
86
|
+
if private:
|
|
87
|
+
handlers.append(urllib.request.ProxyHandler({}))
|
|
88
|
+
request = urllib.request.Request(
|
|
89
|
+
url,
|
|
90
|
+
data=None if body is None else json.dumps(body).encode("utf-8"),
|
|
91
|
+
headers=headers,
|
|
92
|
+
method="GET" if body is None else "POST",
|
|
93
|
+
)
|
|
94
|
+
try:
|
|
95
|
+
with urllib.request.build_opener(*handlers).open(request, timeout=timeout) as response:
|
|
96
|
+
raw = response.read(MAX_PROBE_BYTES + 1)
|
|
97
|
+
except urllib.error.HTTPError as exc:
|
|
98
|
+
if exc.code in (401, 403):
|
|
99
|
+
raise ByokError(
|
|
100
|
+
"BYOK_AUTH_FAILED", "Upstream endpoint rejected the API key (HTTP 401/403)."
|
|
101
|
+
) from None
|
|
102
|
+
if exc.code == 404:
|
|
103
|
+
raise ByokError(
|
|
104
|
+
"BYOK_MODEL_NOT_FOUND", "Upstream endpoint or model was not found (HTTP 404)."
|
|
105
|
+
) from None
|
|
106
|
+
raise ByokError(
|
|
107
|
+
"BYOK_UPSTREAM_REJECTED", f"Upstream endpoint returned HTTP {exc.code}."
|
|
108
|
+
) from None
|
|
109
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
110
|
+
raise ByokError(
|
|
111
|
+
"BYOK_UNREACHABLE", f"Could not reach upstream endpoint ({type(exc).__name__})."
|
|
112
|
+
) from None
|
|
113
|
+
try:
|
|
114
|
+
return json.loads(raw) if len(raw) <= MAX_PROBE_BYTES else None
|
|
115
|
+
except ValueError:
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _model_rows(doc: Any) -> list[ByokModel] | None:
|
|
120
|
+
rows = doc.get("data") if isinstance(doc, dict) else None
|
|
121
|
+
if not isinstance(rows, list):
|
|
122
|
+
return None
|
|
123
|
+
models: list[ByokModel] = []
|
|
124
|
+
for row in rows:
|
|
125
|
+
if not isinstance(row, dict) or not isinstance(row.get("id"), str) or not row["id"]:
|
|
126
|
+
continue
|
|
127
|
+
name = row.get("name") or row.get("display_name")
|
|
128
|
+
window = next(
|
|
129
|
+
(
|
|
130
|
+
row[field]
|
|
131
|
+
for field in _WINDOW_FIELDS
|
|
132
|
+
if type(row.get(field)) is int and 1 <= row[field] <= MAX_CONTEXT_WINDOW
|
|
133
|
+
),
|
|
134
|
+
None,
|
|
135
|
+
)
|
|
136
|
+
models.append(
|
|
137
|
+
{
|
|
138
|
+
"id": row["id"],
|
|
139
|
+
"name": name if isinstance(name, str) and name and name != row["id"] else None,
|
|
140
|
+
"context_window": window,
|
|
141
|
+
}
|
|
142
|
+
)
|
|
143
|
+
return models
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _probe_format(
|
|
147
|
+
root: str, endpoint: ByokEndpoint, protocol: Protocol, private: bool, timeout: float
|
|
148
|
+
) -> None:
|
|
149
|
+
"""Send one small request in ``protocol``; raise ByokError unless it is answered."""
|
|
150
|
+
model = endpoint["model_id"]
|
|
151
|
+
path, body = {
|
|
152
|
+
"anthropic": ("messages", {"model": model, "max_tokens": 16}),
|
|
153
|
+
"openai-responses": ("responses", {"model": model, "max_output_tokens": 16}),
|
|
154
|
+
"openai-chat": ("chat/completions", {"model": model, "max_tokens": 16}),
|
|
155
|
+
}[protocol]
|
|
156
|
+
if protocol == "openai-responses":
|
|
157
|
+
body["input"] = "Reply with OK."
|
|
158
|
+
else:
|
|
159
|
+
body["messages"] = [{"role": "user", "content": "Reply with OK."}]
|
|
160
|
+
if protocol != "anthropic":
|
|
161
|
+
body["stream"] = False
|
|
162
|
+
headers = _headers(protocol, endpoint["api_key"])
|
|
163
|
+
doc = _call(f"{root}/v1/{path}", headers, private, timeout, body)
|
|
164
|
+
if not isinstance(doc, dict) or not isinstance(doc.get(_REPLY_FIELD[protocol]), list):
|
|
165
|
+
raise ByokError(
|
|
166
|
+
"BYOK_UPSTREAM_REJECTED", "Upstream endpoint answered in an unexpected format."
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _window_for(rows: list[ByokModel], target: str) -> int | None:
|
|
171
|
+
"""The listed window of ``target``, matching an exact ID first and then an ID with one
|
|
172
|
+
more provider prefix on either side, since the two halves of a gateway list one model
|
|
173
|
+
under different IDs."""
|
|
174
|
+
exact = [row for row in rows if row["id"] == target]
|
|
175
|
+
loose = [
|
|
176
|
+
row
|
|
177
|
+
for row in rows
|
|
178
|
+
if row["id"].split("/", 1)[-1] == target or target.split("/", 1)[-1] == row["id"]
|
|
179
|
+
]
|
|
180
|
+
return next((row["context_window"] for row in exact + loose if row["context_window"]), None)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _discover_window(
|
|
184
|
+
root: str, endpoint: ByokEndpoint, protocol: Protocol, private: bool, timeout: float
|
|
185
|
+
) -> int | None:
|
|
186
|
+
"""The model's context window from the answering address's model list, or else from
|
|
187
|
+
the other half of a /v1 and /anthropic gateway, whose list may carry windows when the
|
|
188
|
+
answering half's does not."""
|
|
189
|
+
deadline = time.monotonic() + timeout
|
|
190
|
+
alternate = _alternate(root)
|
|
191
|
+
alternate_style: Protocol = (
|
|
192
|
+
"anthropic" if alternate.endswith(ANTHROPIC_SUFFIX) else "openai-chat"
|
|
193
|
+
)
|
|
194
|
+
for listing_root, style in ((root, protocol), (alternate, alternate_style)):
|
|
195
|
+
remaining = deadline - time.monotonic()
|
|
196
|
+
if remaining <= 0:
|
|
197
|
+
return None
|
|
198
|
+
headers = _headers(style, endpoint["api_key"])
|
|
199
|
+
try:
|
|
200
|
+
rows = _model_rows(_call(f"{listing_root}/v1/models", headers, private, remaining))
|
|
201
|
+
except ByokError:
|
|
202
|
+
continue
|
|
203
|
+
window = _window_for(rows or [], endpoint["model_id"])
|
|
204
|
+
if window:
|
|
205
|
+
return window
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def probe_upstream(
|
|
210
|
+
endpoint: ByokEndpoint, runtime: Runtime, *, timeout: float = 35.0
|
|
211
|
+
) -> ByokCredentials:
|
|
212
|
+
"""Find a wire format and address the endpoint answers, in ``runtime``'s order of formats,
|
|
213
|
+
and its context window.
|
|
214
|
+
|
|
215
|
+
An unreachable endpoint stops the search, since every attempt goes to the same host.
|
|
216
|
+
"""
|
|
217
|
+
_, private = validate_url(endpoint["base_url"])
|
|
218
|
+
deadline = time.monotonic() + timeout
|
|
219
|
+
failures: list[ByokError] = []
|
|
220
|
+
for protocol in PROTOCOL_ORDER[runtime]:
|
|
221
|
+
for root in _roots(endpoint["base_url"], protocol):
|
|
222
|
+
remaining = deadline - time.monotonic()
|
|
223
|
+
if remaining <= 0:
|
|
224
|
+
raise ByokError("BYOK_UNREACHABLE", "Upstream endpoint did not answer in time.")
|
|
225
|
+
try:
|
|
226
|
+
_probe_format(root, endpoint, protocol, private, remaining)
|
|
227
|
+
except ByokError as exc:
|
|
228
|
+
if exc.code == "BYOK_UNREACHABLE":
|
|
229
|
+
raise
|
|
230
|
+
failures.append(exc)
|
|
231
|
+
continue
|
|
232
|
+
remaining = deadline - time.monotonic()
|
|
233
|
+
discovered = (
|
|
234
|
+
_discover_window(root, endpoint, protocol, private, min(remaining, 8.0))
|
|
235
|
+
if remaining > 1
|
|
236
|
+
else None
|
|
237
|
+
)
|
|
238
|
+
return {
|
|
239
|
+
"schema": CREDENTIALS_SCHEMA,
|
|
240
|
+
"protocol": protocol,
|
|
241
|
+
"base_url": endpoint["base_url"],
|
|
242
|
+
"upstream_url": root,
|
|
243
|
+
"api_key": endpoint["api_key"],
|
|
244
|
+
"model_id": endpoint["model_id"],
|
|
245
|
+
"context_window": discovered or endpoint["context_window"],
|
|
246
|
+
"key_saved": bool(endpoint["api_key"]),
|
|
247
|
+
}
|
|
248
|
+
raise min(failures, key=lambda exc: _FAILURE_RANK.index(exc.code))
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def list_models(endpoint: ByokEndpoint, *, timeout: float = 20.0) -> tuple[str, list[ByokModel]]:
|
|
252
|
+
"""The models the endpoint lists, sorted by ID, and the address that listed them."""
|
|
253
|
+
_, private = validate_url(endpoint["base_url"])
|
|
254
|
+
deadline = time.monotonic() + timeout
|
|
255
|
+
failures: list[ByokError] = []
|
|
256
|
+
entered = bifrost_provider.origin(endpoint["base_url"])
|
|
257
|
+
for root in (entered, _alternate(entered)):
|
|
258
|
+
for protocol in ("openai-chat", "anthropic"):
|
|
259
|
+
remaining = deadline - time.monotonic()
|
|
260
|
+
if remaining <= 0:
|
|
261
|
+
raise ByokError("BYOK_UNREACHABLE", "Upstream endpoint did not answer in time.")
|
|
262
|
+
headers = _headers(protocol, endpoint["api_key"])
|
|
263
|
+
try:
|
|
264
|
+
rows = _model_rows(_call(f"{root}/v1/models", headers, private, remaining))
|
|
265
|
+
except ByokError as exc:
|
|
266
|
+
if exc.code == "BYOK_UNREACHABLE":
|
|
267
|
+
raise
|
|
268
|
+
failures.append(exc)
|
|
269
|
+
continue
|
|
270
|
+
if rows:
|
|
271
|
+
return root, sorted(rows, key=lambda row: row["id"])[:MAX_LISTED_MODELS]
|
|
272
|
+
failures.append(
|
|
273
|
+
ByokError("BYOK_UPSTREAM_REJECTED", "Upstream endpoint listed no models.")
|
|
274
|
+
)
|
|
275
|
+
raise min(failures, key=lambda exc: _FAILURE_RANK.index(exc.code))
|
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
"""``localmodels source``: manage the active model source (local, subscription, or BYOK)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
from localmodels import (
|
|
13
|
+
cli_help,
|
|
14
|
+
deploy,
|
|
15
|
+
hosts,
|
|
16
|
+
library_convert,
|
|
17
|
+
library_gateway,
|
|
18
|
+
library_jobs,
|
|
19
|
+
library_serve,
|
|
20
|
+
library_state,
|
|
21
|
+
runtime_cli,
|
|
22
|
+
source_byok,
|
|
23
|
+
source_byok_probe,
|
|
24
|
+
)
|
|
25
|
+
from localmodels.library_model import LibraryError
|
|
26
|
+
from localmodels.source_byok import ByokError, Mode, Runtime, SourceState
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _common(parser: argparse.ArgumentParser) -> None:
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"--base-dir",
|
|
32
|
+
default=deploy.DEFAULT_BASE_DIR,
|
|
33
|
+
metavar="DIR",
|
|
34
|
+
help="where local model weights and deployments live",
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--harness-root",
|
|
38
|
+
type=Path,
|
|
39
|
+
metavar="DIR",
|
|
40
|
+
help="managed native runtime root (<home>/runtime/harness)",
|
|
41
|
+
)
|
|
42
|
+
parser.add_argument("--json", action="store_true", help="accepted; output is JSON")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
|
|
46
|
+
parser = sub.add_parser(
|
|
47
|
+
"source", help="inspect, check and switch the active model source (JSON)"
|
|
48
|
+
)
|
|
49
|
+
verbs = parser.add_subparsers(dest="source_command", required=True, metavar="COMMAND")
|
|
50
|
+
|
|
51
|
+
status = verbs.add_parser("status", help="current model source and redacted BYOK metadata")
|
|
52
|
+
_common(status)
|
|
53
|
+
cli_help.document(
|
|
54
|
+
status,
|
|
55
|
+
"Print one localmodels.model-source-status/v1 document with the active mode, runtime, "
|
|
56
|
+
"environment overrides and redacted BYOK configuration.",
|
|
57
|
+
examples=[("%(prog)s --json", "")],
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
check = verbs.add_parser("check", help="verify a BYOK upstream endpoint from stdin JSON")
|
|
61
|
+
check.add_argument(
|
|
62
|
+
"--config-stdin",
|
|
63
|
+
action="store_true",
|
|
64
|
+
required=True,
|
|
65
|
+
help="read BYOK configuration JSON from standard input",
|
|
66
|
+
)
|
|
67
|
+
check.add_argument(
|
|
68
|
+
"--runtime",
|
|
69
|
+
choices=source_byok.RUNTIMES,
|
|
70
|
+
required=True,
|
|
71
|
+
help="agent runtime the endpoint will serve; its own wire format is tried first",
|
|
72
|
+
)
|
|
73
|
+
check.add_argument("--json", action="store_true", help="accepted; output is JSON")
|
|
74
|
+
cli_help.document(
|
|
75
|
+
check,
|
|
76
|
+
"Validate a BYOK endpoint and find the wire format it answers (OpenAI chat, OpenAI "
|
|
77
|
+
"responses, or Anthropic) without saving credentials or changing the active model source.",
|
|
78
|
+
examples=[("%(prog)s --config-stdin --runtime claude --json", "")],
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
models = verbs.add_parser("models", help="list the models a BYOK endpoint serves")
|
|
82
|
+
models.add_argument(
|
|
83
|
+
"--config-stdin",
|
|
84
|
+
action="store_true",
|
|
85
|
+
required=True,
|
|
86
|
+
help="read the BYOK endpoint and key as JSON from standard input",
|
|
87
|
+
)
|
|
88
|
+
models.add_argument("--json", action="store_true", help="accepted; output is JSON")
|
|
89
|
+
cli_help.document(
|
|
90
|
+
models,
|
|
91
|
+
"List the models a BYOK endpoint serves, with their names and context windows when "
|
|
92
|
+
"it reports them, without saving credentials.",
|
|
93
|
+
examples=[("%(prog)s --config-stdin --json", "")],
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
apply_cmd = verbs.add_parser("apply", help="activate local, subscription or BYOK mode")
|
|
97
|
+
apply_cmd.add_argument(
|
|
98
|
+
"--mode",
|
|
99
|
+
choices=source_byok.MODES,
|
|
100
|
+
required=True,
|
|
101
|
+
help="target model source mode",
|
|
102
|
+
)
|
|
103
|
+
apply_cmd.add_argument(
|
|
104
|
+
"--runtime",
|
|
105
|
+
choices=source_byok.RUNTIMES,
|
|
106
|
+
help="target agent runtime (claude, codex, or pi)",
|
|
107
|
+
)
|
|
108
|
+
apply_cmd.add_argument(
|
|
109
|
+
"--model",
|
|
110
|
+
metavar="MODEL",
|
|
111
|
+
help="library model ID to load when switching to local mode",
|
|
112
|
+
)
|
|
113
|
+
apply_cmd.add_argument(
|
|
114
|
+
"--node",
|
|
115
|
+
metavar="PATH",
|
|
116
|
+
help="Node.js executable path when installing a missing managed runtime",
|
|
117
|
+
)
|
|
118
|
+
apply_cmd.add_argument(
|
|
119
|
+
"--config-stdin",
|
|
120
|
+
action="store_true",
|
|
121
|
+
help="read BYOK configuration JSON from standard input",
|
|
122
|
+
)
|
|
123
|
+
_common(apply_cmd)
|
|
124
|
+
cli_help.document(
|
|
125
|
+
apply_cmd,
|
|
126
|
+
"Switch the active model source, mounting BYOK on Bifrost or unloading local models "
|
|
127
|
+
"as needed, and print the resulting localmodels.model-source-status/v1 JSON.",
|
|
128
|
+
examples=[
|
|
129
|
+
("%(prog)s --mode byok --runtime claude --config-stdin --json", ""),
|
|
130
|
+
("%(prog)s --mode subscription --runtime codex --json", ""),
|
|
131
|
+
],
|
|
132
|
+
)
|
|
133
|
+
cli_help.document(
|
|
134
|
+
parser,
|
|
135
|
+
"Inspect, verify and switch between local models, native subscriptions and BYOK on Bifrost.",
|
|
136
|
+
examples=[("%(prog)s status --json", "")],
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _read_stdin_json() -> dict[str, Any]:
|
|
141
|
+
raw = sys.stdin.read()
|
|
142
|
+
if not raw.strip():
|
|
143
|
+
return {}
|
|
144
|
+
try:
|
|
145
|
+
parsed = json.loads(raw)
|
|
146
|
+
except ValueError as exc:
|
|
147
|
+
raise ByokError(
|
|
148
|
+
"BYOK_INVALID_CONFIG", "Invalid JSON on standard input.", exit_code=2
|
|
149
|
+
) from exc
|
|
150
|
+
if not isinstance(parsed, dict):
|
|
151
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Standard input must be a JSON object.", exit_code=2)
|
|
152
|
+
return parsed
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _loaded_local_record() -> dict[str, Any] | None:
|
|
156
|
+
library_convert.convert_once()
|
|
157
|
+
for record in library_state.records():
|
|
158
|
+
if record.get("state") == "loaded":
|
|
159
|
+
return cast(dict[str, Any], record)
|
|
160
|
+
return None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _unload_loaded_local_models(base_dir: str) -> list[str]:
|
|
164
|
+
library_convert.convert_once()
|
|
165
|
+
unloaded: list[str] = []
|
|
166
|
+
for record in list(library_state.records()):
|
|
167
|
+
if record.get("state") == "loaded":
|
|
168
|
+
model_id = str(record["id"])
|
|
169
|
+
library_serve.unload(model_id, base_dir)
|
|
170
|
+
unloaded.append(model_id)
|
|
171
|
+
return unloaded
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _gateway_url() -> str | None:
|
|
175
|
+
record = hosts.load_owned()["gateway"].get("bifrost")
|
|
176
|
+
return f"http://{record['addr']}" if record and record.get("addr") else None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _infer_default_state(harness_root: Path | None) -> SourceState:
|
|
180
|
+
loaded = _loaded_local_record()
|
|
181
|
+
if loaded is not None:
|
|
182
|
+
reg = loaded.get("registration") or {}
|
|
183
|
+
return {
|
|
184
|
+
"schema": source_byok.SOURCE_SCHEMA,
|
|
185
|
+
"mode": "local",
|
|
186
|
+
"runtime": "pi",
|
|
187
|
+
"runtime_model": str(reg.get("pi_model") or ""),
|
|
188
|
+
"model_label": None,
|
|
189
|
+
"gateway_url": _gateway_url(),
|
|
190
|
+
"environment": {"PI_CODING_AGENT_DIR": str(library_gateway.pi_profile())},
|
|
191
|
+
}
|
|
192
|
+
chosen: Runtime = "claude"
|
|
193
|
+
if harness_root is not None and harness_root.exists():
|
|
194
|
+
rows = runtime_cli.inspect_runtimes(harness_root)["runtimes"]
|
|
195
|
+
authed = next(
|
|
196
|
+
(
|
|
197
|
+
r["runtime"]
|
|
198
|
+
for r in rows
|
|
199
|
+
if r["runtime"] in ("claude", "codex") and r["authenticated"]
|
|
200
|
+
),
|
|
201
|
+
None,
|
|
202
|
+
)
|
|
203
|
+
installed = next(
|
|
204
|
+
(
|
|
205
|
+
r["runtime"]
|
|
206
|
+
for r in rows
|
|
207
|
+
if r["runtime"] in ("claude", "codex", "pi") and r["installed"]
|
|
208
|
+
),
|
|
209
|
+
None,
|
|
210
|
+
)
|
|
211
|
+
chosen = cast(Runtime, authed or installed or "claude")
|
|
212
|
+
return {
|
|
213
|
+
"schema": source_byok.SOURCE_SCHEMA,
|
|
214
|
+
"mode": "subscription",
|
|
215
|
+
"runtime": chosen,
|
|
216
|
+
"runtime_model": "",
|
|
217
|
+
"model_label": None,
|
|
218
|
+
"gateway_url": None,
|
|
219
|
+
"environment": {},
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _endpoint_command(schema: str, run: Callable[[dict[str, Any]], dict[str, Any]]) -> int:
|
|
224
|
+
"""Run a read-only BYOK endpoint command on stdin JSON and print its one JSON document."""
|
|
225
|
+
try:
|
|
226
|
+
doc = {"schema": schema, "ok": True, **run(_read_stdin_json())}
|
|
227
|
+
except ByokError as exc:
|
|
228
|
+
doc = {"schema": schema, "ok": False, "code": exc.code, "message": str(exc)}
|
|
229
|
+
print(json.dumps(doc, ensure_ascii=False))
|
|
230
|
+
return exc.exit_code
|
|
231
|
+
print(json.dumps(doc, ensure_ascii=False))
|
|
232
|
+
return 0
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def build_status(harness_root: Path | None = None) -> dict[str, Any]:
|
|
236
|
+
"""Build the redacted ``localmodels.model-source-status/v1`` payload."""
|
|
237
|
+
state = source_byok.load_source_state() or _infer_default_state(harness_root)
|
|
238
|
+
executable_paths: dict[str, str] = {}
|
|
239
|
+
if harness_root is not None and harness_root.exists():
|
|
240
|
+
rows = runtime_cli.inspect_runtimes(harness_root)["runtimes"]
|
|
241
|
+
for row in rows:
|
|
242
|
+
if row.get("installed") and row.get("executable") and not row.get("argvPrefix"):
|
|
243
|
+
executable_paths[str(row["runtime"])] = str(row["executable"])
|
|
244
|
+
return {
|
|
245
|
+
"schema": source_byok.STATUS_SCHEMA,
|
|
246
|
+
"mode": state["mode"],
|
|
247
|
+
"runtime": state["runtime"],
|
|
248
|
+
"runtime_model": state["runtime_model"],
|
|
249
|
+
"gateway_url": state["gateway_url"],
|
|
250
|
+
"environment": state["environment"],
|
|
251
|
+
"runtime_paths": executable_paths,
|
|
252
|
+
"byok": source_byok.credentials_summary(),
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _ensure_runtime_installed(
|
|
257
|
+
runtime: Runtime, harness_root: Path | None, node: str | None
|
|
258
|
+
) -> None:
|
|
259
|
+
if harness_root is None:
|
|
260
|
+
return
|
|
261
|
+
status = runtime_cli.inspect_runtimes(harness_root, node=node)["runtimes"]
|
|
262
|
+
row = next((item for item in status if item["runtime"] == runtime), None)
|
|
263
|
+
if row and row.get("installed"):
|
|
264
|
+
return
|
|
265
|
+
plan = runtime_cli.build_plan(runtime, harness_root, node=node)
|
|
266
|
+
runtime_cli.apply_plan(plan, str(plan["id"]))
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _apply_byok(args: argparse.Namespace, runtime: Runtime) -> SourceState:
|
|
270
|
+
payload = _read_stdin_json() if args.config_stdin else None
|
|
271
|
+
creds = source_byok_probe.probe_upstream(source_byok.resolve_endpoint(payload), runtime)
|
|
272
|
+
_unload_loaded_local_models(args.base_dir)
|
|
273
|
+
source_byok.save_credentials(creds)
|
|
274
|
+
facts = library_jobs.probe()
|
|
275
|
+
gateway_url, env = source_byok.mount_byok(creds, facts)
|
|
276
|
+
return source_byok.save_source_state(
|
|
277
|
+
{
|
|
278
|
+
"schema": source_byok.SOURCE_SCHEMA,
|
|
279
|
+
"mode": "byok",
|
|
280
|
+
"runtime": runtime,
|
|
281
|
+
"runtime_model": source_byok.runtime_model_for_byok(runtime),
|
|
282
|
+
"model_label": creds["model_id"],
|
|
283
|
+
"gateway_url": gateway_url,
|
|
284
|
+
"environment": env,
|
|
285
|
+
}
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _apply_subscription(args: argparse.Namespace, runtime: Runtime) -> SourceState:
|
|
290
|
+
if runtime == "pi":
|
|
291
|
+
raise ByokError(
|
|
292
|
+
"BYOK_INVALID_CONFIG",
|
|
293
|
+
"Subscription mode supports Claude Code or Codex.",
|
|
294
|
+
exit_code=2,
|
|
295
|
+
)
|
|
296
|
+
_unload_loaded_local_models(args.base_dir)
|
|
297
|
+
return source_byok.save_source_state(
|
|
298
|
+
{
|
|
299
|
+
"schema": source_byok.SOURCE_SCHEMA,
|
|
300
|
+
"mode": "subscription",
|
|
301
|
+
"runtime": runtime,
|
|
302
|
+
"runtime_model": "",
|
|
303
|
+
"model_label": None,
|
|
304
|
+
"gateway_url": None,
|
|
305
|
+
"environment": {},
|
|
306
|
+
}
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _apply_local(args: argparse.Namespace) -> SourceState:
|
|
311
|
+
library_convert.convert_once()
|
|
312
|
+
if args.model:
|
|
313
|
+
others = [
|
|
314
|
+
str(r["id"])
|
|
315
|
+
for r in library_state.records()
|
|
316
|
+
if r.get("state") == "loaded" and str(r["id"]) != args.model
|
|
317
|
+
]
|
|
318
|
+
current = next((r for r in library_state.records() if str(r["id"]) == args.model), None)
|
|
319
|
+
if current is None or current.get("state") != "loaded":
|
|
320
|
+
library_serve.load(args.model, args.base_dir, others)
|
|
321
|
+
loaded = _loaded_local_record()
|
|
322
|
+
reg = (loaded or {}).get("registration") or {}
|
|
323
|
+
return source_byok.save_source_state(
|
|
324
|
+
{
|
|
325
|
+
"schema": source_byok.SOURCE_SCHEMA,
|
|
326
|
+
"mode": "local",
|
|
327
|
+
"runtime": "pi",
|
|
328
|
+
"runtime_model": str(reg.get("pi_model") or ""),
|
|
329
|
+
"model_label": None,
|
|
330
|
+
"gateway_url": _gateway_url(),
|
|
331
|
+
"environment": {"PI_CODING_AGENT_DIR": str(library_gateway.pi_profile())},
|
|
332
|
+
}
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def cli(args: argparse.Namespace) -> int:
|
|
337
|
+
verb = args.source_command
|
|
338
|
+
if verb == "status":
|
|
339
|
+
try:
|
|
340
|
+
doc = build_status(args.harness_root)
|
|
341
|
+
except Exception as exc: # noqa: BLE001
|
|
342
|
+
print(f"error: source status failed: {exc}", file=sys.stderr)
|
|
343
|
+
return 1
|
|
344
|
+
print(json.dumps(doc, ensure_ascii=False, indent=1))
|
|
345
|
+
return 0
|
|
346
|
+
if verb == "check":
|
|
347
|
+
runtime = cast(Runtime, args.runtime)
|
|
348
|
+
|
|
349
|
+
def check(payload: dict[str, Any]) -> dict[str, Any]:
|
|
350
|
+
endpoint = source_byok.resolve_endpoint(payload, require_input=True)
|
|
351
|
+
creds = source_byok_probe.probe_upstream(endpoint, runtime)
|
|
352
|
+
return {
|
|
353
|
+
"protocol": creds["protocol"],
|
|
354
|
+
"base_url": creds["upstream_url"],
|
|
355
|
+
"model_id": creds["model_id"],
|
|
356
|
+
"context_window": creds["context_window"],
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return _endpoint_command(source_byok.CHECK_SCHEMA, check)
|
|
360
|
+
if verb == "models":
|
|
361
|
+
|
|
362
|
+
def models(payload: dict[str, Any]) -> dict[str, Any]:
|
|
363
|
+
endpoint = source_byok.resolve_endpoint(
|
|
364
|
+
payload, require_input=True, require_model=False
|
|
365
|
+
)
|
|
366
|
+
root, listed = source_byok_probe.list_models(endpoint)
|
|
367
|
+
return {"base_url": root, "models": listed}
|
|
368
|
+
|
|
369
|
+
return _endpoint_command(source_byok.MODELS_SCHEMA, models)
|
|
370
|
+
|
|
371
|
+
mode = cast(Mode, args.mode)
|
|
372
|
+
current = source_byok.load_source_state()
|
|
373
|
+
default_rt: Runtime = "pi" if mode == "local" else (current["runtime"] if current else "claude")
|
|
374
|
+
if mode == "subscription" and default_rt == "pi":
|
|
375
|
+
default_rt = "claude"
|
|
376
|
+
runtime = cast(Runtime, args.runtime or default_rt)
|
|
377
|
+
try:
|
|
378
|
+
_ensure_runtime_installed(runtime, args.harness_root, args.node)
|
|
379
|
+
if mode == "byok":
|
|
380
|
+
_apply_byok(args, runtime)
|
|
381
|
+
elif mode == "subscription":
|
|
382
|
+
_apply_subscription(args, runtime)
|
|
383
|
+
else:
|
|
384
|
+
_apply_local(args)
|
|
385
|
+
doc = build_status(args.harness_root)
|
|
386
|
+
except ByokError as exc:
|
|
387
|
+
print(
|
|
388
|
+
json.dumps(
|
|
389
|
+
{
|
|
390
|
+
"schema": source_byok.STATUS_SCHEMA,
|
|
391
|
+
"ok": False,
|
|
392
|
+
"code": exc.code,
|
|
393
|
+
"message": str(exc),
|
|
394
|
+
},
|
|
395
|
+
ensure_ascii=False,
|
|
396
|
+
)
|
|
397
|
+
)
|
|
398
|
+
return exc.exit_code
|
|
399
|
+
except LibraryError as exc:
|
|
400
|
+
print(
|
|
401
|
+
json.dumps(
|
|
402
|
+
{
|
|
403
|
+
"schema": source_byok.STATUS_SCHEMA,
|
|
404
|
+
"ok": False,
|
|
405
|
+
"code": exc.code,
|
|
406
|
+
"message": exc.detail,
|
|
407
|
+
},
|
|
408
|
+
ensure_ascii=False,
|
|
409
|
+
)
|
|
410
|
+
)
|
|
411
|
+
return exc.exit_code
|
|
412
|
+
except Exception as exc: # noqa: BLE001
|
|
413
|
+
print(
|
|
414
|
+
json.dumps(
|
|
415
|
+
{
|
|
416
|
+
"schema": source_byok.STATUS_SCHEMA,
|
|
417
|
+
"ok": False,
|
|
418
|
+
"code": "SOURCE_APPLY_FAILED",
|
|
419
|
+
"message": str(exc),
|
|
420
|
+
},
|
|
421
|
+
ensure_ascii=False,
|
|
422
|
+
)
|
|
423
|
+
)
|
|
424
|
+
return 1
|
|
425
|
+
print(json.dumps(doc, ensure_ascii=False, indent=1))
|
|
426
|
+
return 0
|