@simplexai/localmodels-linux-arm64 0.1.0-dev.59 → 0.1.0-dev.61

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 +126 -107
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +107 -44
  5. package/modules/localmodels/apple_sensors.py +431 -0
  6. package/modules/localmodels/auth_proxy.py +185 -19
  7. package/modules/localmodels/bifrost_admin.py +30 -0
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +132 -9
  10. package/modules/localmodels/bifrost_models.py +1 -1
  11. package/modules/localmodels/catalog.json +509 -54
  12. package/modules/localmodels/catalog.py +21 -4
  13. package/modules/localmodels/catalog_add.py +42 -11
  14. package/modules/localmodels/catalog_license.py +2 -0
  15. package/modules/localmodels/catalog_recipes.py +2 -0
  16. package/modules/localmodels/cli_parser.py +6 -2
  17. package/modules/localmodels/context_policy.py +40 -4
  18. package/modules/localmodels/custom_hub.py +983 -0
  19. package/modules/localmodels/custom_hub_http.py +579 -0
  20. package/modules/localmodels/custom_probe.py +451 -0
  21. package/modules/localmodels/debug_mode.py +13 -0
  22. package/modules/localmodels/debug_stub_server.py +156 -1
  23. package/modules/localmodels/deploy.py +38 -7
  24. package/modules/localmodels/deploy_steps.py +5 -0
  25. package/modules/localmodels/download-mirrors.json +20 -0
  26. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  27. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  28. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  29. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  30. package/modules/localmodels/engines.py +38 -8
  31. package/modules/localmodels/estimator.py +60 -7
  32. package/modules/localmodels/gateway.py +48 -3
  33. package/modules/localmodels/gateway_app_bifrost.py +18 -18
  34. package/modules/localmodels/gateway_bifrost.py +102 -16
  35. package/modules/localmodels/gateway_cli.py +14 -80
  36. package/modules/localmodels/gateway_server.py +88 -16
  37. package/modules/localmodels/gguf.py +6 -0
  38. package/modules/localmodels/gpu_specs.py +35 -1
  39. package/modules/localmodels/harness.py +1 -2
  40. package/modules/localmodels/hf_repo.py +12 -4
  41. package/modules/localmodels/host_sensors.py +704 -0
  42. package/modules/localmodels/install.py +4 -4
  43. package/modules/localmodels/library_cli.py +181 -3
  44. package/modules/localmodels/library_custom.py +831 -0
  45. package/modules/localmodels/library_elastic.py +35 -7
  46. package/modules/localmodels/library_gateway.py +94 -32
  47. package/modules/localmodels/library_jobs.py +76 -11
  48. package/modules/localmodels/library_kept.py +50 -6
  49. package/modules/localmodels/library_model.py +254 -2
  50. package/modules/localmodels/library_pricing.py +83 -4
  51. package/modules/localmodels/library_serve.py +178 -60
  52. package/modules/localmodels/library_smoke.py +315 -0
  53. package/modules/localmodels/library_state.py +77 -1
  54. package/modules/localmodels/library_status.py +126 -4
  55. package/modules/localmodels/npm_transport.py +4 -58
  56. package/modules/localmodels/nvml_ctypes.py +431 -0
  57. package/modules/localmodels/plan_envelope.py +14 -6
  58. package/modules/localmodels/recommend_cli.py +2 -1
  59. package/modules/localmodels/records.py +1 -0
  60. package/modules/localmodels/remote_ops.py +120 -665
  61. package/modules/localmodels/remote_ops_common.py +729 -0
  62. package/modules/localmodels/remote_ops_download.py +396 -241
  63. package/modules/localmodels/remote_ops_mirrors.py +26 -65
  64. package/modules/localmodels/remote_ops_prepare.py +43 -35
  65. package/modules/localmodels/remote_ops_ranges.py +98 -65
  66. package/modules/localmodels/remote_ops_remove.py +30 -22
  67. package/modules/localmodels/remote_ops_service.py +103 -95
  68. package/modules/localmodels/remote_ops_verify.py +113 -65
  69. package/modules/localmodels/runtime-lock.json +19 -19
  70. package/modules/localmodels/runtime_cli.py +15 -5
  71. package/modules/localmodels/runtime_io.py +54 -1
  72. package/modules/localmodels/service_control.py +32 -1
  73. package/modules/localmodels/service_wiring.py +2 -3
  74. package/modules/localmodels/service_worker.py +6 -2
  75. package/modules/localmodels/services_cli.py +35 -27
  76. package/modules/localmodels/source_byok.py +3 -5
  77. package/modules/localmodels/speech-sv.txt +93 -0
  78. package/modules/localmodels/speech_admission.py +437 -0
  79. package/modules/localmodels/speech_catalog.py +170 -0
  80. package/modules/localmodels/speech_cli.py +273 -0
  81. package/modules/localmodels/speech_jobs.py +772 -0
  82. package/modules/localmodels/speech_model.py +404 -0
  83. package/modules/localmodels/speech_serve.py +287 -0
  84. package/modules/localmodels/speech_server.py +837 -0
  85. package/modules/localmodels/speech_state.py +697 -0
  86. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  87. package/modules/localmodels/speech_workers.py +783 -0
  88. package/modules/localmodels/stack.py +0 -33
  89. package/modules/localmodels/stack_auto.py +5 -3
  90. package/modules/localmodels/stack_aux_gpu.py +45 -4
  91. package/modules/localmodels/stack_capacity.py +77 -8
  92. package/modules/localmodels/stack_cli.py +16 -1
  93. package/modules/localmodels/stack_compose.py +1 -1
  94. package/modules/localmodels/stack_down.py +24 -1
  95. package/modules/localmodels/stack_hardware.py +57 -88
  96. package/modules/localmodels/stack_hardware_text.py +4 -59
  97. package/modules/localmodels/stack_lifecycle.py +2 -2
  98. package/modules/localmodels/stack_memory.py +14 -3
  99. package/modules/localmodels/stack_suite.py +9 -10
  100. package/modules/localmodels/stack_summary.py +4 -4
  101. package/modules/localmodels/stack_view.py +77 -53
  102. package/modules/localmodels/stack_view_demo.py +36 -5
  103. package/modules/localmodels/stack_view_events.py +147 -12
  104. package/modules/localmodels/stack_view_gpu.py +97 -17
  105. package/modules/localmodels/stack_view_llm.py +16 -1
  106. package/modules/localmodels/stack_view_measure.py +4 -1
  107. package/modules/localmodels/stack_view_schema.py +54 -8
  108. package/modules/localmodels/stack_view_serve.py +40 -3
  109. package/modules/localmodels/stack_view_slots.py +89 -10
  110. package/modules/localmodels/stack_view_telemetry.py +163 -0
  111. package/modules/localmodels/stack_view_text.py +5 -2
  112. package/modules/localmodels/stack_view_tick.py +658 -0
  113. package/modules/localmodels/stack_view_words.py +4 -0
  114. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  115. package/modules/localmodels/suite.py +3 -1
  116. package/modules/localmodels/telemetry_math.py +538 -0
  117. package/modules/localmodels/transport.py +3 -2
  118. package/modules/localmodels/tui_views.py +2 -2
  119. package/modules/localmodels/web/view/view.js +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
  121. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
  122. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
  123. package/package.json +1 -1
  124. package/tool.json +1 -1
  125. package/modules/localmodels/bifrost_datasheet.py +0 -53
  126. package/modules/localmodels/bifrost_provider.py +0 -88
  127. package/modules/localmodels/bifrost_unit.py +0 -99
  128. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
  129. package/modules/localmodels/gateway_switch.py +0 -51
  130. package/modules/localmodels/library_floor.py +0 -78
  131. package/modules/localmodels/service_stop.py +0 -52
  132. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -2,9 +2,8 @@
2
2
  """remote_ops ``verify`` action: readiness is a real request for the contract, never /health alone.
3
3
 
4
4
  Part of the remote_ops bundle shipped to the target as one stdin payload (transport.BUNDLES):
5
- standard library only, Python 3.8+. Shared primitives stay in the entry module and are used
6
- here as ``remote_ops.<name>``, so the bundle keeps one patchable surface and needs no
7
- private-name imports.
5
+ standard library only, Python 3.8+. Shared primitives live in ``remote_ops_common`` and are used
6
+ here via ``remote_ops_common.<name>`` so the bundle stays acyclic with no private-name accesses.
8
7
  """
9
8
 
10
9
  from __future__ import annotations
@@ -19,16 +18,21 @@ import struct
19
18
  import sys
20
19
  import time
21
20
  import urllib.error
22
- import urllib.parse
23
21
  import wave
24
22
  import zlib
25
23
  from typing import Callable, cast
26
24
 
27
25
  try:
28
- from localmodels import process_identity, remote_ops, remote_ops_launchd
26
+ from localmodels import (
27
+ process_identity,
28
+ remote_ops_common,
29
+ remote_ops_download,
30
+ remote_ops_launchd,
31
+ )
29
32
  except ImportError: # run as a bare file from this directory
30
33
  import process_identity # type: ignore[import-not-found,no-redef]
31
- import remote_ops # type: ignore[import-not-found,no-redef]
34
+ import remote_ops_common # type: ignore[import-not-found,no-redef]
35
+ import remote_ops_download # type: ignore[import-not-found,no-redef]
32
36
  import remote_ops_launchd # type: ignore[import-not-found,no-redef]
33
37
 
34
38
 
@@ -37,30 +41,44 @@ LIMIT_UNIT = " apple" # repeated to size inputs; /tokenize gives the real count
37
41
  LIMIT_MARGIN = 32 # tokens either side of the limit: room for the special tokens added
38
42
 
39
43
 
40
- def _restarts(p: remote_ops.ServiceParams) -> int:
44
+ def _restarts(p: remote_ops_common.ServiceParams) -> int:
41
45
  """systemd's restart count for the unit; it survives stop/start, so callers take deltas."""
42
- _, out = remote_ops._systemctl("show", "-p", "NRestarts", "--value", p["service"] + ".service")
46
+ _, out = remote_ops_common.systemctl(
47
+ "show", "-p", "NRestarts", "--value", p["service"] + ".service"
48
+ )
43
49
  return int(out) if out.isdigit() else 0
44
50
 
45
51
 
46
- def _health_ready(root: str, health_path: str, p: remote_ops.VerifyParams) -> bool:
47
- if remote_ops.receipts():
52
+ def _health_ready(root: str, health_path: str, p: remote_ops_common.VerifyParams) -> bool:
53
+ if remote_ops_common.receipts():
48
54
  state, pid = (
49
55
  remote_ops_launchd.status(p["deploy_dir"])
50
56
  if p["service_kind"] == "launchd-user"
51
- else process_identity.status(remote_ops._paths(p)["pid"])
57
+ else process_identity.status(remote_ops_common.paths(p)["pid"])
52
58
  )
53
59
  if state != "active" or not process_identity.listener_owned(p["port"], pid):
54
60
  return False
55
61
  return (
56
- remote_ops._http(root + health_path, p["api_key"], timeout=5).get("status", "ok")
57
- in remote_ops.READY
62
+ remote_ops_common.http_json(root + health_path, p["api_key"], timeout=5).get("status", "ok")
63
+ in remote_ops_common.READY
64
+ )
65
+
66
+
67
+ def _evaluate_chat_answer(content: str, reasoning: str, *, smoke: bool) -> tuple[bool, str, str]:
68
+ if smoke:
69
+ text = content.strip() or reasoning.strip()
70
+ return bool(text), text[:200], "the smoke completion was empty"
71
+ blob = content + " " + reasoning
72
+ return (
73
+ remote_ops_common.TOUCH_EXPECT in blob.lower(),
74
+ content[:200],
75
+ f"the answer lacks {remote_ops_common.TOUCH_EXPECT!r}",
58
76
  )
59
77
 
60
78
 
61
- def act_verify(p: remote_ops.VerifyParams) -> None:
79
+ def act_verify(p: remote_ops_common.VerifyParams) -> None:
62
80
  """Readiness is a real generation, never /health alone (Hermes' touch generation)."""
63
- paths = remote_ops._paths(p)
81
+ paths = remote_ops_common.paths(p)
64
82
  base_restarts = _restarts(p) if p["service_kind"] == "systemd-user" else 0
65
83
  root = f"http://127.0.0.1:{p['port']}"
66
84
  deadline = time.monotonic() + p.get("timeout_s", 900)
@@ -72,39 +90,51 @@ def act_verify(p: remote_ops.VerifyParams) -> None:
72
90
  except (urllib.error.URLError, OSError, ValueError):
73
91
  pass
74
92
  if p["service_kind"] == "systemd-user":
75
- _, state = remote_ops._systemctl("is-active", p["service"] + ".service")
93
+ _, state = remote_ops_common.systemctl("is-active", p["service"] + ".service")
76
94
  if state in ("failed", "inactive"):
77
95
  raise RuntimeError(
78
- f"the service exited ({state}). Log tail:\n{remote_ops._log_tail(paths)}"
96
+ f"the service exited ({state}). Log tail:\n{remote_ops_common.log_tail(paths)}"
79
97
  )
80
98
  restarts = _restarts(p) - base_restarts
81
- if restarts >= remote_ops.CRASH_RESTARTS:
99
+ if restarts >= remote_ops_common.CRASH_RESTARTS:
82
100
  # Restart=on-failure would retry forever; this service is ours to stop.
83
- remote_ops._systemctl("stop", p["service"] + ".service")
101
+ remote_ops_common.systemctl("stop", p["service"] + ".service")
84
102
  raise RuntimeError(
85
103
  f"the service kept exiting after start ({restarts} restarts this time) and was stopped. "
86
- f"Log tail:\n{remote_ops._log_tail(paths)}"
104
+ f"Log tail:\n{remote_ops_common.log_tail(paths)}"
87
105
  )
88
106
  elif (
89
107
  remote_ops_launchd.status(p["deploy_dir"])[0] != "active"
90
108
  if p["service_kind"] == "launchd-user"
91
- else remote_ops._pid_alive(paths["pid"]) is None
109
+ else remote_ops_common.pid_alive(paths["pid"]) is None
92
110
  ):
93
- raise RuntimeError("the process exited. Log tail:\n" + remote_ops._log_tail(paths))
111
+ raise RuntimeError(
112
+ "the process exited. Log tail:\n" + remote_ops_common.log_tail(paths)
113
+ )
94
114
  if time.monotonic() > deadline:
95
115
  raise RuntimeError(
96
- "timed out waiting for the model to load. Log tail:\n" + remote_ops._log_tail(paths)
116
+ "timed out waiting for the model to load. Log tail:\n"
117
+ + remote_ops_common.log_tail(paths)
97
118
  )
98
- remote_ops.emit("progress", phase="loading")
119
+ remote_ops_common.emit("progress", phase="loading")
99
120
  time.sleep(3)
100
121
  contract = p.get("contract")
101
122
  if contract in CONTRACTS:
102
123
  CONTRACTS[contract](root, p)
103
124
  return
104
125
  started = time.monotonic()
105
- messages = [{"role": "user", "content": remote_ops.TOUCH_PROMPT}]
106
- body = {"model": p["model_alias"], "messages": messages, "max_tokens": 512, "temperature": 0}
107
- resp = remote_ops._http(root + "/v1/chat/completions", p["api_key"], body, timeout=300)
126
+ smoke = bool(p.get("smoke"))
127
+ prompt = "Reply with OK." if smoke else remote_ops_common.TOUCH_PROMPT
128
+ messages = [{"role": "user", "content": prompt}]
129
+ body = {
130
+ "model": p["model_alias"],
131
+ "messages": messages,
132
+ "max_tokens": 16 if smoke else 512,
133
+ "temperature": 0,
134
+ }
135
+ resp = remote_ops_common.http_json(
136
+ root + "/v1/chat/completions", p["api_key"], body, timeout=300
137
+ )
108
138
  choices = resp.get("choices")
109
139
  if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
110
140
  raise ValueError("missing completion choices")
@@ -114,11 +144,9 @@ def act_verify(p: remote_ops.VerifyParams) -> None:
114
144
  content, reasoning = msg.get("content") or "", msg.get("reasoning_content") or ""
115
145
  if not isinstance(content, str) or not isinstance(reasoning, str):
116
146
  raise ValueError("invalid completion text")
117
- blob = content + " " + reasoning
118
147
  build_info, n_ctx = _served(root, p)
119
148
  extra = {"build_info": build_info, "n_ctx": n_ctx, "usage": resp.get("usage")}
120
- answer, failure = content[:200], f"the answer lacks {remote_ops.TOUCH_EXPECT!r}"
121
- ok = remote_ops.TOUCH_EXPECT in blob.lower()
149
+ ok, answer, failure = _evaluate_chat_answer(content, reasoning, smoke=smoke)
122
150
  short = _short_window(p, n_ctx)
123
151
  if ok and short:
124
152
  ok, failure = False, short
@@ -129,7 +157,7 @@ def act_verify(p: remote_ops.VerifyParams) -> None:
129
157
  _report(ok, answer, started, failure, timings=resp.get("timings"), **extra, **_released(ok, p))
130
158
 
131
159
 
132
- def _released(ok: bool, p: remote_ops.VerifyParams) -> dict[str, int]:
160
+ def _released(ok: bool, p: remote_ops_common.VerifyParams) -> dict[str, int]:
133
161
  """Windows keeps the pages a model was read through in the server's working set after the
134
162
  weights are in VRAM, until memory runs short: 4.9 GiB for a 4.1 GiB model. Given back once
135
163
  the server has answered, they left 4.5 GB more available in 0.4 s and the next request was
@@ -137,23 +165,23 @@ def _released(ok: bool, p: remote_ops.VerifyParams) -> dict[str, int]:
137
165
  for a model with weights in host memory, a failed check, or another system."""
138
166
  if not ok or not p.get("weights_on_gpu") or sys.platform != "win32":
139
167
  return {}
140
- state, pid = process_identity.status(remote_ops._paths(p)["pid"])
168
+ state, pid = process_identity.status(remote_ops_common.paths(p)["pid"])
141
169
  freed = process_identity.release_working_set(pid) if state == "active" and pid else 0
142
170
  return {"released_bytes": freed}
143
171
 
144
172
 
145
- def _served(root: str, p: remote_ops.VerifyParams) -> tuple[object, object]:
173
+ def _served(root: str, p: remote_ops_common.VerifyParams) -> tuple[object, object]:
146
174
  """llama-server's build and per-slot window from /props; (None, None) when it does not say."""
147
175
  props = {}
148
176
  try:
149
- props = remote_ops._http(root + "/props", p["api_key"], timeout=5)
177
+ props = remote_ops_common.http_json(root + "/props", p["api_key"], timeout=5)
150
178
  except (urllib.error.URLError, OSError, ValueError):
151
179
  pass
152
180
  dgs = props.get("default_generation_settings")
153
181
  return props.get("build_info"), dgs.get("n_ctx") if isinstance(dgs, dict) else None
154
182
 
155
183
 
156
- def _short_window(p: remote_ops.VerifyParams, n_ctx: object) -> str:
184
+ def _short_window(p: remote_ops_common.VerifyParams, n_ctx: object) -> str:
157
185
  """Why the served window falls short of the planned one, "" when it does not or is unknown.
158
186
  llama-server pads -c up to a multiple of 256 (200000 serves 200192), so at least the plan."""
159
187
  window = p.get("window")
@@ -181,7 +209,7 @@ def _solid_png(rgb: tuple[int, int, int], side: int = 224) -> bytes:
181
209
  )
182
210
 
183
211
 
184
- def _picture_answer(root: str, p: remote_ops.VerifyParams) -> str:
212
+ def _picture_answer(root: str, p: remote_ops_common.VerifyParams) -> str:
185
213
  """The model's answer, with its reasoning, about a synthetic red picture (decision 31)."""
186
214
  image = "data:image/png;base64," + base64.b64encode(_solid_png((220, 20, 20))).decode()
187
215
  parts = [
@@ -194,7 +222,9 @@ def _picture_answer(root: str, p: remote_ops.VerifyParams) -> str:
194
222
  "max_tokens": 512,
195
223
  "temperature": 0,
196
224
  }
197
- resp = remote_ops._http(root + "/v1/chat/completions", p["api_key"], body, timeout=300)
225
+ resp = remote_ops_common.http_json(
226
+ root + "/v1/chat/completions", p["api_key"], body, timeout=300
227
+ )
198
228
  choices = resp.get("choices")
199
229
  if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
200
230
  raise ValueError("missing picture completion choices")
@@ -207,12 +237,16 @@ def _picture_answer(root: str, p: remote_ops.VerifyParams) -> str:
207
237
  return content + " " + reasoning
208
238
 
209
239
 
210
- def _verify_decision(root: str, p: remote_ops.VerifyParams) -> None:
240
+ def _verify_decision(root: str, p: remote_ops_common.VerifyParams) -> None:
211
241
  """Readiness of a System One model is a probability for an unambiguous question."""
212
242
  started = time.monotonic()
213
- body = {"model": p["model_alias"], "state": remote_ops.DECISION_STATE, "questions": {}}
214
- body["questions"] = {"outage": remote_ops.DECISION_QUESTION}
215
- resp = remote_ops._http(root + "/v1/systemone", p["api_key"], body, timeout=300)
243
+ body = {
244
+ "model": p["model_alias"],
245
+ "state": remote_ops_common.DECISION_STATE,
246
+ "questions": {},
247
+ }
248
+ body["questions"] = {"outage": remote_ops_common.DECISION_QUESTION}
249
+ resp = remote_ops_common.http_json(root + "/v1/systemone", p["api_key"], body, timeout=300)
216
250
  answers = resp.get("answers")
217
251
  answer = answers.get("outage") if isinstance(answers, dict) else None
218
252
  noul = answer.get("noul") if isinstance(answer, dict) else None
@@ -236,18 +270,20 @@ def _finite(values: object) -> list[float]:
236
270
 
237
271
 
238
272
  def _report(ok: bool, answer: str, started: float, failure: str, **extra: object) -> None:
239
- remote_ops.emit(
273
+ remote_ops_common.emit(
240
274
  "result", ready=ok, answer=answer, seconds=round(time.monotonic() - started, 2), **extra
241
275
  )
242
276
  if not ok:
243
277
  raise RuntimeError("readiness check failed: " + failure)
244
278
 
245
279
 
246
- def _sized(root: str, p: remote_ops.VerifyParams, tokens: int) -> tuple[str, int]:
280
+ def _sized(root: str, p: remote_ops_common.VerifyParams, tokens: int) -> tuple[str, int]:
247
281
  """Text of about ``tokens`` tokens and its count, both from the server's own tokenizer."""
248
282
 
249
283
  def count(text: str) -> int:
250
- found = remote_ops._http(root + "/tokenize", p["api_key"], {"content": text}, timeout=60)
284
+ found = remote_ops_common.http_json(
285
+ root + "/tokenize", p["api_key"], {"content": text}, timeout=60
286
+ )
251
287
  if not isinstance(found.get("tokens"), list):
252
288
  raise ValueError("invalid /tokenize response")
253
289
  return len(cast("list[object]", found["tokens"]))
@@ -256,7 +292,9 @@ def _sized(root: str, p: remote_ops.VerifyParams, tokens: int) -> tuple[str, int
256
292
  return text, count(text)
257
293
 
258
294
 
259
- def _input_limit(root: str, p: remote_ops.VerifyParams, send: Callable[[str], object]) -> str:
295
+ def _input_limit(
296
+ root: str, p: remote_ops_common.VerifyParams, send: Callable[[str], object]
297
+ ) -> str:
260
298
  """The declared token limit holds: an input just under it is served; one just over it
261
299
  refuses the whole request with an HTTP error instead of being truncated, and the service
262
300
  keeps answering."""
@@ -284,12 +322,18 @@ def _input_limit(root: str, p: remote_ops.VerifyParams, send: Callable[[str], ob
284
322
  return f" limit={limit}: {served} served, {refused} refused"
285
323
 
286
324
 
287
- def _verify_embedding(root: str, p: remote_ops.VerifyParams) -> None:
325
+ def _verify_embedding(root: str, p: remote_ops_common.VerifyParams) -> None:
288
326
  """Finite unit vectors of one width; a paraphrase lands nearer than an unrelated sentence."""
289
327
  started = time.monotonic()
290
- texts = [remote_ops.EMBED_QUERY, remote_ops.EMBED_NEAR, remote_ops.EMBED_FAR]
328
+ texts = [
329
+ remote_ops_common.EMBED_QUERY,
330
+ remote_ops_common.EMBED_NEAR,
331
+ remote_ops_common.EMBED_FAR,
332
+ ]
291
333
  body = {"model": p["model_alias"], "input": texts}
292
- data = remote_ops._http(root + "/v1/embeddings", p["api_key"], body, timeout=120).get("data")
334
+ data = remote_ops_common.http_json(
335
+ root + "/v1/embeddings", p["api_key"], body, timeout=120
336
+ ).get("data")
293
337
  if (
294
338
  not isinstance(data, list)
295
339
  or len(data) != len(texts)
@@ -315,24 +359,26 @@ def _verify_embedding(root: str, p: remote_ops.VerifyParams) -> None:
315
359
  answer += _input_limit(
316
360
  root,
317
361
  p,
318
- lambda text: remote_ops._http(
362
+ lambda text: remote_ops_common.http_json(
319
363
  root + "/v1/embeddings", p["api_key"], {**body, "input": [text]}, timeout=300
320
364
  ),
321
365
  )
322
366
  _report(all(abs(n - 1) < 1e-2 for n in norms) and near > far, answer, started, answer)
323
367
 
324
368
 
325
- def _verify_rerank(root: str, p: remote_ops.VerifyParams) -> None:
369
+ def _verify_rerank(root: str, p: remote_ops_common.VerifyParams) -> None:
326
370
  """The known relevant document, not placed first, must rank first. llama-server returns the
327
371
  results sorted by score and cut to ``top_n``, so ask for every document."""
328
- started, docs = time.monotonic(), remote_ops.RERANK_DOCS
372
+ started, docs = time.monotonic(), remote_ops_common.RERANK_DOCS
329
373
  body = {
330
374
  "model": p["model_alias"],
331
- "query": remote_ops.RERANK_QUERY,
375
+ "query": remote_ops_common.RERANK_QUERY,
332
376
  "documents": docs,
333
377
  "top_n": len(docs),
334
378
  }
335
- results = remote_ops._http(root + "/v1/rerank", p["api_key"], body, timeout=120).get("results")
379
+ results = remote_ops_common.http_json(root + "/v1/rerank", p["api_key"], body, timeout=120).get(
380
+ "results"
381
+ )
336
382
  if not isinstance(results, list) or not all(isinstance(r, dict) for r in results):
337
383
  raise ValueError("invalid rerank results")
338
384
  scored: list[tuple[float, int]] = []
@@ -341,7 +387,7 @@ def _verify_rerank(root: str, p: remote_ops.VerifyParams) -> None:
341
387
  if type(index) is not int:
342
388
  raise ValueError("invalid rerank index")
343
389
  scored.append((_finite([result.get("relevance_score")])[0], index))
344
- if sorted(i for _, i in scored) != list(range(len(remote_ops.RERANK_DOCS))):
390
+ if sorted(i for _, i in scored) != list(range(len(remote_ops_common.RERANK_DOCS))):
345
391
  raise ValueError("rerank indices do not cover every document")
346
392
  if any(scored[i][0] < scored[i + 1][0] for i in range(len(scored) - 1)):
347
393
  raise ValueError("rerank results are not sorted by descending score")
@@ -351,7 +397,7 @@ def _verify_rerank(root: str, p: remote_ops.VerifyParams) -> None:
351
397
  limit = _input_limit(
352
398
  root,
353
399
  p,
354
- lambda text: remote_ops._http(
400
+ lambda text: remote_ops_common.http_json(
355
401
  root + "/v1/rerank",
356
402
  p["api_key"],
357
403
  {**body, "documents": [text], "top_n": 1},
@@ -359,18 +405,20 @@ def _verify_rerank(root: str, p: remote_ops.VerifyParams) -> None:
359
405
  ),
360
406
  )
361
407
  _report(
362
- best == remote_ops.RERANK_RELEVANT,
408
+ best == remote_ops_common.RERANK_RELEVANT,
363
409
  f"top={best}{limit}",
364
410
  started,
365
411
  f"document {best} ranked first",
366
412
  )
367
413
 
368
414
 
369
- def _verify_stt(root: str, p: remote_ops.VerifyParams) -> None:
415
+ def verify_stt(root: str, p: remote_ops_common.VerifyParams) -> None:
370
416
  """A pinned recording transcribes to text containing its known phrase."""
371
417
  fx = p.get("fixture") or {}
372
- dest = os.path.join(remote_ops._expand(p["deploy_dir"]), str(fx["name"]))
373
- remote_ops.fetch(str(fx["url"]), dest, str(fx["sha256"]), int(str(fx["size_bytes"])), dest)
418
+ dest = os.path.join(remote_ops_common.expand(p["deploy_dir"]), str(fx["name"]))
419
+ remote_ops_download.fetch(
420
+ str(fx["url"]), dest, str(fx["sha256"]), int(str(fx["size_bytes"])), dest
421
+ )
374
422
  with open(dest, "rb") as f:
375
423
  audio = f.read()
376
424
  mark = "--localmodels" + hashlib.sha256(audio).hexdigest()[:16]
@@ -380,7 +428,7 @@ def _verify_stt(root: str, p: remote_ops.VerifyParams) -> None:
380
428
  body += f"\r\n{mark}--\r\n".encode()
381
429
  kind, started = "multipart/form-data; boundary=" + mark[2:], time.monotonic()
382
430
  resp = json.loads(
383
- remote_ops._request(root + str(fx["path"]), p["api_key"], body, kind, 300) or b"{}"
431
+ remote_ops_common.request(root + str(fx["path"]), p["api_key"], body, kind, 300) or b"{}"
384
432
  )
385
433
  text = resp.get("text") if isinstance(resp, dict) else None
386
434
  if not isinstance(text, str):
@@ -390,15 +438,15 @@ def _verify_stt(root: str, p: remote_ops.VerifyParams) -> None:
390
438
  _report(ok, text.strip()[:120], started, f"the transcript lacks {expect!r}")
391
439
 
392
440
 
393
- def _verify_tts(root: str, p: remote_ops.VerifyParams) -> None:
441
+ def _verify_tts(root: str, p: remote_ops_common.VerifyParams) -> None:
394
442
  """Each fixture sentence (Chinese and English: both G2P paths) comes back as audible 16-bit
395
443
  mono WAV of a sentence's length. Whether it says the words is a round trip through STT."""
396
444
  started, heard = time.monotonic(), []
397
445
  samples = cast("list[dict[str, str]]", (p.get("fixture") or {}).get("samples") or [])
398
446
  for s in samples:
399
447
  body = json.dumps({"model": p["model_alias"], "voice": s["voice"], "input": s["input"]})
400
- audio = remote_ops._request(
401
- root + "/v1/audio/speech", p["api_key"], body.encode(), remote_ops.JSON, 300
448
+ audio = remote_ops_common.request(
449
+ root + "/v1/audio/speech", p["api_key"], body.encode(), remote_ops_common.JSON, 300
402
450
  )
403
451
  with wave.open(io.BytesIO(audio)) as w:
404
452
  mono16, frames = (w.getnchannels(), w.getsampwidth()) == (1, 2), w.getnframes()
@@ -417,11 +465,11 @@ def _verify_tts(root: str, p: remote_ops.VerifyParams) -> None:
417
465
 
418
466
  CONTRACTS = {
419
467
  "systemone": _verify_decision,
420
- "health": lambda root, p: remote_ops.emit(
468
+ "health": lambda root, p: remote_ops_common.emit(
421
469
  "result", ready=True
422
470
  ), # behind a front that checks it
423
471
  "embedding": _verify_embedding,
424
472
  "rerank": _verify_rerank,
425
- "stt": _verify_stt,
473
+ "stt": verify_stt,
426
474
  "tts": _verify_tts,
427
475
  }
@@ -2,7 +2,7 @@
2
2
  "schema": "localmodels.runtime-lock/v1",
3
3
  "versions": {
4
4
  "codex": "0.171.0",
5
- "claude": "2.1.325"
5
+ "claude": "2.1.326"
6
6
  },
7
7
  "baselines": {
8
8
  "codex": "0.166.0",
@@ -62,60 +62,60 @@
62
62
  ],
63
63
  "claude/win32-arm64": [
64
64
  {
65
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.325/win32-arm64/claude.exe",
65
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.326/win32-arm64/claude.exe",
66
66
  "algorithm": "sha256",
67
- "digest": "45c1d546a0048dcdde3433ada6c10f7f23bd71a96868b9d75e28f1ac266f1a25",
68
- "maxBytes": 354470048,
67
+ "digest": "12042740540c184b351274c11aa808252796770626ce990be740dd0d11d67e5b",
68
+ "maxBytes": 360077472,
69
69
  "format": "binary",
70
70
  "executable": "claude.exe"
71
71
  }
72
72
  ],
73
73
  "claude/win32-x64": [
74
74
  {
75
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.325/win32-x64/claude.exe",
75
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.326/win32-x64/claude.exe",
76
76
  "algorithm": "sha256",
77
- "digest": "87e0cb6ae0f4775da388cd3043f4d8097ef961dcddbf55fe90bc61ffc3f57a30",
78
- "maxBytes": 372461728,
77
+ "digest": "44e85ac6d3e36b924a0d631d3f69c13a6907491115d71e97c8eb6160c82b2aed",
78
+ "maxBytes": 378067616,
79
79
  "format": "binary",
80
80
  "executable": "claude.exe"
81
81
  }
82
82
  ],
83
83
  "claude/darwin-arm64": [
84
84
  {
85
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.325/darwin-arm64/claude",
85
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.326/darwin-arm64/claude",
86
86
  "algorithm": "sha256",
87
- "digest": "84590fefe6338be9087f5814b61f9a54c5f21524163a4c127cb5a808e31009f2",
88
- "maxBytes": 347406976,
87
+ "digest": "e214ad76dcc0e846b03be28ed1c2734aacd4e27acb527cb7f8a9e2bed644e837",
88
+ "maxBytes": 353037664,
89
89
  "format": "binary",
90
90
  "executable": "claude"
91
91
  }
92
92
  ],
93
93
  "claude/darwin-x64": [
94
94
  {
95
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.325/darwin-x64/claude",
95
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.326/darwin-x64/claude",
96
96
  "algorithm": "sha256",
97
- "digest": "af9760c59f947044e2a0d5072343de563f31efb68bd18ccee4f43c5240570de7",
98
- "maxBytes": 362162560,
97
+ "digest": "bd8e26290f93353590b831600a7ced02d625018fbaa2a82d8817368d3e2d2f82",
98
+ "maxBytes": 367809664,
99
99
  "format": "binary",
100
100
  "executable": "claude"
101
101
  }
102
102
  ],
103
103
  "claude/linux-arm64": [
104
104
  {
105
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.325/linux-arm64/claude",
105
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.326/linux-arm64/claude",
106
106
  "algorithm": "sha256",
107
- "digest": "7b6e484b1989a5a14a4b354709ccc8672518a3ec5b9ccd7981fc6254327fde67",
108
- "maxBytes": 364701112,
107
+ "digest": "98d56f6ffe53469767a74864a38eaf359d62ef557a8de1b1ad524d61a66ec119",
108
+ "maxBytes": 370271672,
109
109
  "format": "binary",
110
110
  "executable": "claude"
111
111
  }
112
112
  ],
113
113
  "claude/linux-x64": [
114
114
  {
115
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.325/linux-x64/claude",
115
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.326/linux-x64/claude",
116
116
  "algorithm": "sha256",
117
- "digest": "0dc4f4a9a165fc60746d7ae8489712e5fc352f1e7ad4eb22e7141bd0812eb0cf",
118
- "maxBytes": 365842960,
117
+ "digest": "b6b3647d981130dc44fc670846ae97b6cde531ffb667cf9c4d17cfcafb38cb37",
118
+ "maxBytes": 371429904,
119
119
  "format": "binary",
120
120
  "executable": "claude"
121
121
  }
@@ -47,18 +47,25 @@ RUNTIMES = ("codex", "claude", "pi")
47
47
  LOCK = Path(__file__).with_name("runtime-lock.json")
48
48
  PROFILE_KEYS = {"codex": "CODEX_HOME", "claude": "CLAUDE_CONFIG_DIR", "pi": "PI_CODING_AGENT_DIR"}
49
49
  PROFILE_DIRS = {"codex": ".codex", "claude": ".claude", "pi": ".pi/agent"}
50
- _platform = runtime_discovery.platform_tag
50
+ platform = runtime_discovery.platform_tag
51
+ _platform = platform
51
52
 
52
53
 
53
- def _owned_profile(directory: Path) -> bool:
54
+ def owned_profile(directory: Path) -> bool:
54
55
  files = owned_files(directory) if _private_file(directory / "localmodels-auth.json") else {}
55
56
  return bool(files) and all(_private_file(directory / name) for name in files)
56
57
 
57
58
 
58
- def _active_profile(runtime: str, env: dict[str, str]) -> Path:
59
+ _owned_profile = owned_profile
60
+
61
+
62
+ def active_profile(runtime: str, env: dict[str, str]) -> Path:
59
63
  return Path(env.get(PROFILE_KEYS[runtime], str(Path.home() / PROFILE_DIRS[runtime])))
60
64
 
61
65
 
66
+ _active_profile = active_profile
67
+
68
+
62
69
  def _probe(
63
70
  argv: list[str], env: dict[str, str] | None = None, *, timeout: float = 5
64
71
  ) -> tuple[int, str]:
@@ -139,15 +146,18 @@ def _managed_command(root: Path, runtime: str, node: str | None = None) -> list[
139
146
  return [str(target / artifacts[0]["executable"])] if artifacts else []
140
147
 
141
148
 
142
- def _runtime_env(root: Path, runtime: str) -> dict[str, str]:
149
+ def runtime_env(root: Path, runtime: str) -> dict[str, str]:
143
150
  env = dict(os.environ)
144
151
  directory = root / "runtime" / runtime
145
152
  validate_runtime_root(directory)
146
- if _owned_profile(directory):
153
+ if owned_profile(directory):
147
154
  env[PROFILE_KEYS[runtime]] = str(directory)
148
155
  return env
149
156
 
150
157
 
158
+ _runtime_env = runtime_env
159
+
160
+
151
161
  def _credential_ambiguous(
152
162
  runtime: str, profile: Path, owned: dict[str, str], env: dict[str, str]
153
163
  ) -> bool:
@@ -21,7 +21,7 @@ import urllib.parse
21
21
  import urllib.request
22
22
  import zipfile
23
23
  from collections import deque
24
- from collections.abc import Callable
24
+ from collections.abc import Callable, Mapping
25
25
  from pathlib import Path
26
26
  from typing import Any, cast
27
27
 
@@ -654,6 +654,59 @@ def cached_download(
654
654
  return kept
655
655
 
656
656
 
657
+ def _archive_pin(build: Mapping[str, Any]) -> tuple[str, int]:
658
+ """The npm tarball's SHA256 and size, which every Bifrost build of the tool lock carries."""
659
+ pin = build["npm"]
660
+ digest, size = pin.get("sha256"), pin.get("bytes")
661
+ if (
662
+ not isinstance(digest, str)
663
+ or not re.fullmatch("[0-9a-f]{64}", digest)
664
+ or type(size) is not int
665
+ or not 0 < size <= npm_transport.archive_size_cap(build["size_bytes"])
666
+ ):
667
+ raise ValueError(
668
+ "Bifrost npm archive pin is missing or invalid (the tool lock needs npm sha256 and"
669
+ " bytes)"
670
+ )
671
+ return digest, size
672
+
673
+
674
+ def _sha256(path: Path) -> str:
675
+ digest = hashlib.sha256()
676
+ with path.open("rb") as stream:
677
+ for chunk in iter(lambda: stream.read(1 << 20), b""):
678
+ digest.update(chunk)
679
+ return digest.hexdigest()
680
+
681
+
682
+ def fetch_bifrost(
683
+ build: Mapping[str, Any],
684
+ destination: Path,
685
+ archive: Path,
686
+ event: Event,
687
+ ) -> None:
688
+ """Put the pinned Bifrost binary of ``build`` at ``destination``. The npm tarball downloads
689
+ to ``archive``, which must outlive this call: an interrupted download keeps
690
+ ``archive.part`` for the next call to resume (``download``, which also moves between the npm
691
+ registry and its mirror), and a complete tarball left by a crash before extraction is reused
692
+ when it matches the pin. The tarball is deleted once extracted."""
693
+ digest, size = _archive_pin(build)
694
+ if archive.exists() or archive.is_symlink():
695
+ if archive.is_file() and not archive.is_symlink() and _sha256(archive) == digest:
696
+ event({"kind": "stage", "stage": "download", "state": "reused"})
697
+ else:
698
+ archive.unlink()
699
+ if not archive.exists():
700
+ pin = build["npm"]
701
+ url = npm_transport.check_url(
702
+ npm_transport.package_url(pin["package"], pin["version"], "global", os.environ)
703
+ )
704
+ artifact = {"url": url, "algorithm": "sha256", "digest": digest, "maxBytes": size}
705
+ download(artifact, archive, event)
706
+ npm_transport.extract_bifrost(archive, destination, build["sha256"], build["size_bytes"])
707
+ archive.unlink()
708
+
709
+
657
710
  def error_cause(error: BaseException) -> str:
658
711
  """What went wrong, without native tool output or anything read from the network."""
659
712
  if isinstance(error, RuntimeDownloadError):