@simplexai/localmodels-darwin-arm64 0.1.0-dev.39 → 0.1.0-dev.42

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 (72) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +70 -69
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +74 -16
  5. package/modules/localmodels/budget.py +27 -18
  6. package/modules/localmodels/catalog.json +4 -130
  7. package/modules/localmodels/catalog.py +10 -0
  8. package/modules/localmodels/chat_template.py +35 -0
  9. package/modules/localmodels/debug_mode.py +8 -0
  10. package/modules/localmodels/deploy.py +7 -1
  11. package/modules/localmodels/download-mirrors.json +0 -8
  12. package/modules/localmodels/gateway.py +2 -0
  13. package/modules/localmodels/gateway_bifrost.py +3 -0
  14. package/modules/localmodels/gateway_home.py +132 -0
  15. package/modules/localmodels/harness.py +48 -13
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/library_gateway.py +13 -2
  18. package/modules/localmodels/library_jobs.py +63 -6
  19. package/modules/localmodels/library_model.py +60 -15
  20. package/modules/localmodels/library_pricing.py +99 -26
  21. package/modules/localmodels/library_serve.py +69 -14
  22. package/modules/localmodels/library_state.py +33 -2
  23. package/modules/localmodels/library_status.py +109 -13
  24. package/modules/localmodels/llm_rank.py +16 -27
  25. package/modules/localmodels/metal.py +29 -12
  26. package/modules/localmodels/probe.py +4 -0
  27. package/modules/localmodels/recommend.py +30 -13
  28. package/modules/localmodels/recommend_cli.py +6 -4
  29. package/modules/localmodels/remote_ops_download.py +75 -14
  30. package/modules/localmodels/remote_ops_remove.py +15 -0
  31. package/modules/localmodels/remote_ops_service.py +10 -0
  32. package/modules/localmodels/reuse.py +31 -5
  33. package/modules/localmodels/runtime_cli.py +61 -40
  34. package/modules/localmodels/runtime_discovery.py +38 -10
  35. package/modules/localmodels/runtime_install.py +31 -10
  36. package/modules/localmodels/runtime_io.py +4 -3
  37. package/modules/localmodels/runtime_pi.py +71 -19
  38. package/modules/localmodels/runtime_process.py +4 -2
  39. package/modules/localmodels/service_deployment.py +5 -3
  40. package/modules/localmodels/service_probe.py +84 -27
  41. package/modules/localmodels/setup_inspection.py +104 -25
  42. package/modules/localmodels/setup_text.py +12 -5
  43. package/modules/localmodels/sizecalc.py +0 -2
  44. package/modules/localmodels/slot_cache.py +467 -0
  45. package/modules/localmodels/stack_binding.py +90 -13
  46. package/modules/localmodels/stack_capacity.py +3 -3
  47. package/modules/localmodels/stack_card.py +1 -0
  48. package/modules/localmodels/stack_compose.py +2 -3
  49. package/modules/localmodels/stack_down.py +22 -7
  50. package/modules/localmodels/stack_events.py +59 -0
  51. package/modules/localmodels/stack_hardware.py +35 -29
  52. package/modules/localmodels/stack_hardware_text.py +40 -35
  53. package/modules/localmodels/stack_lifecycle.py +12 -3
  54. package/modules/localmodels/stack_mlx.py +4 -1
  55. package/modules/localmodels/stack_picks.py +6 -1
  56. package/modules/localmodels/stack_plan.py +1 -0
  57. package/modules/localmodels/stack_rollback.py +9 -4
  58. package/modules/localmodels/stack_summary.py +2 -0
  59. package/modules/localmodels/stack_up.py +27 -20
  60. package/modules/localmodels/stack_update.py +3 -1
  61. package/modules/localmodels/stack_warm.py +21 -11
  62. package/modules/localmodels/stack_warm_store.py +5 -16
  63. package/modules/localmodels/tools.json +1 -0
  64. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/METADATA +1 -1
  65. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/RECORD +67 -66
  66. package/package.json +1 -1
  67. package/tool.json +1 -1
  68. package/modules/localmodels/engines-b12167.json +0 -26
  69. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/WHEEL +0 -0
  70. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/entry_points.txt +0 -0
  71. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/NOTICE +0 -0
  72. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -778,7 +778,7 @@
778
778
  "family": "other",
779
779
  "publisher": "OpenBMB",
780
780
  "parameters": "2B",
781
- "status": "candidate",
781
+ "status": "deprecated",
782
782
  "tasks": [
783
783
  "llm"
784
784
  ],
@@ -835,7 +835,7 @@
835
835
  "family": "other",
836
836
  "publisher": "OpenBMB",
837
837
  "parameters": "2B",
838
- "status": "candidate",
838
+ "status": "deprecated",
839
839
  "tasks": [
840
840
  "llm"
841
841
  ],
@@ -1171,71 +1171,6 @@
1171
1171
  "ssm_n_group": 8,
1172
1172
  "ssm_dt_rank": 64
1173
1173
  },
1174
- {
1175
- "id": "spark-x2.6-1.7b",
1176
- "display_name": "Spark-X2.6 1.7B",
1177
- "description": "Spark-X2.6 1.7B (2026-10, hybrid SWA attention) at Q8_0: user-selected 16 GB Mac fastest choice and every Mac's last fallback (roadmap decision 57), at a 64K window shared by two slots; no SimplexAI score, vendor anchor 55 never ranks it",
1178
- "repo": "XHToken/Spark-X2.6-1.7B-GGUF",
1179
- "license": "Apache-2.0",
1180
- "license_url": "https://huggingface.co/XHToken/Spark-X2.6-1.7B-GGUF/blob/cdc3d8893fba4ce0687f1b49ce1e18b29cae96d0/README.md",
1181
- "family": "other",
1182
- "publisher": "XHToken",
1183
- "parameters": "1.7B",
1184
- "status": "candidate",
1185
- "reasoning_efforts": [
1186
- "low",
1187
- "high"
1188
- ],
1189
- "tasks": [
1190
- "llm"
1191
- ],
1192
- "evidence": [
1193
- "2026-11-16-spark-mac16-ladder"
1194
- ],
1195
- "variants": [
1196
- {
1197
- "quant": "Q8_0",
1198
- "files": [
1199
- {
1200
- "path": "Spark-X2.6-1.7B-Q8_0.gguf",
1201
- "size_bytes": 1820113440,
1202
- "revision": "cdc3d8893fba4ce0687f1b49ce1e18b29cae96d0",
1203
- "sha256": "8d96279c95ae2be111576f3f599880598be0922efee15069b4d7e4dd96ef6ed4"
1204
- }
1205
- ],
1206
- "lazy_bytes": 0,
1207
- "embd_table_bytes": 285212672,
1208
- "mtp_layer_bytes": 0
1209
- }
1210
- ],
1211
- "n_ctx_train": 1048576,
1212
- "max_agent_window": 65536,
1213
- "full_layers": 7,
1214
- "recurrent_layers": 0,
1215
- "per_layer_f16": 2048,
1216
- "swa_layers": 21,
1217
- "swa_window": 512,
1218
- "moe": false,
1219
- "n_vocab": 131072,
1220
- "architecture": "spark2_5",
1221
- "n_embd": 2048,
1222
- "tied_embeddings": true,
1223
- "sampling": {
1224
- "top-k": "-1",
1225
- "top-p": "0.95",
1226
- "temp": "1"
1227
- },
1228
- "quality": {
1229
- "score": 55,
1230
- "sources": [
1231
- {
1232
- "type": "editorial",
1233
- "ref": "editorial anchor: vendor-reported BFCL-V4 55.2 / tau2-bench 85.3 / IFEval 89.4 (thinking=high) on https://github.com/XHToken/Spark-X2.6 (self-reported, not measured here); same table gives MiniCPM5-2B BFCL-V4 66.6 / tau2 82.2",
1234
- "date": "2026-10-30"
1235
- }
1236
- ]
1237
- }
1238
- },
1239
1174
  {
1240
1175
  "id": "spark-x2.6-4b",
1241
1176
  "display_name": "Spark-X2.6 4B",
@@ -1305,7 +1240,7 @@
1305
1240
  {
1306
1241
  "id": "spark-x2.6-4b-q4km",
1307
1242
  "display_name": "Spark-X2.6 4B",
1308
- "description": "Spark-X2.6 4B Q4_K_M candidate: user-selected Mac small-memory default (16 GB smartest, 24 GB fastest, every Mac's fallback below Qwen3.8-27B; roadmap decision 57), at a 64K window shared by two slots. No SimplexAI score; physical 16 GB Mac installation and full product acceptance pending",
1243
+ "description": "Spark-X2.6 4B Q4_K_M candidate: user-selected Mac small-memory default and fastest rung (16 GB+ Macs when no >=50-score validated model fits, roadmap decisions 57 and 61), at a 64K window shared by two slots. No SimplexAI score; physical 16 GB Mac installation and full product acceptance pending",
1309
1244
  "repo": "XHToken/Spark-X2.6-4B-GGUF",
1310
1245
  "license": "Apache-2.0",
1311
1246
  "license_url": "https://huggingface.co/XHToken/Spark-X2.6-4B-GGUF/blob/9d716770ac7477776de5f891f70cdf98b003a5cd/README.md",
@@ -1367,67 +1302,6 @@
1367
1302
  ]
1368
1303
  }
1369
1304
  },
1370
- {
1371
- "id": "lfm3-1.7b",
1372
- "display_name": "LFM3 1.7B",
1373
- "description": "Liquid LFM3-1.7B Q8_0: user-selected Mac 16/24 GB default; LFM1 component evidence, physical small-Mac installation and full product acceptance pending",
1374
- "repo": "LiquidAI/LFM3-1.7B-GGUF",
1375
- "license": "LFM Open License v1.0",
1376
- "license_url": "https://huggingface.co/LiquidAI/LFM3-1.7B-GGUF/blob/cd0c74c575b5c416f3011b5b4c298077f26ca8c2/LICENSE",
1377
- "family": "other",
1378
- "publisher": "Liquid AI",
1379
- "parameters": "1.7B",
1380
- "status": "candidate",
1381
- "tasks": [
1382
- "llm"
1383
- ],
1384
- "evidence": [
1385
- "2026-11-06-lfm-mac-8g16g"
1386
- ],
1387
- "variants": [
1388
- {
1389
- "quant": "Q8_0",
1390
- "files": [
1391
- {
1392
- "path": "LFM3-1.7B-Q8_0.gguf",
1393
- "size_bytes": 1846238496,
1394
- "revision": "cd0c74c575b5c416f3011b5b4c298077f26ca8c2",
1395
- "sha256": "8f6b24182258205e9e01e21f1f24a1f208c1e8115578825d202ce39976af20b6"
1396
- }
1397
- ],
1398
- "lazy_bytes": 0,
1399
- "embd_table_bytes": 278528000,
1400
- "mtp_layer_bytes": 0
1401
- }
1402
- ],
1403
- "n_ctx_train": 262144,
1404
- "full_layers": 6,
1405
- "recurrent_layers": 13,
1406
- "per_layer_f16": 2048,
1407
- "swa_layers": 5,
1408
- "swa_window": 256,
1409
- "moe": false,
1410
- "n_vocab": 128000,
1411
- "architecture": "lfm3",
1412
- "n_embd": 2048,
1413
- "tied_embeddings": true,
1414
- "min_engine": "b12167",
1415
- "sampling": {
1416
- "top-k": "50",
1417
- "temp": "0.1",
1418
- "repeat-penalty": "1.1"
1419
- },
1420
- "quality": {
1421
- "score": 0,
1422
- "sources": [
1423
- {
1424
- "type": "editorial",
1425
- "ref": "User decision 2026-11-08: Mac 16/24 GB default based on LFM1 BFCL 63.0 and agentloop c1/c2-n2. No SimplexAI score; 0 is unranked, not a measured capability score. evidence/2026-11-06-lfm-mac-8g16g/REPORT.md",
1426
- "date": "2026-11-08"
1427
- }
1428
- ]
1429
- }
1430
- },
1431
1305
  {
1432
1306
  "id": "ling-3.0-tiny",
1433
1307
  "display_name": "Ling 3.0 tiny",
@@ -1656,7 +1530,7 @@
1656
1530
  "family": "qwen",
1657
1531
  "publisher": "Qwen",
1658
1532
  "parameters": "2B",
1659
- "status": "candidate",
1533
+ "status": "deprecated",
1660
1534
  "tasks": [
1661
1535
  "llm"
1662
1536
  ],
@@ -287,6 +287,16 @@ _MEASURED_DECODE_TOK_S = {
287
287
  }
288
288
 
289
289
 
290
+ def decode_advisory(tok_s: float, *, measured: bool) -> str | None:
291
+ if tok_s >= PLEASANT_FLOOR_TOK_S:
292
+ return None
293
+ source = "measured on the same device model" if measured else "estimated, not measured"
294
+ return (
295
+ f"single-stream decode is below the pleasant floor of {PLEASANT_FLOOR_TOK_S:g} tok/s "
296
+ f"({source})"
297
+ )
298
+
299
+
290
300
  def is_nvidia_n1x_pci_id(pci_id: int) -> bool:
291
301
  """NVML packs the device ID above the 16-bit vendor ID."""
292
302
  return pci_id & 0xFFFF == 0x10DE and 0x2E00 <= pci_id >> 16 <= 0x2E3F
@@ -3,15 +3,20 @@
3
3
  Qwen3.8-27B's template refuses a system message after the first turn, which Claude Code sends
4
4
  (its "# Environment" block). ``chat_templates/qwen3.8-27b.jinja`` is that template with the one
5
5
  ``raise_exception`` turned into a system turn (tests/test_chat_template.py pins the original).
6
+
7
+ ``keep_prefix`` is the other step that puts files beside a llama-server deployment through
8
+ ``config_files``: the launcher that keeps the agent's prompt prefix (slot_cache.py).
6
9
  """
7
10
 
8
11
  from __future__ import annotations
9
12
 
13
+ import sys
10
14
  from pathlib import Path
11
15
 
12
16
  from localmodels.records import Launch
13
17
 
14
18
  DIRECTORY = Path(__file__).with_name("chat_templates")
19
+ SLOT_CACHE = "slot_cache.py" # copied beside an agent-posture llama.cpp deployment
15
20
 
16
21
 
17
22
  def launch(name: str, deploy_dir: str, argv: list[str], env: dict[str, str]) -> Launch:
@@ -25,3 +30,33 @@ def launch(name: str, deploy_dir: str, argv: list[str], env: dict[str, str]) ->
25
30
  service["argv"] = [*argv, "--chat-template-file", path]
26
31
  service["config_files"] = {path: (DIRECTORY / name).read_text(encoding="utf-8")}
27
32
  return service
33
+
34
+
35
+ def keep_prefix(service: Launch, root: str, *, local: bool, agent_posture: bool) -> Launch:
36
+ """Agent posture outside Windows: slot_cache.py, copied beside the deployment with the
37
+ auth_proxy.py it forwards through, serves the planned port in front of llama-server, finds
38
+ the prompt prefix the traffic repeats most and
39
+ puts it back into slot 0 after every start (llama-server saves it under ``root/slots``).
40
+ It reads the port, key and slot directory from llama-server's own flags, so a plan moved to
41
+ another port moves it too. Other launches are returned unchanged, so their plans and
42
+ approval ids stay as they were."""
43
+ if not agent_posture:
44
+ return service
45
+ slots, script = f"{root}/slots", f"{root}/{SLOT_CACHE}"
46
+ return {
47
+ **service,
48
+ "argv": [
49
+ sys.executable if local else "python3",
50
+ script,
51
+ *service["argv"],
52
+ "--slot-save-path",
53
+ slots,
54
+ ],
55
+ "config_files": {
56
+ **service.get("config_files", {}),
57
+ **{
58
+ f"{root}/{name}": Path(__file__).with_name(name).read_text(encoding="utf-8")
59
+ for name in (SLOT_CACHE, "auth_proxy.py")
60
+ },
61
+ },
62
+ }
@@ -280,6 +280,14 @@ def _synthetic_facts(real: dict[str, Any] | None, vram_gb: int) -> dict[str, Any
280
280
  "errors": [],
281
281
  }
282
282
  if is_mac:
283
+ doc["ram"].update(pressure_level=1, swap_used_bytes=0)
284
+ doc["services"] = {
285
+ "compute_processes": [],
286
+ "systemd_units": [],
287
+ "containers": [],
288
+ "ports": [],
289
+ "unknown": {},
290
+ }
283
291
  doc["metal"] = {
284
292
  "name": f"Simulated Apple Silicon ({vram_gb}GB)",
285
293
  "recommended_max_working_set_bytes": total,
@@ -506,6 +506,12 @@ def build_plan(
506
506
  if options.agent is not None and entry.mmproj is not None and mmproj is None:
507
507
  warnings.append("image input is off (--vision off): the mmproj projector is not loaded")
508
508
  require_free_port(facts, options.port, fix="pick a free port with --port")
509
+ service = chat_template.keep_prefix(
510
+ chat_template.launch(entry.chat_template, where.deploy_dir, argv, env),
511
+ where.deploy_dir,
512
+ local=host_id == hosts.LOCAL_ID,
513
+ agent_posture=options.agent is not None and facts["platform"] != "win32",
514
+ )
509
515
 
510
516
  return plan_envelope(
511
517
  host_id,
@@ -570,7 +576,7 @@ def build_plan(
570
576
  else {}
571
577
  ),
572
578
  },
573
- service=chat_template.launch(entry.chat_template, where.deploy_dir, argv, env),
579
+ service=service,
574
580
  endpoint={"model": variant.model_id},
575
581
  warnings=warnings,
576
582
  )
@@ -18,10 +18,6 @@
18
18
  "repo": "LiquidAI/LFM2.5-24B-A2B-GGUF",
19
19
  "path": "LFM2.5-24B-A2B-QAD-Q4_0.gguf"
20
20
  },
21
- "8f6b24182258205e9e01e21f1f24a1f208c1e8115578825d202ce39976af20b6": {
22
- "repo": "LiquidAI/LFM3-1.7B-GGUF",
23
- "path": "LFM3-1.7B-Q8_0.gguf"
24
- },
25
21
  "16aff27ea2eefdc32b9897f43854a5d3170c1dc8dccb9c756905af30a4e22402": {
26
22
  "repo": "LiquidAI/d1-3B-GGUF",
27
23
  "path": "d1-3B-Q4_K_M.gguf"
@@ -34,10 +30,6 @@
34
30
  "repo": "Qwen/Qwen3-Embedding-0.6B-GGUF",
35
31
  "path": "Qwen3-Embedding-0.6B-Q8_0.gguf"
36
32
  },
37
- "8d96279c95ae2be111576f3f599880598be0922efee15069b4d7e4dd96ef6ed4": {
38
- "repo": "XHToken/Spark-X2.6-1.7B-GGUF",
39
- "path": "Spark-X2.6-1.7B-Q8_0.gguf"
40
- },
41
33
  "91cb2811aebb47ac916aa619d27d4cdd7f4143106b7917accb8ead4cd7f5cbd9": {
42
34
  "repo": "XHToken/Spark-X2.6-4B-GGUF",
43
35
  "path": "Spark-X2.6-4B-Q4_K_M.gguf"
@@ -21,6 +21,7 @@ from localmodels import (
21
21
  gateway_accept,
22
22
  gateway_admin,
23
23
  gateway_clients,
24
+ gateway_home,
24
25
  gateway_keys,
25
26
  harness,
26
27
  harness_gateway,
@@ -439,6 +440,7 @@ def point_pi(plan: ToolPlan, before: str | None, target: str) -> str:
439
440
  agent = harness.gateway_environment(plan).get("PI_CODING_AGENT_DIR")
440
441
  home = harness_probe.gateway_home(plan["tools_dir"])
441
442
  if agent and Path(agent).is_relative_to(home):
443
+ gateway_home.reclaim(plan["tools_dir"]) # an elevated run's folder (GitLab #15)
442
444
  runtime_io.private_directory(Path(agent))
443
445
  _require(_magpie(plan, "pi", target), "pi")
444
446
  return f"pi → {model}"
@@ -19,6 +19,7 @@ from localmodels import (
19
19
  bifrost_datasheet,
20
20
  bifrost_search,
21
21
  bifrost_unit,
22
+ gateway_home,
22
23
  gateway_keys,
23
24
  harness,
24
25
  harness_gateway,
@@ -430,6 +431,8 @@ def ensure(plan: ToolPlan) -> str:
430
431
  previous = require_target(plan)
431
432
  if previous and previous["binary"] != harness.tool_path(plan, "bifrost"):
432
433
  _retire(previous)
434
+ if "environment" not in plan:
435
+ gateway_home.reclaim(plan["tools_dir"]) # an elevated run's folder (GitLab #15)
433
436
  harness_gateway.private_home(plan) # before wire writes pi and the clients into it
434
437
  record = _record(plan, _gateway(plan)["action"])
435
438
  app = Path(record["app_dir"])
@@ -0,0 +1,132 @@
1
+ """Recover this tool's private gateway client context, ``gateway-home``, on Windows.
2
+
3
+ An elevated run (Run as administrator, or an elevated shell) creates files owned by
4
+ BUILTIN\\Administrators, not by the user. A ``gateway-home`` made that way fails the private
5
+ check of every later, unelevated run, so every library load failed after its model reached the
6
+ GPU (GitLab #15). Such an owner can only come from an elevated process, so when the tools
7
+ directory around it is this user's private one, the folder is this tool's own: its contents are
8
+ copied into a new private ``gateway-home`` and the old folder is kept beside it, renamed, for
9
+ the user to delete. Any other foreign owner is left alone and reported with a remedy
10
+ (``GatewayHomeError``). The location does not move (a later release decides that).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from localmodels import harness, harness_probe, runtime_io
23
+
24
+ ADMINISTRATORS_SID = "S-1-5-32-544"
25
+ STAGING = "gateway-home.recovering"
26
+ BACKUP_PREFIX = "gateway-home.elevated-"
27
+ CAUSE = "GATEWAY_HOME_NOT_PRIVATE"
28
+ _REPARSE_POINT = 0x400
29
+
30
+
31
+ class GatewayHomeError(harness.HarnessError):
32
+ """``gateway-home`` is not this user's private folder and this tool cannot prove it its own:
33
+ ``cause`` and ``path`` are the structured fields an installer maps to its own copy."""
34
+
35
+ cause = CAUSE
36
+
37
+ def __init__(self, path: Path, why: str) -> None:
38
+ self.path = path
39
+ super().__init__(
40
+ f"{path} is not a private folder of the current Windows user ({why}); nothing was "
41
+ "changed. Close Linger and stop the localmodels gateway if it is running, then rename "
42
+ "that folder in File Explorer (for example to gateway-home.old; ask an administrator "
43
+ "if Windows denies it) and try again without Run as administrator."
44
+ )
45
+
46
+
47
+ def reclaim(tools_dir: str) -> Path | None:
48
+ """On Windows, replace an Administrators-owned ``gateway-home`` with a private copy; return
49
+ where the old folder was kept, or None when there was nothing to recover. Elsewhere, or when
50
+ the folder is missing or already private, nothing happens."""
51
+ if sys.platform != "win32":
52
+ return None
53
+ home = harness_probe.gateway_home(tools_dir)
54
+ if not os.path.lexists(home):
55
+ return None
56
+ try:
57
+ runtime_io.private_permissions(home)
58
+ return None
59
+ except ValueError as exc:
60
+ problem = str(exc)
61
+ parent = home.parent
62
+ try:
63
+ runtime_io.private_permissions(parent)
64
+ except ValueError as exc:
65
+ raise GatewayHomeError(home, f"{problem}; its parent folder: {exc}") from None
66
+ try:
67
+ owner = owner_sid(home)
68
+ except (OSError, ValueError) as exc:
69
+ raise GatewayHomeError(home, f"{problem}; owner unreadable: {exc}") from None
70
+ if owner != ADMINISTRATORS_SID:
71
+ raise GatewayHomeError(home, f"{problem}; owner {owner}")
72
+ return _replace(home)
73
+
74
+
75
+ def _replace(home: Path) -> Path:
76
+ staging = home.with_name(STAGING)
77
+ backup = home.with_name(BACKUP_PREFIX + time.strftime("%Y%m%dT%H%M%S"))
78
+ try:
79
+ if os.path.lexists(staging):
80
+ runtime_io.private_permissions(staging) # a copy an interrupted recovery left
81
+ shutil.rmtree(staging)
82
+ runtime_io.private_directory(staging)
83
+ _copy(home, staging)
84
+ os.rename(home, backup)
85
+ except (OSError, ValueError) as exc:
86
+ shutil.rmtree(staging, ignore_errors=True)
87
+ raise GatewayHomeError(home, f"owned by Administrators; recovery failed: {exc}") from None
88
+ try:
89
+ os.rename(staging, home)
90
+ except OSError as exc:
91
+ os.rename(backup, home) # put the original back; the copy is discarded
92
+ shutil.rmtree(staging, ignore_errors=True)
93
+ raise GatewayHomeError(home, f"owned by Administrators; recovery failed: {exc}") from None
94
+ return backup
95
+
96
+
97
+ def _copy(source: Path, target: Path) -> None:
98
+ """Regular files and folders only; links and junctions are not followed or copied. New files
99
+ inherit the private folder's access list."""
100
+ for entry in os.scandir(source):
101
+ info = entry.stat(follow_symlinks=False)
102
+ if entry.is_symlink() or getattr(info, "st_file_attributes", 0) & _REPARSE_POINT:
103
+ continue
104
+ destination = target / entry.name
105
+ if entry.is_dir(follow_symlinks=False):
106
+ destination.mkdir()
107
+ _copy(Path(entry.path), destination)
108
+ elif entry.is_file(follow_symlinks=False):
109
+ shutil.copyfile(entry.path, destination)
110
+
111
+
112
+ def owner_sid(path: Path) -> str:
113
+ """The owner of ``path`` as a string SID (Windows only)."""
114
+ import ctypes
115
+
116
+ api, kernel = _api()
117
+ owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
118
+ try:
119
+ # SE_FILE_OBJECT (1), OWNER_SECURITY_INFORMATION (1)
120
+ error = api.GetNamedSecurityInfoW(
121
+ str(path), 1, 0x1, ctypes.byref(owner), None, None, None, ctypes.byref(descriptor)
122
+ )
123
+ if error:
124
+ raise OSError(error, "cannot read the folder's owner")
125
+ return runtime_io._windows_sid_text(api, kernel, owner)
126
+ finally:
127
+ if descriptor.value:
128
+ kernel.LocalFree(descriptor)
129
+
130
+
131
+ def _api() -> tuple[Any, Any]:
132
+ return runtime_io._windows_api()
@@ -17,10 +17,11 @@ import shutil
17
17
  import subprocess
18
18
  import tempfile
19
19
  from collections.abc import Callable
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
21
  from pathlib import Path
21
22
  from typing import Any, Literal, TypedDict, cast
22
23
 
23
- from localmodels import harness_probe, hosts, region
24
+ from localmodels import harness_probe, hosts, region, runtime_discovery
24
25
  from localmodels.contracts import decode
25
26
  from localmodels.harness_cleanup import (
26
27
  changed as changed,
@@ -51,6 +52,7 @@ from localmodels.npm_transport import install_bifrost
51
52
  from localmodels.remote_ops import Archive, fetch
52
53
  from localmodels.remote_ops_download import npm_copies
53
54
  from localmodels.runtime_io import error_cause
55
+ from localmodels.stack_events import CombinedEvents as _CombinedEvents
54
56
  from localmodels.stack_events import ToolEvents
55
57
  from localmodels.tool_archive import (
56
58
  ArchiveError,
@@ -114,6 +116,7 @@ class PiLock(NpmArtifact):
114
116
 
115
117
  entry: str
116
118
  modules: list[PiModule]
119
+ longest_path: int # characters of the deepest file below the package root
117
120
 
118
121
 
119
122
  class MagpieLock(TypedDict):
@@ -357,8 +360,8 @@ def plan_tools(
357
360
  and not _owned_wrapper(wrapper)
358
361
  ):
359
362
  raise HarnessError(
360
- f"{wrapper} exists but does not run and localmodels did not create it;"
361
- " deal with it first"
363
+ f"{wrapper} exists but does not run or cannot load extensions, and localmodels"
364
+ " did not create it; deal with it first"
362
365
  )
363
366
  if not state["bin_on_path"]:
364
367
  warnings.append(
@@ -515,18 +518,48 @@ def _fetch(tools_dir: Path, artifact: Artifact, log: Callable[[str], None]) -> P
515
518
  staged.replace(path)
516
519
  return path
517
520
  with contextlib.redirect_stdout(_Events(log)):
518
- fetch(
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(),
526
- )
521
+ _download(path, artifact)
527
522
  return path
528
523
 
529
524
 
525
+ def _download(path: Path, artifact: Artifact) -> None:
526
+ fetch(
527
+ artifact["url"],
528
+ str(path),
529
+ artifact["sha256"],
530
+ artifact["size_bytes"],
531
+ artifact["name"],
532
+ npm_copies(cast(Archive, artifact)),
533
+ region.current_region(),
534
+ )
535
+
536
+
537
+ PI_DOWNLOADS = 8 # pi's tree is ~120 small tarballs; one at a time takes minutes
538
+
539
+
540
+ def _fetch_many(
541
+ tools_dir: Path, artifacts: list[Artifact], log: Callable[[str], None]
542
+ ) -> list[Path]:
543
+ """Download ``artifacts`` eight at a time, reported as one download of their total bytes;
544
+ the first failure cancels the ones still queued. A tarball two of them share downloads
545
+ once."""
546
+ unique = {a["name"]: a for a in artifacts}
547
+ events = _CombinedEvents(log, {name: a["size_bytes"] for name, a in unique.items()})
548
+ pool = ThreadPoolExecutor(PI_DOWNLOADS)
549
+ try:
550
+ with contextlib.redirect_stdout(events):
551
+ futures = {
552
+ pool.submit(_download, tools_dir / ".archives" / name, a): name
553
+ for name, a in unique.items()
554
+ }
555
+ for future in as_completed(futures):
556
+ future.result()
557
+ events.finished(futures[future])
558
+ finally:
559
+ pool.shutdown(wait=True, cancel_futures=True)
560
+ return [tools_dir / ".archives" / a["name"] for a in artifacts]
561
+
562
+
530
563
  def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], marker: str) -> Path:
531
564
  """Unpack into tools_dir/name once; a matching .complete marker means it is already there."""
532
565
  final = tools_dir / name
@@ -559,7 +592,7 @@ def _install_pi(
559
592
  modules = action["artifacts"][1:]
560
593
  if any("path" not in m for m in modules): # plans saved before 2026-11-18
561
594
  raise HarnessError("this plan installs pi without its dependency tree; plan again")
562
- archives = [_fetch(tools_dir, a, log) for a in action["artifacts"]]
595
+ archives = _fetch_many(tools_dir, action["artifacts"], log)
563
596
 
564
597
  def unpack_pi(dest: Path) -> None:
565
598
  _safe_extract(archives[0], dest)
@@ -577,6 +610,8 @@ def _install_pi(
577
610
  about = f"{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; remove this file and {tree}"
578
611
  write_launcher(wrapper, [node, str(tree / pi["entry"])], about)
579
612
  wrapper.chmod(0o755)
613
+ if not runtime_discovery.pi_loads_extensions([str(wrapper)]):
614
+ raise HarnessError(f"pi {pi['version']} at {wrapper} could not load an extension")
580
615
  log(f"pi {pi['version']} installed: {wrapper}")
581
616
  return [str(tree), str(wrapper)]
582
617
 
@@ -13,7 +13,7 @@ import sys
13
13
  from pathlib import Path
14
14
  from typing import TYPE_CHECKING, TypedDict
15
15
 
16
- from localmodels import hosts
16
+ from localmodels import hosts, runtime_discovery
17
17
 
18
18
  if TYPE_CHECKING:
19
19
  from localmodels import harness
@@ -264,6 +264,10 @@ def inspect(
264
264
  pi_version = (
265
265
  first_line(harness.run_tool([pi, "--version"], timeout=30, env=env)) if pi else None
266
266
  )
267
+ if pi and pi_version and not runtime_discovery.pi_loads_extensions([pi], env):
268
+ # localmodels before 0.1.0.dev39 installed pi without jiti, so it cannot load the
269
+ # extension Linger starts it with: plan_tools installs the pinned tree over an owned one.
270
+ pi_version = None
267
271
  magpie_version = pi_model = None
268
272
  gateway_up = False
269
273
  if magpie and not bifrost:
@@ -28,6 +28,7 @@ from localmodels import (
28
28
  bifrost_models,
29
29
  bifrost_unit,
30
30
  gateway_bifrost,
31
+ gateway_home,
31
32
  harness,
32
33
  harness_probe,
33
34
  hosts,
@@ -66,6 +67,16 @@ def pi_profile() -> Path:
66
67
  return Path(harness_probe.client_environment(hosts.tools_dir())["PI_CODING_AGENT_DIR"])
67
68
 
68
69
 
70
+ def _gateway_error(exc: Exception) -> LibraryError:
71
+ """GATEWAY_REGISTRATION_FAILED for ``exc``; a gateway-home this tool could not recover
72
+ (GitLab #15) adds ``cause`` and ``path`` for the installer's own remedy copy."""
73
+ if isinstance(exc, gateway_home.GatewayHomeError):
74
+ return LibraryError(
75
+ "GATEWAY_REGISTRATION_FAILED", str(exc), cause=exc.cause, path=str(exc.path)
76
+ )
77
+ return _fail(str(exc))
78
+
79
+
69
80
  def _fail(detail: str) -> LibraryError:
70
81
  return LibraryError("GATEWAY_REGISTRATION_FAILED", detail)
71
82
 
@@ -423,7 +434,7 @@ def _register(
423
434
  except LibraryError:
424
435
  raise
425
436
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
426
- raise _fail(str(exc)) from None
437
+ raise _gateway_error(exc) from None
427
438
  return added
428
439
 
429
440
 
@@ -446,7 +457,7 @@ def _unregister(registration: Registration) -> None:
446
457
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
447
458
  apply_config(record, config, sheet)
448
459
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
449
- raise _fail(str(exc)) from None
460
+ raise _gateway_error(exc) from None
450
461
 
451
462
 
452
463
  def _stack_owns_pi() -> bool: