@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37

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 (126) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +124 -102
  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_config.py +188 -0
  7. package/modules/localmodels/budget.py +15 -2
  8. package/modules/localmodels/catalog.json +235 -2
  9. package/modules/localmodels/catalog.py +51 -320
  10. package/modules/localmodels/catalog_add.py +2 -8
  11. package/modules/localmodels/catalog_recipes.py +321 -0
  12. package/modules/localmodels/cli_parser.py +4 -1
  13. package/modules/localmodels/console.py +5 -4
  14. package/modules/localmodels/contracts.py +13 -3
  15. package/modules/localmodels/debug_cli.py +158 -0
  16. package/modules/localmodels/debug_mode.py +727 -0
  17. package/modules/localmodels/debug_stub_server.py +192 -0
  18. package/modules/localmodels/decode_calibration.json +1 -1
  19. package/modules/localmodels/decode_calibration.py +34 -17
  20. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  21. package/modules/localmodels/gateway.py +21 -155
  22. package/modules/localmodels/gateway_accept.py +201 -0
  23. package/modules/localmodels/gateway_bifrost.py +19 -184
  24. package/modules/localmodels/gateway_cli.py +11 -4
  25. package/modules/localmodels/gateway_foundations.py +2 -4
  26. package/modules/localmodels/gateway_probe.py +0 -1
  27. package/modules/localmodels/gateway_server.py +2 -3
  28. package/modules/localmodels/gpu_specs.py +12 -0
  29. package/modules/localmodels/guard.py +2 -7
  30. package/modules/localmodels/harness.py +16 -129
  31. package/modules/localmodels/harness_cleanup.py +135 -0
  32. package/modules/localmodels/harness_gateway.py +16 -14
  33. package/modules/localmodels/harness_probe.py +12 -4
  34. package/modules/localmodels/hosts.py +25 -2
  35. package/modules/localmodels/http_local.py +59 -0
  36. package/modules/localmodels/install.py +23 -8
  37. package/modules/localmodels/library_gateway.py +9 -9
  38. package/modules/localmodels/library_jobs.py +76 -27
  39. package/modules/localmodels/library_serve.py +12 -1
  40. package/modules/localmodels/library_state.py +6 -1
  41. package/modules/localmodels/llm_rank.py +155 -7
  42. package/modules/localmodels/metal_probe.py +11 -7
  43. package/modules/localmodels/probe.py +108 -174
  44. package/modules/localmodels/process_identity.py +109 -154
  45. package/modules/localmodels/process_windows.py +86 -0
  46. package/modules/localmodels/recommend.py +32 -3
  47. package/modules/localmodels/recommend_cli.py +14 -6
  48. package/modules/localmodels/remote_ops.py +65 -0
  49. package/modules/localmodels/remote_ops_download.py +2 -2
  50. package/modules/localmodels/remote_ops_prepare.py +19 -0
  51. package/modules/localmodels/remote_ops_service.py +14 -2
  52. package/modules/localmodels/runtime_args.py +10 -3
  53. package/modules/localmodels/runtime_auth.py +5 -9
  54. package/modules/localmodels/runtime_cli.py +128 -129
  55. package/modules/localmodels/runtime_discovery.py +84 -0
  56. package/modules/localmodels/runtime_install.py +101 -0
  57. package/modules/localmodels/runtime_releases.py +302 -0
  58. package/modules/localmodels/service_stop.py +8 -108
  59. package/modules/localmodels/service_upgrade.py +394 -63
  60. package/modules/localmodels/services_cli.py +24 -14
  61. package/modules/localmodels/setup_inspection.py +97 -9
  62. package/modules/localmodels/setup_text.py +7 -0
  63. package/modules/localmodels/sizecalc.py +0 -1
  64. package/modules/localmodels/stack.py +14 -221
  65. package/modules/localmodels/stack_arena.py +732 -0
  66. package/modules/localmodels/stack_args.py +15 -9
  67. package/modules/localmodels/stack_auto.py +384 -3
  68. package/modules/localmodels/stack_aux_gpu.py +4 -3
  69. package/modules/localmodels/stack_capacity.py +138 -0
  70. package/modules/localmodels/stack_cleanup.py +9 -4
  71. package/modules/localmodels/stack_cli.py +286 -0
  72. package/modules/localmodels/stack_compose.py +76 -32
  73. package/modules/localmodels/stack_console.py +9 -6
  74. package/modules/localmodels/stack_hardware.py +96 -270
  75. package/modules/localmodels/stack_hardware_text.py +263 -0
  76. package/modules/localmodels/stack_journal.py +3 -9
  77. package/modules/localmodels/stack_ledger.py +48 -18
  78. package/modules/localmodels/stack_lifecycle.py +33 -312
  79. package/modules/localmodels/stack_mcp.py +729 -0
  80. package/modules/localmodels/stack_memory.py +0 -2
  81. package/modules/localmodels/stack_picks.py +73 -18
  82. package/modules/localmodels/stack_plan.py +23 -5
  83. package/modules/localmodels/stack_preflight.py +11 -19
  84. package/modules/localmodels/stack_remove.py +373 -0
  85. package/modules/localmodels/stack_route.py +101 -17
  86. package/modules/localmodels/stack_suite.py +16 -10
  87. package/modules/localmodels/stack_summary.py +14 -0
  88. package/modules/localmodels/stack_try.py +238 -24
  89. package/modules/localmodels/stack_try_client.py +53 -15
  90. package/modules/localmodels/stack_try_docs.py +2 -2
  91. package/modules/localmodels/stack_view.py +24 -171
  92. package/modules/localmodels/stack_view_access.py +114 -1
  93. package/modules/localmodels/stack_view_agent.py +3 -13
  94. package/modules/localmodels/stack_view_hub.py +9 -10
  95. package/modules/localmodels/stack_view_llm.py +1 -1
  96. package/modules/localmodels/stack_view_sandbox.py +2 -2
  97. package/modules/localmodels/stack_view_schema.py +183 -0
  98. package/modules/localmodels/stack_view_serve.py +7 -1
  99. package/modules/localmodels/stack_view_service.py +1 -2
  100. package/modules/localmodels/stack_view_text.py +13 -9
  101. package/modules/localmodels/stack_warm.py +3 -0
  102. package/modules/localmodels/stack_warm_store.py +517 -0
  103. package/modules/localmodels/tui.py +28 -4
  104. package/modules/localmodels/tui_dialogs.py +136 -0
  105. package/modules/localmodels/tui_modals.py +279 -0
  106. package/modules/localmodels/tui_screen.py +113 -154
  107. package/modules/localmodels/tui_views.py +134 -203
  108. package/modules/localmodels/web/index.html +510 -101
  109. package/modules/localmodels/web/sizecalc/app.js +363 -10
  110. package/modules/localmodels/web/sizecalc/page.html +27 -3
  111. package/modules/localmodels/web/view/fleet.html +11 -2
  112. package/modules/localmodels/web/view/fleet.js +191 -17
  113. package/modules/localmodels/web/view/i18n.js +3 -2
  114. package/modules/localmodels/web/view/index.html +1 -1
  115. package/modules/localmodels/web/view/nav.js +22 -3
  116. package/modules/localmodels/web/view/view.css +63 -18
  117. package/modules/localmodels/web/view/view.js +169 -32
  118. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  119. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
  120. package/package.json +1 -1
  121. package/tool.json +1 -1
  122. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  123. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  124. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  125. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,321 @@
1
+ """Component recipes and schema-3 validation helpers shared with localmodels.catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+ from typing import TypedDict, cast
10
+
11
+ from localmodels.contracts import decode
12
+
13
+ CATALOG_PATH = Path(__file__).with_name("catalog.json")
14
+ FIXTURE_DIR = Path(__file__).with_name("fixtures")
15
+
16
+ SCHEMA_VERSION = 3
17
+ STATUSES = ("candidate", "validated", "deprecated")
18
+ PLATFORMS = ("linux", "darwin", "win32") # validated_on: Linux, Apple Silicon Macs, Windows
19
+ EFFORT_LEVELS = ("low", "medium", "high") # reasoning_effort values a gateway may send, in order
20
+ TASKS = tuple("llm vision decision embedding reranker stt tts search privacy-span".split())
21
+ # intelligence_score: the installed SimplexAI score (decisions 26, 33); make check keeps it equal
22
+ QUALITY_SOURCE_TYPES = ("editorial", "own_eval", "external_index", "kld", "intelligence_score")
23
+
24
+
25
+ class QualitySource(TypedDict):
26
+ type: str # one of QUALITY_SOURCE_TYPES
27
+ ref: str # a run id, report path or citation; "editorial" names whose judgement it was
28
+ date: str
29
+
30
+
31
+ class AssetData(TypedDict):
32
+ path: str
33
+ size_bytes: int
34
+
35
+
36
+ class OptionalAssetData(AssetData, total=False):
37
+ local: str
38
+ repo: str
39
+ revision: str
40
+ sha256: str # with a 40-hex commit revision
41
+
42
+
43
+ class VariantData(TypedDict):
44
+ quant: str
45
+ files: list[OptionalAssetData]
46
+
47
+
48
+ class OptionalVariantData(VariantData, total=False):
49
+ validated: bool
50
+ lazy_bytes: int
51
+ embd_table_bytes: int
52
+ mtp_layer_bytes: int
53
+
54
+
55
+ class ModelData(TypedDict):
56
+ id: str
57
+ display_name: str
58
+ description: str
59
+ repo: str
60
+ variants: list[OptionalVariantData]
61
+ n_ctx_train: int
62
+ full_layers: int
63
+ recurrent_layers: int
64
+ per_layer_f16: int
65
+
66
+
67
+ class QualityData(TypedDict):
68
+ score: int
69
+ sources: list[QualitySource]
70
+
71
+
72
+ class ProvenanceData(TypedDict, total=False):
73
+ """Where an installable entry comes from and what governs its use. ``license`` is the license
74
+ a user must honour; a quantization of third-party weights inherits ``base_license`` from
75
+ ``base_model`` and names the quantizer's own ``artifact_license`` beside it."""
76
+
77
+ license: str
78
+ license_url: str
79
+ status: str # one of STATUSES
80
+ tasks: list[str] # TASKS; a component's own task is one of them
81
+ evidence: list[str] # catalog/<run id> or a report path; empty for an untested candidate
82
+ validated_on: list[str] # since 2026-10-29: the platforms its evidence covers, if not all
83
+ reasoning_efforts: list[str] # since 2026-10-30: the levels its template accepts, if not all
84
+ artifact_license: str
85
+ artifact_license_url: str
86
+ base_model: str
87
+ base_license: str
88
+ base_license_url: str
89
+
90
+
91
+ class OptionalModelData(ModelData, ProvenanceData, total=False):
92
+ runtime: str
93
+ swa_layers: int
94
+ swa_window: int
95
+ moe: bool
96
+ mtp: bool
97
+ mtp_draft_depth: int
98
+ agent_mtp: bool
99
+ n_vocab: int
100
+ sampling: dict[str, str]
101
+ min_engine: str
102
+ chat_template: str
103
+ quality: int | QualityData
104
+ decode_fraction: float
105
+ architecture: str
106
+ ssm_d_inner: int
107
+ ssm_d_state: int
108
+ ssm_d_conv: int
109
+ ssm_n_group: int
110
+ ssm_dt_rank: int
111
+ n_embd: int
112
+ tied_embeddings: bool
113
+ kv_k_only: bool
114
+ mmproj: OptionalAssetData | None
115
+ draft: OptionalAssetData | None
116
+ mtp_head: OptionalAssetData | None
117
+
118
+
119
+ class _ComponentFileOptional(TypedDict, total=False):
120
+ url: str # llama components: absolute URL off the Hub (self-quantized GGUF); suites: a template
121
+
122
+
123
+ class ComponentFile(_ComponentFileOptional):
124
+ path: str
125
+ size_bytes: int
126
+ sha256: str
127
+
128
+
129
+ class ComponentRecipe(ProvenanceData):
130
+ id: str
131
+ task: str
132
+ runtime: str
133
+ version: str
134
+ repo: str
135
+ revision: str
136
+ memory_estimate_bytes: int
137
+ files: list[ComponentFile]
138
+
139
+
140
+ class CatalogData(TypedDict):
141
+ schema_version: int
142
+ models: list[OptionalModelData]
143
+
144
+
145
+ class OptionalCatalogData(CatalogData, total=False):
146
+ components: list[ComponentRecipe]
147
+
148
+
149
+ class LlamaComponentRecipe(ComponentRecipe):
150
+ """A task component served by a pinned llama-server build (runtime llama.cpp-cpu, or
151
+ llama.cpp for a decision model, which only runs on a GPU)."""
152
+
153
+ engine: str # engine lock tag; engines-<tag>.json beside the catalog
154
+ alias: str
155
+ context: int # the default prompt cap; a decision prompt is one ubatch, so -c = -b = -ub
156
+ contract: str # the readiness request remote_ops sends, e.g. "systemone"
157
+ note: str
158
+
159
+
160
+ class DecisionTier(TypedDict):
161
+ """One prompt cap of a decision model, measured on lab-12021 (RTX 4090 D, llama.cpp b11583)."""
162
+
163
+ context: int
164
+ vram_bytes: int # peak of the llama-server process with a prompt of about 80% of the cap
165
+ index: (
166
+ float # Decision Index 0.3 public-index estimate, 14,000-row sample; refusals count wrong
167
+ )
168
+
169
+
170
+ class DecisionFrontend(TypedDict):
171
+ """startlux-decide in front of llama-server: the model folder's tokenizer and decision_config
172
+ plus the hash-locked package environment named by ``requirements`` beside the catalog."""
173
+
174
+ kind: str
175
+ repo: str
176
+ revision: str
177
+ files: list[ComponentFile]
178
+ requirements: str
179
+ memory_estimate_bytes: int
180
+
181
+
182
+ class _DecisionOptional(TypedDict, total=False):
183
+ frontend: DecisionFrontend # absent: llama-server answers /v1/systemone itself
184
+
185
+
186
+ class DecisionRecipe(LlamaComponentRecipe, _DecisionOptional):
187
+ """A Jev-like decision model. It only ever runs on a GPU: on a CPU it is 40-70 times slower
188
+ than on a GPU, which forfeits its System One role (AGENTS.md)."""
189
+
190
+ family: str
191
+ commercial_use: bool # False: the weights' license restricts commercial use
192
+ tiers: list[DecisionTier]
193
+ board: dict[str, float] # leaderboard public and full score, snapshot named in evidence
194
+ latency_ms: dict[str, float] # single-stream p50 on lab-12021: 1 and 16 questions
195
+ pros: list[str]
196
+ cons: list[str]
197
+
198
+
199
+ def components() -> list[ComponentRecipe]:
200
+ """Every task recipe in catalog order. Task recipes share the catalog, but never enter the
201
+ GGUF recommender."""
202
+ raw = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
203
+ return decode(raw.get("components", []), list[ComponentRecipe])
204
+
205
+
206
+ def component_recipe(model_id: str) -> ComponentRecipe:
207
+ return next(recipe for recipe in components() if recipe["id"] == model_id)
208
+
209
+
210
+ def llama_components(task: str) -> list[LlamaComponentRecipe]:
211
+ """llama-server task components in catalog order (the first is the default)."""
212
+ return [
213
+ decode(recipe, LlamaComponentRecipe)
214
+ for recipe in components()
215
+ if recipe["task"] == task and recipe["runtime"] in ("llama.cpp-cpu", "llama.cpp")
216
+ ]
217
+
218
+
219
+ def decision_components() -> list[DecisionRecipe]:
220
+ """Jev-like decision models in catalog order."""
221
+ return [decode(recipe, DecisionRecipe) for recipe in llama_components("decision")]
222
+
223
+
224
+ _REQUIRED_PROVENANCE = ("license", "license_url", "status", "tasks", "evidence")
225
+ _STRATA_PROVENANCE = (
226
+ "artifact_license",
227
+ "artifact_license_url",
228
+ "base_model",
229
+ "base_license",
230
+ "base_license_url",
231
+ )
232
+
233
+
234
+ def _entry_problems(
235
+ item: OptionalModelData | ComponentRecipe, task: str, runtime: str
236
+ ) -> list[str]:
237
+ fields = cast(dict[str, object], item)
238
+ required = _REQUIRED_PROVENANCE + (_STRATA_PROVENANCE if runtime == "strata" else ())
239
+ found = [
240
+ f"{key} is missing"
241
+ for key in required
242
+ if key not in fields or (key != "evidence" and not fields[key])
243
+ ]
244
+ found += [
245
+ f"{key} is not an https URL"
246
+ for key in ("license_url", "artifact_license_url", "base_license_url")
247
+ if fields.get(key) and not str(fields[key]).startswith("https://")
248
+ ]
249
+ if item.get("status") and item.get("status") not in STATUSES:
250
+ found.append(f"status is not one of {', '.join(STATUSES)}")
251
+ if item.get("status") == "validated" and not item.get("evidence"):
252
+ found.append("validated status needs at least one evidence reference")
253
+ scope = item.get("validated_on")
254
+ if scope is not None and (not scope or any(p not in PLATFORMS for p in scope)):
255
+ found.append(f"validated_on must name some of {', '.join(PLATFORMS)}")
256
+ if scope and item.get("status") != "validated":
257
+ found.append("validated_on needs status validated")
258
+ efforts = item.get("reasoning_efforts")
259
+ if efforts is not None and (
260
+ not efforts or list(efforts) != [e for e in EFFORT_LEVELS if e in efforts]
261
+ ):
262
+ found.append(f"reasoning_efforts must list some of {', '.join(EFFORT_LEVELS)} in order")
263
+ tasks = item.get("tasks") or []
264
+ if any(t not in TASKS for t in tasks):
265
+ found.append("tasks has an unknown task")
266
+ if tasks and task not in tasks:
267
+ found.append(f"tasks does not include its task {task}")
268
+ if item.get("base_license") and item.get("license") != item.get("base_license"):
269
+ found.append("license must be the inherited base_license")
270
+ return found
271
+
272
+
273
+ def _pin_problems(model: OptionalModelData) -> list[str]:
274
+ """A file pinned by content must name that content and the commit that holds it."""
275
+ assets = [f for v in model["variants"] for f in v["files"]]
276
+ assets += [a for a in (model.get("mmproj"), model.get("draft"), model.get("mtp_head")) if a]
277
+ found = []
278
+ for asset in assets:
279
+ if "sha256" not in asset:
280
+ continue
281
+ if not re.fullmatch(r"[0-9a-f]{64}", asset["sha256"]):
282
+ found.append(f"{asset['path']} sha256 is not 64 hex digits")
283
+ if not re.fullmatch(r"[0-9a-f]{40}", asset.get("revision", "")):
284
+ found.append(f"{asset['path']} sha256 needs a 40-hex commit revision")
285
+ return found
286
+
287
+
288
+ def problems(value: object) -> list[str]:
289
+ """Why this catalog is not complete as schema 3, one line per entry and field (never values):
290
+ every model and component names its license with an https link, status, tasks and evidence;
291
+ a model cites the source of its quality score; a Strata recipe of third-party weights names
292
+ its artifact license and the base license it inherits."""
293
+ doc = decode(value, OptionalCatalogData)
294
+ if doc.get("schema_version") != SCHEMA_VERSION:
295
+ return [f"schema_version is not {SCHEMA_VERSION}"]
296
+ found = []
297
+ for m in doc["models"]:
298
+ issues = _entry_problems(m, "llm", "llama.cpp")
299
+ if m.get("runtime", "llama.cpp") not in ("llama.cpp", "mlx-lm"):
300
+ issues.append("runtime is unknown")
301
+ quality = m.get("quality")
302
+ if not isinstance(quality, dict) or not quality["sources"]:
303
+ issues.append("quality has no sources")
304
+ elif any(s["type"] not in QUALITY_SOURCE_TYPES for s in quality["sources"]):
305
+ issues.append("quality.sources[].type is unknown")
306
+ issues += _pin_problems(m)
307
+ found += [f"models.{m['id']}: {issue}" for issue in issues]
308
+ for c in doc.get("components", []):
309
+ issues = _entry_problems(c, c["task"], c["runtime"])
310
+ found += [f"components.{c['id']}: {issue}" for issue in issues]
311
+ return found
312
+
313
+
314
+ def shipped_fixture(fixture: dict[str, object]) -> dict[str, object]:
315
+ """An acceptance input this package ships travels with the verify step as a data: URL, so the
316
+ target needs no network for it; the target still checks its size and SHA256."""
317
+ path = FIXTURE_DIR / str(fixture.get("name"))
318
+ if not path.is_file():
319
+ return fixture
320
+ data = base64.b64encode(path.read_bytes()).decode()
321
+ return {**fixture, "url": "data:application/octet-stream;base64," + data}
@@ -9,6 +9,7 @@ from localmodels import (
9
9
  __version__,
10
10
  catalog_add,
11
11
  cli_help,
12
+ debug_cli,
12
13
  deploy,
13
14
  gateway_cli,
14
15
  guard,
@@ -38,7 +39,7 @@ GROUPS = (
38
39
  ("devices", ("discover", "devices", "desktop-snapshot")),
39
40
  (
40
41
  "installer integration",
41
- ("setup", "library", "foundations", "harness", "gateway", "magpie", "guard"),
42
+ ("setup", "library", "foundations", "harness", "gateway", "magpie", "guard", "debug"),
42
43
  ),
43
44
  ("interfaces and catalog", ("tui", "serve", "catalog", "commands", "completion")),
44
45
  )
@@ -51,6 +52,7 @@ SUMMARIES = {
51
52
  "guard": "optional CPU privacy profile; never rewires services",
52
53
  "magpie": "Magpie alone for Claude Code/Codex subscriptions (no local model)",
53
54
  "catalog": "maintain the model catalog (`add` drafts an entry from a GGUF)",
55
+ "debug": "toggle simulate or tiny debug mode for fast testing and E2E",
54
56
  }
55
57
  SECTIONS = (
56
58
  (
@@ -325,6 +327,7 @@ def argument_parser() -> argparse.ArgumentParser:
325
327
  setup_inspection.add_parser(sub)
326
328
  services_cli.add_parser(sub)
327
329
  library_cli.add_parser(sub)
330
+ debug_cli.add_parser(sub)
328
331
  for name, summary in SUMMARIES.items():
329
332
  cli_help.summarize(sub, name, summary)
330
333
  cli_help.document(parser, DESCRIPTION, sections=SECTIONS)
@@ -143,18 +143,19 @@ def cells(text: str) -> int:
143
143
  )
144
144
 
145
145
 
146
- def clip(text: str, width: int) -> str:
147
- """``text`` (no escapes) cut to ``width`` columns, ending with an ellipsis when cut."""
146
+ def clip(text: str, width: int, *, ellipsis: str = "\u2026") -> str:
147
+ """``text`` (no escapes) cut to ``width`` columns, ending with ``ellipsis`` when cut."""
148
148
  if cells(text) <= width:
149
149
  return text
150
+ budget = max(0, width - cells(ellipsis)) if ellipsis else max(0, width)
150
151
  out, used = [], 0
151
152
  for c in text:
152
153
  w = cells(c)
153
- if used + w > width - 1:
154
+ if used + w > budget:
154
155
  break
155
156
  out.append(c)
156
157
  used += w
157
- return "".join(out) + "…"
158
+ return "".join(out) + ellipsis
158
159
 
159
160
 
160
161
  def pad(text: str, width: int) -> str:
@@ -2,12 +2,22 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import functools
5
6
  import types
6
- from typing import TypeVar, Union, cast, get_args, get_origin, get_type_hints, is_typeddict
7
+ from typing import Any, TypeVar, Union, cast, get_args, get_origin, get_type_hints, is_typeddict
7
8
 
8
9
  T = TypeVar("T")
9
10
 
10
11
 
12
+ @functools.cache
13
+ def _record_fields(schema: Any) -> tuple[frozenset[str], tuple[tuple[str, object], ...]]:
14
+ """Cache TypedDict required keys and resolved type hints across repeated decodes."""
15
+ return (
16
+ cast(frozenset[str], vars(schema)["__required_keys__"]),
17
+ tuple(get_type_hints(schema).items()),
18
+ )
19
+
20
+
11
21
  def decode(value: object, schema: type[T]) -> T:
12
22
  """Reject malformed external data before it reaches typed application code.
13
23
 
@@ -56,8 +66,8 @@ def _validate(value: object, schema: object, path: str) -> None:
56
66
  def _validate_record(value: object, schema: object, path: str) -> None:
57
67
  if not isinstance(value, dict):
58
68
  raise ValueError(f"{path}: expected object")
59
- required = cast(frozenset[str], vars(schema)["__required_keys__"])
60
- for key, field in get_type_hints(schema).items():
69
+ required, fields = _record_fields(schema)
70
+ for key, field in fields:
61
71
  if key in value:
62
72
  _validate(value[key], field, f"{path}.{key}")
63
73
  elif key in required:
@@ -0,0 +1,158 @@
1
+ """CLI for ``localmodels debug``: inspect or toggle ``simulate`` and ``tiny`` debug modes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import dataclasses
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from localmodels import cli_help, debug_mode
14
+
15
+ DESCRIPTION = (
16
+ "Inspect or toggle local debug modes (simulate or tiny) for fast UI, Desktop and E2E testing. "
17
+ "User-scoped settings live in ~/.config/localmodels/debug.json so packaged Desktop builds pick "
18
+ "them up automatically without terminal environment variables."
19
+ )
20
+
21
+
22
+ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
23
+ parser = sub.add_parser("debug", help="toggle simulate or tiny debug mode for fast testing")
24
+ verbs = parser.add_subparsers(dest="debug_command", required=True, metavar="COMMAND")
25
+
26
+ status = verbs.add_parser("status", help="print active debug configuration (JSON)")
27
+ status.add_argument("--json", action="store_true", help="accepted; output is JSON")
28
+ cli_help.document(
29
+ status,
30
+ "Print the active debug mode, its source (env, state, user or default) and parameters.",
31
+ examples=[("%(prog)s --json", "")],
32
+ )
33
+
34
+ set_cmd = verbs.add_parser("set", help="enable simulate or tiny mode")
35
+ set_cmd.add_argument("mode", choices=("simulate", "tiny"), help="debug mode to activate")
36
+ set_cmd.add_argument(
37
+ "--scope",
38
+ choices=("user", "state"),
39
+ default="user",
40
+ help="write to user config (default, affects packaged Desktop too) or LOCALMODELS_STATE",
41
+ )
42
+ set_cmd.add_argument("--download-ms", type=int, default=2000, help="simulated download time")
43
+ set_cmd.add_argument("--load-ms", type=int, default=300, help="simulated warmup time")
44
+ set_cmd.add_argument("--vram-gb", type=int, default=None, help="synthetic GPU VRAM size in GiB")
45
+ set_cmd.add_argument("--cache-dir", default=None, help="persistent SHA256 artifact cache path")
46
+ set_cmd.add_argument(
47
+ "--offline-gateway",
48
+ action="store_true",
49
+ help="register directly in pi without starting Bifrost (simulate mode)",
50
+ )
51
+ set_cmd.add_argument(
52
+ "--no-isolate-gateway",
53
+ action="store_true",
54
+ help="share the default gateway directory instead of isolating under LOCALMODELS_STATE",
55
+ )
56
+ set_cmd.add_argument(
57
+ "--fail",
58
+ action="append",
59
+ default=[],
60
+ metavar="STEP=MESSAGE",
61
+ help="inject an executor failure in simulate mode (repeatable, e.g. download=low disk space)",
62
+ )
63
+ cli_help.document(
64
+ set_cmd,
65
+ "Write debug.json so subsequent CLI, daemon and packaged Desktop calls run in the chosen "
66
+ "debug mode.",
67
+ examples=[
68
+ ("%(prog)s simulate --download-ms 2000", "2s simulated downloads across Desktop & Web"),
69
+ ("%(prog)s tiny", "enable real ~1.5 GB tiny models + persistent SHA256 cache"),
70
+ ],
71
+ )
72
+
73
+ off = verbs.add_parser("off", help="disable debug mode and remove debug.json")
74
+ off.add_argument(
75
+ "--scope",
76
+ choices=("user", "state", "all"),
77
+ default="all",
78
+ help="which debug.json file(s) to remove (default: all)",
79
+ )
80
+ cli_help.document(
81
+ off,
82
+ "Remove saved debug.json files so localmodels returns to normal production behavior.",
83
+ examples=[("%(prog)s", "turn off debug mode")],
84
+ )
85
+
86
+ cli_help.document(
87
+ parser,
88
+ DESCRIPTION,
89
+ examples=[
90
+ ("%(prog)s status", "show active mode"),
91
+ ("%(prog)s set simulate", "fast simulated downloads and loads"),
92
+ ("%(prog)s set tiny", "real llama-server with 1.5 GB tiny models and local cache"),
93
+ ("%(prog)s off", "restore production behavior"),
94
+ ],
95
+ )
96
+
97
+
98
+ def _write_private_json(path: Path, payload: dict[str, Any]) -> None:
99
+ path.parent.mkdir(parents=True, exist_ok=True)
100
+ if sys.platform != "win32":
101
+ with contextlib.suppress(OSError):
102
+ path.parent.chmod(0o700)
103
+ tmp = path.with_name(path.name + ".tmp")
104
+ tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
105
+ if sys.platform != "win32":
106
+ tmp.chmod(0o600)
107
+ path.parent.joinpath(tmp.name).replace(path)
108
+
109
+
110
+ def cli(args: argparse.Namespace) -> int:
111
+ if args.debug_command == "status":
112
+ cfg = debug_mode.resolve_config()
113
+ print(json.dumps(dataclasses.asdict(cfg), indent=2))
114
+ return 0
115
+ if args.debug_command == "off":
116
+ removed = []
117
+ targets = (
118
+ [debug_mode.state_config_path(), debug_mode.user_config_path()]
119
+ if args.scope == "all"
120
+ else [
121
+ debug_mode.state_config_path()
122
+ if args.scope == "state"
123
+ else debug_mode.user_config_path()
124
+ ]
125
+ )
126
+ for target in targets:
127
+ if target.exists():
128
+ target.unlink()
129
+ removed.append(str(target))
130
+ print(json.dumps({"mode": "off", "removed": removed}, indent=2))
131
+ return 0
132
+
133
+ fail_map: dict[str, str] = {}
134
+ for item in args.fail:
135
+ step, eq, message = str(item).partition("=")
136
+ if not eq or not step.strip() or not message.strip():
137
+ print(f"error: --fail expects STEP=MESSAGE, got {item!r}", file=sys.stderr)
138
+ return 2
139
+ fail_map[step.strip()] = message.strip()
140
+ payload: dict[str, Any] = {
141
+ "mode": args.mode,
142
+ "download_ms": max(0, int(args.download_ms)),
143
+ "load_ms": max(0, int(args.load_ms)),
144
+ "isolate_gateway": not args.no_isolate_gateway,
145
+ "offline_gateway": bool(args.offline_gateway),
146
+ }
147
+ if args.vram_gb is not None:
148
+ payload["vram_gb"] = int(args.vram_gb)
149
+ if args.cache_dir:
150
+ payload["cache_dir"] = str(args.cache_dir)
151
+ if fail_map:
152
+ payload["fail"] = fail_map
153
+ target = (
154
+ debug_mode.state_config_path() if args.scope == "state" else debug_mode.user_config_path()
155
+ )
156
+ _write_private_json(target, payload)
157
+ print(json.dumps({"written": str(target), **payload}, indent=2))
158
+ return 0