@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
|
@@ -22,6 +22,7 @@ import socket
|
|
|
22
22
|
import subprocess
|
|
23
23
|
import sys
|
|
24
24
|
import threading
|
|
25
|
+
import time
|
|
25
26
|
from email.message import Message
|
|
26
27
|
from pathlib import Path
|
|
27
28
|
|
|
@@ -45,60 +46,150 @@ KILL_AFTER_S = 10.0 # the backend's time to exit on SIGTERM before SIGKILL
|
|
|
45
46
|
DISCARD_MAX = 256 << 20 # a refused upload larger than this is cut off, not read
|
|
46
47
|
|
|
47
48
|
|
|
49
|
+
def _http_version(version: str) -> tuple[int, int]:
|
|
50
|
+
"""Numeric (major, minor) of an HTTP request version string, defaulting to (1, 0)."""
|
|
51
|
+
if not version.startswith("HTTP/"):
|
|
52
|
+
return (1, 0)
|
|
53
|
+
parts = version[5:].split(".", 1)
|
|
54
|
+
try:
|
|
55
|
+
return (int(parts[0]), int(parts[1]) if len(parts) == 2 else 0)
|
|
56
|
+
except ValueError:
|
|
57
|
+
return (1, 0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _is_chunked(headers: Message) -> bool:
|
|
61
|
+
return "chunked" in (headers.get("Transfer-Encoding") or "").lower()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _response_has_no_body(method: str, status: int) -> bool:
|
|
65
|
+
return method == "HEAD" or 100 <= status < 200 or status in (204, 304)
|
|
66
|
+
|
|
67
|
+
|
|
48
68
|
def body_length(value: str | None) -> int:
|
|
49
69
|
"""A request's Content-Length; -1 when it is not a whole number."""
|
|
50
70
|
try:
|
|
51
|
-
|
|
71
|
+
length = int(value or 0)
|
|
52
72
|
except ValueError:
|
|
53
73
|
return -1
|
|
74
|
+
return length if length >= 0 else -1
|
|
54
75
|
|
|
55
76
|
|
|
56
77
|
def drain(stream: io.BufferedIOBase, length: int) -> bool:
|
|
57
|
-
"""Read and drop ``length`` bytes; False
|
|
58
|
-
over DISCARD_MAX."""
|
|
78
|
+
"""Read and drop ``length`` bytes; False when malformed, over DISCARD_MAX, or truncated."""
|
|
59
79
|
if not 0 <= length <= DISCARD_MAX:
|
|
60
80
|
return False
|
|
61
|
-
while length > 0
|
|
81
|
+
while length > 0:
|
|
82
|
+
chunk = stream.read(min(length, 65536))
|
|
83
|
+
if not chunk:
|
|
84
|
+
return False
|
|
62
85
|
length -= len(chunk)
|
|
63
86
|
return True
|
|
64
87
|
|
|
65
88
|
|
|
89
|
+
def drain_chunked(stream: io.BufferedIOBase, limit: int = DISCARD_MAX) -> bool:
|
|
90
|
+
"""Read and drop a chunked request body up to ``limit`` bytes; False when malformed or over."""
|
|
91
|
+
total = 0
|
|
92
|
+
while True:
|
|
93
|
+
line = stream.readline(65537)
|
|
94
|
+
if not line:
|
|
95
|
+
return False
|
|
96
|
+
try:
|
|
97
|
+
size = int(line.split(b";", 1)[0].strip(), 16)
|
|
98
|
+
except ValueError:
|
|
99
|
+
return False
|
|
100
|
+
if size < 0 or total + size > limit:
|
|
101
|
+
return False
|
|
102
|
+
if size == 0:
|
|
103
|
+
break
|
|
104
|
+
remaining = size
|
|
105
|
+
while remaining > 0:
|
|
106
|
+
chunk = stream.read(min(remaining, 65536))
|
|
107
|
+
if not chunk:
|
|
108
|
+
return False
|
|
109
|
+
remaining -= len(chunk)
|
|
110
|
+
total += len(chunk)
|
|
111
|
+
if not stream.readline(65537):
|
|
112
|
+
return False
|
|
113
|
+
while True:
|
|
114
|
+
trailer = stream.readline(65537)
|
|
115
|
+
if not trailer:
|
|
116
|
+
return False
|
|
117
|
+
if not trailer.strip():
|
|
118
|
+
return True
|
|
119
|
+
|
|
120
|
+
|
|
66
121
|
def read_chunked(stream: io.BufferedIOBase) -> bytes:
|
|
67
122
|
"""A request body sent with Transfer-Encoding: chunked, its trailers read and dropped."""
|
|
68
123
|
parts: list[bytes] = []
|
|
69
|
-
while
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
124
|
+
while True:
|
|
125
|
+
line = stream.readline(65537)
|
|
126
|
+
if not line:
|
|
127
|
+
raise EOFError("truncated chunked request")
|
|
128
|
+
size = int(line.split(b";", 1)[0].strip(), 16)
|
|
129
|
+
if size < 0:
|
|
130
|
+
raise ValueError("negative chunk size")
|
|
131
|
+
if size == 0:
|
|
132
|
+
break
|
|
133
|
+
chunk = stream.read(size)
|
|
134
|
+
if len(chunk) < size:
|
|
135
|
+
raise EOFError("truncated chunked body")
|
|
136
|
+
parts.append(chunk)
|
|
137
|
+
if not stream.readline(65537):
|
|
138
|
+
raise EOFError("truncated chunk terminator")
|
|
139
|
+
while True:
|
|
140
|
+
trailer = stream.readline(65537)
|
|
141
|
+
if not trailer:
|
|
142
|
+
raise EOFError("truncated chunked trailers")
|
|
143
|
+
if not trailer.strip():
|
|
144
|
+
break
|
|
74
145
|
return b"".join(parts)
|
|
75
146
|
|
|
76
147
|
|
|
77
148
|
def read_body(stream: io.BufferedIOBase, headers: Message) -> bytes | None:
|
|
78
149
|
"""A request's body, by its Content-Length or its chunks."""
|
|
79
|
-
if
|
|
150
|
+
if _is_chunked(headers):
|
|
80
151
|
return read_chunked(stream)
|
|
81
|
-
size =
|
|
82
|
-
|
|
152
|
+
size = body_length(headers.get("Content-Length"))
|
|
153
|
+
if size < 0:
|
|
154
|
+
raise ValueError("invalid Content-Length")
|
|
155
|
+
if size == 0:
|
|
156
|
+
return None
|
|
157
|
+
data = stream.read(size)
|
|
158
|
+
if len(data) < size:
|
|
159
|
+
raise EOFError("truncated request body")
|
|
160
|
+
return data
|
|
83
161
|
|
|
84
162
|
|
|
85
163
|
def client_gone(client: socket.socket) -> bool:
|
|
86
164
|
"""A client socket that is readable with nothing to read has hung up."""
|
|
165
|
+
previous = client.gettimeout()
|
|
87
166
|
try:
|
|
167
|
+
client.settimeout(0.0)
|
|
88
168
|
return client.recv(1, socket.MSG_PEEK) == b""
|
|
169
|
+
except (BlockingIOError, InterruptedError):
|
|
170
|
+
return False
|
|
89
171
|
except OSError:
|
|
90
172
|
return True
|
|
173
|
+
finally:
|
|
174
|
+
try:
|
|
175
|
+
client.settimeout(previous)
|
|
176
|
+
except OSError:
|
|
177
|
+
pass
|
|
91
178
|
|
|
92
179
|
|
|
93
180
|
def reply_or_hangup(upstream: socket.socket, client: socket.socket, timeout: float) -> bool:
|
|
94
181
|
"""Wait for the backend's reply. False when the client hangs up first: the caller then
|
|
95
182
|
closes the backend connection, and a backend that drops a request whose client is gone
|
|
96
183
|
(llama-server, while it still reads the prompt) drops this one as if connected directly."""
|
|
184
|
+
deadline = time.monotonic() + timeout
|
|
97
185
|
with selectors.DefaultSelector() as watch:
|
|
98
186
|
watch.register(upstream, selectors.EVENT_READ)
|
|
99
187
|
watch.register(client, selectors.EVENT_READ)
|
|
100
188
|
while True:
|
|
101
|
-
|
|
189
|
+
remaining = deadline - time.monotonic()
|
|
190
|
+
if remaining <= 0:
|
|
191
|
+
raise socket.timeout("the backend sent no reply")
|
|
192
|
+
ready = [key.fileobj for key, _ in watch.select(remaining)]
|
|
102
193
|
if not ready:
|
|
103
194
|
raise socket.timeout("the backend sent no reply")
|
|
104
195
|
if upstream in ready:
|
|
@@ -108,16 +199,77 @@ def reply_or_hangup(upstream: socket.socket, client: socket.socket, timeout: flo
|
|
|
108
199
|
watch.unregister(client) # more bytes from the client: nothing to learn from them
|
|
109
200
|
|
|
110
201
|
|
|
111
|
-
def send_head(
|
|
112
|
-
|
|
113
|
-
|
|
202
|
+
def send_head(
|
|
203
|
+
to: http.server.BaseHTTPRequestHandler, resp: http.client.HTTPResponse
|
|
204
|
+
) -> tuple[str, int | None]:
|
|
205
|
+
"""Forward the backend's status and headers with proper HTTP/1.1 framing.
|
|
206
|
+
|
|
207
|
+
Fixed-length replies preserve Content-Length; unknown-length or chunked streams use
|
|
208
|
+
Transfer-Encoding: chunked for HTTP/1.1 clients (so persistent connections stay framed and
|
|
209
|
+
each frame flushes immediately) and close-delimited framing for HTTP/1.0 clients.
|
|
210
|
+
"""
|
|
114
211
|
to.send_response(resp.status)
|
|
115
212
|
for k, v in resp.getheaders():
|
|
116
213
|
if k.lower() not in DROPPED:
|
|
117
214
|
to.send_header(k, v)
|
|
118
|
-
|
|
119
|
-
|
|
215
|
+
raw_length = resp.getheader("Content-Length")
|
|
216
|
+
length = body_length(raw_length) if raw_length is not None and not resp.chunked else -1
|
|
217
|
+
if _response_has_no_body(to.command, resp.status):
|
|
218
|
+
if to.command == "HEAD" and length >= 0:
|
|
219
|
+
to.send_header("Content-Length", str(length))
|
|
220
|
+
mode, expected = "none", None
|
|
221
|
+
elif length >= 0:
|
|
222
|
+
to.send_header("Content-Length", str(length))
|
|
223
|
+
mode, expected = "length", length
|
|
224
|
+
elif _http_version(to.request_version) >= (1, 1):
|
|
225
|
+
to.send_header("Transfer-Encoding", "chunked")
|
|
226
|
+
mode, expected = "chunked", None
|
|
227
|
+
else:
|
|
228
|
+
to.close_connection = True
|
|
229
|
+
mode, expected = "close", None
|
|
230
|
+
if to.close_connection:
|
|
231
|
+
to.send_header("Connection", "close")
|
|
120
232
|
to.end_headers()
|
|
233
|
+
return mode, expected
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def forward_body(
|
|
237
|
+
to: http.server.BaseHTTPRequestHandler,
|
|
238
|
+
resp: http.client.HTTPResponse,
|
|
239
|
+
mode: str,
|
|
240
|
+
expected: int | None,
|
|
241
|
+
) -> None:
|
|
242
|
+
"""Stream the backend's response body according to the framing chosen by ``send_head``."""
|
|
243
|
+
if mode == "none":
|
|
244
|
+
return
|
|
245
|
+
if mode == "length":
|
|
246
|
+
written = 0
|
|
247
|
+
while True:
|
|
248
|
+
data = resp.read1(65536)
|
|
249
|
+
if not data:
|
|
250
|
+
break
|
|
251
|
+
to.wfile.write(data)
|
|
252
|
+
to.wfile.flush()
|
|
253
|
+
written += len(data)
|
|
254
|
+
if expected is not None and written != expected:
|
|
255
|
+
to.close_connection = True
|
|
256
|
+
return
|
|
257
|
+
if mode == "chunked":
|
|
258
|
+
while True:
|
|
259
|
+
data = resp.read1(65536)
|
|
260
|
+
if not data:
|
|
261
|
+
break
|
|
262
|
+
to.wfile.write(f"{len(data):x}\r\n".encode("ascii") + data + b"\r\n")
|
|
263
|
+
to.wfile.flush()
|
|
264
|
+
to.wfile.write(b"0\r\n\r\n")
|
|
265
|
+
to.wfile.flush()
|
|
266
|
+
return
|
|
267
|
+
while True:
|
|
268
|
+
data = resp.read1(65536)
|
|
269
|
+
if not data:
|
|
270
|
+
break
|
|
271
|
+
to.wfile.write(data)
|
|
272
|
+
to.wfile.flush()
|
|
121
273
|
|
|
122
274
|
|
|
123
275
|
def free_port() -> int:
|
|
@@ -126,76 +278,127 @@ def free_port() -> int:
|
|
|
126
278
|
return int(s.getsockname()[1])
|
|
127
279
|
|
|
128
280
|
|
|
281
|
+
def _discard_request(stream: io.BufferedIOBase, headers: Message) -> bool:
|
|
282
|
+
"""Drain a refused request's body up to DISCARD_MAX bytes; False when malformed or larger."""
|
|
283
|
+
if _is_chunked(headers):
|
|
284
|
+
return drain_chunked(stream)
|
|
285
|
+
return drain(stream, body_length(headers.get("Content-Length")))
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _proxy_upstream(
|
|
289
|
+
to: http.server.BaseHTTPRequestHandler,
|
|
290
|
+
upstream: int,
|
|
291
|
+
body: bytes | None,
|
|
292
|
+
headers: dict[str, str],
|
|
293
|
+
) -> bool:
|
|
294
|
+
"""Forward one request to ``upstream``; returns True once response headers were sent."""
|
|
295
|
+
conn = http.client.HTTPConnection("127.0.0.1", upstream, timeout=TIMEOUT_S)
|
|
296
|
+
started = False
|
|
297
|
+
try:
|
|
298
|
+
conn.request(to.command, to.path, body=body, headers=headers)
|
|
299
|
+
if not reply_or_hangup(conn.sock, to.connection, TIMEOUT_S):
|
|
300
|
+
to.close_connection = True # nobody is left to answer
|
|
301
|
+
return True
|
|
302
|
+
resp = conn.getresponse()
|
|
303
|
+
mode, expected_length = send_head(to, resp)
|
|
304
|
+
started = True
|
|
305
|
+
forward_body(to, resp, mode, expected_length)
|
|
306
|
+
return True
|
|
307
|
+
except (OSError, http.client.HTTPException): # a reply cut short is not an OSError
|
|
308
|
+
if started:
|
|
309
|
+
to.close_connection = True
|
|
310
|
+
return started
|
|
311
|
+
finally:
|
|
312
|
+
conn.close()
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class _ForwardBase(http.server.BaseHTTPRequestHandler):
|
|
316
|
+
protocol_version = "HTTP/1.1"
|
|
317
|
+
disable_nagle_algorithm = True
|
|
318
|
+
_expected: bytes | None = None
|
|
319
|
+
_upstream: int = 0
|
|
320
|
+
_dropped: frozenset[str] = frozenset(DROPPED)
|
|
321
|
+
body_read = False
|
|
322
|
+
|
|
323
|
+
def log_message(self, *args: object) -> None:
|
|
324
|
+
pass # request lines carry paths and queries; the service log keeps none of them
|
|
325
|
+
|
|
326
|
+
def handle_one_request(self) -> None:
|
|
327
|
+
try:
|
|
328
|
+
super().handle_one_request()
|
|
329
|
+
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
|
330
|
+
self.close_connection = True
|
|
331
|
+
|
|
332
|
+
def parse_request(self) -> bool:
|
|
333
|
+
self.body_read = False # per request: one keep-alive connection carries several
|
|
334
|
+
return super().parse_request()
|
|
335
|
+
|
|
336
|
+
def _read_body(self) -> bytes | None:
|
|
337
|
+
self.body_read = True
|
|
338
|
+
return read_body(self.rfile, self.headers)
|
|
339
|
+
|
|
340
|
+
def _discard_body(self) -> None:
|
|
341
|
+
"""Read a refused request's body so the reply arrives, up to DISCARD_MAX bytes; a
|
|
342
|
+
longer or malformed one closes the connection instead (no unbounded read for a
|
|
343
|
+
caller without the key)."""
|
|
344
|
+
self.body_read = True
|
|
345
|
+
if not _discard_request(self.rfile, self.headers):
|
|
346
|
+
self.close_connection = True
|
|
347
|
+
|
|
348
|
+
def _reply(self, code: int, body: bytes, kind: str = "application/json") -> None:
|
|
349
|
+
# A refusal (401, 404) still reads the body: closing on unread bytes resets the
|
|
350
|
+
# connection, and a client still uploading gets a broken pipe instead of the reply.
|
|
351
|
+
if not self.body_read:
|
|
352
|
+
self._discard_body()
|
|
353
|
+
self.send_response(code)
|
|
354
|
+
self.send_header("Content-Type", kind)
|
|
355
|
+
self.send_header("Content-Length", str(len(body)))
|
|
356
|
+
if self.close_connection:
|
|
357
|
+
self.send_header("Connection", "close")
|
|
358
|
+
self.end_headers()
|
|
359
|
+
self.wfile.write(body)
|
|
360
|
+
self.wfile.flush()
|
|
361
|
+
|
|
362
|
+
def _safe_reply(self, code: int, body: bytes) -> None:
|
|
363
|
+
try:
|
|
364
|
+
self._reply(code, body)
|
|
365
|
+
except OSError:
|
|
366
|
+
self.close_connection = True
|
|
367
|
+
|
|
368
|
+
def _forward(self) -> None:
|
|
369
|
+
given = (self.headers.get("Authorization") or "").encode()
|
|
370
|
+
if self._expected is not None and not hmac.compare_digest(given, self._expected):
|
|
371
|
+
self._safe_reply(401, b'{"error":{"code":401,"message":"invalid API key"}}')
|
|
372
|
+
return
|
|
373
|
+
try:
|
|
374
|
+
body = self._read_body()
|
|
375
|
+
except ValueError:
|
|
376
|
+
self.close_connection = True
|
|
377
|
+
self._safe_reply(400, b'{"error":{"code":400,"message":"invalid request body"}}')
|
|
378
|
+
return
|
|
379
|
+
except (EOFError, OSError):
|
|
380
|
+
self.close_connection = True
|
|
381
|
+
return
|
|
382
|
+
headers = {k: v for k, v in self.headers.items() if k.lower() not in self._dropped}
|
|
383
|
+
headers["Connection"] = "close"
|
|
384
|
+
if not _proxy_upstream(self, self._upstream, body, headers):
|
|
385
|
+
self._safe_reply(503, b'{"error":{"code":503,"message":"backend not ready"}}')
|
|
386
|
+
|
|
387
|
+
do_GET = do_POST = do_DELETE = do_HEAD = _forward # whisper-server routes: GET, POST
|
|
388
|
+
|
|
389
|
+
|
|
129
390
|
def handler(
|
|
130
391
|
key: str | None, upstream: int, *, pass_auth: bool = False
|
|
131
392
|
) -> type[http.server.BaseHTTPRequestHandler]:
|
|
132
393
|
"""The forwarding handler. ``key`` None checks no key here (the upstream checks its own);
|
|
133
394
|
``pass_auth`` lets the caller's Authorization header reach the upstream."""
|
|
134
395
|
expected = None if key is None else ("Bearer " + key).encode()
|
|
135
|
-
dropped = DROPPED - {"authorization"} if pass_auth else DROPPED
|
|
136
|
-
|
|
137
|
-
class Forward(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
pass # request lines carry paths and queries; the service log keeps none of them
|
|
142
|
-
|
|
143
|
-
body_read = False
|
|
144
|
-
|
|
145
|
-
def parse_request(self) -> bool:
|
|
146
|
-
self.body_read = False # per request: one keep-alive connection carries several
|
|
147
|
-
return super().parse_request()
|
|
148
|
-
|
|
149
|
-
def _read_body(self) -> bytes | None:
|
|
150
|
-
self.body_read = True
|
|
151
|
-
return read_body(self.rfile, self.headers)
|
|
152
|
-
|
|
153
|
-
def _discard_body(self) -> None:
|
|
154
|
-
"""Read a refused request's body so the reply arrives, up to DISCARD_MAX bytes; a
|
|
155
|
-
longer or malformed one closes the connection instead (no unbounded read for a
|
|
156
|
-
caller without the key)."""
|
|
157
|
-
self.body_read = True
|
|
158
|
-
if not drain(self.rfile, body_length(self.headers.get("Content-Length"))):
|
|
159
|
-
self.close_connection = True
|
|
160
|
-
|
|
161
|
-
def _reply(self, code: int, body: bytes, kind: str = "application/json") -> None:
|
|
162
|
-
# A refusal (401, 404) still reads the body: closing on unread bytes resets the
|
|
163
|
-
# connection, and a client still uploading gets a broken pipe instead of the reply.
|
|
164
|
-
if not self.body_read:
|
|
165
|
-
self._discard_body()
|
|
166
|
-
self.send_response(code)
|
|
167
|
-
self.send_header("Content-Type", kind)
|
|
168
|
-
self.send_header("Content-Length", str(len(body)))
|
|
169
|
-
self.end_headers()
|
|
170
|
-
self.wfile.write(body)
|
|
171
|
-
|
|
172
|
-
def _forward(self) -> None:
|
|
173
|
-
given = (self.headers.get("Authorization") or "").encode()
|
|
174
|
-
if expected is not None and not hmac.compare_digest(given, expected):
|
|
175
|
-
self._reply(401, b'{"error":{"code":401,"message":"invalid API key"}}')
|
|
176
|
-
return
|
|
177
|
-
body = self._read_body()
|
|
178
|
-
headers = {k: v for k, v in self.headers.items() if k.lower() not in dropped}
|
|
179
|
-
conn = http.client.HTTPConnection("127.0.0.1", upstream, timeout=TIMEOUT_S)
|
|
180
|
-
started = False
|
|
181
|
-
try:
|
|
182
|
-
conn.request(self.command, self.path, body=body, headers=headers)
|
|
183
|
-
if not reply_or_hangup(conn.sock, self.connection, TIMEOUT_S):
|
|
184
|
-
self.close_connection = True # nobody is left to answer
|
|
185
|
-
return
|
|
186
|
-
resp = conn.getresponse()
|
|
187
|
-
send_head(self, resp)
|
|
188
|
-
started = True
|
|
189
|
-
while data := resp.read1(65536):
|
|
190
|
-
self.wfile.write(data)
|
|
191
|
-
self.wfile.flush()
|
|
192
|
-
except (OSError, http.client.HTTPException): # a reply cut short is not an OSError
|
|
193
|
-
if not started:
|
|
194
|
-
self._reply(503, b'{"error":{"code":503,"message":"backend not ready"}}')
|
|
195
|
-
finally:
|
|
196
|
-
conn.close()
|
|
197
|
-
|
|
198
|
-
do_GET = do_POST = do_DELETE = _forward # whisper-server routes: GET, POST
|
|
396
|
+
dropped = frozenset(DROPPED - {"authorization"} if pass_auth else DROPPED)
|
|
397
|
+
|
|
398
|
+
class Forward(_ForwardBase):
|
|
399
|
+
_expected = expected
|
|
400
|
+
_upstream = upstream
|
|
401
|
+
_dropped = dropped
|
|
199
402
|
|
|
200
403
|
return Forward
|
|
201
404
|
|
|
@@ -46,6 +46,7 @@ class LlmFacts(TypedDict):
|
|
|
46
46
|
context: int
|
|
47
47
|
efforts: list[str] # reasoning_effort values the LLM's template accepts, low to high
|
|
48
48
|
defaultEffort: str
|
|
49
|
+
vision: bool # True when the served LLM reads images (vision.reads_pictures)
|
|
49
50
|
|
|
50
51
|
|
|
51
52
|
class GatewayFacts(TypedDict):
|
|
@@ -95,6 +96,11 @@ def default_effort(levels: list[str]) -> str:
|
|
|
95
96
|
return "medium" if "medium" in levels else levels[(len(levels) - 1) // 2]
|
|
96
97
|
|
|
97
98
|
|
|
99
|
+
def input_modalities(facts: LlmFacts) -> list[str]:
|
|
100
|
+
"""Input modalities for Codex (``input_modalities``) and pi (``input``)."""
|
|
101
|
+
return ["text", "image"] if facts.get("vision") else ["text"]
|
|
102
|
+
|
|
103
|
+
|
|
98
104
|
def llm_facts(gw: GatewayPlan, display: str) -> LlmFacts:
|
|
99
105
|
levels = efforts(gw)
|
|
100
106
|
return {
|
|
@@ -102,6 +108,7 @@ def llm_facts(gw: GatewayPlan, display: str) -> LlmFacts:
|
|
|
102
108
|
"context": int(gw.get("context") or DEFAULT_CONTEXT),
|
|
103
109
|
"efforts": levels,
|
|
104
110
|
"defaultEffort": default_effort(levels),
|
|
111
|
+
"vision": bool(gw.get("vision")),
|
|
105
112
|
}
|
|
106
113
|
|
|
107
114
|
|
|
@@ -153,7 +160,7 @@ def codex_catalog(facts: LlmFacts, model: str) -> dict[str, Any]:
|
|
|
153
160
|
"context_window": facts["context"],
|
|
154
161
|
"max_context_window": facts["context"],
|
|
155
162
|
"effective_context_window_percent": 95,
|
|
156
|
-
"input_modalities":
|
|
163
|
+
"input_modalities": input_modalities(facts),
|
|
157
164
|
"shell_type": "unified_exec",
|
|
158
165
|
"base_instructions": CODEX_INSTRUCTIONS,
|
|
159
166
|
"support_verbosity": False,
|
|
@@ -188,7 +195,7 @@ def pi_provider(facts: LlmFacts, model: str, base: str) -> dict[str, Any]:
|
|
|
188
195
|
"thinkingLevelMap": {
|
|
189
196
|
level: level if level in facts["efforts"] else None for level in PI_LEVELS
|
|
190
197
|
},
|
|
191
|
-
"input":
|
|
198
|
+
"input": input_modalities(facts),
|
|
192
199
|
"contextWindow": context,
|
|
193
200
|
"maxTokens": min(32768, max(4096, context // 4)),
|
|
194
201
|
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
|
|
@@ -2,10 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import ipaddress
|
|
6
|
+
import urllib.parse
|
|
5
7
|
from typing import Any
|
|
6
8
|
|
|
7
9
|
from localmodels import harness
|
|
8
10
|
|
|
11
|
+
# Loopback upstreams (llama-server uses cpp-httplib's 5 s keep-alive timeout; auth_proxy fronts
|
|
12
|
+
# local services) sit on 127.0.0.1 where a fresh dial costs microseconds, while Bifrost's
|
|
13
|
+
# fasthttp pool defaults to a 30 s idle timeout and its StaleConnectionRetryIfErr only matches
|
|
14
|
+
# POSIX "broken pipe" / "connection reset by peer", not Windows Winsock WSAECONNABORTED (10053)
|
|
15
|
+
# or WSAECONNRESET (10054). Closing loopback connections after each response, capping idle
|
|
16
|
+
# keep-alive below 5 s, and allowing 2 fast retries on pre-response transport failures prevents
|
|
17
|
+
# Windows 502 wsasend aborts (evidence/2026-11-19-linger-agentic-batch1/REPORT.md, Issue #3).
|
|
18
|
+
LOOPBACK_KEEP_ALIVE_S = 2
|
|
19
|
+
LOOPBACK_MAX_RETRIES = 2
|
|
20
|
+
LOOPBACK_RETRY_INITIAL_MS = 100
|
|
21
|
+
LOOPBACK_RETRY_MAX_MS = 500
|
|
22
|
+
|
|
9
23
|
# What each provider may be asked: everything else Bifrost refuses before it reaches the
|
|
10
24
|
# service. The LLM speaks chat only, so Bifrost turns Responses (Codex) and Anthropic Messages
|
|
11
25
|
# (Claude Code) requests into chat completions instead of calling /v1/responses upstream.
|
|
@@ -21,6 +35,16 @@ _ALLOWED = {
|
|
|
21
35
|
_BASE_TYPE = {"decision": "typesafe", "rerank": "cohere"}
|
|
22
36
|
|
|
23
37
|
|
|
38
|
+
def _is_loopback(url: str) -> bool:
|
|
39
|
+
host = (urllib.parse.urlsplit(url).hostname or "").strip().lower()
|
|
40
|
+
if host == "localhost":
|
|
41
|
+
return True
|
|
42
|
+
try:
|
|
43
|
+
return ipaddress.ip_address(host).is_loopback
|
|
44
|
+
except ValueError:
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
24
48
|
def render(role: str, url: str, model: str, key: str, pid: str) -> dict[str, Any]:
|
|
25
49
|
custom: dict[str, Any] = {
|
|
26
50
|
"base_provider_type": _BASE_TYPE.get(role, "openai"),
|
|
@@ -34,15 +58,26 @@ def render(role: str, url: str, model: str, key: str, pid: str) -> dict[str, Any
|
|
|
34
58
|
# a name only when the key has it in both ``models`` and ``aliases``; either alone does not.
|
|
35
59
|
entry["models"] = [model, harness.GROUP]
|
|
36
60
|
entry["aliases"] = {harness.GROUP: model}
|
|
61
|
+
network_config: dict[str, Any] = {
|
|
62
|
+
"base_url": origin(url),
|
|
63
|
+
"allow_private_network": True,
|
|
64
|
+
"max_retries": 0,
|
|
65
|
+
"default_request_timeout_in_seconds": 600,
|
|
66
|
+
"stream_idle_timeout_in_seconds": 600,
|
|
67
|
+
}
|
|
68
|
+
if _is_loopback(url):
|
|
69
|
+
network_config.update(
|
|
70
|
+
{
|
|
71
|
+
"max_retries": LOOPBACK_MAX_RETRIES,
|
|
72
|
+
"retry_backoff_initial": LOOPBACK_RETRY_INITIAL_MS,
|
|
73
|
+
"retry_backoff_max": LOOPBACK_RETRY_MAX_MS,
|
|
74
|
+
"keep_alive_timeout_in_seconds": LOOPBACK_KEEP_ALIVE_S,
|
|
75
|
+
"extra_headers": {"Connection": "close"},
|
|
76
|
+
}
|
|
77
|
+
)
|
|
37
78
|
return {
|
|
38
79
|
"keys": [entry],
|
|
39
|
-
"network_config":
|
|
40
|
-
"base_url": origin(url),
|
|
41
|
-
"allow_private_network": True,
|
|
42
|
-
"max_retries": 0,
|
|
43
|
-
"default_request_timeout_in_seconds": 600,
|
|
44
|
-
"stream_idle_timeout_in_seconds": 600,
|
|
45
|
-
},
|
|
80
|
+
"network_config": network_config,
|
|
46
81
|
"custom_provider_config": custom,
|
|
47
82
|
}
|
|
48
83
|
|
|
@@ -552,7 +552,6 @@ def _install_direct_pi_gateway() -> None:
|
|
|
552
552
|
"""Offline fallback for ``simulate`` when Bifrost is unavailable or ``offline_gateway`` is set."""
|
|
553
553
|
from localmodels import bifrost_models, library_gateway
|
|
554
554
|
from localmodels import catalog as cat
|
|
555
|
-
from localmodels.library_model import display_name, split_id
|
|
556
555
|
from localmodels.library_state import Registration
|
|
557
556
|
|
|
558
557
|
original_register = library_gateway.register
|
|
@@ -568,14 +567,7 @@ def _install_direct_pi_gateway() -> None:
|
|
|
568
567
|
stack_provider: str | None = None,
|
|
569
568
|
) -> Registration:
|
|
570
569
|
added = library_gateway.planned(model, plan, stack_provider=stack_provider)
|
|
571
|
-
|
|
572
|
-
context = int(str(plan["launch"].get("window") or 0)) or bifrost_models.DEFAULT_CONTEXT
|
|
573
|
-
facts_: bifrost_models.LlmFacts = {
|
|
574
|
-
"display": display_name(entry.display_name, split_id(model)[1]),
|
|
575
|
-
"context": context,
|
|
576
|
-
"efforts": levels,
|
|
577
|
-
"defaultEffort": bifrost_models.default_effort(levels),
|
|
578
|
-
}
|
|
570
|
+
facts_ = library_gateway.model_facts(model, entry, plan)
|
|
579
571
|
base_url = str(plan["endpoint"]["base_url"]).removesuffix("/v1").rstrip("/")
|
|
580
572
|
served = str(plan["endpoint"]["model"])
|
|
581
573
|
pi_entry = bifrost_models.pi_provider(facts_, served, base_url)["models"][0]
|
|
@@ -680,7 +672,6 @@ def _install_simulate_mode(config: DebugConfig) -> None:
|
|
|
680
672
|
if config.offline_gateway:
|
|
681
673
|
from localmodels import bifrost_models
|
|
682
674
|
from localmodels import catalog as cat
|
|
683
|
-
from localmodels.library_model import display_name, split_id
|
|
684
675
|
from localmodels.library_state import Registration
|
|
685
676
|
|
|
686
677
|
def offline_only_register(
|
|
@@ -694,14 +685,7 @@ def _install_simulate_mode(config: DebugConfig) -> None:
|
|
|
694
685
|
) -> Registration:
|
|
695
686
|
_ = key, facts
|
|
696
687
|
added = library_gateway.planned(model, plan, stack_provider=stack_provider)
|
|
697
|
-
|
|
698
|
-
context = int(str(plan["launch"].get("window") or 0)) or bifrost_models.DEFAULT_CONTEXT
|
|
699
|
-
facts_: bifrost_models.LlmFacts = {
|
|
700
|
-
"display": display_name(entry.display_name, split_id(model)[1]),
|
|
701
|
-
"context": context,
|
|
702
|
-
"efforts": levels,
|
|
703
|
-
"defaultEffort": bifrost_models.default_effort(levels),
|
|
704
|
-
}
|
|
688
|
+
facts_ = library_gateway.model_facts(model, entry, plan)
|
|
705
689
|
base_url = str(plan["endpoint"]["base_url"]).removesuffix("/v1").rstrip("/")
|
|
706
690
|
served = str(plan["endpoint"]["model"])
|
|
707
691
|
pi_entry = bifrost_models.pi_provider(facts_, served, base_url)["models"][0]
|
|
@@ -37,8 +37,9 @@ def _version(text: str | None) -> tuple[int, ...]:
|
|
|
37
37
|
return tuple(int(x) for x in re.findall(r"\d+", text or "")[:2])
|
|
38
38
|
|
|
39
39
|
|
|
40
|
-
def _cuda_tuple(version: str) -> tuple[int,
|
|
41
|
-
|
|
40
|
+
def _cuda_tuple(version: str) -> tuple[int, int]:
|
|
41
|
+
parts = [int(x) for x in re.findall(r"\d+", version)[:2]]
|
|
42
|
+
return (parts[0], parts[1] if len(parts) > 1 else 0) if parts else (0, 0)
|
|
42
43
|
|
|
43
44
|
|
|
44
45
|
def engine_lock_path(tag: str | None = None) -> Path:
|
|
@@ -75,9 +76,12 @@ def select_engine_build(
|
|
|
75
76
|
for b in lock["builds"]
|
|
76
77
|
if b["platform"] == platform and b["arch"] == facts.get("arch") and b["backend"] in accepted
|
|
77
78
|
]
|
|
78
|
-
|
|
79
|
+
platform_builds = builds
|
|
80
|
+
driver_cuda = ""
|
|
81
|
+
driver = (0, 0)
|
|
79
82
|
if backend == "cuda":
|
|
80
|
-
|
|
83
|
+
driver_cuda = ((facts.get("nvidia") or {}).get("cuda_version") or "").strip()
|
|
84
|
+
driver = _cuda_tuple(driver_cuda)
|
|
81
85
|
builds = [b for b in builds if _cuda_tuple(b["min_cuda"]) <= driver]
|
|
82
86
|
builds.sort(
|
|
83
87
|
key=lambda b: (_cuda_tuple(b.get("min_cuda", "")), _version(b.get("min_glibc"))),
|
|
@@ -102,9 +106,18 @@ def select_engine_build(
|
|
|
102
106
|
"host; this tool does not install system packages"
|
|
103
107
|
)
|
|
104
108
|
if not builds:
|
|
109
|
+
detail = ""
|
|
110
|
+
if backend == "cuda" and platform_builds:
|
|
111
|
+
oldest = min((b["min_cuda"] for b in platform_builds), key=_cuda_tuple)
|
|
112
|
+
if driver == (0, 0):
|
|
113
|
+
detail = f" (could not detect the driver's CUDA version; requires CUDA >= {oldest})"
|
|
114
|
+
else:
|
|
115
|
+
detail = (
|
|
116
|
+
f" (the driver supports CUDA {driver_cuda}, "
|
|
117
|
+
f"older than the required CUDA >= {oldest})"
|
|
118
|
+
)
|
|
105
119
|
raise PlanError(
|
|
106
|
-
f"no {lock['tag']} prebuilt engine for {platform}/{facts.get('arch')}/{backend}"
|
|
107
|
-
+ (" (the driver supports too old a CUDA version)" if for_platform else "")
|
|
120
|
+
f"no {lock['tag']} prebuilt engine for {platform}/{facts.get('arch')}/{backend}{detail}"
|
|
108
121
|
)
|
|
109
122
|
return {"tag": lock["tag"], "commit": lock["commit"], **builds[0]}
|
|
110
123
|
|