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

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 (86) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +85 -78
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/bifrost_checks.py +9 -6
  6. package/modules/localmodels/bifrost_config.py +35 -1
  7. package/modules/localmodels/bifrost_datasheet.py +12 -2
  8. package/modules/localmodels/catalog.json +155 -8
  9. package/modules/localmodels/catalog.py +19 -1
  10. package/modules/localmodels/catalog_recipes.py +33 -2
  11. package/modules/localmodels/cli_parser.py +26 -3
  12. package/modules/localmodels/deploy.py +37 -9
  13. package/modules/localmodels/deploy_steps.py +6 -3
  14. package/modules/localmodels/download-mirrors.json +52 -4
  15. package/modules/localmodels/engines-b11583.json +20 -4
  16. package/modules/localmodels/engines-b12167.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  19. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  20. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  21. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  22. package/modules/localmodels/engines.json +55 -11
  23. package/modules/localmodels/frontend.py +5 -2
  24. package/modules/localmodels/gateway_bifrost.py +11 -9
  25. package/modules/localmodels/gateway_cli.py +4 -2
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +65 -33
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/hf_repo.py +15 -8
  30. package/modules/localmodels/library_gateway.py +26 -13
  31. package/modules/localmodels/library_jobs.py +51 -3
  32. package/modules/localmodels/library_model.py +10 -0
  33. package/modules/localmodels/library_pricing.py +29 -22
  34. package/modules/localmodels/library_serve.py +5 -0
  35. package/modules/localmodels/library_state.py +9 -1
  36. package/modules/localmodels/library_status.py +30 -0
  37. package/modules/localmodels/llm_rank.py +83 -30
  38. package/modules/localmodels/metal_probe.py +16 -6
  39. package/modules/localmodels/npm_signatures.py +131 -0
  40. package/modules/localmodels/npm_transport.py +26 -10
  41. package/modules/localmodels/process_identity.py +32 -5
  42. package/modules/localmodels/recommend.py +5 -2
  43. package/modules/localmodels/region.py +244 -0
  44. package/modules/localmodels/remote_ops.py +69 -13
  45. package/modules/localmodels/remote_ops_download.py +210 -10
  46. package/modules/localmodels/remote_ops_prepare.py +61 -8
  47. package/modules/localmodels/runtime-lock.json +13 -13
  48. package/modules/localmodels/runtime_args.py +4 -2
  49. package/modules/localmodels/runtime_cli.py +19 -37
  50. package/modules/localmodels/runtime_discovery.py +30 -0
  51. package/modules/localmodels/runtime_install.py +81 -6
  52. package/modules/localmodels/runtime_io.py +61 -5
  53. package/modules/localmodels/runtime_pi.py +79 -0
  54. package/modules/localmodels/runtime_process.py +99 -15
  55. package/modules/localmodels/runtime_releases.py +51 -71
  56. package/modules/localmodels/search_server.py +5 -1
  57. package/modules/localmodels/service_probe.py +62 -4
  58. package/modules/localmodels/setup_inspection.py +21 -4
  59. package/modules/localmodels/setup_text.py +6 -0
  60. package/modules/localmodels/source_byok.py +484 -0
  61. package/modules/localmodels/source_byok_probe.py +275 -0
  62. package/modules/localmodels/source_cli.py +426 -0
  63. package/modules/localmodels/stack.py +31 -14
  64. package/modules/localmodels/stack_args.py +8 -4
  65. package/modules/localmodels/stack_binding.py +47 -4
  66. package/modules/localmodels/stack_cli.py +2 -0
  67. package/modules/localmodels/stack_compose.py +5 -5
  68. package/modules/localmodels/stack_events.py +3 -0
  69. package/modules/localmodels/stack_hardware.py +21 -6
  70. package/modules/localmodels/stack_llm_ram.py +16 -6
  71. package/modules/localmodels/stack_picks.py +4 -4
  72. package/modules/localmodels/stack_progress.py +9 -1
  73. package/modules/localmodels/stack_run.py +29 -0
  74. package/modules/localmodels/stack_suite.py +10 -3
  75. package/modules/localmodels/stack_warm.py +45 -4
  76. package/modules/localmodels/tools.json +1396 -32
  77. package/modules/localmodels/transport.py +40 -13
  78. package/modules/localmodels/windows_job.py +69 -0
  79. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/METADATA +1 -1
  80. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/RECORD +82 -75
  81. package/package.json +1 -1
  82. package/tool.json +1 -1
  83. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/WHEEL +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/entry_points.txt +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/NOTICE +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -9,6 +9,7 @@ artifacts, with ownership recorded for safe removal. The controller must be the
9
9
  from __future__ import annotations
10
10
 
11
11
  import contextlib
12
+ import hashlib
12
13
  import json
13
14
  import os
14
15
  import re
@@ -19,7 +20,7 @@ from collections.abc import Callable
19
20
  from pathlib import Path
20
21
  from typing import Any, Literal, TypedDict, cast
21
22
 
22
- from localmodels import harness_probe, hosts
23
+ from localmodels import harness_probe, hosts, region
23
24
  from localmodels.contracts import decode
24
25
  from localmodels.harness_cleanup import (
25
26
  changed as changed,
@@ -47,7 +48,8 @@ from localmodels.harness_probe import shown_pi_model as shown_pi_model
47
48
  from localmodels.npm_transport import Artifact as Artifact
48
49
  from localmodels.npm_transport import ToolBuild as ToolBuild
49
50
  from localmodels.npm_transport import install_bifrost
50
- from localmodels.remote_ops import fetch
51
+ from localmodels.remote_ops import Archive, fetch
52
+ from localmodels.remote_ops_download import npm_copies
51
53
  from localmodels.runtime_io import error_cause
52
54
  from localmodels.stack_events import ToolEvents
53
55
  from localmodels.tool_archive import (
@@ -97,9 +99,21 @@ class NpmArtifact(TypedDict):
97
99
  integrity: str
98
100
 
99
101
 
102
+ class _PiModuleOptional(NpmArtifact, total=False):
103
+ install_script: str # "skipped": npm would run one; scripts/pin_pi.py says why it is not
104
+
105
+
106
+ class PiModule(_PiModuleOptional):
107
+ path: (
108
+ str # its place under the package root, npm's lockfile key: node_modules/a[/node_modules/b]
109
+ )
110
+
111
+
100
112
  class PiLock(NpmArtifact):
113
+ """pi and its whole production dependency tree, written by scripts/pin_pi.py."""
114
+
101
115
  entry: str
102
- modules: list[NpmArtifact]
116
+ modules: list[PiModule]
103
117
 
104
118
 
105
119
  class MagpieLock(TypedDict):
@@ -275,7 +289,7 @@ def tool_build(builds: list[ToolBuild], platform: str, arch: str, tool: str) ->
275
289
  return match
276
290
 
277
291
 
278
- def tool_artifact(item: ToolBuild | NpmArtifact) -> Artifact:
292
+ def tool_artifact(item: ToolBuild | NpmArtifact | PiModule) -> Artifact:
279
293
  artifact: Artifact = {
280
294
  "name": item["name"],
281
295
  "url": item["url"],
@@ -284,6 +298,10 @@ def tool_artifact(item: ToolBuild | NpmArtifact) -> Artifact:
284
298
  }
285
299
  if "npm" in item:
286
300
  artifact["npm"] = cast(ToolBuild, item)["npm"]
301
+ if "npm_copy" in item:
302
+ artifact["npm_copy"] = cast(ToolBuild, item)["npm_copy"]
303
+ if "path" in item:
304
+ artifact["path"] = cast(PiModule, item)["path"]
287
305
  return artifact
288
306
 
289
307
 
@@ -498,7 +516,13 @@ def _fetch(tools_dir: Path, artifact: Artifact, log: Callable[[str], None]) -> P
498
516
  return path
499
517
  with contextlib.redirect_stdout(_Events(log)):
500
518
  fetch(
501
- artifact["url"], str(path), artifact["sha256"], artifact["size_bytes"], artifact["name"]
519
+ artifact["url"],
520
+ str(path),
521
+ artifact["sha256"],
522
+ artifact["size_bytes"],
523
+ artifact["name"],
524
+ npm_copies(cast(Archive, artifact)),
525
+ region.current_region(),
502
526
  )
503
527
  return path
504
528
 
@@ -522,6 +546,41 @@ def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], ma
522
546
  return final
523
547
 
524
548
 
549
+ def _install_pi(
550
+ tools_dir: Path,
551
+ bin_dir: Path,
552
+ action: ToolAction,
553
+ pi: PiLock,
554
+ node: str,
555
+ log: Callable[[str], None],
556
+ ) -> list[str]:
557
+ """pi's package with its dependency tree, each module at the plan's path, and the wrapper
558
+ in ``bin_dir``; returns the tree and the wrapper."""
559
+ modules = action["artifacts"][1:]
560
+ if any("path" not in m for m in modules): # plans saved before 2026-11-18
561
+ raise HarnessError("this plan installs pi without its dependency tree; plan again")
562
+ archives = [_fetch(tools_dir, a, log) for a in action["artifacts"]]
563
+
564
+ def unpack_pi(dest: Path) -> None:
565
+ _safe_extract(archives[0], dest)
566
+ for module, archive in zip(modules, archives[1:], strict=True):
567
+ target = dest.joinpath(*module["path"].split("/"))
568
+ target.mkdir(parents=True)
569
+ _safe_extract(archive, target)
570
+
571
+ marker = hashlib.sha256(",".join(a["sha256"] for a in action["artifacts"]).encode())
572
+ tree = _install_tree(tools_dir, f"pi-{pi['version']}", unpack_pi, marker.hexdigest())
573
+ wrapper = bin_dir / launcher_name()
574
+ bin_dir.mkdir(parents=True, exist_ok=True)
575
+ if wrapper.exists() and not _owned_wrapper(str(wrapper)):
576
+ raise HarnessError(f"{wrapper} exists and localmodels did not create it; not overwritten")
577
+ about = f"{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; remove this file and {tree}"
578
+ write_launcher(wrapper, [node, str(tree / pi["entry"])], about)
579
+ wrapper.chmod(0o755)
580
+ log(f"pi {pi['version']} installed: {wrapper}")
581
+ return [str(tree), str(wrapper)]
582
+
583
+
525
584
  def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: None) -> list[str]:
526
585
  """Install the tools the plan marks ``install``; returns the paths created (owned)."""
527
586
  lock = load_lock()
@@ -543,34 +602,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
543
602
  owned.append(str(tree))
544
603
  log(f"Node.js {lock['node']['version']} installed to {tree}")
545
604
  if actions["pi"]["action"] == "install":
546
- pi = lock["pi"]
547
- archives = [_fetch(tools_dir, a, log) for a in actions["pi"]["artifacts"]]
548
-
549
- def unpack_pi(dest: Path) -> None:
550
- _safe_extract(archives[0], dest)
551
- for module, archive in zip(pi["modules"], archives[1:], strict=False):
552
- target = dest / "node_modules" / module["package"]
553
- target.mkdir(parents=True)
554
- _safe_extract(archive, target)
555
-
556
- tree = _install_tree(
557
- tools_dir,
558
- f"pi-{pi['version']}",
559
- unpack_pi,
560
- ",".join(a["sha256"] for a in actions["pi"]["artifacts"]),
561
- )
562
- owned.append(str(tree))
563
- wrapper = bin_dir / launcher_name()
564
- bin_dir.mkdir(parents=True, exist_ok=True)
565
- if wrapper.exists() and not _owned_wrapper(str(wrapper)):
566
- raise HarnessError(
567
- f"{wrapper} exists and localmodels did not create it; not overwritten"
568
- )
569
- about = f"{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; remove this file and {tree}"
570
- write_launcher(wrapper, [node, str(tree / pi["entry"])], about)
571
- wrapper.chmod(0o755)
572
- owned.append(str(wrapper))
573
- log(f"pi {pi['version']} installed: {wrapper}")
605
+ owned += _install_pi(tools_dir, bin_dir, actions["pi"], lock["pi"], node, log)
574
606
  if "bifrost" in actions and actions["bifrost"]["action"] == "install":
575
607
  from localmodels import gateway_bifrost
576
608
 
@@ -346,15 +346,21 @@ def stop_gateway(
346
346
 
347
347
 
348
348
  def private_home(plan: harness.ToolPlan) -> None:
349
- """Create the stack's private client context (``tools/gateway-home``) 0700 before anything is
350
- written into it, as Magpie's ``_serve`` does. One that exists must already be private: it is
351
- never loosened or repaired automatically, the user is told how to fix it."""
349
+ """Create the private client context before wiring clients, without repairing existing state."""
352
350
  if "environment" in plan:
353
351
  return
354
352
  home = harness_probe.gateway_home(plan["tools_dir"])
355
353
  try:
356
354
  runtime_io.private_directory(home)
357
355
  except ValueError as exc:
356
+ if sys.platform == "win32":
357
+ raise harness.HarnessError(
358
+ f"{home} is not a private directory for the current Windows user ({exc});"
359
+ " no config changed. Close Linger and stop the localmodels gateway if it is"
360
+ " running. If you confirm localmodels created this folder, rename it in File"
361
+ " Explorer to keep a backup (ask an administrator if denied), then retry"
362
+ " without elevation."
363
+ ) from exc
358
364
  raise harness.HarnessError(
359
365
  f"{home} is not a directory private to the current user ({exc}; should be 0700); no"
360
366
  f" config changed. Once you confirm this tool created it, run chmod 700 {home} and retry"
@@ -18,13 +18,14 @@ import difflib
18
18
  import io
19
19
  import json
20
20
  import re
21
+ import urllib.error
21
22
  import urllib.parse
22
23
  import urllib.request
23
24
  from collections.abc import Callable, Sequence
24
25
  from typing import NamedTuple, TypedDict
25
26
 
26
27
  from localmodels import catalog as cat
27
- from localmodels import catalog_add
28
+ from localmodels import catalog_add, region
28
29
  from localmodels.contracts import decode
29
30
  from localmodels.gguf import SPLIT_PART_RE, GGUFHeader, model_id_from_stem, read_header_stream
30
31
  from localmodels.plan_envelope import PlanError
@@ -227,13 +228,19 @@ def entry_for(
227
228
  if not api:
228
229
  raise PlanError(f"--llm {spec} needs a Hub endpoint to resolve")
229
230
  repo, quant, revision = parts
230
- if revision:
231
- doc = decode(
232
- hf_get(f"{api}/api/models/{repo}/revision/{urllib.parse.quote(revision)}"),
233
- ModelInfo,
234
- )
235
- else:
236
- doc = decode(hf_get(f"{api}/api/models/{repo}"), ModelInfo)
231
+ # The pins of an ad-hoc repo are minted here: only from the Hub the user trusts, never from
232
+ # the region's mirror (region.MINT_REFUSAL).
233
+ first = f"{api}/api/models/{repo}" + (
234
+ f"/revision/{urllib.parse.quote(revision)}" if revision else ""
235
+ )
236
+ try:
237
+ doc = decode(hf_get(first), ModelInfo)
238
+ except urllib.error.HTTPError:
239
+ raise
240
+ except OSError as exc:
241
+ if region.explicit_hub(api):
242
+ raise
243
+ raise PlanError(region.MINT_REFUSAL.format(what=repo)) from exc
237
244
  commit = doc.get("sha")
238
245
  if not commit:
239
246
  raise PlanError(f"{repo} does not resolve on the Hub")
@@ -23,6 +23,7 @@ from pathlib import Path
23
23
  from typing import Any
24
24
 
25
25
  from localmodels import (
26
+ bifrost_config,
26
27
  bifrost_datasheet,
27
28
  bifrost_models,
28
29
  bifrost_unit,
@@ -39,6 +40,8 @@ from localmodels.probe import HostFacts
39
40
  from localmodels.records import Plan
40
41
 
41
42
  PROVIDER_PREFIX = "localmodels-lib-"
43
+ # Windows cannot delete the config store a running Bifrost holds open: stop it before a change.
44
+ STOP_BEFORE_CONFIG_CHANGE = os.name == "nt"
42
45
  PI_PROVIDER = "localmodels-library"
43
46
 
44
47
 
@@ -127,14 +130,16 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
127
130
  return record
128
131
 
129
132
 
130
- def _instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
133
+ def ensure_instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
134
+ """Return this tool's Bifrost record, installing it first when ``facts`` are supplied."""
131
135
  record = hosts.load_owned()["gateway"].get("bifrost")
132
136
  if record is None and facts is not None:
133
137
  record = _install(facts)
134
138
  return record
135
139
 
136
140
 
137
- def _sheet(app: Path) -> dict[str, Any]:
141
+ def read_sheet(app: Path) -> dict[str, Any]:
142
+ """Read the current model datasheet of ``app``, or an empty mapping when absent."""
138
143
  try:
139
144
  value = json.loads((app / bifrost_datasheet.DATASHEET).read_text(encoding="utf-8"))
140
145
  except (OSError, ValueError):
@@ -142,13 +147,21 @@ def _sheet(app: Path) -> dict[str, Any]:
142
147
  return value if isinstance(value, dict) else {}
143
148
 
144
149
 
145
- def _apply(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
150
+ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
146
151
  """Write the config and datasheet; restart the instance when they changed. A gateway left
147
152
  with no provider at all (no library model, and nothing of the stack such as its LLM,
148
153
  decision model or foundation services) serves nobody: it is stopped instead, its record
149
154
  and config kept, and the next load starts it again."""
150
155
  app = Path(record["app_dir"])
151
156
  params = {bifrost_datasheet.DATASHEET: sheet, bifrost_datasheet.PARAMETERS: {}}
157
+ if (
158
+ STOP_BEFORE_CONFIG_CHANGE
159
+ and record["how"] != "unit"
160
+ and bifrost_config.differs(app, config, params)
161
+ ):
162
+ # A change drops the config store, which Windows cannot delete while Bifrost holds it
163
+ # open (WinError 32 on unload, homewin): stop it first; it restarts on the change.
164
+ gateway_bifrost._stop_serve(app)
152
165
  changed = gateway_bifrost._write_config(app, config, params)
153
166
  if not config.get("providers"):
154
167
  _stop(record)
@@ -370,11 +383,11 @@ def _register(
370
383
  shared = stack_provider is not None and _stack_owns_pi()
371
384
  if not shared:
372
385
  _pi_free(pi_provider)
373
- record = _instance(facts)
386
+ record = ensure_instance(facts)
374
387
  assert record is not None
375
388
  app = Path(record["app_dir"])
376
389
  config = gateway_bifrost.read_config(app)
377
- before, before_sheet = copy.deepcopy(config), _sheet(app)
390
+ before, before_sheet = copy.deepcopy(config), read_sheet(app)
378
391
  providers = config.setdefault("providers", {})
379
392
  if stack_provider is not None:
380
393
  providers[pid] = bifrost_provider.render("llm", url, name, key, pid)
@@ -388,7 +401,7 @@ def _register(
388
401
  before_sheet
389
402
  | bifrost_datasheet.sheets(pid, names, context)[bifrost_datasheet.DATASHEET]
390
403
  )
391
- _apply(record, config, sheet)
404
+ apply_config(record, config, sheet)
392
405
  try:
393
406
  if listed_as not in bifrost_models.listed(record["addr"]):
394
407
  raise _fail(f"Bifrost does not list {listed_as}")
@@ -405,7 +418,7 @@ def _register(
405
418
  _pi_add(pi_provider, pi_entry, base)
406
419
  except BaseException: # roll the gateway back to what it was before this call
407
420
  with contextlib.suppress(harness.HarnessError, OSError, ValueError, LibraryError):
408
- _apply(record, before, before_sheet)
421
+ apply_config(record, before, before_sheet)
409
422
  raise
410
423
  except LibraryError:
411
424
  raise
@@ -420,7 +433,7 @@ def _unregister(registration: Registration) -> None:
420
433
  _unwire_member(registration)
421
434
  return
422
435
  _pi_drop(registration.get("pi_provider", PI_PROVIDER), registration["model"])
423
- record = _instance(None)
436
+ record = ensure_instance(None)
424
437
  if record is None:
425
438
  return
426
439
  app = Path(record["app_dir"])
@@ -430,8 +443,8 @@ def _unregister(registration: Registration) -> None:
430
443
  return
431
444
  del providers[registration["provider"]]
432
445
  prefix = registration["provider"] + "/"
433
- sheet = {k: v for k, v in _sheet(app).items() if not k.startswith(prefix)}
434
- _apply(record, config, sheet)
446
+ sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
447
+ apply_config(record, config, sheet)
435
448
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
436
449
  raise _fail(str(exc)) from None
437
450
 
@@ -449,7 +462,7 @@ def _unwire_member(registration: Registration) -> None:
449
462
  gateway stops only when nothing at all is left for it to serve."""
450
463
  from localmodels import bifrost_clients, bifrost_pi
451
464
 
452
- record = _instance(None)
465
+ record = ensure_instance(None)
453
466
  app = Path(record["app_dir"]) if record else None
454
467
  config = gateway_bifrost.read_config(app) if app else {}
455
468
  providers = config.get("providers") or {}
@@ -467,5 +480,5 @@ def _unwire_member(registration: Registration) -> None:
467
480
  return
468
481
  _route_agent(config)
469
482
  prefix = registration["provider"] + "/"
470
- sheet = {k: v for k, v in _sheet(app).items() if not k.startswith(prefix)}
471
- _apply(record, config, sheet)
483
+ sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
484
+ apply_config(record, config, sheet)
@@ -12,8 +12,10 @@ from __future__ import annotations
12
12
 
13
13
  import os
14
14
  import signal
15
+ import threading
15
16
  import time
16
- from collections.abc import Callable
17
+ from collections.abc import Callable, Iterator
18
+ from contextlib import contextmanager
17
19
  from pathlib import Path
18
20
 
19
21
  from localmodels import (
@@ -25,6 +27,7 @@ from localmodels import (
25
27
  library_state,
26
28
  library_status,
27
29
  plan_envelope,
30
+ process_identity,
28
31
  remote_ops_download,
29
32
  )
30
33
  from localmodels.deploy_steps import Action
@@ -61,6 +64,45 @@ def cancel_on_sigterm() -> None:
61
64
  signal.signal(signal.SIGTERM, once)
62
65
 
63
66
 
67
+ WATCH_S = 0.2 # how often a Windows download looks for its cancel mark
68
+ CANCEL_BY_MARK = os.name == "nt" # Windows: no signal reaches a job; it watches its mark
69
+
70
+
71
+ @contextmanager
72
+ def watch_cancel(job: Job) -> Iterator[None]:
73
+ """Windows: a cancel cannot signal this process (another console process can only end it,
74
+ which would leave no CANCELLED line and no cleanup), so ``cancel`` marks the job and waits.
75
+ While the body runs, a thread looks for the mark and ends the download helper this process
76
+ runs, again until the body is over: the transfer then fails, the job sees its mark
77
+ (``_cancelled``) and ends as a cancel does on POSIX. POSIX gets SIGTERM instead."""
78
+ if not CANCEL_BY_MARK:
79
+ yield
80
+ return
81
+ done = threading.Event()
82
+
83
+ def watch() -> None:
84
+ while not done.wait(WATCH_S):
85
+ if library_state.cancelled(job):
86
+ try:
87
+ process_identity.stop_children(os.getpid())
88
+ except (OSError, RuntimeError, ValueError):
89
+ pass # the cancel ends the whole tree after its grace
90
+
91
+ thread = threading.Thread(target=watch, name="cancel-watch", daemon=True)
92
+ thread.start()
93
+ try:
94
+ yield
95
+ finally:
96
+ done.set()
97
+ thread.join(timeout=5)
98
+
99
+
100
+ def _cancelled(job: Job) -> None:
101
+ """Windows: a cancel marked this job; end it the way a cancel's SIGTERM ends it on POSIX."""
102
+ if CANCEL_BY_MARK and library_state.cancelled(job):
103
+ raise KeyboardInterrupt
104
+
105
+
64
106
  def dests(plan: Plan) -> list[str]:
65
107
  return [os.path.expanduser(f["dest"]) for f in plan["files"]]
66
108
 
@@ -190,6 +232,7 @@ def _shared(model: str, plan: Plan, handle: JobHandle, run: Executor, waiting: l
190
232
  or claim and fetch one when its download ended without it."""
191
233
  by_dest = {os.path.expanduser(f["dest"]): f for f in plan["files"]}
192
234
  while waiting:
235
+ _cancelled(handle.job)
193
236
  for dest in list(waiting):
194
237
  if plan_envelope.verified_in_place(by_dest[dest]):
195
238
  waiting.remove(dest)
@@ -256,8 +299,13 @@ def _fetch_and_commit(
256
299
  """Fetch the files this job claimed, wait for the ones another download claimed, then
257
300
  record the model as this job, unless a cancel marked it."""
258
301
  job = handle.job
259
- fetch(model.id, plan, handle, executor(), set(mine))
260
- _shared(model.id, plan, handle, executor(), [f for f in files if f not in mine])
302
+ try:
303
+ with watch_cancel(job):
304
+ fetch(model.id, plan, handle, executor(), set(mine))
305
+ _shared(model.id, plan, handle, executor(), [f for f in files if f not in mine])
306
+ except LibraryError:
307
+ _cancelled(job) # the failure is the helper a cancel ended (Windows)
308
+ raise
261
309
  selector = library_gateway.pi_model(model.id, str(plan["endpoint"]["model"]))
262
310
  record: Record = library_state.new_record(
263
311
  model.id, model.entry.id, model.variant.quant, pool, plan, selector
@@ -169,6 +169,16 @@ class Row(_Row, total=False):
169
169
  endpoint: Endpoint # loaded only
170
170
  pi_model: str # every model not absent: <pi provider>/<pi model id> once it is loaded
171
171
  tokens_per_second: float # the last measured warm speed; absent when unknown
172
+ # The model card (Linger's LocalModel fields): from the catalog, each absent when unknown.
173
+ family: str
174
+ publisher: str
175
+ architecture: str # dense | moe
176
+ parameters: str
177
+ active_parameters: str
178
+ capabilities: list[str]
179
+ license: str
180
+ source_url: str
181
+ prompt_tokens_per_second: float # the last load's measured prefill speed
172
182
  error: Problem # failed only
173
183
  note: Note # idle only, when autoload was skipped
174
184
 
@@ -63,11 +63,18 @@ def is_chat(entry: cat.CatalogEntry) -> bool:
63
63
 
64
64
 
65
65
  def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
66
- """The chat models validated for this platform, one row per variant."""
66
+ """The chat models validated for this platform, and the candidates ``stack --llm auto``
67
+ picks here too (the Mac small-memory ladder, the Windows NVIDIA fallback): one row per
68
+ variant. Ling-3.0-tiny, which the ladder replaces in automatic selection, stays listed."""
67
69
  return [
68
70
  Model(e, v)
69
71
  for e in catalog
70
- if is_chat(e) and cat.validated_here(e, facts["platform"])
72
+ if is_chat(e)
73
+ and (
74
+ cat.validated_here(e, facts["platform"])
75
+ or llm_rank.mac_rung(e, facts)
76
+ or llm_rank.windows_fallback(e, facts)
77
+ )
71
78
  for v in e.variants
72
79
  ]
73
80
 
@@ -320,28 +327,28 @@ def download_reason(facts: HostFacts, priced: Priced, disk_free: int) -> Reason
320
327
  return None
321
328
 
322
329
 
323
- def rank(facts: HostFacts, model: Model, pool: str) -> tuple[int, float]:
324
- """``llm_rank``'s order (the installed score, then predicted decode speed on that card)."""
325
- index = gpu_index(pool)
326
- try:
327
- if index is None:
328
- index = (metal.device(facts) or {"index": 0})["index"]
329
- from localmodels import stack
330
+ def smartest(facts: HostFacts) -> tuple[str, str] | None:
331
+ """(catalog id, quant) of the smartest pick ``stack hardware`` shows for this computer with
332
+ its memory free (stack_picks, decision 45): what ``stack plan --llm auto`` installs on it,
333
+ the Mac ladder and the Windows fallback included. None when nothing fits automatically."""
334
+ from localmodels import stack
330
335
 
331
- card, _ = stack_hardware.llm_budget(
332
- capacity(facts), index, stack.default_options(), entry=model.entry, posture=posture()
333
- )
334
- return llm_rank.rank_key(model.entry, model.variant, card)
335
- except (KeyError, StopIteration, ValueError, TypeError):
336
- return (model.entry.quality, 0.0)
336
+ seen = capacity(facts)
337
+ seen["disk"] = facts["disk"] # Strata's fit still sees the real disk
338
+ if seen["ram"].get("pressure_level") is not None: # a Mac with its memory free: no pressure
339
+ seen["ram"]["pressure_level"] = 1
340
+ try:
341
+ view = stack_hardware.view(seen, stack.default_options(), posture())
342
+ except (KeyError, ValueError, TypeError, OSError):
343
+ return None
344
+ pick = next((p for p in view.get("picks") or [] if p["role"] == "smartest"), None)
345
+ return (pick["id"], pick["quant"]) if pick is not None else None
337
346
 
338
347
 
339
348
  def recommend(facts: HostFacts, candidates: list[tuple[Model, str]]) -> str | None:
340
- """The one model to suggest among absent, downloadable ones: the smartest by llm_rank."""
341
- if not candidates:
349
+ """The one model to suggest: the CLI's smartest pick, when it is among the absent,
350
+ downloadable ``candidates``. None when it is already on disk, not a library model (a
351
+ Strata recipe) or nothing fits: never a runner-up in its place."""
352
+ if not candidates or (pick := smartest(facts)) is None:
342
353
  return None
343
- ranked = [(rank(facts, m, pool), m.id, 0) for m, pool in candidates]
344
- small_mac = llm_rank.mac_default(facts)
345
- default = next((m.id for m, _ in candidates if m.entry.id == small_mac), None)
346
- chosen, _ = llm_rank.choose(ranked, "smartest", default)
347
- return chosen
354
+ return next((m.id for m, _ in candidates if (m.entry.id, m.variant.quant) == pick), None)
@@ -222,9 +222,14 @@ def _start(
222
222
  progress(model.id, "load", len(steps), len(steps))
223
223
  progress(model.id, "warm", 0, 2)
224
224
  speed = stack_warm.warm_llm(plan)["decode_tok_s"]
225
+ prefill = stack_warm.prompt_speed(plan) # one more request; warm still counts two steps
225
226
  progress(model.id, "warm", 2, 2)
226
227
  if speed is not None:
227
228
  record["tokens_per_second"] = float(speed)
229
+ if prefill is not None:
230
+ record["prompt_tokens_per_second"] = prefill
231
+ else: # the last load's measurement, or none
232
+ record.pop("prompt_tokens_per_second", None)
228
233
  key = stack_verify.key(plan) or ""
229
234
  member = stack_member(record)
230
235
  record["registration"] = library_gateway.planned(model.id, plan, stack_provider=member)
@@ -60,6 +60,7 @@ class Record(_RecordRequired, total=False):
60
60
  base_dir: str # where it was downloaded: its weights, engine and deployments live there
61
61
  memory_bytes: int # the footprint priced at download (on the pool's whole capacity)
62
62
  tokens_per_second: float
63
+ prompt_tokens_per_second: float
63
64
  registration: Registration
64
65
  error: Problem
65
66
  note: Note
@@ -357,13 +358,20 @@ def receipt(model: str) -> process_identity.Identity | None:
357
358
  def stop_process(saved: process_identity.Identity, grace: float = 20.0) -> str:
358
359
  """Stop exactly the process group ``saved`` names (SIGTERM, then SIGKILL), whatever job
359
360
  file now sits at its path: "gone" when it had ended, "stopped" otherwise. RuntimeError
360
- when it outlives SIGKILL."""
361
+ when it outlives SIGKILL. Windows has no signal one console process can send another, so
362
+ there the job ends itself once it sees its cancel mark (``library_jobs.watch_cancel``): it
363
+ is given ``grace`` to, and only then its tree is ended by force."""
361
364
  import signal
362
365
  import time
363
366
 
364
367
  if process_identity.inspect(saved["pid"]) != saved:
365
368
  return "gone"
366
369
  if os.name == "nt":
370
+ deadline = time.monotonic() + grace
371
+ while time.monotonic() < deadline:
372
+ if process_identity.inspect(saved["pid"]) != saved:
373
+ return "stopped"
374
+ time.sleep(0.1)
367
375
  if process_identity.windows_stop_tree(saved["pid"], saved, grace):
368
376
  return "stopped"
369
377
  raise RuntimeError(f"process {saved['pid']} is still running")
@@ -5,8 +5,10 @@ probe's; the web formats them and infers nothing."""
5
5
  from __future__ import annotations
6
6
 
7
7
  import datetime as dt
8
+ import re
8
9
  import urllib.request
9
10
  from dataclasses import dataclass, field
11
+ from typing import cast
10
12
 
11
13
  from localmodels import (
12
14
  __version__,
@@ -162,6 +164,31 @@ def pi_model_of(model: Model, record: Record | None) -> str | None:
162
164
  return library_gateway.pi_model(model.id, model.variant.model_id)
163
165
 
164
166
 
167
+ HUB_REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*")
168
+
169
+
170
+ def card(model: Model, vision_on: bool) -> Row:
171
+ """The model card fields of a row, each only when the catalog states it: family,
172
+ publisher and parameter scales as written there, the architecture from its MoE flag, its
173
+ license, the Hugging Face page of the repository the weights come from, and vision when
174
+ this deployment reads images (its projector is pinned and priced). Nothing is guessed from
175
+ a name; Linger rejects a whole status document over one value outside its sets."""
176
+ entry = model.entry
177
+ found: dict[str, object] = {
178
+ "family": entry.family,
179
+ "publisher": entry.publisher.strip()[:120],
180
+ "architecture": "moe" if entry.moe else "dense",
181
+ "parameters": entry.parameters,
182
+ "active_parameters": entry.active_parameters if entry.moe else "",
183
+ "license": entry.license.strip()[:120],
184
+ }
185
+ if HUB_REPO.fullmatch(entry.repo):
186
+ found["source_url"] = f"https://huggingface.co/{entry.repo}"
187
+ if vision_on:
188
+ found["capabilities"] = ["vision"]
189
+ return cast(Row, {k: v for k, v in found.items() if v})
190
+
191
+
165
192
  def row(lib: Library, model: Model) -> Row:
166
193
  record = lib.records.get(model.id)
167
194
  priced = lib.judge(model)
@@ -210,6 +237,7 @@ def row(lib: Library, model: Model) -> Row:
210
237
  "total_bytes": job["total"],
211
238
  "bytes_per_second": job["bytes_per_second"],
212
239
  }
240
+ found.update(card(model, found["vision"]))
213
241
  if state != "absent":
214
242
  if (selector := pi_model_of(model, record)) is not None:
215
243
  found["pi_model"] = selector
@@ -221,6 +249,8 @@ def row(lib: Library, model: Model) -> Row:
221
249
  }
222
250
  if (speed := record.get("tokens_per_second")) is not None:
223
251
  found["tokens_per_second"] = round(speed, 1)
252
+ if (prefill := record.get("prompt_tokens_per_second")) is not None:
253
+ found["prompt_tokens_per_second"] = round(prefill, 1)
224
254
  if state == "idle" and (note := record.get("note")):
225
255
  found["note"] = note
226
256
  if state == "failed" and problem is not None: