@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38

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.
Files changed (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +132 -110
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_checks.py +9 -6
  7. package/modules/localmodels/bifrost_config.py +203 -0
  8. package/modules/localmodels/bifrost_datasheet.py +12 -2
  9. package/modules/localmodels/budget.py +13 -2
  10. package/modules/localmodels/catalog.json +137 -2
  11. package/modules/localmodels/catalog.py +70 -321
  12. package/modules/localmodels/catalog_add.py +2 -8
  13. package/modules/localmodels/catalog_recipes.py +352 -0
  14. package/modules/localmodels/cli_parser.py +4 -1
  15. package/modules/localmodels/console.py +5 -4
  16. package/modules/localmodels/contracts.py +13 -3
  17. package/modules/localmodels/debug_cli.py +158 -0
  18. package/modules/localmodels/debug_mode.py +727 -0
  19. package/modules/localmodels/debug_stub_server.py +192 -0
  20. package/modules/localmodels/decode_calibration.json +1 -1
  21. package/modules/localmodels/decode_calibration.py +34 -17
  22. package/modules/localmodels/gateway.py +21 -155
  23. package/modules/localmodels/gateway_accept.py +201 -0
  24. package/modules/localmodels/gateway_bifrost.py +30 -193
  25. package/modules/localmodels/gateway_cli.py +15 -6
  26. package/modules/localmodels/gateway_foundations.py +2 -4
  27. package/modules/localmodels/gateway_probe.py +0 -1
  28. package/modules/localmodels/gateway_server.py +2 -3
  29. package/modules/localmodels/gpu_specs.py +12 -0
  30. package/modules/localmodels/guard.py +2 -7
  31. package/modules/localmodels/harness.py +16 -129
  32. package/modules/localmodels/harness_cleanup.py +135 -0
  33. package/modules/localmodels/harness_gateway.py +16 -14
  34. package/modules/localmodels/harness_probe.py +12 -4
  35. package/modules/localmodels/hosts.py +25 -2
  36. package/modules/localmodels/http_local.py +59 -0
  37. package/modules/localmodels/install.py +23 -8
  38. package/modules/localmodels/library_gateway.py +20 -9
  39. package/modules/localmodels/library_jobs.py +125 -28
  40. package/modules/localmodels/library_model.py +10 -0
  41. package/modules/localmodels/library_pricing.py +29 -22
  42. package/modules/localmodels/library_serve.py +17 -1
  43. package/modules/localmodels/library_state.py +15 -2
  44. package/modules/localmodels/library_status.py +30 -0
  45. package/modules/localmodels/llm_rank.py +185 -39
  46. package/modules/localmodels/probe.py +108 -174
  47. package/modules/localmodels/process_identity.py +120 -154
  48. package/modules/localmodels/process_windows.py +86 -0
  49. package/modules/localmodels/recommend.py +6 -3
  50. package/modules/localmodels/recommend_cli.py +14 -6
  51. package/modules/localmodels/remote_ops.py +65 -0
  52. package/modules/localmodels/remote_ops_service.py +14 -2
  53. package/modules/localmodels/runtime_args.py +10 -3
  54. package/modules/localmodels/runtime_auth.py +5 -9
  55. package/modules/localmodels/runtime_cli.py +128 -129
  56. package/modules/localmodels/runtime_discovery.py +84 -0
  57. package/modules/localmodels/runtime_install.py +101 -0
  58. package/modules/localmodels/runtime_releases.py +302 -0
  59. package/modules/localmodels/search_server.py +5 -1
  60. package/modules/localmodels/service_stop.py +8 -108
  61. package/modules/localmodels/service_upgrade.py +394 -63
  62. package/modules/localmodels/services_cli.py +24 -14
  63. package/modules/localmodels/setup_inspection.py +97 -9
  64. package/modules/localmodels/setup_text.py +7 -0
  65. package/modules/localmodels/sizecalc.py +0 -1
  66. package/modules/localmodels/stack.py +45 -235
  67. package/modules/localmodels/stack_arena.py +732 -0
  68. package/modules/localmodels/stack_args.py +21 -12
  69. package/modules/localmodels/stack_auto.py +384 -3
  70. package/modules/localmodels/stack_aux_gpu.py +4 -3
  71. package/modules/localmodels/stack_capacity.py +138 -0
  72. package/modules/localmodels/stack_cleanup.py +9 -4
  73. package/modules/localmodels/stack_cli.py +288 -0
  74. package/modules/localmodels/stack_compose.py +63 -30
  75. package/modules/localmodels/stack_console.py +9 -6
  76. package/modules/localmodels/stack_hardware.py +95 -265
  77. package/modules/localmodels/stack_hardware_text.py +263 -0
  78. package/modules/localmodels/stack_journal.py +3 -9
  79. package/modules/localmodels/stack_ledger.py +48 -18
  80. package/modules/localmodels/stack_lifecycle.py +33 -312
  81. package/modules/localmodels/stack_llm_ram.py +16 -6
  82. package/modules/localmodels/stack_mcp.py +729 -0
  83. package/modules/localmodels/stack_memory.py +0 -2
  84. package/modules/localmodels/stack_picks.py +62 -15
  85. package/modules/localmodels/stack_plan.py +19 -1
  86. package/modules/localmodels/stack_preflight.py +11 -19
  87. package/modules/localmodels/stack_progress.py +9 -1
  88. package/modules/localmodels/stack_remove.py +373 -0
  89. package/modules/localmodels/stack_route.py +101 -17
  90. package/modules/localmodels/stack_run.py +29 -0
  91. package/modules/localmodels/stack_suite.py +21 -10
  92. package/modules/localmodels/stack_summary.py +14 -0
  93. package/modules/localmodels/stack_try.py +238 -24
  94. package/modules/localmodels/stack_try_client.py +53 -15
  95. package/modules/localmodels/stack_try_docs.py +2 -2
  96. package/modules/localmodels/stack_view.py +24 -171
  97. package/modules/localmodels/stack_view_access.py +114 -1
  98. package/modules/localmodels/stack_view_agent.py +3 -13
  99. package/modules/localmodels/stack_view_hub.py +9 -10
  100. package/modules/localmodels/stack_view_llm.py +1 -1
  101. package/modules/localmodels/stack_view_sandbox.py +2 -2
  102. package/modules/localmodels/stack_view_schema.py +183 -0
  103. package/modules/localmodels/stack_view_serve.py +7 -1
  104. package/modules/localmodels/stack_view_service.py +1 -2
  105. package/modules/localmodels/stack_view_text.py +13 -9
  106. package/modules/localmodels/stack_warm.py +48 -4
  107. package/modules/localmodels/stack_warm_store.py +517 -0
  108. package/modules/localmodels/tools.json +32 -18
  109. package/modules/localmodels/transport.py +38 -13
  110. package/modules/localmodels/tui.py +28 -4
  111. package/modules/localmodels/tui_dialogs.py +136 -0
  112. package/modules/localmodels/tui_modals.py +279 -0
  113. package/modules/localmodels/tui_screen.py +113 -154
  114. package/modules/localmodels/tui_views.py +134 -203
  115. package/modules/localmodels/web/index.html +510 -101
  116. package/modules/localmodels/web/sizecalc/app.js +363 -10
  117. package/modules/localmodels/web/sizecalc/page.html +27 -3
  118. package/modules/localmodels/web/view/fleet.html +11 -2
  119. package/modules/localmodels/web/view/fleet.js +191 -17
  120. package/modules/localmodels/web/view/i18n.js +3 -2
  121. package/modules/localmodels/web/view/index.html +1 -1
  122. package/modules/localmodels/web/view/nav.js +22 -3
  123. package/modules/localmodels/web/view/view.css +63 -18
  124. package/modules/localmodels/web/view/view.js +169 -32
  125. package/modules/localmodels/windows_job.py +69 -0
  126. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  127. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
  128. package/package.json +1 -1
  129. package/tool.json +1 -1
  130. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  131. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  132. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,192 @@
1
+ """Loopback OpenAI-compatible stub server for ``LOCALMODELS_DEBUG=simulate``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import signal
8
+ import sys
9
+ import time
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from typing import Any
12
+
13
+
14
+ def _last_user_text(messages: Any) -> str:
15
+ if not isinstance(messages, list):
16
+ return "ping"
17
+ for item in reversed(messages):
18
+ if isinstance(item, dict) and item.get("role") == "user":
19
+ content = item.get("content", "")
20
+ if isinstance(content, str) and content.strip():
21
+ return content.strip()[:80]
22
+ if isinstance(content, list):
23
+ parts = [
24
+ str(p.get("text", "")) for p in content if isinstance(p, dict) and p.get("text")
25
+ ]
26
+ if parts:
27
+ return " ".join(parts).strip()[:80]
28
+ return "ready"
29
+
30
+
31
+ def _make_handler(served_model: str) -> type[BaseHTTPRequestHandler]:
32
+ class Handler(BaseHTTPRequestHandler):
33
+ protocol_version = "HTTP/1.1"
34
+
35
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002
36
+ return
37
+
38
+ def _send_json(self, status: int, body: dict[str, Any]) -> None:
39
+ raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
40
+ self.send_response(status)
41
+ self.send_header("Content-Type", "application/json; charset=utf-8")
42
+ self.send_header("Content-Length", str(len(raw)))
43
+ self.end_headers()
44
+ self.wfile.write(raw)
45
+
46
+ def do_GET(self) -> None: # noqa: N802
47
+ if self.path.startswith(("/health", "/v1/health")):
48
+ self._send_json(200, {"status": "ok"})
49
+ return
50
+ if self.path.startswith("/v1/models"):
51
+ self._send_json(
52
+ 200,
53
+ {
54
+ "object": "list",
55
+ "data": [
56
+ {
57
+ "id": served_model,
58
+ "object": "model",
59
+ "created": 1700000000,
60
+ "owned_by": "localmodels-simulate",
61
+ }
62
+ ],
63
+ },
64
+ )
65
+ return
66
+ self._send_json(404, {"error": {"message": "not found"}})
67
+
68
+ def do_POST(self) -> None: # noqa: N802
69
+ length = int(self.headers.get("Content-Length") or "0")
70
+ raw = self.rfile.read(length) if length > 0 else b"{}"
71
+ try:
72
+ payload = json.loads(raw.decode("utf-8"))
73
+ except ValueError:
74
+ payload = {}
75
+ if not isinstance(payload, dict):
76
+ payload = {}
77
+
78
+ if self.path.startswith("/v1/embeddings"):
79
+ inputs = payload.get("input")
80
+ items = inputs if isinstance(inputs, list) else [inputs]
81
+ self._send_json(
82
+ 200,
83
+ {
84
+ "object": "list",
85
+ "model": served_model,
86
+ "data": [
87
+ {"object": "embedding", "index": i, "embedding": [0.01] * 16}
88
+ for i in range(max(1, len(items)))
89
+ ],
90
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
91
+ },
92
+ )
93
+ return
94
+
95
+ if self.path.startswith(("/rerank", "/v1/rerank")):
96
+ docs = payload.get("documents")
97
+ count = len(docs) if isinstance(docs, list) else 0
98
+ self._send_json(
99
+ 200,
100
+ {
101
+ "results": [
102
+ {"index": i, "relevance_score": 1.0 / (i + 1)} for i in range(count)
103
+ ]
104
+ },
105
+ )
106
+ return
107
+
108
+ if self.path.startswith("/v1/chat/completions"):
109
+ preview = _last_user_text(payload.get("messages"))
110
+ reply = f"[Simulated {served_model}] {preview}"
111
+ now = int(time.time())
112
+ if payload.get("stream"):
113
+ chunk = {
114
+ "id": f"chatcmpl-sim-{now}",
115
+ "object": "chat.completion.chunk",
116
+ "created": now,
117
+ "model": served_model,
118
+ "choices": [
119
+ {
120
+ "index": 0,
121
+ "delta": {"role": "assistant", "content": reply},
122
+ "finish_reason": None,
123
+ }
124
+ ],
125
+ }
126
+ done_chunk = {
127
+ "id": f"chatcmpl-sim-{now}",
128
+ "object": "chat.completion.chunk",
129
+ "created": now,
130
+ "model": served_model,
131
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
132
+ }
133
+ body = (
134
+ f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
135
+ f"data: {json.dumps(done_chunk, ensure_ascii=False)}\n\n"
136
+ "data: [DONE]\n\n"
137
+ ).encode()
138
+ self.send_response(200)
139
+ self.send_header("Content-Type", "text/event-stream; charset=utf-8")
140
+ self.send_header("Cache-Control", "no-cache")
141
+ self.send_header("Content-Length", str(len(body)))
142
+ self.end_headers()
143
+ self.wfile.write(body)
144
+ return
145
+
146
+ self._send_json(
147
+ 200,
148
+ {
149
+ "id": f"chatcmpl-sim-{now}",
150
+ "object": "chat.completion",
151
+ "created": now,
152
+ "model": served_model,
153
+ "choices": [
154
+ {
155
+ "index": 0,
156
+ "message": {"role": "assistant", "content": reply},
157
+ "finish_reason": "stop",
158
+ }
159
+ ],
160
+ "usage": {
161
+ "prompt_tokens": 12,
162
+ "completion_tokens": 12,
163
+ "total_tokens": 24,
164
+ },
165
+ },
166
+ )
167
+ return
168
+
169
+ self._send_json(404, {"error": {"message": "not found"}})
170
+
171
+ return Handler
172
+
173
+
174
+ def main(argv: list[str] | None = None) -> int:
175
+ parser = argparse.ArgumentParser(description="Simulated localmodels inference endpoint")
176
+ parser.add_argument("--bind", default="127.0.0.1")
177
+ parser.add_argument("--port", type=int, required=True)
178
+ parser.add_argument("--model", required=True)
179
+ args = parser.parse_args(argv)
180
+ server = ThreadingHTTPServer((args.bind, args.port), _make_handler(args.model))
181
+ signal.signal(signal.SIGTERM, lambda *_a: sys.exit(0))
182
+ try:
183
+ server.serve_forever(poll_interval=0.2)
184
+ except KeyboardInterrupt:
185
+ pass
186
+ finally:
187
+ server.server_close()
188
+ return 0
189
+
190
+
191
+ if __name__ == "__main__":
192
+ sys.exit(main())
@@ -1,5 +1,5 @@
1
1
  {
2
- "schema_version": 1,
2
+ "schema_version": 2,
3
3
  "method": "No factor shipped. The Blackwell-only llama.cpp/CUDA MoE candidate failed the shown-pick measurement floor and its own Flash-Next training measurements; see the retained analysis.",
4
4
  "report": "evidence/2026-11-13-decode-calibration/REPORT.md",
5
5
  "factors": []
@@ -9,13 +9,15 @@ from functools import lru_cache
9
9
  from pathlib import Path
10
10
  from typing import Protocol, TypedDict
11
11
 
12
+ from localmodels import gpu_specs
12
13
  from localmodels.contracts import decode
13
14
 
14
15
  CALIBRATION_PATH = Path(__file__).with_suffix(".json")
15
16
  ARCHITECTURES = ("dense", "moe", "hybrid", "swa")
16
17
  ENGINES = ("llama.cpp", "Strata", "MLX")
17
18
  BACKENDS = ("cuda", "metal")
18
- Category = tuple[str, str, str]
19
+ WILDCARD_DEVICE_CLASSES = ("*", "all", "any", "default")
20
+ Category = tuple[str, str, str, str]
19
21
 
20
22
 
21
23
  class DecodeModel(Protocol):
@@ -37,7 +39,7 @@ class DecodeEstimate:
37
39
  bytes_per_token: float
38
40
 
39
41
 
40
- def category(entry: DecodeModel, backend: str) -> Category:
42
+ def category(entry: DecodeModel, backend: str, device_name: str = "") -> Category:
41
43
  """MoE takes precedence over recurrent attention, then hybrid, SWA and dense."""
42
44
  architecture = (
43
45
  "moe"
@@ -49,13 +51,14 @@ def category(entry: DecodeModel, backend: str) -> Category:
49
51
  else "dense"
50
52
  )
51
53
  engine = "MLX" if entry.runtime == "mlx-lm" else entry.runtime
52
- return (architecture, engine, backend)
54
+ return (architecture, engine, backend, gpu_specs.device_class(device_name))
53
55
 
54
56
 
55
57
  class Factor(TypedDict):
56
58
  architecture: str
57
59
  engine: str
58
60
  backend: str
61
+ device_class: str
59
62
  factor: float
60
63
  sample_count: int
61
64
  runs: list[str]
@@ -70,25 +73,37 @@ class Calibration(TypedDict):
70
73
  factors: list[Factor]
71
74
 
72
75
 
76
+ def _valid_device_class(value: str) -> bool:
77
+ return (
78
+ bool(value)
79
+ and value not in WILDCARD_DEVICE_CLASSES
80
+ and value == gpu_specs.device_class(value)
81
+ )
82
+
83
+
84
+ def _valid_factor(row: Factor) -> bool:
85
+ return (
86
+ row["architecture"] in ARCHITECTURES
87
+ and row["engine"] in ENGINES
88
+ and row["backend"] in BACKENDS
89
+ and _valid_device_class(row["device_class"])
90
+ and math.isfinite(row["factor"])
91
+ and row["factor"] > 0
92
+ and row["sample_count"] >= 5
93
+ and len(set(row["runs"])) >= 2
94
+ and len(set(row["models"])) >= 2
95
+ )
96
+
97
+
73
98
  def load_factors(path: Path) -> dict[Category, float]:
74
99
  """Validate shipped data rather than silently accepting a corrupt correction."""
75
100
  doc = decode(json.loads(path.read_text(encoding="utf-8")), Calibration)
76
- if doc["schema_version"] != 1:
101
+ if doc["schema_version"] != 2:
77
102
  raise ValueError("unsupported decode calibration schema")
78
103
  found: dict[Category, float] = {}
79
104
  for row in doc["factors"]:
80
- key = (row["architecture"], row["engine"], row["backend"])
81
- if (
82
- key[0] not in ARCHITECTURES
83
- or key[1] not in ENGINES
84
- or key[2] not in BACKENDS
85
- or key in found
86
- or not math.isfinite(row["factor"])
87
- or row["factor"] <= 0
88
- or row["sample_count"] < 5
89
- or len(set(row["runs"])) < 2
90
- or len(set(row["models"])) < 2
91
- ):
105
+ key = (row["architecture"], row["engine"], row["backend"], row["device_class"])
106
+ if key in found or not _valid_factor(row):
92
107
  raise ValueError("invalid decode calibration factor")
93
108
  found[key] = row["factor"]
94
109
  return found
@@ -100,5 +115,7 @@ def factors() -> dict[Category, float]:
100
115
 
101
116
 
102
117
  def efficiency(category: Category) -> float:
103
- """Only recorded categories receive a correction; missing categories keep physics."""
118
+ """Only recorded categories receive a correction; missing or unnamed classes keep physics."""
119
+ if not category[3]:
120
+ return 1.0
104
121
  return factors().get(category, 1.0)
@@ -5,25 +5,20 @@ Both gateways retain their native routing and private client configuration.
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
- import csv
9
8
  import http.client
10
- import io
11
9
  import json
12
10
  import os
13
11
  import secrets
14
12
  import shutil
15
13
  import subprocess
16
- import tempfile
17
14
  import time
18
- import urllib.error
19
- import urllib.request
20
- import uuid
21
15
  from collections.abc import Callable
22
16
  from http.cookies import SimpleCookie
23
17
  from pathlib import Path
24
18
  from typing import TypedDict
25
19
 
26
20
  from localmodels import (
21
+ gateway_accept,
27
22
  gateway_admin,
28
23
  gateway_clients,
29
24
  gateway_keys,
@@ -38,14 +33,12 @@ from localmodels import (
38
33
  from localmodels.contracts import decode
39
34
  from localmodels.gateway_requests import PI_ACCEPT_FLAGS as PI_ACCEPT_FLAGS
40
35
  from localmodels.gateway_requests import AuxEndpoint as AuxEndpoint
41
- from localmodels.gateway_requests import aux_answer as _aux_answer
42
36
  from localmodels.gateway_requests import post as _post
43
- from localmodels.gateway_requests import text as _text
44
37
  from localmodels.gateway_search import SEARCH as SEARCH
45
38
  from localmodels.gateway_search import Check as Check
46
- from localmodels.gateway_search import search_checks, wire_search
47
39
  from localmodels.gateway_search import search_url as search_url
48
40
  from localmodels.gateway_search import unwire as unwire_search
41
+ from localmodels.gateway_search import wire_search
49
42
  from localmodels.harness import (
50
43
  Endpoint,
51
44
  GatewayPlan,
@@ -55,21 +48,11 @@ from localmodels.harness import (
55
48
  run_tool,
56
49
  tool_path,
57
50
  )
51
+ from localmodels.harness_gateway import SERVE_PID as SERVE_PID
52
+ from localmodels.harness_gateway import SERVE_STOPPED as SERVE_STOPPED
58
53
  from localmodels.harness_gateway import stop_gateway as stop_gateway
59
- from localmodels.remote_ops import (
60
- DECISION_QUESTION,
61
- DECISION_STATE,
62
- TOUCH_EXPECT,
63
- TOUCH_PROMPT,
64
- )
65
54
 
66
55
  EFFORTS = ("low", "medium", "high") # a plan saved before the LLM's own levels were recorded
67
- SERVE_PID = "magpie-serve.pid" # with magpie-serve.pid.identity.json: process_identity.save
68
- SERVE_STOPPED = {
69
- "stopped": "magpie serve stopped",
70
- "gone": "magpie serve no longer running, process receipt cleared",
71
- "none": "magpie serve has no process receipt, no signal sent",
72
- }
73
56
 
74
57
 
75
58
  def effort_levels(gw: GatewayPlan) -> tuple[str, str]:
@@ -454,7 +437,7 @@ def point_pi(plan: ToolPlan, before: str | None, target: str) -> str:
454
437
  # Newer Magpie (0.1.3733, 2026-11-11) refuses a PI_CODING_AGENT_DIR that does not exist yet;
455
438
  # the stack's own one lives in its private gateway home and is created private here.
456
439
  agent = harness.gateway_environment(plan).get("PI_CODING_AGENT_DIR")
457
- home = Path(plan["tools_dir"]).expanduser() / "gateway-home"
440
+ home = harness_probe.gateway_home(plan["tools_dir"])
458
441
  if agent and Path(agent).is_relative_to(home):
459
442
  runtime_io.private_directory(Path(agent))
460
443
  _require(_magpie(plan, "pi", target), "pi")
@@ -589,55 +572,17 @@ def _unwire_magpie(
589
572
 
590
573
  def check_decision(url: str, model: str, key: str, timeout: float = 120) -> Check:
591
574
  """The same readiness question remote_ops asks a decision model this tool deploys."""
592
- name = f"decision {url}/systemone"
593
- try:
594
- resp = _post(
595
- f"{url}/systemone",
596
- {
597
- "model": model,
598
- "state": DECISION_STATE,
599
- "questions": {"outage": DECISION_QUESTION},
600
- },
601
- key,
602
- timeout,
603
- )
604
- except (urllib.error.URLError, OSError, ValueError) as exc:
605
- return {"check": name, "ok": False, "detail": f"{type(exc).__name__}: {exc}"}
606
- answers = resp.get("answers")
607
- answer = answers.get("outage") if isinstance(answers, dict) else None
608
- noul = answer.get("noul") if isinstance(answer, dict) else None
609
- ok = isinstance(noul, int | float) and not isinstance(noul, bool) and 0.5 < noul <= 1
610
- return {"check": name, "ok": ok, "detail": f"noul={noul}"}
575
+ return gateway_accept.check_decision(url, model, key, timeout, post_fn=_post)
611
576
 
612
577
 
613
578
  def logged_calls(plan: ToolPlan, provider: str, kind: str | None = None) -> int | None:
614
579
  """Successful calls to ``provider`` in Magpie's usage log, only those of ``kind`` if given
615
580
  (``routing`` for classifier calls; an embedding or rerank call has none)."""
616
- out = _magpie(plan, "usage", "--csv", "--last", "6h", timeout=60)
617
- if out.returncode != 0:
618
- return None
619
- rows = list(csv.DictReader(io.StringIO(out.stdout)))
620
- if rows and "kind" not in rows[0]:
621
- return None
622
- return len(
623
- [
624
- r
625
- for r in rows
626
- if r.get("provider") == provider
627
- and (kind is None or r.get("kind") == kind)
628
- and r.get("status") == "200"
629
- ]
630
- )
581
+ return gateway_accept.logged_calls(plan, provider, kind, magpie=_magpie)
631
582
 
632
583
 
633
584
  def logged_after(plan: ToolPlan, provider: str, kind: str | None, before: int | None) -> int | None:
634
- after = before
635
- for _ in range(10): # the usage log is written just after the reply
636
- after = logged_calls(plan, provider, kind)
637
- if before is None or after is None or after > before:
638
- break
639
- time.sleep(1)
640
- return after
585
+ return gateway_accept.logged_after(plan, provider, kind, before, calls_fn=logged_calls)
641
586
 
642
587
 
643
588
  def accept(
@@ -647,96 +592,17 @@ def accept(
647
592
  gateway (the decision model must be consulted), one embedding, rerank or transcription request
648
593
  per wired auxiliary (Magpie's usage log must gain its row), and one pi prompt with the stack's model.
649
594
  A Bifrost plan is accepted by ``bifrost_checks.accept``."""
650
- if _bifrost(plan):
651
- from localmodels import bifrost_checks
652
-
653
- return bifrost_checks.accept(plan, decision_key, aux, timeout)
654
- gw = plan["gateway"]
655
- checks: list[Check] = []
656
-
657
- def check(name: str, ok: bool, detail: str) -> None:
658
- checks.append({"check": name, "ok": ok, "detail": detail[-300:]})
659
-
660
- def provider_test(pid: str, kind: str) -> None:
661
- out = _magpie(plan, "provider", "test", pid, timeout=timeout)
662
- lines = [ln.strip() for ln in out.stdout.splitlines() if kind in ln]
663
- check(
664
- f"magpie provider test {pid}",
665
- out.returncode == 0 and any("✓" in ln for ln in lines),
666
- "; ".join(lines) or out.stderr.strip()[-200:],
667
- )
668
-
669
- provider_test(gw["llm_provider"], "chat")
670
- if gw["decision"] is not None and decision_key is not None:
671
- provider_test(gw["decision_provider"], "decide")
672
- routed = gw["decision"] is not None and decision_key is not None
673
- decider = gw["decision_provider"]
674
- before = logged_calls(plan, decider, "routing") if routed else None
675
- # Magpie remembers a classified message's intent; a fresh nonce per run reaches the classifier.
676
- prompt = f"{TOUCH_PROMPT} (check {uuid.uuid4().hex[:8]})"
677
- try:
678
- harness_gateway.require_target(plan)
679
- resp = _post(
680
- f"http://{gw['addr']}/v1/chat/completions",
681
- {
682
- "model": f"group/{gw['group']}",
683
- "messages": [{"role": "user", "content": prompt}],
684
- "max_tokens": 512,
685
- "temperature": 0,
686
- },
687
- "magpie",
688
- timeout,
689
- )
690
- answer = _text(resp)
691
- check(f"gateway group/{gw['group']}", TOUCH_EXPECT in answer.lower(), answer.strip()[:200])
692
- except (urllib.error.URLError, OSError, ValueError) as exc:
693
- check(f"gateway group/{gw['group']}", False, f"{type(exc).__name__}: {exc}")
694
- if routed:
695
- after = logged_after(plan, decider, "routing", before)
696
- check(
697
- "gateway consulted decision model",
698
- before is not None and after is not None and after > before,
699
- f"Magpie routing calls to {decider}: {before} → {after}",
700
- )
701
- for ep in aux:
702
- if ep["contract"] == SEARCH:
703
- checks += search_checks(plan, search_url(ep), timeout)
704
- continue
705
- pid = AUX_PROVIDERS[ep["contract"]]
706
- name = f"gateway {ep['contract']} {pid}/{ep['model']}"
707
- before = logged_calls(plan, pid)
708
- try:
709
- harness_gateway.require_target(plan)
710
- check(name, *_aux_answer(gw["addr"], ep, f"{pid}/{ep['model']}", timeout))
711
- except (urllib.error.URLError, OSError, ValueError) as exc:
712
- check(name, False, f"{type(exc).__name__}: {exc}")
713
- continue
714
- after = logged_after(plan, pid, None, before)
715
- check(
716
- f"Magpie logged {ep['contract']}",
717
- before is not None and after is not None and after > before,
718
- f"Magpie calls to {pid}: {before} → {after}",
719
- )
720
- pi = tool_path(plan, "pi")
721
- env = harness.checked_gateway_environment(plan)
722
- loopback = "127.0.0.1,localhost"
723
- env["NO_PROXY"] = env["no_proxy"] = ",".join(x for x in (env.get("NO_PROXY"), loopback) if x)
724
- with tempfile.TemporaryDirectory(prefix="localmodels-pi-") as cwd:
725
- out = run_tool([pi, *PI_ACCEPT_FLAGS, TOUCH_PROMPT], timeout=timeout, cwd=cwd, env=env)
726
- check(
727
- "pi -p via Magpie",
728
- out.returncode == 0 and TOUCH_EXPECT in out.stdout.lower(),
729
- (out.stdout.strip() or out.stderr.strip())[-200:],
595
+ return gateway_accept.accept(
596
+ plan,
597
+ decision_key,
598
+ aux,
599
+ timeout,
600
+ aux_providers=AUX_PROVIDERS,
601
+ is_bifrost=_bifrost(plan),
602
+ post_fn=_post,
603
+ magpie=_magpie,
604
+ run_tool=run_tool,
605
+ tool_path=tool_path,
606
+ calls_fn=logged_calls,
607
+ after_fn=logged_after,
730
608
  )
731
- checks += [
732
- decode(result, Check)
733
- for result in gateway_clients.accept(
734
- plan,
735
- TOUCH_PROMPT,
736
- TOUCH_EXPECT,
737
- timeout,
738
- lambda: logged_calls(plan, gw["llm_provider"]),
739
- lambda before: logged_after(plan, gw["llm_provider"], None, before),
740
- )
741
- ]
742
- return checks