@simplexai/localmodels-darwin-arm64 0.1.0-dev.43 → 0.1.0-dev.44
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 +39 -38
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/auth_proxy.py +285 -82
- package/modules/localmodels/bifrost_models.py +9 -2
- package/modules/localmodels/bifrost_provider.py +42 -7
- package/modules/localmodels/debug_mode.py +2 -18
- package/modules/localmodels/engines.py +19 -6
- package/modules/localmodels/gateway_bifrost.py +10 -1
- package/modules/localmodels/harness.py +3 -1
- package/modules/localmodels/library_convert.py +491 -57
- package/modules/localmodels/library_gateway.py +15 -7
- package/modules/localmodels/library_pricing.py +159 -31
- package/modules/localmodels/library_status.py +29 -4
- package/modules/localmodels/probe.py +42 -9
- package/modules/localmodels/runtime_args.py +2 -1
- package/modules/localmodels/runtime_auth.py +75 -25
- package/modules/localmodels/runtime_cli.py +9 -9
- package/modules/localmodels/runtime_install.py +55 -22
- package/modules/localmodels/runtime_io.py +76 -210
- package/modules/localmodels/runtime_process.py +15 -7
- package/modules/localmodels/runtime_windows_acl.py +196 -0
- package/modules/localmodels/source_byok.py +116 -30
- package/modules/localmodels/source_byok_probe.py +57 -141
- package/modules/localmodels/source_cli.py +11 -17
- package/modules/localmodels/stack.py +12 -1
- package/modules/localmodels/stack_client_settings.py +8 -1
- package/modules/localmodels/stack_compose.py +1 -0
- package/modules/localmodels/stack_route.py +1 -5
- package/modules/localmodels/stack_up.py +20 -1
- package/modules/localmodels/vision.py +2 -1
- package/modules/localmodels/web/view/view.css +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/RECORD +36 -35
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Windows NTFS owner and protected-DACL checks for private runtime state."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@functools.lru_cache(maxsize=1)
|
|
11
|
+
def api() -> tuple[Any, Any]:
|
|
12
|
+
"""Load advapi32 and kernel32 once per process with typed security signatures."""
|
|
13
|
+
import ctypes
|
|
14
|
+
|
|
15
|
+
load: Any = vars(ctypes)["WinDLL"]
|
|
16
|
+
advapi, kernel = load("advapi32", use_last_error=True), load("kernel32", use_last_error=True)
|
|
17
|
+
pointer, integer, wide = ctypes.c_void_p, ctypes.c_uint, ctypes.c_wchar_p
|
|
18
|
+
out, uint_ptr = ctypes.POINTER(pointer), ctypes.POINTER(integer)
|
|
19
|
+
int_ptr, ushort_ptr = ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ushort)
|
|
20
|
+
signatures = {
|
|
21
|
+
"OpenProcessToken": [pointer, integer, out],
|
|
22
|
+
"GetTokenInformation": [pointer, integer, pointer, integer, uint_ptr],
|
|
23
|
+
"GetNamedSecurityInfoW": [wide, integer, integer, out, out, out, out, out],
|
|
24
|
+
"SetNamedSecurityInfoW": [wide, integer, integer, pointer, pointer, pointer, pointer],
|
|
25
|
+
"EqualSid": [pointer, pointer],
|
|
26
|
+
"ConvertSidToStringSidW": [pointer, out],
|
|
27
|
+
"ConvertStringSecurityDescriptorToSecurityDescriptorW": [wide, integer, out, uint_ptr],
|
|
28
|
+
"GetSecurityDescriptorDacl": [pointer, int_ptr, out, int_ptr],
|
|
29
|
+
"GetSecurityDescriptorControl": [pointer, ushort_ptr, uint_ptr],
|
|
30
|
+
"GetAce": [pointer, integer, out],
|
|
31
|
+
}
|
|
32
|
+
for name, arguments in signatures.items():
|
|
33
|
+
function = getattr(advapi, name)
|
|
34
|
+
function.argtypes, function.restype = arguments, integer
|
|
35
|
+
kernel.GetCurrentProcess.restype = pointer
|
|
36
|
+
kernel.CloseHandle.argtypes = [pointer]
|
|
37
|
+
kernel.LocalFree.argtypes, kernel.LocalFree.restype = [pointer], pointer
|
|
38
|
+
return advapi, kernel
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@functools.lru_cache(maxsize=1)
|
|
42
|
+
def identity() -> tuple[Any, Any, Any, Any, str]:
|
|
43
|
+
"""Current process user and default creator SIDs; buffers stay alive for cached pointers."""
|
|
44
|
+
import ctypes
|
|
45
|
+
|
|
46
|
+
advapi, kernel = api()
|
|
47
|
+
token = ctypes.c_void_p()
|
|
48
|
+
try:
|
|
49
|
+
if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), 0x8, ctypes.byref(token)):
|
|
50
|
+
raise ValueError("Cannot query current user SID")
|
|
51
|
+
size = ctypes.c_uint()
|
|
52
|
+
advapi.GetTokenInformation(token, 1, None, 0, ctypes.byref(size))
|
|
53
|
+
buffer = ctypes.create_string_buffer(size.value)
|
|
54
|
+
if not advapi.GetTokenInformation(token, 1, buffer, size, ctypes.byref(size)):
|
|
55
|
+
raise ValueError("Cannot query current user SID")
|
|
56
|
+
user = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0]
|
|
57
|
+
# TokenOwner (4): the owner this process gives what it creates. An elevated
|
|
58
|
+
# administrator's token (the built-in Administrator always) names BUILTIN\Administrators,
|
|
59
|
+
# so this process's own new files are owned by that group, not by its user.
|
|
60
|
+
advapi.GetTokenInformation(token, 4, None, 0, ctypes.byref(size))
|
|
61
|
+
default = ctypes.create_string_buffer(max(size.value, 8))
|
|
62
|
+
creator = (
|
|
63
|
+
ctypes.cast(default, ctypes.POINTER(ctypes.c_void_p))[0]
|
|
64
|
+
if advapi.GetTokenInformation(token, 4, default, size, ctypes.byref(size))
|
|
65
|
+
else None
|
|
66
|
+
)
|
|
67
|
+
return buffer, user, default, creator, sid_text(advapi, kernel, user)
|
|
68
|
+
finally:
|
|
69
|
+
if token.value:
|
|
70
|
+
kernel.CloseHandle(token)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def private_permissions(path: Path, created: bool) -> None:
|
|
74
|
+
"""Query owner/DACL only; protect a newly created DACL without changing owner/group/SACL."""
|
|
75
|
+
import ctypes
|
|
76
|
+
|
|
77
|
+
advapi, kernel = api()
|
|
78
|
+
_, user, _, creator, user_sid = identity()
|
|
79
|
+
descriptor = ctypes.c_void_p()
|
|
80
|
+
try:
|
|
81
|
+
owner, dacl = ctypes.c_void_p(), ctypes.c_void_p()
|
|
82
|
+
# OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; never request SACL.
|
|
83
|
+
error = advapi.GetNamedSecurityInfoW(
|
|
84
|
+
str(path),
|
|
85
|
+
1,
|
|
86
|
+
0x5,
|
|
87
|
+
ctypes.byref(owner),
|
|
88
|
+
None,
|
|
89
|
+
ctypes.byref(dacl),
|
|
90
|
+
None,
|
|
91
|
+
ctypes.byref(descriptor),
|
|
92
|
+
)
|
|
93
|
+
if error or not (
|
|
94
|
+
advapi.EqualSid(owner, user)
|
|
95
|
+
or (creator is not None and advapi.EqualSid(owner, creator))
|
|
96
|
+
):
|
|
97
|
+
raise ValueError("Runtime state has a foreign or unreadable owner")
|
|
98
|
+
if created:
|
|
99
|
+
protect(advapi, kernel, path, user_sid)
|
|
100
|
+
else:
|
|
101
|
+
control, revision = ctypes.c_ushort(), ctypes.c_uint()
|
|
102
|
+
# Protected (SE_DACL_PROTECTED), or inherited whole from a private parent: a program
|
|
103
|
+
# this tool runs (Magpie) replaces its own files, which then inherit that DACL.
|
|
104
|
+
if (
|
|
105
|
+
not advapi.GetSecurityDescriptorControl(
|
|
106
|
+
descriptor, ctypes.byref(control), ctypes.byref(revision)
|
|
107
|
+
)
|
|
108
|
+
or not dacl.value
|
|
109
|
+
):
|
|
110
|
+
raise ValueError("Existing runtime state must already have a private DACL")
|
|
111
|
+
count = ctypes.c_ushort.from_address(dacl.value + 4).value
|
|
112
|
+
entries: list[tuple[int, int, int, str]] = []
|
|
113
|
+
if count not in (1, 2):
|
|
114
|
+
raise ValueError("Existing runtime state must already have a private DACL")
|
|
115
|
+
for index in range(count):
|
|
116
|
+
ace = ctypes.c_void_p()
|
|
117
|
+
if not advapi.GetAce(dacl, index, ctypes.byref(ace)) or not ace.value:
|
|
118
|
+
raise ValueError("Cannot inspect runtime DACL entry")
|
|
119
|
+
kind = ctypes.c_ubyte.from_address(ace.value).value
|
|
120
|
+
if kind != 0:
|
|
121
|
+
raise ValueError("Existing runtime state must already have a private DACL")
|
|
122
|
+
entries.append(
|
|
123
|
+
(
|
|
124
|
+
kind,
|
|
125
|
+
ctypes.c_ubyte.from_address(ace.value + 1).value,
|
|
126
|
+
ctypes.c_uint.from_address(ace.value + 4).value,
|
|
127
|
+
sid_text(advapi, kernel, ace.value + 8),
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
if not private_dacl_entries(
|
|
131
|
+
entries, user_sid, protected=True, inherited=not control.value & 0x1000
|
|
132
|
+
):
|
|
133
|
+
raise ValueError("Existing runtime state must already have a private DACL")
|
|
134
|
+
finally:
|
|
135
|
+
if descriptor.value:
|
|
136
|
+
kernel.LocalFree(descriptor)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def private_dacl_entries(
|
|
140
|
+
entries: list[tuple[int, int, int, str]],
|
|
141
|
+
user_sid: str,
|
|
142
|
+
*,
|
|
143
|
+
protected: bool,
|
|
144
|
+
inherited: bool = False,
|
|
145
|
+
) -> bool:
|
|
146
|
+
"""A private DACL grants full access to the owner and optionally Local System only. An
|
|
147
|
+
``inherited`` (unprotected) DACL counts only when every entry came from its parent."""
|
|
148
|
+
identities = [sid for _, _, _, sid in entries]
|
|
149
|
+
return (
|
|
150
|
+
protected
|
|
151
|
+
and (not inherited or all(flags & 0x10 for _, flags, _, _ in entries))
|
|
152
|
+
and len(identities) in (1, 2)
|
|
153
|
+
and user_sid in identities
|
|
154
|
+
and len(set(identities)) == len(identities)
|
|
155
|
+
and set(identities).issubset({user_sid, "S-1-5-18"})
|
|
156
|
+
and all(
|
|
157
|
+
kind == 0 and not flags & 0x8 and mask & 0x1F01FF == 0x1F01FF
|
|
158
|
+
for kind, flags, mask, _ in entries
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def sid_text(advapi: Any, kernel: Any, sid: Any) -> str:
|
|
164
|
+
import ctypes
|
|
165
|
+
|
|
166
|
+
text = ctypes.c_void_p()
|
|
167
|
+
try:
|
|
168
|
+
if not advapi.ConvertSidToStringSidW(sid, ctypes.byref(text)) or text.value is None:
|
|
169
|
+
raise ValueError("Cannot format runtime SID")
|
|
170
|
+
return ctypes.wstring_at(text.value)
|
|
171
|
+
finally:
|
|
172
|
+
if text.value:
|
|
173
|
+
kernel.LocalFree(text)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def protect(advapi: Any, kernel: Any, path: Path, user_sid: str) -> None:
|
|
177
|
+
import ctypes
|
|
178
|
+
|
|
179
|
+
security = ctypes.c_void_p()
|
|
180
|
+
try:
|
|
181
|
+
inheritance = "OICI" if path.is_dir() else ""
|
|
182
|
+
sddl = f"D:P(A;{inheritance};FA;;;{user_sid})"
|
|
183
|
+
if not advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
184
|
+
sddl, 1, ctypes.byref(security), None
|
|
185
|
+
):
|
|
186
|
+
raise ValueError("Cannot construct private runtime DACL")
|
|
187
|
+
present, defaulted, dacl = ctypes.c_int(), ctypes.c_int(), ctypes.c_void_p()
|
|
188
|
+
if not advapi.GetSecurityDescriptorDacl(
|
|
189
|
+
security, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted)
|
|
190
|
+
):
|
|
191
|
+
raise ValueError("Cannot inspect private runtime DACL")
|
|
192
|
+
if advapi.SetNamedSecurityInfoW(str(path), 1, 0x80000004, None, None, dacl, None):
|
|
193
|
+
raise ValueError("Cannot protect new runtime state DACL")
|
|
194
|
+
finally:
|
|
195
|
+
if security.value:
|
|
196
|
+
kernel.LocalFree(security)
|
|
@@ -30,12 +30,18 @@ Mode = Literal["local", "subscription", "byok"]
|
|
|
30
30
|
Runtime = Literal["claude", "codex", "pi"]
|
|
31
31
|
|
|
32
32
|
PROTOCOLS: tuple[Protocol, ...] = ("openai-chat", "openai-responses", "anthropic")
|
|
33
|
-
#
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
|
|
33
|
+
# Where each wire format is served under an API root such as https://host/v1.
|
|
34
|
+
PROTOCOL_ENDPOINTS: dict[Protocol, str] = {
|
|
35
|
+
"openai-chat": "/chat/completions",
|
|
36
|
+
"openai-responses": "/responses",
|
|
37
|
+
"anthropic": "/messages",
|
|
38
|
+
}
|
|
39
|
+
# The Bifrost request types each wire format serves. Claude Code's Messages calls arrive as
|
|
40
|
+
# responses requests and Pi's as chat completions, so an Anthropic upstream takes both.
|
|
41
|
+
_BYOK_REQUESTS: dict[Protocol, tuple[str, ...]] = {
|
|
42
|
+
"openai-chat": ("chat_completion", "chat_completion_stream"),
|
|
43
|
+
"openai-responses": ("responses", "responses_stream"),
|
|
44
|
+
"anthropic": ("chat_completion", "chat_completion_stream", "responses", "responses_stream"),
|
|
39
45
|
}
|
|
40
46
|
MODES: tuple[Mode, ...] = ("local", "subscription", "byok")
|
|
41
47
|
RUNTIMES: tuple[Runtime, ...] = ("claude", "codex", "pi")
|
|
@@ -46,8 +52,13 @@ BYOK_PI_MODEL = f"{gateway_bifrost.PI_PROVIDER}/{BYOK_MODEL}"
|
|
|
46
52
|
DEFAULT_CONTEXT_WINDOW = bifrost_models.DEFAULT_CONTEXT
|
|
47
53
|
MAX_CONTEXT_WINDOW = 2_147_483_647
|
|
48
54
|
MODEL_ID_PATTERN = re.compile(r"^[-a-zA-Z0-9_./:@]{1,256}$")
|
|
55
|
+
# A path or endpoint is empty or whole segments each led by one slash, so appending it to
|
|
56
|
+
# the base URL can only extend the path, never change the host, query or fragment.
|
|
57
|
+
URL_PATH_PATTERN = re.compile(r"^(?:/[^/?#\s\\]+)*$")
|
|
58
|
+
MAX_URL_PATH = 256
|
|
49
59
|
|
|
50
|
-
CREDENTIALS_SCHEMA = "localmodels.byok-credentials/
|
|
60
|
+
CREDENTIALS_SCHEMA = "localmodels.byok-credentials/v2"
|
|
61
|
+
_V1_CREDENTIALS_SCHEMA = "localmodels.byok-credentials/v1"
|
|
51
62
|
SOURCE_SCHEMA = "localmodels.model-source/v1"
|
|
52
63
|
STATUS_SCHEMA = "localmodels.model-source-status/v1"
|
|
53
64
|
CHECK_SCHEMA = "localmodels.byok-check/v1"
|
|
@@ -55,7 +66,12 @@ MODELS_SCHEMA = "localmodels.byok-models/v1"
|
|
|
55
66
|
|
|
56
67
|
|
|
57
68
|
class ByokEndpoint(TypedDict):
|
|
69
|
+
# Requests go to base_url + path + endpoint and models are listed at
|
|
70
|
+
# base_url + path + /models; protocol is the wire format the caller chose.
|
|
58
71
|
base_url: str
|
|
72
|
+
path: str
|
|
73
|
+
endpoint: str
|
|
74
|
+
protocol: Protocol
|
|
59
75
|
api_key: str
|
|
60
76
|
model_id: str
|
|
61
77
|
context_window: int
|
|
@@ -64,10 +80,9 @@ class ByokEndpoint(TypedDict):
|
|
|
64
80
|
class ByokCredentials(TypedDict):
|
|
65
81
|
schema: str
|
|
66
82
|
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
83
|
base_url: str
|
|
70
|
-
|
|
84
|
+
path: str
|
|
85
|
+
endpoint: str
|
|
71
86
|
api_key: str
|
|
72
87
|
model_id: str
|
|
73
88
|
context_window: int
|
|
@@ -78,6 +93,8 @@ class ByokSummary(TypedDict):
|
|
|
78
93
|
configured: bool
|
|
79
94
|
protocol: Protocol | None
|
|
80
95
|
base_url: str | None
|
|
96
|
+
path: str | None
|
|
97
|
+
endpoint: str | None
|
|
81
98
|
model_id: str | None
|
|
82
99
|
context_window: int | None
|
|
83
100
|
key_saved: bool
|
|
@@ -176,6 +193,39 @@ def validate_url(raw: object) -> tuple[str, bool]:
|
|
|
176
193
|
return value, private
|
|
177
194
|
|
|
178
195
|
|
|
196
|
+
def validate_url_path(raw: object, label: str) -> str:
|
|
197
|
+
"""Validate an optional path or endpoint appended to the base URL."""
|
|
198
|
+
if not isinstance(raw, str) or len(raw) > MAX_URL_PATH or not URL_PATH_PATTERN.fullmatch(raw):
|
|
199
|
+
raise ByokError(
|
|
200
|
+
"BYOK_INVALID_CONFIG",
|
|
201
|
+
f"{label} must be empty or a path such as /v1.",
|
|
202
|
+
exit_code=2,
|
|
203
|
+
)
|
|
204
|
+
return raw
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def request_url(endpoint: ByokEndpoint | ByokCredentials) -> str:
|
|
208
|
+
"""The one address the endpoint's requests are sent to."""
|
|
209
|
+
return endpoint["base_url"] + endpoint["path"] + endpoint["endpoint"]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def models_url(endpoint: ByokEndpoint | ByokCredentials) -> str:
|
|
213
|
+
"""The address that lists the endpoint's models."""
|
|
214
|
+
return endpoint["base_url"] + endpoint["path"] + "/models"
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _from_v1(raw: dict[str, Any]) -> dict[str, Any]:
|
|
218
|
+
"""A v1 file sent its requests to upstream_url + /v1 + the wire format's endpoint, so it
|
|
219
|
+
converts to v2 exactly."""
|
|
220
|
+
return {
|
|
221
|
+
**raw,
|
|
222
|
+
"schema": CREDENTIALS_SCHEMA,
|
|
223
|
+
"base_url": raw.get("upstream_url"),
|
|
224
|
+
"path": "/v1",
|
|
225
|
+
"endpoint": PROTOCOL_ENDPOINTS[raw["protocol"]],
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
|
|
179
229
|
def load_credentials() -> ByokCredentials | None:
|
|
180
230
|
"""Read saved BYOK credentials from private state, or None when absent."""
|
|
181
231
|
path = _credentials_path()
|
|
@@ -183,13 +233,14 @@ def load_credentials() -> ByokCredentials | None:
|
|
|
183
233
|
return None
|
|
184
234
|
runtime_io.private_permissions(path)
|
|
185
235
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
186
|
-
if not isinstance(raw, dict) or raw.get("
|
|
236
|
+
if not isinstance(raw, dict) or raw.get("protocol") not in PROTOCOLS:
|
|
237
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK credentials are invalid.")
|
|
238
|
+
converted = raw.get("schema") == _V1_CREDENTIALS_SCHEMA
|
|
239
|
+
if converted:
|
|
240
|
+
raw = _from_v1(raw)
|
|
241
|
+
if raw.get("schema") != CREDENTIALS_SCHEMA:
|
|
187
242
|
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
243
|
url, _ = validate_url(raw.get("base_url"))
|
|
192
|
-
upstream, _ = validate_url(raw.get("upstream_url"))
|
|
193
244
|
model_id = str(raw.get("model_id") or "")
|
|
194
245
|
if not MODEL_ID_PATTERN.fullmatch(model_id):
|
|
195
246
|
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK model ID is invalid.")
|
|
@@ -197,16 +248,25 @@ def load_credentials() -> ByokCredentials | None:
|
|
|
197
248
|
if not isinstance(key, str):
|
|
198
249
|
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK key is invalid.")
|
|
199
250
|
window = int(raw.get("context_window") or DEFAULT_CONTEXT_WINDOW)
|
|
200
|
-
|
|
251
|
+
try:
|
|
252
|
+
url_path = validate_url_path(raw.get("path"), "Path")
|
|
253
|
+
endpoint = validate_url_path(raw.get("endpoint"), "Endpoint")
|
|
254
|
+
except ByokError:
|
|
255
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Saved BYOK credentials are invalid.") from None
|
|
256
|
+
creds: ByokCredentials = {
|
|
201
257
|
"schema": CREDENTIALS_SCHEMA,
|
|
202
|
-
"protocol": protocol,
|
|
258
|
+
"protocol": raw["protocol"],
|
|
203
259
|
"base_url": url,
|
|
204
|
-
"
|
|
260
|
+
"path": url_path,
|
|
261
|
+
"endpoint": endpoint,
|
|
205
262
|
"api_key": key,
|
|
206
263
|
"model_id": model_id,
|
|
207
264
|
"context_window": window if 1 <= window <= MAX_CONTEXT_WINDOW else DEFAULT_CONTEXT_WINDOW,
|
|
208
265
|
"key_saved": bool(key),
|
|
209
266
|
}
|
|
267
|
+
if converted:
|
|
268
|
+
save_credentials(creds)
|
|
269
|
+
return creds
|
|
210
270
|
|
|
211
271
|
|
|
212
272
|
def save_credentials(creds: ByokCredentials) -> None:
|
|
@@ -224,6 +284,8 @@ def credentials_summary(creds: ByokCredentials | None = None) -> ByokSummary:
|
|
|
224
284
|
"configured": False,
|
|
225
285
|
"protocol": None,
|
|
226
286
|
"base_url": None,
|
|
287
|
+
"path": None,
|
|
288
|
+
"endpoint": None,
|
|
227
289
|
"model_id": None,
|
|
228
290
|
"context_window": None,
|
|
229
291
|
"key_saved": False,
|
|
@@ -232,6 +294,8 @@ def credentials_summary(creds: ByokCredentials | None = None) -> ByokSummary:
|
|
|
232
294
|
"configured": True,
|
|
233
295
|
"protocol": loaded["protocol"],
|
|
234
296
|
"base_url": loaded["base_url"],
|
|
297
|
+
"path": loaded["path"],
|
|
298
|
+
"endpoint": loaded["endpoint"],
|
|
235
299
|
"model_id": loaded["model_id"],
|
|
236
300
|
"context_window": loaded["context_window"],
|
|
237
301
|
"key_saved": loaded["key_saved"],
|
|
@@ -267,17 +331,31 @@ def resolve_endpoint(
|
|
|
267
331
|
raise ByokError("BYOK_INVALID_CONFIG", "BYOK configuration is required.", exit_code=2)
|
|
268
332
|
return {
|
|
269
333
|
"base_url": saved["base_url"],
|
|
334
|
+
"path": saved["path"],
|
|
335
|
+
"endpoint": saved["endpoint"],
|
|
336
|
+
"protocol": saved["protocol"],
|
|
270
337
|
"api_key": saved["api_key"],
|
|
271
338
|
"model_id": saved["model_id"],
|
|
272
339
|
"context_window": saved["context_window"],
|
|
273
340
|
}
|
|
274
|
-
allowed = {
|
|
341
|
+
allowed = {
|
|
342
|
+
"baseUrl",
|
|
343
|
+
"path",
|
|
344
|
+
"endpoint",
|
|
345
|
+
"protocol",
|
|
346
|
+
"apiKey",
|
|
347
|
+
"modelId",
|
|
348
|
+
"contextWindow",
|
|
349
|
+
"reuseSavedKey",
|
|
350
|
+
}
|
|
275
351
|
if not isinstance(payload, dict) or set(payload) - allowed:
|
|
276
352
|
raise ByokError(
|
|
277
353
|
"BYOK_INVALID_CONFIG", "BYOK configuration fields are invalid.", exit_code=2
|
|
278
354
|
)
|
|
279
|
-
|
|
280
|
-
|
|
355
|
+
base_url, private = validate_url(payload.get("baseUrl"))
|
|
356
|
+
protocol = payload.get("protocol")
|
|
357
|
+
if protocol not in PROTOCOLS:
|
|
358
|
+
raise ByokError("BYOK_INVALID_CONFIG", "Wire format is invalid.", exit_code=2)
|
|
281
359
|
model_raw = payload.get("modelId") or (saved["model_id"] if saved and require_model else "")
|
|
282
360
|
if not isinstance(model_raw, str) or (
|
|
283
361
|
(require_model or model_raw) and not MODEL_ID_PATTERN.fullmatch(model_raw.strip())
|
|
@@ -294,6 +372,9 @@ def resolve_endpoint(
|
|
|
294
372
|
)
|
|
295
373
|
return {
|
|
296
374
|
"base_url": base_url,
|
|
375
|
+
"path": validate_url_path(payload.get("path"), "Path"),
|
|
376
|
+
"endpoint": validate_url_path(payload.get("endpoint"), "Endpoint"),
|
|
377
|
+
"protocol": protocol,
|
|
297
378
|
"api_key": _resolve_key(payload, saved, private),
|
|
298
379
|
"model_id": model_raw.strip(),
|
|
299
380
|
"context_window": window,
|
|
@@ -301,23 +382,27 @@ def resolve_endpoint(
|
|
|
301
382
|
|
|
302
383
|
|
|
303
384
|
def render_byok_provider(creds: ByokCredentials) -> dict[str, Any]:
|
|
304
|
-
"""Render the Bifrost provider entry for ``localmodels-byok``.
|
|
385
|
+
"""Render the Bifrost provider entry for ``localmodels-byok``.
|
|
386
|
+
|
|
387
|
+
Every allowed request type gets an absolute URL: Bifrost sends an empty override to its
|
|
388
|
+
own /v1/... path, so only a full URL reaches a base URL that is already the whole address.
|
|
389
|
+
"""
|
|
305
390
|
key = creds["api_key"] or gateway_bifrost.CALLER_KEY
|
|
306
391
|
model = creds["model_id"]
|
|
307
|
-
entry = bifrost_provider.render("llm", creds["
|
|
392
|
+
entry = bifrost_provider.render("llm", creds["base_url"], model, key, BYOK_PROVIDER)
|
|
393
|
+
entry["network_config"]["base_url"] = creds["base_url"]
|
|
308
394
|
first = entry["keys"][0]
|
|
309
395
|
first["models"] = [model] if model == BYOK_MODEL else [model, BYOK_MODEL]
|
|
310
396
|
first["aliases"] = {BYOK_MODEL: model}
|
|
397
|
+
url = request_url(creds)
|
|
398
|
+
overrides = {name: url for name in _BYOK_REQUESTS[creds["protocol"]]}
|
|
399
|
+
overrides["list_models"] = models_url(creds)
|
|
311
400
|
custom = entry["custom_provider_config"]
|
|
312
401
|
if creds["protocol"] == "anthropic":
|
|
313
402
|
custom["base_provider_type"] = "anthropic"
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
"list_models": True,
|
|
318
|
-
"responses": True,
|
|
319
|
-
"responses_stream": True,
|
|
320
|
-
}
|
|
403
|
+
overrides["count_tokens"] = f"{url}/count_tokens"
|
|
404
|
+
custom["allowed_requests"] = dict.fromkeys(overrides, True)
|
|
405
|
+
custom["request_path_overrides"] = overrides
|
|
321
406
|
return entry
|
|
322
407
|
|
|
323
408
|
|
|
@@ -387,6 +472,7 @@ def write_byok_profiles(addr: str, creds: ByokCredentials) -> dict[str, str]:
|
|
|
387
472
|
"context": creds["context_window"],
|
|
388
473
|
"efforts": ["low", "medium", "high"],
|
|
389
474
|
"defaultEffort": "medium",
|
|
475
|
+
"vision": False,
|
|
390
476
|
}
|
|
391
477
|
return {
|
|
392
478
|
"CODEX_HOME": _write_codex_profile(root, addr, facts),
|