@simplexai/localmodels-darwin-arm64 0.1.0-dev.43 → 0.1.0-dev.45
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 +76 -79
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +0 -1
- package/modules/localmodels/auth_proxy.py +285 -82
- package/modules/localmodels/bifrost_checks.py +3 -127
- package/modules/localmodels/bifrost_clients.py +1 -1
- package/modules/localmodels/bifrost_config.py +2 -2
- package/modules/localmodels/bifrost_models.py +9 -2
- package/modules/localmodels/bifrost_pi.py +1 -1
- package/modules/localmodels/bifrost_provider.py +42 -7
- package/modules/localmodels/budget.py +16 -1
- package/modules/localmodels/catalog.json +15 -50
- package/modules/localmodels/catalog_recipes.py +1 -1
- package/modules/localmodels/debug_mode.py +2 -18
- package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
- package/modules/localmodels/engines.py +19 -6
- package/modules/localmodels/gateway.py +50 -15
- package/modules/localmodels/gateway_accept.py +8 -5
- package/modules/localmodels/gateway_bifrost.py +23 -13
- package/modules/localmodels/gateway_cli.py +5 -2
- package/modules/localmodels/gateway_requests.py +9 -2
- package/modules/localmodels/harness.py +41 -12
- package/modules/localmodels/harness_gateway.py +1 -1
- package/modules/localmodels/hosts.py +7 -20
- package/modules/localmodels/library_convert.py +491 -57
- package/modules/localmodels/library_gateway.py +27 -16
- package/modules/localmodels/library_pricing.py +155 -31
- package/modules/localmodels/library_status.py +29 -4
- package/modules/localmodels/npm_transport.py +62 -54
- package/modules/localmodels/probe.py +42 -9
- package/modules/localmodels/recommend.py +1 -1
- package/modules/localmodels/recommend_cli.py +2 -2
- package/modules/localmodels/remote_ops.py +14 -6
- package/modules/localmodels/remote_ops_download.py +1 -1
- package/modules/localmodels/remote_ops_verify.py +0 -33
- 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 +57 -23
- package/modules/localmodels/runtime_io.py +224 -243
- package/modules/localmodels/runtime_process.py +15 -7
- package/modules/localmodels/runtime_windows_acl.py +196 -0
- package/modules/localmodels/source_byok.py +122 -33
- package/modules/localmodels/source_byok_probe.py +57 -141
- package/modules/localmodels/source_cli.py +19 -18
- package/modules/localmodels/stack.py +13 -6
- package/modules/localmodels/stack_args.py +6 -8
- package/modules/localmodels/stack_binding.py +3 -3
- package/modules/localmodels/stack_client_settings.py +8 -1
- package/modules/localmodels/stack_compose.py +4 -8
- package/modules/localmodels/stack_events.py +2 -1
- package/modules/localmodels/stack_plan.py +1 -4
- package/modules/localmodels/stack_ports.py +0 -1
- package/modules/localmodels/stack_route.py +1 -5
- package/modules/localmodels/stack_run.py +15 -30
- package/modules/localmodels/stack_suite.py +23 -46
- package/modules/localmodels/stack_summary.py +0 -1
- package/modules/localmodels/stack_try.py +3 -92
- package/modules/localmodels/stack_up.py +27 -4
- package/modules/localmodels/stack_update.py +5 -5
- package/modules/localmodels/stack_view_apply.py +1 -1
- package/modules/localmodels/stack_view_sandbox.py +0 -2
- package/modules/localmodels/stack_view_text.py +0 -1
- package/modules/localmodels/stack_view_words.py +0 -1
- package/modules/localmodels/suite.py +4 -7
- package/modules/localmodels/tui_dialogs.py +0 -1
- package/modules/localmodels/vision.py +2 -1
- package/modules/localmodels/web/view/view.css +1 -4
- package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/RECORD +73 -76
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/bifrost_search.py +0 -66
- package/modules/localmodels/gateway_search.py +0 -223
- package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
- package/modules/localmodels/search_server.py +0 -474
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.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
|
|
|
@@ -18,7 +18,6 @@ from pathlib import Path
|
|
|
18
18
|
from typing import Any, Literal, TypedDict
|
|
19
19
|
|
|
20
20
|
from localmodels import bifrost_pi, gateway_requests, harness, harness_gateway, hosts
|
|
21
|
-
from localmodels.bifrost_search import SEARCH_CLIENT, SEARCH_TOOL, WEB_SEARCH, wired_search
|
|
22
21
|
from localmodels.bifrost_unit import unit
|
|
23
22
|
from localmodels.gateway_bifrost import (
|
|
24
23
|
ADMIN_USER,
|
|
@@ -37,10 +36,9 @@ from localmodels.gateway_bifrost import (
|
|
|
37
36
|
read_config,
|
|
38
37
|
require_target,
|
|
39
38
|
)
|
|
40
|
-
from localmodels.gateway_requests import AuxEndpoint
|
|
41
|
-
from localmodels.gateway_search import SEARCH, Check, search_url
|
|
39
|
+
from localmodels.gateway_requests import AuxEndpoint, Check
|
|
42
40
|
from localmodels.harness import HarnessPlan
|
|
43
|
-
from localmodels.remote_ops import
|
|
41
|
+
from localmodels.remote_ops import TOUCH_EXPECT, TOUCH_PROMPT
|
|
44
42
|
|
|
45
43
|
|
|
46
44
|
def _admin_get(addr: str, path: str, timeout: float = 20) -> dict[str, Any]:
|
|
@@ -210,93 +208,13 @@ def direct_targets(gw: harness.GatewayPlan, timeout: float) -> list[Check]:
|
|
|
210
208
|
return checks
|
|
211
209
|
|
|
212
210
|
|
|
213
|
-
def searched_calls(addr: str) -> int | None:
|
|
214
|
-
"""Runs of the injected search in Bifrost's MCP tool log (no arguments are kept); None when
|
|
215
|
-
the log cannot be read. A run counts whether or not its engines found anything: the log
|
|
216
|
-
records that the tool answered, so result pages are the direct check's to prove."""
|
|
217
|
-
query = {"tool_names": SEARCH_TOOL, "server_labels": SEARCH_CLIENT, "limit": "1"}
|
|
218
|
-
try:
|
|
219
|
-
found = _admin_get(addr, "/api/mcp-logs?" + urllib.parse.urlencode(query))
|
|
220
|
-
except (urllib.error.URLError, OSError, ValueError):
|
|
221
|
-
return None
|
|
222
|
-
page = found.get("pagination")
|
|
223
|
-
total = page.get("total_count") if isinstance(page, dict) else None
|
|
224
|
-
return total if isinstance(total, int) else None
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
def _search_through_gateway(addr: str, timeout: float) -> tuple[bool, str]:
|
|
228
|
-
"""One agent turn that must call a tool and declares none of its own: only the injected
|
|
229
|
-
``web_search`` is there to call, and Bifrost's MCP tool log has to gain the run."""
|
|
230
|
-
before = searched_calls(addr)
|
|
231
|
-
resp = gateway_requests.post(
|
|
232
|
-
f"http://{addr}/v1/chat/completions",
|
|
233
|
-
{
|
|
234
|
-
"model": AGENT_MODEL,
|
|
235
|
-
"messages": [
|
|
236
|
-
{
|
|
237
|
-
"role": "user",
|
|
238
|
-
"content": f"Search the web for {SEARCH_QUERY} and reply with one result URL.",
|
|
239
|
-
}
|
|
240
|
-
],
|
|
241
|
-
"tool_choice": "required",
|
|
242
|
-
"max_tokens": 1024,
|
|
243
|
-
"temperature": 0,
|
|
244
|
-
},
|
|
245
|
-
CALLER_KEY,
|
|
246
|
-
timeout,
|
|
247
|
-
)
|
|
248
|
-
answer = " ".join(gateway_requests.text(resp).split())
|
|
249
|
-
after = before
|
|
250
|
-
for _ in range(10): # the log is written just after the reply
|
|
251
|
-
after = searched_calls(addr)
|
|
252
|
-
if before is None or after is None or after > before:
|
|
253
|
-
break
|
|
254
|
-
time.sleep(1)
|
|
255
|
-
ran = before is not None and after is not None and after > before
|
|
256
|
-
return ran, f"Bifrost ran {WEB_SEARCH} {before} → {after} times; answer: {answer[:150]}"
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
SEARCH_ATTEMPTS = 3 # as the search verify: free engines throttle by exit IP (aws-l4, 2026-11-09)
|
|
260
|
-
SEARCH_RETRY_S = 5.0
|
|
261
|
-
# The check's detail when no engine answered any attempt: the code the result JSON reports as the
|
|
262
|
-
# cause (stack_run.SEARCH_UNAVAILABLE), so an unreachable search is not an unexplained failure.
|
|
263
|
-
UNANSWERED = "SEARCH_PROVIDER_UNAVAILABLE"
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
def _search_direct(url: str, timeout: float) -> tuple[bool, str]:
|
|
267
|
-
"""The search service itself: one query, result URLs back. Only "no engine answered" is
|
|
268
|
-
asked again, a few times and spaced out; when no attempt is answered the check fails with
|
|
269
|
-
UNANSWERED as its detail (home-m6, 2026-11-17: only Yahoo answers from that network, and
|
|
270
|
-
not every time)."""
|
|
271
|
-
query = urllib.parse.urlencode({"q": "Paris France capital", "format": "json"})
|
|
272
|
-
for attempt in range(1, SEARCH_ATTEMPTS + 1):
|
|
273
|
-
try:
|
|
274
|
-
with opener().open(f"{url.rstrip('/')}/search?{query}", timeout=timeout) as r:
|
|
275
|
-
value = json.loads(r.read(1 << 20) or b"{}")
|
|
276
|
-
break
|
|
277
|
-
except urllib.error.HTTPError as exc:
|
|
278
|
-
if exc.code != 502 or json.loads(exc.read(1024) or b"{}") != {"error": UNANSWERED}:
|
|
279
|
-
raise
|
|
280
|
-
if attempt == SEARCH_ATTEMPTS:
|
|
281
|
-
return False, UNANSWERED
|
|
282
|
-
time.sleep(SEARCH_RETRY_S)
|
|
283
|
-
results = value.get("results") if isinstance(value, dict) else None
|
|
284
|
-
urls = [
|
|
285
|
-
str(x.get("url"))
|
|
286
|
-
for x in (results if isinstance(results, list) else [])
|
|
287
|
-
if isinstance(x, dict) and str(x.get("url", "")).startswith("http")
|
|
288
|
-
]
|
|
289
|
-
return bool(urls), f"{len(urls)} results"
|
|
290
|
-
|
|
291
|
-
|
|
292
211
|
def accept(
|
|
293
212
|
plan: HarnessPlan, decision_key: str | None, aux: list[AuxEndpoint], timeout: float = 600
|
|
294
213
|
) -> list[Check]:
|
|
295
214
|
"""Each claim needs a request: Bifrost lists the providers and the agent model's names, one
|
|
296
215
|
turn of ``localmodels-agent`` answers through the routing rule (and Bifrost's log shows the
|
|
297
216
|
decision model classified it), one embedding, rerank or transcription request per wired
|
|
298
|
-
auxiliary (the log gains its row),
|
|
299
|
-
tool runs the injected web search, pi answers with its default model, and so do the
|
|
217
|
+
auxiliary (the log gains its row), pi answers with its default model, and so do the
|
|
300
218
|
clients."""
|
|
301
219
|
from localmodels import bifrost_clients
|
|
302
220
|
|
|
@@ -386,17 +304,6 @@ def accept(
|
|
|
386
304
|
)
|
|
387
305
|
checks += tier_routes(gw, timeout)
|
|
388
306
|
for ep in aux:
|
|
389
|
-
if ep["contract"] == SEARCH:
|
|
390
|
-
try:
|
|
391
|
-
check("search service", *_search_direct(search_url(ep), timeout))
|
|
392
|
-
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
393
|
-
check("search service", False, f"{type(exc).__name__}: {exc}")
|
|
394
|
-
name = f"gateway {WEB_SEARCH} via {SEARCH_CLIENT}"
|
|
395
|
-
try:
|
|
396
|
-
check(name, *_search_through_gateway(addr, timeout))
|
|
397
|
-
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
398
|
-
check(name, False, f"{type(exc).__name__}: {exc}")
|
|
399
|
-
continue
|
|
400
307
|
pid = AUX_PROVIDERS[ep["contract"]]
|
|
401
308
|
name = f"gateway {ep['contract']} {pid}/{ep['model']}"
|
|
402
309
|
before = logged_calls(addr, pid)
|
|
@@ -505,11 +412,8 @@ def inspect(doc: hosts.Owned, plan: Any, reapply: str) -> list[Finding]:
|
|
|
505
412
|
config = read_config(Path(record["app_dir"]))
|
|
506
413
|
providers = config.get("providers") if isinstance(config.get("providers"), dict) else {}
|
|
507
414
|
expected: dict[str, tuple[str, str]] = {}
|
|
508
|
-
search: str | None = None
|
|
509
|
-
llm_provider = ""
|
|
510
415
|
if plan is not None and harness.gateway_kind(plan["harness"]["gateway"]) == "bifrost":
|
|
511
416
|
g = plan["harness"]["gateway"]
|
|
512
|
-
llm_provider = g["llm_provider"]
|
|
513
417
|
expected[g["llm_provider"]] = (g["llm"]["url"], g["llm"]["model"])
|
|
514
418
|
if fast := g.get("llm_fast"):
|
|
515
419
|
expected[FAST_PROVIDER] = (fast["url"], fast["model"])
|
|
@@ -517,8 +421,6 @@ def inspect(doc: hosts.Owned, plan: Any, reapply: str) -> list[Finding]:
|
|
|
517
421
|
expected[g["decision_provider"]] = (g["decision"]["url"], g["decision"]["model"])
|
|
518
422
|
for part in plan.get("aux", []):
|
|
519
423
|
contract = part["endpoint"].get("contract", "")
|
|
520
|
-
if contract == SEARCH:
|
|
521
|
-
search = search_url({"url": part["endpoint"]["base_url"]})
|
|
522
424
|
pid = AUX_PROVIDERS.get(contract)
|
|
523
425
|
if pid:
|
|
524
426
|
expected[pid] = (part["endpoint"]["base_url"], part["endpoint"]["model"])
|
|
@@ -546,8 +448,6 @@ def inspect(doc: hosts.Owned, plan: Any, reapply: str) -> list[Finding]:
|
|
|
546
448
|
)
|
|
547
449
|
else:
|
|
548
450
|
found.append(finding(f"gateway.provider.{pid}", "pass", f"{pid} → {base} ({model})"))
|
|
549
|
-
if search:
|
|
550
|
-
found.append(_search_finding(config, providers, llm_provider, search, reapply))
|
|
551
451
|
rules = config.get("governance", {}).get("routing_rules") if config else None
|
|
552
452
|
has_route = isinstance(rules, list) and any(r.get("id") == AGENT_RULE for r in rules)
|
|
553
453
|
found.append(
|
|
@@ -580,30 +480,6 @@ def inspect(doc: hosts.Owned, plan: Any, reapply: str) -> list[Finding]:
|
|
|
580
480
|
return found
|
|
581
481
|
|
|
582
482
|
|
|
583
|
-
def _search_finding(
|
|
584
|
-
config: dict[str, Any], providers: Any, llm_provider: str, search: str, reapply: str
|
|
585
|
-
) -> Finding:
|
|
586
|
-
"""The config still runs the plan's search service as the LLM's injected web search."""
|
|
587
|
-
wired = wired_search(config)
|
|
588
|
-
entry = providers.get(llm_provider) if isinstance(providers, dict) else None
|
|
589
|
-
injected = (entry or {}).get("injected_tools")
|
|
590
|
-
names = (
|
|
591
|
-
{t.get("name") for t in injected if isinstance(t, dict)}
|
|
592
|
-
if isinstance(injected, list)
|
|
593
|
-
else set()
|
|
594
|
-
)
|
|
595
|
-
if wired and wired[0]["url"] == search and WEB_SEARCH in names:
|
|
596
|
-
return finding(
|
|
597
|
-
"gateway.search", "pass", f"{WEB_SEARCH} → {search} (injected into {llm_provider})"
|
|
598
|
-
)
|
|
599
|
-
return finding(
|
|
600
|
-
"gateway.search",
|
|
601
|
-
"fail",
|
|
602
|
-
f"the config does not inject {WEB_SEARCH} from {search} into {llm_provider}",
|
|
603
|
-
f"rewire: {reapply}",
|
|
604
|
-
)
|
|
605
|
-
|
|
606
|
-
|
|
607
483
|
def usage(doc: hosts.Owned) -> Finding | None:
|
|
608
484
|
"""Request counts of the last hour from Bifrost's log store (doctor)."""
|
|
609
485
|
record = doc["gateway"].get("bifrost")
|
|
@@ -30,7 +30,7 @@ from localmodels import (
|
|
|
30
30
|
runtime_cli,
|
|
31
31
|
stack_clients,
|
|
32
32
|
)
|
|
33
|
-
from localmodels.
|
|
33
|
+
from localmodels.gateway_requests import Check
|
|
34
34
|
|
|
35
35
|
BEGIN = "# localmodels: Bifrost provider; stack remove deletes this block"
|
|
36
36
|
END = "# localmodels: end of Bifrost provider"
|
|
@@ -47,8 +47,8 @@ def render(
|
|
|
47
47
|
*,
|
|
48
48
|
fast_key: str | None = None,
|
|
49
49
|
) -> dict[str, Any]:
|
|
50
|
-
"""The config.json for one approved plan
|
|
51
|
-
|
|
50
|
+
"""The config.json for one approved plan. ``keep`` carries providers of an earlier config
|
|
51
|
+
this call does not manage (a re-sync keeps the STT provider)."""
|
|
52
52
|
llm = gw["llm"]
|
|
53
53
|
providers: dict[str, Any] = dict(keep or {})
|
|
54
54
|
providers[gw["llm_provider"]] = bifrost_provider.render(
|