@simplexai/localmodels-linux-arm64 0.1.0-dev.61 → 0.1.0-dev.63
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 +66 -63
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/bifrost_checks.py +19 -13
- package/modules/localmodels/bifrost_clients.py +38 -36
- package/modules/localmodels/bifrost_config.py +19 -6
- package/modules/localmodels/bifrost_log.py +3 -3
- package/modules/localmodels/bifrost_models.py +9 -8
- package/modules/localmodels/bifrost_pi.py +27 -72
- package/modules/localmodels/catalog.json +51 -58
- package/modules/localmodels/custom_hub.py +10 -1
- package/modules/localmodels/custom_hub_http.py +41 -107
- package/modules/localmodels/debug_mode.py +3 -3
- package/modules/localmodels/gateway.py +56 -55
- package/modules/localmodels/gateway_bifrost.py +70 -83
- package/modules/localmodels/gateway_clients.py +33 -116
- package/modules/localmodels/gateway_home.py +5 -5
- package/modules/localmodels/gateway_keys.py +8 -6
- package/modules/localmodels/gateway_probe.py +4 -4
- package/modules/localmodels/gateway_server.py +4 -4
- package/modules/localmodels/gateway_speed.py +2 -2
- package/modules/localmodels/harness.py +185 -401
- package/modules/localmodels/harness_core.py +409 -0
- package/modules/localmodels/harness_gateway.py +75 -73
- package/modules/localmodels/harness_probe.py +19 -216
- package/modules/localmodels/library_custom.py +51 -16
- package/modules/localmodels/library_elastic.py +1 -1
- package/modules/localmodels/library_gateway.py +59 -176
- package/modules/localmodels/library_jobs.py +4 -0
- package/modules/localmodels/library_model.py +23 -0
- package/modules/localmodels/library_pricing.py +2 -2
- package/modules/localmodels/library_serve.py +5 -3
- package/modules/localmodels/library_smoke.py +33 -21
- package/modules/localmodels/library_status.py +330 -2
- package/modules/localmodels/llm_rank.py +14 -5
- package/modules/localmodels/magpie_setup.py +5 -4
- package/modules/localmodels/magpie_windows.py +1 -1
- package/modules/localmodels/memcalc_load.py +9 -4
- package/modules/localmodels/pi_profile.py +384 -0
- package/modules/localmodels/process_identity.py +3 -3
- package/modules/localmodels/remote_ops_common.py +31 -90
- package/modules/localmodels/remote_ops_download.py +2 -0
- package/modules/localmodels/remote_ops_mirrors.py +1 -1
- package/modules/localmodels/remote_ops_ranges.py +4 -1
- package/modules/localmodels/remote_ops_redirect.py +393 -0
- package/modules/localmodels/runtime_cli.py +32 -46
- package/modules/localmodels/runtime_pi.py +1 -1
- package/modules/localmodels/source_byok.py +9 -16
- package/modules/localmodels/source_cli.py +136 -23
- package/modules/localmodels/speech_jobs.py +4 -0
- package/modules/localmodels/stack_binding.py +9 -7
- package/modules/localmodels/stack_clients.py +137 -21
- package/modules/localmodels/stack_doctor.py +6 -3
- package/modules/localmodels/stack_hardware.py +18 -0
- package/modules/localmodels/stack_lifecycle.py +3 -2
- package/modules/localmodels/stack_remove.py +2 -1
- package/modules/localmodels/stack_verify.py +2 -2
- package/modules/localmodels/stack_view_events.py +2 -2
- package/modules/localmodels/transport.py +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/RECORD +63 -60
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -7,21 +7,20 @@ sizes well below the repository line cap. Strictly stdlib Python (no third-party
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
9
|
import hashlib
|
|
10
|
-
import ipaddress
|
|
11
10
|
import json
|
|
12
11
|
import os
|
|
13
12
|
import re
|
|
14
|
-
import socket
|
|
15
|
-
import urllib.error
|
|
16
13
|
import urllib.parse
|
|
17
14
|
import urllib.request
|
|
18
15
|
from collections.abc import Mapping, Sequence
|
|
19
|
-
from
|
|
20
|
-
from typing import IO, NamedTuple, cast
|
|
16
|
+
from typing import NamedTuple, cast
|
|
21
17
|
|
|
22
|
-
from localmodels import region
|
|
18
|
+
from localmodels import region, remote_ops_redirect
|
|
23
19
|
from localmodels.library_model import CustomHub, LibraryError
|
|
24
20
|
|
|
21
|
+
UnsafeRedirectError = remote_ops_redirect.UnsafeRedirectError
|
|
22
|
+
is_hf_mirror_host = remote_ops_redirect.is_hf_mirror_host
|
|
23
|
+
|
|
25
24
|
HF_HOSTS = frozenset({"huggingface.co", "www.huggingface.co", "hf-mirror.com", "www.hf-mirror.com"})
|
|
26
25
|
HF_OFFICIAL_HOSTS = frozenset({"huggingface.co", "www.huggingface.co"})
|
|
27
26
|
HF_MIRROR_HOSTS = frozenset({"hf-mirror.com", "www.hf-mirror.com"})
|
|
@@ -37,10 +36,10 @@ MAX_JSON_RESPONSE_BYTES = 16 * 1024 * 1024
|
|
|
37
36
|
_BEARER_SECRET_RE = re.compile(r"(?i)\bBearer\s+[^\s,;\"']+")
|
|
38
37
|
_HF_TOKEN_RE = re.compile(r"\bhf_[A-Za-z0-9]+\b")
|
|
39
38
|
_MS_TOKEN_RE = re.compile(r"\bms[-_][A-Za-z0-9_-]+\b")
|
|
40
|
-
_BLOCKED_HOST_SUFFIXES = (".localhost", ".local", ".internal", ".home.arpa")
|
|
41
39
|
|
|
42
40
|
# Internal unit-test hook ONLY; strictly False in production.
|
|
43
41
|
_ALLOW_INSECURE_LOOPBACK_FOR_TESTS = False
|
|
42
|
+
is_hf_mirror_host = remote_ops_redirect.is_hf_mirror_host
|
|
44
43
|
|
|
45
44
|
|
|
46
45
|
def redact_secrets(text: str, *, extra_token: str | None = None) -> str:
|
|
@@ -105,8 +104,8 @@ def _configured_hf_endpoint_host(env: Mapping[str, str] | None = None) -> str |
|
|
|
105
104
|
parsed = urllib.parse.urlsplit(raw)
|
|
106
105
|
if parsed.scheme.lower() != "https" or not parsed.hostname:
|
|
107
106
|
return None
|
|
108
|
-
host = parsed.hostname
|
|
109
|
-
return None if host
|
|
107
|
+
host = remote_ops_redirect.normalize_host(parsed.hostname)
|
|
108
|
+
return None if not host or is_hf_mirror_host(host) else host
|
|
110
109
|
|
|
111
110
|
|
|
112
111
|
def token_for_endpoint(
|
|
@@ -125,19 +124,19 @@ def token_for_endpoint(
|
|
|
125
124
|
return None
|
|
126
125
|
parts = urllib.parse.urlsplit(url)
|
|
127
126
|
scheme = parts.scheme.lower()
|
|
128
|
-
host = (parts.hostname
|
|
127
|
+
host = remote_ops_redirect.normalize_host(parts.hostname)
|
|
129
128
|
if not host:
|
|
130
129
|
return None
|
|
131
130
|
if scheme != "https":
|
|
132
131
|
if (
|
|
133
132
|
_ALLOW_INSECURE_LOOPBACK_FOR_TESTS
|
|
134
133
|
and scheme == "http"
|
|
135
|
-
and host in ("127.0.0.1", "localhost")
|
|
134
|
+
and host in ("127.0.0.1", "localhost", "::1")
|
|
136
135
|
):
|
|
137
136
|
return clean
|
|
138
137
|
return None
|
|
139
138
|
if hub == "huggingface":
|
|
140
|
-
if host
|
|
139
|
+
if is_hf_mirror_host(host):
|
|
141
140
|
return None
|
|
142
141
|
if host in HF_OFFICIAL_HOSTS:
|
|
143
142
|
return clean
|
|
@@ -146,103 +145,28 @@ def token_for_endpoint(
|
|
|
146
145
|
return clean if host in MS_HOSTS else None
|
|
147
146
|
|
|
148
147
|
|
|
149
|
-
def
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
def _origin(url: str) -> tuple[str, str, int]:
|
|
157
|
-
parts = urllib.parse.urlsplit(url)
|
|
158
|
-
return (
|
|
159
|
-
parts.scheme.lower(),
|
|
160
|
-
(parts.hostname or "").lower().rstrip("."),
|
|
161
|
-
_effective_port(parts),
|
|
162
|
-
)
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
def _is_disallowed_ip(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
|
166
|
-
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
|
|
167
|
-
addr = addr.ipv4_mapped
|
|
168
|
-
return (
|
|
169
|
-
addr.is_loopback
|
|
170
|
-
or addr.is_private
|
|
171
|
-
or addr.is_link_local
|
|
172
|
-
or addr.is_multicast
|
|
173
|
-
or addr.is_unspecified
|
|
174
|
-
or addr.is_reserved
|
|
175
|
-
or not addr.is_global
|
|
176
|
-
)
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
def validate_redirect_target(url: str, *, allow_insecure_loopback: bool | None = None) -> None:
|
|
180
|
-
"""Enforce HTTPS and block loopback/private/link-local SSRF targets on redirects."""
|
|
148
|
+
def validate_redirect_target(
|
|
149
|
+
url: str,
|
|
150
|
+
*,
|
|
151
|
+
allow_insecure_loopback: bool | None = None,
|
|
152
|
+
source_url: str | None = None,
|
|
153
|
+
) -> None:
|
|
154
|
+
"""Enforce HTTPS and apply unified proxy/Fake-IP-aware anti-SSRF validation on redirects."""
|
|
181
155
|
allow_test = (
|
|
182
156
|
_ALLOW_INSECURE_LOOPBACK_FOR_TESTS
|
|
183
157
|
if allow_insecure_loopback is None
|
|
184
158
|
else allow_insecure_loopback
|
|
185
159
|
)
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
raise urllib.error.URLError(f"blocked redirect to local hostname {host!r}")
|
|
197
|
-
try:
|
|
198
|
-
literal = ipaddress.ip_address(host.split("%", 1)[0])
|
|
199
|
-
except ValueError:
|
|
200
|
-
literal = None
|
|
201
|
-
if literal is not None:
|
|
202
|
-
if _is_disallowed_ip(literal):
|
|
203
|
-
raise urllib.error.URLError(f"blocked redirect to non-public IP {host!r}")
|
|
204
|
-
return
|
|
205
|
-
port = _effective_port(parts) or 443
|
|
206
|
-
try:
|
|
207
|
-
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
208
|
-
except OSError as exc:
|
|
209
|
-
raise urllib.error.URLError(
|
|
210
|
-
f"blocked redirect: DNS resolution failed for {host!r}: {exc}"
|
|
211
|
-
) from None
|
|
212
|
-
if not infos:
|
|
213
|
-
raise urllib.error.URLError(f"blocked redirect: no addresses resolved for {host!r}")
|
|
214
|
-
for info in infos:
|
|
215
|
-
raw_ip = str(info[4][0]).split("%", 1)[0]
|
|
216
|
-
try:
|
|
217
|
-
resolved_ip = ipaddress.ip_address(raw_ip)
|
|
218
|
-
except ValueError:
|
|
219
|
-
raise urllib.error.URLError(f"blocked redirect: unparseable IP for {host!r}") from None
|
|
220
|
-
if _is_disallowed_ip(resolved_ip):
|
|
221
|
-
raise urllib.error.URLError(f"blocked redirect to non-public IP for {host!r}")
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
class SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
225
|
-
"""Enforce HTTPS + anti-SSRF on redirects and strip ``Authorization`` on any origin change."""
|
|
226
|
-
|
|
227
|
-
def redirect_request(
|
|
228
|
-
self,
|
|
229
|
-
req: urllib.request.Request,
|
|
230
|
-
fp: IO[bytes],
|
|
231
|
-
code: int,
|
|
232
|
-
msg: str,
|
|
233
|
-
headers: HTTPMessage,
|
|
234
|
-
newurl: str,
|
|
235
|
-
) -> urllib.request.Request | None:
|
|
236
|
-
resolved = urllib.parse.urljoin(req.full_url, newurl)
|
|
237
|
-
validate_redirect_target(resolved)
|
|
238
|
-
new_req = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
239
|
-
if new_req is None:
|
|
240
|
-
return None
|
|
241
|
-
if _origin(req.full_url) != _origin(resolved):
|
|
242
|
-
for mapping in (new_req.headers, new_req.unredirected_hdrs):
|
|
243
|
-
for key in [k for k in mapping if k.lower() == "authorization"]:
|
|
244
|
-
del mapping[key]
|
|
245
|
-
return new_req
|
|
160
|
+
remote_ops_redirect.validate_redirect_url(
|
|
161
|
+
url, source_url=source_url, allow_insecure_loopback=allow_test
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class SafeRedirectHandler(remote_ops_redirect.SafeRedirectHandler):
|
|
166
|
+
"""Enforce HTTPS + anti-SSRF on redirects and strip sensitive headers on origin change."""
|
|
167
|
+
|
|
168
|
+
def allow_loopback(self) -> bool:
|
|
169
|
+
return super().allow_loopback() or _ALLOW_INSECURE_LOOPBACK_FOR_TESTS
|
|
246
170
|
|
|
247
171
|
|
|
248
172
|
def build_opener() -> urllib.request.OpenerDirector:
|
|
@@ -406,8 +330,8 @@ def _parse_hf_url(url: urllib.parse.SplitResult) -> ParsedRepoSpec:
|
|
|
406
330
|
repo_id = _validate_owner_repo(parts[0], parts[1])
|
|
407
331
|
rev = parts[3] if len(parts) >= 4 and parts[2] in ("blob", "resolve", "tree") else None
|
|
408
332
|
file_name = "/".join(parts[4:]) if len(parts) > 4 and parts[2] in ("blob", "resolve") else None
|
|
409
|
-
host = (url.hostname
|
|
410
|
-
explicit = f"https://{host}" if host
|
|
333
|
+
host = remote_ops_redirect.normalize_host(url.hostname)
|
|
334
|
+
explicit = f"https://{host}" if is_hf_mirror_host(host) else None
|
|
411
335
|
return ParsedRepoSpec(
|
|
412
336
|
"huggingface", repo_id, _validate_revision(rev), None, file_name, explicit
|
|
413
337
|
)
|
|
@@ -492,7 +416,17 @@ def parse_repo_spec(
|
|
|
492
416
|
)
|
|
493
417
|
if lower_raw.startswith("https://"):
|
|
494
418
|
url = urllib.parse.urlsplit(raw)
|
|
495
|
-
|
|
419
|
+
if url.username is not None or url.password is not None:
|
|
420
|
+
raise LibraryError("INVALID_REPO_SPEC", "repository URL must not contain credentials")
|
|
421
|
+
try:
|
|
422
|
+
port = url.port
|
|
423
|
+
except ValueError:
|
|
424
|
+
raise LibraryError("INVALID_REPO_SPEC", "invalid port in repository URL") from None
|
|
425
|
+
if port is not None and port != 443:
|
|
426
|
+
raise LibraryError(
|
|
427
|
+
"INVALID_REPO_SPEC", f"non-standard port {port} is not allowed in repository URL"
|
|
428
|
+
)
|
|
429
|
+
host = remote_ops_redirect.normalize_host(url.hostname)
|
|
496
430
|
if host in HF_HOSTS:
|
|
497
431
|
parsed = _parse_hf_url(url)
|
|
498
432
|
elif host in MS_HOSTS:
|
|
@@ -588,12 +588,12 @@ def _install_direct_pi_gateway() -> None:
|
|
|
588
588
|
served = str(plan["endpoint"]["model"])
|
|
589
589
|
pi_entry = bifrost_models.pi_provider(facts_, served, base_url)["models"][0]
|
|
590
590
|
with library_gateway.gateway_locked():
|
|
591
|
-
library_gateway.
|
|
591
|
+
library_gateway.pi_add(added["pi_provider"], pi_entry, base_url)
|
|
592
592
|
return {**added, "model": served, "pi_model": f"{added['pi_provider']}/{served}"}
|
|
593
593
|
|
|
594
594
|
def direct_unregister(registration: Registration) -> None:
|
|
595
595
|
with library_gateway.gateway_locked():
|
|
596
|
-
library_gateway.
|
|
596
|
+
library_gateway.pi_drop(registration["pi_provider"], registration["model"])
|
|
597
597
|
|
|
598
598
|
def register_with_fallback(
|
|
599
599
|
model: str,
|
|
@@ -706,7 +706,7 @@ def _install_simulate_mode(config: DebugConfig) -> None:
|
|
|
706
706
|
served = str(plan["endpoint"]["model"])
|
|
707
707
|
pi_entry = bifrost_models.pi_provider(facts_, served, base_url)["models"][0]
|
|
708
708
|
with library_gateway.gateway_locked():
|
|
709
|
-
library_gateway.
|
|
709
|
+
library_gateway.pi_add(added["pi_provider"], pi_entry, base_url)
|
|
710
710
|
return {**added, "model": served, "pi_model": f"{added['pi_provider']}/{served}"}
|
|
711
711
|
|
|
712
712
|
library_gateway.register = offline_only_register
|
|
@@ -19,15 +19,18 @@ from pathlib import Path
|
|
|
19
19
|
from typing import Literal, TypedDict
|
|
20
20
|
|
|
21
21
|
from localmodels import (
|
|
22
|
+
bifrost_clients,
|
|
22
23
|
gateway_accept,
|
|
23
24
|
gateway_admin,
|
|
25
|
+
gateway_bifrost,
|
|
24
26
|
gateway_clients,
|
|
25
27
|
gateway_home,
|
|
26
28
|
gateway_keys,
|
|
27
|
-
|
|
29
|
+
harness_core,
|
|
28
30
|
harness_gateway,
|
|
29
31
|
harness_probe,
|
|
30
32
|
hosts,
|
|
33
|
+
pi_profile,
|
|
31
34
|
process_identity,
|
|
32
35
|
runtime_io,
|
|
33
36
|
runtime_process,
|
|
@@ -37,7 +40,7 @@ from localmodels.gateway_requests import PI_ACCEPT_FLAGS as PI_ACCEPT_FLAGS
|
|
|
37
40
|
from localmodels.gateway_requests import AuxEndpoint as AuxEndpoint
|
|
38
41
|
from localmodels.gateway_requests import Check as Check
|
|
39
42
|
from localmodels.gateway_requests import post as _post
|
|
40
|
-
from localmodels.
|
|
43
|
+
from localmodels.harness_core import (
|
|
41
44
|
Endpoint,
|
|
42
45
|
GatewayPlan,
|
|
43
46
|
HarnessError,
|
|
@@ -70,34 +73,34 @@ WIRED = tuple(AUX_PROVIDERS)
|
|
|
70
73
|
FOUNDATION_PROVIDERS = {
|
|
71
74
|
AUX_PROVIDERS["embedding"],
|
|
72
75
|
AUX_PROVIDERS["rerank"],
|
|
73
|
-
|
|
76
|
+
harness_core.DECISION_PROVIDER,
|
|
74
77
|
}
|
|
75
78
|
|
|
76
79
|
|
|
77
|
-
def
|
|
80
|
+
def run_magpie(plan: ToolPlan, *args: str, timeout: float = 60) -> subprocess.CompletedProcess[str]:
|
|
78
81
|
harness_gateway.require_target(plan)
|
|
79
82
|
return run_tool(
|
|
80
|
-
[tool_path(plan, "magpie"), *args],
|
|
83
|
+
[tool_path(plan, "magpie"), *args],
|
|
84
|
+
timeout=timeout,
|
|
85
|
+
env=harness_core.gateway_environment(plan),
|
|
81
86
|
)
|
|
82
87
|
|
|
83
88
|
|
|
84
|
-
def
|
|
89
|
+
def require_magpie(out: subprocess.CompletedProcess[str], what: str) -> None:
|
|
85
90
|
if out.returncode != 0:
|
|
86
91
|
raise HarnessError(f"magpie {what} failed (exit {out.returncode})")
|
|
87
92
|
|
|
88
93
|
|
|
89
94
|
def _bifrost(plan: ToolPlan) -> bool:
|
|
90
|
-
return
|
|
95
|
+
return harness_core.gateway_kind(plan.get("gateway")) == "bifrost" # type: ignore[arg-type]
|
|
91
96
|
|
|
92
97
|
|
|
93
98
|
def ensure_gateway(plan: ToolPlan) -> str:
|
|
94
99
|
"""Reuse a gateway that answers; otherwise start the one the plan names."""
|
|
95
100
|
if _bifrost(plan):
|
|
96
|
-
from localmodels import gateway_bifrost
|
|
97
|
-
|
|
98
101
|
return gateway_bifrost.ensure(plan)
|
|
99
102
|
action = next(t for t in plan["tools"] if t["tool"] == "gateway")
|
|
100
|
-
if
|
|
103
|
+
if run_magpie(plan, "healthcheck", timeout=20).returncode == 0:
|
|
101
104
|
return "reused"
|
|
102
105
|
if harness_gateway.pending_owned(plan):
|
|
103
106
|
_await_gateway(plan)
|
|
@@ -111,8 +114,6 @@ def ensure_gateway(plan: ToolPlan) -> str:
|
|
|
111
114
|
|
|
112
115
|
def revive(plan: HarnessPlan, started: str | None) -> str:
|
|
113
116
|
if _bifrost(plan):
|
|
114
|
-
from localmodels import gateway_bifrost
|
|
115
|
-
|
|
116
117
|
return gateway_bifrost.revive(plan)
|
|
117
118
|
return _revive_magpie(plan, started)
|
|
118
119
|
|
|
@@ -120,7 +121,7 @@ def revive(plan: HarnessPlan, started: str | None) -> str:
|
|
|
120
121
|
def _revive_magpie(plan: HarnessPlan, started: str | None) -> str:
|
|
121
122
|
"""``stack up``: a gateway that answers stays; one this tool started (the owned manifest's
|
|
122
123
|
``started``) is started the same way again; someone else's gateway is theirs to start."""
|
|
123
|
-
if
|
|
124
|
+
if run_magpie(plan, "healthcheck", timeout=20).returncode == 0:
|
|
124
125
|
return "reused"
|
|
125
126
|
if started not in ("daemon", "serve"):
|
|
126
127
|
raise HarnessError(
|
|
@@ -153,7 +154,7 @@ def _serve(plan: ToolPlan) -> None:
|
|
|
153
154
|
harness_gateway.require_inactive(tools_dir)
|
|
154
155
|
except HarnessError as exc:
|
|
155
156
|
raise HarnessError(f"magpie serve not started: {exc}") from exc
|
|
156
|
-
env =
|
|
157
|
+
env = harness_core.gateway_environment(plan)
|
|
157
158
|
if "environment" not in plan:
|
|
158
159
|
runtime_io.private_directory(Path(env["HOME"]))
|
|
159
160
|
config = Path(env["XDG_CONFIG_HOME"]) / "magpie"
|
|
@@ -197,21 +198,25 @@ def _serve(plan: ToolPlan) -> None:
|
|
|
197
198
|
def _await_gateway(plan: ToolPlan) -> None:
|
|
198
199
|
addr = next(t["path"] for t in plan["tools"] if t["tool"] == "gateway")
|
|
199
200
|
deadline = time.monotonic() + 60
|
|
200
|
-
while
|
|
201
|
+
while run_magpie(plan, "healthcheck", timeout=20).returncode != 0:
|
|
201
202
|
if time.monotonic() > deadline:
|
|
202
203
|
raise HarnessError(f"Magpie gateway {addr} does not answer")
|
|
203
204
|
time.sleep(2)
|
|
204
205
|
|
|
205
206
|
|
|
206
|
-
def
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
207
|
+
def configure_provider(
|
|
208
|
+
plan: ToolPlan, pid: str, name: str, field: str, ep: Endpoint, key: str
|
|
209
|
+
) -> None:
|
|
210
|
+
if run_magpie(plan, "provider", pid).returncode == 0:
|
|
211
|
+
require_magpie(
|
|
212
|
+
run_magpie(
|
|
213
|
+
plan, "provider", "set", pid, f"{field}={ep['url']}", f"models={ep['model']}"
|
|
214
|
+
),
|
|
210
215
|
f"provider set {pid}",
|
|
211
216
|
)
|
|
212
217
|
else:
|
|
213
|
-
|
|
214
|
-
|
|
218
|
+
require_magpie(
|
|
219
|
+
run_magpie(
|
|
215
220
|
plan,
|
|
216
221
|
"provider",
|
|
217
222
|
"add",
|
|
@@ -242,7 +247,7 @@ def _provider_key(plan: ToolPlan, pid: str, key: str) -> None:
|
|
|
242
247
|
"""Use Magpie's authenticated native UI API; its CLI only accepts keys in argv."""
|
|
243
248
|
admin_key = secrets.token_urlsafe(32)
|
|
244
249
|
env = {
|
|
245
|
-
**
|
|
250
|
+
**harness_gateway.checked_gateway_environment(plan),
|
|
246
251
|
"MAGPIE_WEB_KEY": admin_key,
|
|
247
252
|
"MAGPIE_NO_ACCOUNTS": "1",
|
|
248
253
|
}
|
|
@@ -333,7 +338,7 @@ def wire_foundations(
|
|
|
333
338
|
decision_key: str | None,
|
|
334
339
|
aux: list[AuxEndpoint],
|
|
335
340
|
*,
|
|
336
|
-
decision_provider: str =
|
|
341
|
+
decision_provider: str = harness_core.DECISION_PROVIDER,
|
|
337
342
|
) -> list[str]:
|
|
338
343
|
"""Register foundation providers in Magpie's existing catalog without selecting clients."""
|
|
339
344
|
done: list[str] = []
|
|
@@ -344,14 +349,16 @@ def wire_foundations(
|
|
|
344
349
|
managed = {*FOUNDATION_PROVIDERS, decision_provider}
|
|
345
350
|
for pid in hosts.load_owned(tools_dir)["gateway"]["providers"]:
|
|
346
351
|
if pid in managed and pid not in desired:
|
|
347
|
-
if
|
|
348
|
-
|
|
352
|
+
if run_magpie(plan, "provider", pid).returncode == 0:
|
|
353
|
+
require_magpie(run_magpie(plan, "provider", "rm", pid), f"provider rm {pid}")
|
|
349
354
|
hosts.own_listed(tools_dir, "providers", pid, False)
|
|
350
355
|
done.append(f"removed provider {pid}")
|
|
351
356
|
if decision is not None and decision_key is not None:
|
|
352
357
|
pid = decision_provider
|
|
353
358
|
hosts.own_listed(tools_dir, "providers", pid, True)
|
|
354
|
-
|
|
359
|
+
configure_provider(
|
|
360
|
+
plan, pid, "Local Jev-like (localmodels)", "decide", decision, decision_key
|
|
361
|
+
)
|
|
355
362
|
done.append(f"provider {pid}")
|
|
356
363
|
for ep in aux:
|
|
357
364
|
if ep["contract"] not in AUX_PROVIDERS:
|
|
@@ -359,7 +366,9 @@ def wire_foundations(
|
|
|
359
366
|
pid = AUX_PROVIDERS[ep["contract"]]
|
|
360
367
|
hosts.own_listed(tools_dir, "providers", pid, True)
|
|
361
368
|
name = f"Local {ep['contract']} (localmodels)"
|
|
362
|
-
|
|
369
|
+
configure_provider(
|
|
370
|
+
plan, pid, name, "url", {"url": ep["url"], "model": ep["model"]}, ep["key"]
|
|
371
|
+
)
|
|
363
372
|
done.append(f"provider {pid}")
|
|
364
373
|
|
|
365
374
|
return done
|
|
@@ -370,8 +379,6 @@ def leave_magpie(tools_dir: str) -> list[str]:
|
|
|
370
379
|
plan being wired is already the latest run record, so both the unwiring and the shutdown are
|
|
371
380
|
checked against the earlier approved plan that ran Magpie (``magpie_target``); without one
|
|
372
381
|
they fail closed and leave Magpie and its records as they are."""
|
|
373
|
-
from localmodels import bifrost_clients
|
|
374
|
-
|
|
375
382
|
doc = hosts.load_owned(tools_dir)
|
|
376
383
|
started = doc["gateway"]["started"]
|
|
377
384
|
if not bifrost_clients.magpie_wired(doc) and not started:
|
|
@@ -397,8 +404,6 @@ def leave_magpie(tools_dir: str) -> list[str]:
|
|
|
397
404
|
|
|
398
405
|
def leave(tools_dir: str) -> list[str]:
|
|
399
406
|
"""Before a Magpie wiring: stop this tool's Bifrost and give pi and the clients back."""
|
|
400
|
-
from localmodels import gateway_bifrost
|
|
401
|
-
|
|
402
407
|
if not hosts.load_owned(tools_dir)["gateway"].get("bifrost"):
|
|
403
408
|
return []
|
|
404
409
|
results = gateway_bifrost.unwire(tools_dir)
|
|
@@ -422,8 +427,6 @@ def wire(
|
|
|
422
427
|
point pi at it. Idempotent: providers are updated by id, and adding a group by its name
|
|
423
428
|
replaces it with its rules. A re-sync (``select_pi=False``) leaves the gateway keys alone, so a
|
|
424
429
|
key the user removed stays removed. A Bifrost plan goes to ``gateway_bifrost.wire``."""
|
|
425
|
-
from localmodels import gateway_bifrost
|
|
426
|
-
|
|
427
430
|
tools_dir = plan["tools_dir"]
|
|
428
431
|
if _bifrost(plan):
|
|
429
432
|
done = leave_magpie(tools_dir) if select_pi else []
|
|
@@ -434,16 +437,18 @@ def wire(
|
|
|
434
437
|
|
|
435
438
|
gw = plan["gateway"]
|
|
436
439
|
hosts.own_listed(tools_dir, "providers", gw["llm_provider"], True)
|
|
437
|
-
|
|
440
|
+
configure_provider(
|
|
441
|
+
plan, gw["llm_provider"], "Local LLM (localmodels)", "url", gw["llm"], llm_key
|
|
442
|
+
)
|
|
438
443
|
llm_model = f"{gw['llm_provider']}/{gw['llm']['model']}"
|
|
439
444
|
hosts.own_listed(tools_dir, "efforts", llm_model, True)
|
|
440
445
|
everyday, hard = effort_levels(gw)
|
|
441
446
|
levels = ",".join(gw.get("efforts") or EFFORTS)
|
|
442
|
-
|
|
447
|
+
require_magpie(run_magpie(plan, "model", "efforts", llm_model, levels), "model efforts")
|
|
443
448
|
done.append(f"provider {gw['llm_provider']}")
|
|
444
449
|
hosts.own_gateway(tools_dir, "group", gw["group"])
|
|
445
|
-
|
|
446
|
-
|
|
450
|
+
require_magpie(
|
|
451
|
+
run_magpie(
|
|
447
452
|
plan, "group", "add", gw["group"], f"models={llm_model}:{everyday},{llm_model}:{hard}"
|
|
448
453
|
),
|
|
449
454
|
"group add",
|
|
@@ -454,8 +459,8 @@ def wire(
|
|
|
454
459
|
)
|
|
455
460
|
if gw["decision"] is not None and decision_key is not None:
|
|
456
461
|
classifier = f"{gw['decision_provider']}/{gw['decision']['model']}"
|
|
457
|
-
|
|
458
|
-
|
|
462
|
+
require_magpie(
|
|
463
|
+
run_magpie(
|
|
459
464
|
plan,
|
|
460
465
|
"group",
|
|
461
466
|
"rule",
|
|
@@ -489,17 +494,17 @@ def point_pi(plan: ToolPlan, before: str | None, target: str) -> str:
|
|
|
489
494
|
hosts.update_owned(replace_pi, plan["tools_dir"])
|
|
490
495
|
# Newer Magpie (0.1.3733, 2026-11-11) refuses a PI_CODING_AGENT_DIR that does not exist yet;
|
|
491
496
|
# the stack's own one lives in its private gateway home and is created private here.
|
|
492
|
-
agent =
|
|
493
|
-
home =
|
|
497
|
+
agent = harness_core.gateway_environment(plan).get("PI_CODING_AGENT_DIR")
|
|
498
|
+
home = pi_profile.gateway_home(plan["tools_dir"])
|
|
494
499
|
if agent and Path(agent).is_relative_to(home):
|
|
495
500
|
gateway_home.reclaim(plan["tools_dir"]) # an elevated run's folder (GitLab #15)
|
|
496
501
|
runtime_io.private_directory(Path(agent))
|
|
497
|
-
|
|
502
|
+
require_magpie(run_magpie(plan, "pi", target), "pi")
|
|
498
503
|
return f"pi → {model}"
|
|
499
504
|
|
|
500
505
|
|
|
501
506
|
def _pi_model(plan: ToolPlan) -> str | None:
|
|
502
|
-
return
|
|
507
|
+
return harness_probe.shown_pi_model(run_magpie(plan, "pi", timeout=20).stdout)
|
|
503
508
|
|
|
504
509
|
|
|
505
510
|
def magpie_binary(doc: hosts.Owned) -> str | None:
|
|
@@ -508,8 +513,8 @@ def magpie_binary(doc: hosts.Owned) -> str | None:
|
|
|
508
513
|
ours = next((t["path"] for t in doc["tools"] if Path(t["path"]).name in names), None)
|
|
509
514
|
if ours and os.access(ours, os.X_OK):
|
|
510
515
|
return ours
|
|
511
|
-
search = os.pathsep.join([os.environ.get("PATH", ""), os.path.expanduser(
|
|
512
|
-
# As
|
|
516
|
+
search = os.pathsep.join([os.environ.get("PATH", ""), os.path.expanduser(harness_core.BIN_DIR)])
|
|
517
|
+
# As harness.inspect: the Windows app's magpie.com shim stands for its magpie.exe.
|
|
513
518
|
return harness_probe.windows_program(shutil.which("magpie", path=search))
|
|
514
519
|
|
|
515
520
|
|
|
@@ -525,8 +530,6 @@ def unwire(
|
|
|
525
530
|
Magpie plan): pi gets its model back unless changed since; our routing group and rule,
|
|
526
531
|
reasoning levels, providers, gateway keys and search APIs go. An entry leaves the manifest
|
|
527
532
|
only once its removal succeeded."""
|
|
528
|
-
from localmodels import gateway_bifrost
|
|
529
|
-
|
|
530
533
|
results = gateway_bifrost.unwire(tools_dir, plan=plan)
|
|
531
534
|
if any(not check["ok"] for check in results):
|
|
532
535
|
return results
|
|
@@ -561,8 +564,6 @@ def _restore_pi(
|
|
|
561
564
|
def _unwire_magpie(
|
|
562
565
|
magpie: str | None, tools_dir: str, *, plan: ToolPlan | None = None
|
|
563
566
|
) -> list[Check]:
|
|
564
|
-
from localmodels import gateway_bifrost
|
|
565
|
-
|
|
566
567
|
doc = hosts.load_owned(tools_dir)
|
|
567
568
|
gw, pi = doc["gateway"], doc["pi"]
|
|
568
569
|
if pi and pi["model"] == gateway_bifrost.PI_MODEL:
|
|
@@ -597,7 +598,7 @@ def _unwire_magpie(
|
|
|
597
598
|
return results
|
|
598
599
|
|
|
599
600
|
def run(name: str, *args: str) -> bool:
|
|
600
|
-
out =
|
|
601
|
+
out = run_magpie(target, *args, timeout=60)
|
|
601
602
|
lines = [ln for ln in (out.stdout + out.stderr).splitlines() if "plugin [" not in ln]
|
|
602
603
|
detail = " ".join(lines[-2:])[-200:]
|
|
603
604
|
results.append({"check": name, "ok": out.returncode == 0, "detail": detail})
|
|
@@ -614,7 +615,7 @@ def _unwire_magpie(
|
|
|
614
615
|
if run(f"model efforts {model} --reset", "model", "efforts", model, "--reset"):
|
|
615
616
|
hosts.own_listed(tools_dir, "efforts", model, False)
|
|
616
617
|
for pid in gw["providers"]:
|
|
617
|
-
gone =
|
|
618
|
+
gone = run_magpie(target, "provider", pid, timeout=20).returncode != 0
|
|
618
619
|
if gone or run(f"provider rm {pid}", "provider", "rm", pid):
|
|
619
620
|
hosts.own_listed(tools_dir, "providers", pid, False)
|
|
620
621
|
results += _unwire_search(target, gw.get("search"), bool(gw.get("search_you")), tools_dir)
|
|
@@ -625,7 +626,7 @@ def _search_apis(plan: ToolPlan) -> dict[str, str]:
|
|
|
625
626
|
"""Magpie's search APIs as {api: URL}. ``magpie search`` lists one per line, as
|
|
626
627
|
``N. SearXNG no key <url> [off]`` or ``N. You.com no key``; the api is the name's first
|
|
627
628
|
word in lower case (``you``)."""
|
|
628
|
-
out =
|
|
629
|
+
out = run_magpie(plan, "search", timeout=20)
|
|
629
630
|
if out.returncode != 0:
|
|
630
631
|
raise HarnessError(f"magpie search failed (exit {out.returncode})")
|
|
631
632
|
found: dict[str, str] = {}
|
|
@@ -655,7 +656,7 @@ def _unwire_search(plan: ToolPlan, url: str | None, you: bool, tools_dir: str) -
|
|
|
655
656
|
checks: list[Check] = []
|
|
656
657
|
for api, ours, field in entries:
|
|
657
658
|
if ours:
|
|
658
|
-
out =
|
|
659
|
+
out = run_magpie(plan, "search", "rm", api, timeout=60)
|
|
659
660
|
detail = " ".join((out.stdout + out.stderr).split())[-200:]
|
|
660
661
|
checks.append(
|
|
661
662
|
{"check": f"search rm {api}", "ok": out.returncode == 0, "detail": detail}
|
|
@@ -677,7 +678,7 @@ def check_decision(url: str, model: str, key: str, timeout: float = 120) -> Chec
|
|
|
677
678
|
def logged_calls(plan: ToolPlan, provider: str, kind: str | None = None) -> int | None:
|
|
678
679
|
"""Successful calls to ``provider`` in Magpie's usage log, only those of ``kind`` if given
|
|
679
680
|
(``routing`` for classifier calls; an embedding or rerank call has none)."""
|
|
680
|
-
return gateway_accept.logged_calls(plan, provider, kind, magpie=
|
|
681
|
+
return gateway_accept.logged_calls(plan, provider, kind, magpie=run_magpie)
|
|
681
682
|
|
|
682
683
|
|
|
683
684
|
def logged_after(plan: ToolPlan, provider: str, kind: str | None, before: int | None) -> int | None:
|
|
@@ -699,7 +700,7 @@ def accept(
|
|
|
699
700
|
aux_providers=AUX_PROVIDERS,
|
|
700
701
|
is_bifrost=_bifrost(plan),
|
|
701
702
|
post_fn=_post,
|
|
702
|
-
magpie=
|
|
703
|
+
magpie=run_magpie,
|
|
703
704
|
run_tool=run_tool,
|
|
704
705
|
tool_path=tool_path,
|
|
705
706
|
calls_fn=logged_calls,
|