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

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 (82) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +81 -73
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/auth_proxy.py +74 -16
  6. package/modules/localmodels/bifrost_config.py +19 -0
  7. package/modules/localmodels/budget.py +27 -18
  8. package/modules/localmodels/catalog.json +18 -6
  9. package/modules/localmodels/chat_template.py +35 -0
  10. package/modules/localmodels/cli_parser.py +26 -3
  11. package/modules/localmodels/deploy.py +44 -10
  12. package/modules/localmodels/deploy_steps.py +6 -3
  13. package/modules/localmodels/download-mirrors.json +52 -4
  14. package/modules/localmodels/engines-b11583.json +20 -4
  15. package/modules/localmodels/engines-b12167.json +5 -1
  16. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  19. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  20. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  21. package/modules/localmodels/engines.json +55 -11
  22. package/modules/localmodels/frontend.py +5 -2
  23. package/modules/localmodels/gateway.py +2 -0
  24. package/modules/localmodels/gateway_bifrost.py +3 -0
  25. package/modules/localmodels/gateway_home.py +132 -0
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +104 -37
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/harness_probe.py +5 -1
  30. package/modules/localmodels/hf_repo.py +15 -8
  31. package/modules/localmodels/library_gateway.py +28 -15
  32. package/modules/localmodels/library_jobs.py +7 -1
  33. package/modules/localmodels/library_serve.py +5 -0
  34. package/modules/localmodels/metal.py +29 -12
  35. package/modules/localmodels/metal_probe.py +16 -6
  36. package/modules/localmodels/npm_signatures.py +131 -0
  37. package/modules/localmodels/npm_transport.py +26 -10
  38. package/modules/localmodels/probe.py +4 -0
  39. package/modules/localmodels/process_identity.py +21 -5
  40. package/modules/localmodels/region.py +244 -0
  41. package/modules/localmodels/remote_ops.py +69 -13
  42. package/modules/localmodels/remote_ops_download.py +217 -10
  43. package/modules/localmodels/remote_ops_prepare.py +61 -8
  44. package/modules/localmodels/remote_ops_remove.py +15 -0
  45. package/modules/localmodels/remote_ops_service.py +10 -0
  46. package/modules/localmodels/runtime-lock.json +13 -13
  47. package/modules/localmodels/runtime_args.py +4 -2
  48. package/modules/localmodels/runtime_cli.py +76 -74
  49. package/modules/localmodels/runtime_discovery.py +58 -0
  50. package/modules/localmodels/runtime_install.py +103 -7
  51. package/modules/localmodels/runtime_io.py +64 -7
  52. package/modules/localmodels/runtime_pi.py +122 -0
  53. package/modules/localmodels/runtime_process.py +101 -15
  54. package/modules/localmodels/runtime_releases.py +51 -71
  55. package/modules/localmodels/service_deployment.py +5 -3
  56. package/modules/localmodels/service_probe.py +146 -31
  57. package/modules/localmodels/setup_inspection.py +110 -14
  58. package/modules/localmodels/setup_text.py +13 -0
  59. package/modules/localmodels/slot_cache.py +467 -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_args.py +2 -1
  64. package/modules/localmodels/stack_binding.py +125 -5
  65. package/modules/localmodels/stack_capacity.py +3 -3
  66. package/modules/localmodels/stack_down.py +22 -7
  67. package/modules/localmodels/stack_events.py +62 -0
  68. package/modules/localmodels/stack_hardware.py +20 -17
  69. package/modules/localmodels/stack_lifecycle.py +12 -3
  70. package/modules/localmodels/stack_rollback.py +9 -4
  71. package/modules/localmodels/stack_up.py +27 -20
  72. package/modules/localmodels/stack_update.py +3 -1
  73. package/modules/localmodels/tools.json +1365 -14
  74. package/modules/localmodels/transport.py +2 -0
  75. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
  76. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +78 -70
  77. package/package.json +1 -1
  78. package/tool.json +1 -1
  79. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -18,7 +18,11 @@
18
18
  "name": "llama-b11370-bin-ubuntu-cuda-12.8-x64.tar.gz",
19
19
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-cuda-12.8-x64.tar.gz",
20
20
  "sha256": "047089347a554f06ada3d8036be8c74cba0e77add5188f31fd502303de5d272c",
21
- "size_bytes": 171364601
21
+ "size_bytes": 171364601,
22
+ "npm_copy": {
23
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-cuda-12.8-x64",
24
+ "version": "0.0.0-sha256-047089347a554f06"
25
+ }
22
26
  },
23
27
  {
24
28
  "name": "cudart-llama-b11370-bin-ubuntu-cuda-12.8-x64.tar.gz",
@@ -65,7 +69,11 @@
65
69
  "name": "llama-b11370-bin-ubuntu-cuda-13.4-x64.tar.gz",
66
70
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-cuda-13.4-x64.tar.gz",
67
71
  "sha256": "81ced34431758b1d1932cf7eb99852598c76bec1885009f4519ad4f54bb0159b",
68
- "size_bytes": 152247644
72
+ "size_bytes": 152247644,
73
+ "npm_copy": {
74
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-cuda-13.4-x64",
75
+ "version": "0.0.0-sha256-81ced34431758b1d"
76
+ }
69
77
  },
70
78
  {
71
79
  "name": "cudart-llama-b11370-bin-ubuntu-cuda-13.4-x64.tar.gz",
@@ -89,7 +97,11 @@
89
97
  "name": "llama-b11370-bin-ubuntu-cuda-13.4-arm64.tar.gz",
90
98
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-cuda-13.4-arm64.tar.gz",
91
99
  "sha256": "d417ce88799fb5bca9a51b53c36585fec9d7a8e7415873424919af0cb64d33e2",
92
- "size_bytes": 147493813
100
+ "size_bytes": 147493813,
101
+ "npm_copy": {
102
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-cuda-13.4-arm64",
103
+ "version": "0.0.0-sha256-d417ce88799fb5bc"
104
+ }
93
105
  },
94
106
  {
95
107
  "name": "cudart-llama-b11370-bin-ubuntu-cuda-13.4-arm64.tar.gz",
@@ -111,7 +123,11 @@
111
123
  "name": "llama-b11370-bin-ubuntu-vulkan-x64.tar.gz",
112
124
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-vulkan-x64.tar.gz",
113
125
  "sha256": "46bb8add9cf46dee199692cf7852927758d7b2ad663949d81c8c80974032a398",
114
- "size_bytes": 31577653
126
+ "size_bytes": 31577653,
127
+ "npm_copy": {
128
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-vulkan-x64",
129
+ "version": "0.0.0-sha256-46bb8add9cf46dee"
130
+ }
115
131
  }
116
132
  ]
117
133
  },
@@ -127,7 +143,11 @@
127
143
  "name": "llama-b11370-bin-ubuntu-vulkan-arm64.tar.gz",
128
144
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-vulkan-arm64.tar.gz",
129
145
  "sha256": "cb8ab033dd9565e0d82aa3b6c407527966661d8a1736ae083c417338025d4e9d",
130
- "size_bytes": 24820336
146
+ "size_bytes": 24820336,
147
+ "npm_copy": {
148
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-vulkan-arm64",
149
+ "version": "0.0.0-sha256-cb8ab033dd9565e0"
150
+ }
131
151
  }
132
152
  ]
133
153
  },
@@ -159,7 +179,11 @@
159
179
  "name": "llama-b11370-bin-ubuntu-x64.tar.gz",
160
180
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-x64.tar.gz",
161
181
  "sha256": "1c86f91cb0e2bbf5bce7eae7c0ce6beb95137e41251b1dbb19839175d624d0cf",
162
- "size_bytes": 17634362
182
+ "size_bytes": 17634362,
183
+ "npm_copy": {
184
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-x64",
185
+ "version": "0.0.0-sha256-1c86f91cb0e2bbf5"
186
+ }
163
187
  }
164
188
  ],
165
189
  "min_glibc": "2.34"
@@ -176,7 +200,11 @@
176
200
  "name": "llama-b11370-bin-ubuntu-arm64.tar.gz",
177
201
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-ubuntu-arm64.tar.gz",
178
202
  "sha256": "2589668b61f4b2a2baa1a860c45e3dbd75af89e3620340589929632d981d28f2",
179
- "size_bytes": 13661001
203
+ "size_bytes": 13661001,
204
+ "npm_copy": {
205
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu-arm64",
206
+ "version": "0.0.0-sha256-2589668b61f4b2a2"
207
+ }
180
208
  }
181
209
  ]
182
210
  },
@@ -189,7 +217,11 @@
189
217
  "name": "llama-b11370-bin-macos-arm64.tar.gz",
190
218
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-macos-arm64.tar.gz",
191
219
  "sha256": "9d7d074ca8db0c2233af760ca2ad89182a52c909abdcbfa3b94e27fb78de9355",
192
- "size_bytes": 11894187
220
+ "size_bytes": 11894187,
221
+ "npm_copy": {
222
+ "package": "@simplexai/engine-llama-b11370-bin-macos-arm64",
223
+ "version": "0.0.0-sha256-9d7d074ca8db0c22"
224
+ }
193
225
  }
194
226
  ]
195
227
  },
@@ -202,7 +234,11 @@
202
234
  "name": "llama-b11370-bin-macos-x64.tar.gz",
203
235
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-macos-x64.tar.gz",
204
236
  "sha256": "2bdcdc8936621840fc246198da8a7d4e87d2db58ae232c6126ee54b594be3746",
205
- "size_bytes": 11445204
237
+ "size_bytes": 11445204,
238
+ "npm_copy": {
239
+ "package": "@simplexai/engine-llama-b11370-bin-macos-x64",
240
+ "version": "0.0.0-sha256-2bdcdc8936621840"
241
+ }
206
242
  }
207
243
  ]
208
244
  },
@@ -238,7 +274,11 @@
238
274
  "name": "llama-b11370-bin-win-cuda-13.4-x64.zip",
239
275
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-win-cuda-13.4-x64.zip",
240
276
  "sha256": "05a1e951d7eb3fb32a8159b6f6dc06f5e8f681154b57369d585ae4100bae4999",
241
- "size_bytes": 152876036
277
+ "size_bytes": 152876036,
278
+ "npm_copy": {
279
+ "package": "@simplexai/engine-llama-b11370-bin-win-cuda-13.4-x64",
280
+ "version": "0.0.0-sha256-05a1e951d7eb3fb3"
281
+ }
242
282
  },
243
283
  {
244
284
  "name": "cudart-llama-bin-win-cuda-13.4-x64.zip",
@@ -258,7 +298,11 @@
258
298
  "name": "llama-b11370-bin-win-cpu-x64.zip",
259
299
  "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11370/llama-b11370-bin-win-cpu-x64.zip",
260
300
  "sha256": "e433a6b1592af1deedf001dcc1abc933e990be8dc94e5d28104c3c4406a1d35f",
261
- "size_bytes": 19333283
301
+ "size_bytes": 19333283,
302
+ "npm_copy": {
303
+ "package": "@simplexai/engine-llama-b11370-bin-win-cpu-x64",
304
+ "version": "0.0.0-sha256-e433a6b1592af1de"
305
+ }
262
306
  }
263
307
  ]
264
308
  }
@@ -18,7 +18,7 @@ import sys
18
18
  from collections.abc import Callable
19
19
  from pathlib import Path
20
20
 
21
- from localmodels import hosts
21
+ from localmodels import hosts, region
22
22
  from localmodels.component import front_venv, venv_python
23
23
  from localmodels.records import Plan
24
24
 
@@ -105,8 +105,11 @@ def install(
105
105
  [interpreter or sys.executable, "-m", "venv", "--without-pip", str(venv)],
106
106
  _installer(python, source),
107
107
  ]
108
+ env = region.pip_environment() # hash-locked; in cn a China index unless pip has its own
108
109
  for command in steps:
109
- result = subprocess.run(command, capture_output=True, text=True, timeout=1200, check=False)
110
+ result = subprocess.run(
111
+ command, capture_output=True, text=True, timeout=1200, check=False, env=env
112
+ )
110
113
  if result.returncode:
111
114
  raise FrontendError(
112
115
  f"{' '.join(command[:4])} failed: {(result.stderr or result.stdout).strip()[-400:]}"
@@ -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()
@@ -15,7 +15,7 @@ import sys
15
15
  from pathlib import Path
16
16
  from typing import Literal, TypedDict
17
17
 
18
- from localmodels import cli_help, http_local, probe
18
+ from localmodels import cli_help, http_local, probe, region
19
19
  from localmodels.catalog import ComponentRecipe, component_recipe
20
20
  from localmodels.contracts import decode
21
21
  from localmodels.privacy import PrivacyError, PrivacySession, Span, parse_spans, strict_json
@@ -148,7 +148,9 @@ def _check_tree(directory: Path) -> None:
148
148
 
149
149
 
150
150
  def _run(command: list[str], *, timeout: int) -> None:
151
- result = subprocess.run(command, capture_output=True, timeout=timeout, check=False)
151
+ result = subprocess.run(
152
+ command, capture_output=True, timeout=timeout, check=False, env=region.pip_environment()
153
+ )
152
154
  if result.returncode:
153
155
  raise PrivacyError("CPU runtime setup failed; rerun the same approved plan")
154
156
 
@@ -231,14 +233,19 @@ def _download(directory: Path, recipe: ComponentRecipe) -> None:
231
233
  or _sha(target) != item["sha256"]
232
234
  ):
233
235
  marker.unlink()
234
- fetch(
235
- f"https://huggingface.co/{recipe['repo']}/resolve/{recipe['revision']}/{path}",
236
+ switch = fetch(
237
+ f"{region.HF_API}/{recipe['repo']}/resolve/{recipe['revision']}/{path}",
236
238
  str(target),
237
239
  str(item["sha256"]),
238
240
  int(str(item["size_bytes"])),
239
241
  path,
242
+ None,
243
+ where,
240
244
  )
245
+ if switch:
246
+ region.fallback_to(switch)
241
247
 
248
+ where = region.current_region()
242
249
  with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
243
250
  list(pool.map(download, [dict(item) for item in recipe["files"]]))
244
251
 
@@ -346,8 +353,10 @@ def _prepare_parsers(commands: argparse._SubParsersAction[argparse.ArgumentParse
346
353
  cli_help.document(
347
354
  command,
348
355
  "Prepare the plan's directory: copy the worker and its runtime lock, download the pinned "
349
- "model files from huggingface.co with size and SHA256 checks, create a venv with this "
350
- "Python and pip install the hash-locked CPU wheels, then verify every file. Refuses "
356
+ "model files from huggingface.co (hf-mirror.com first in region cn) with size and SHA256 "
357
+ "checks, create a venv with this Python and pip install the hash-locked CPU wheels (from "
358
+ "a China PyPI mirror in region cn unless pip has an index of its own), then verify every "
359
+ "file. Refuses "
351
360
  "unless --approve equals the plan's plan_id and a plan built now (same Python, same "
352
361
  "package) is identical, the directory is empty or marked as this recipe's, and free disk "
353
362
  "and available RAM leave headroom. Prints a short JSON result; after an interruption "
@@ -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
@@ -16,10 +17,11 @@ import shutil
16
17
  import subprocess
17
18
  import tempfile
18
19
  from collections.abc import Callable
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
19
21
  from pathlib import Path
20
22
  from typing import Any, Literal, TypedDict, cast
21
23
 
22
- from localmodels import harness_probe, hosts
24
+ from localmodels import harness_probe, hosts, region, runtime_discovery
23
25
  from localmodels.contracts import decode
24
26
  from localmodels.harness_cleanup import (
25
27
  changed as changed,
@@ -47,8 +49,10 @@ from localmodels.harness_probe import shown_pi_model as shown_pi_model
47
49
  from localmodels.npm_transport import Artifact as Artifact
48
50
  from localmodels.npm_transport import ToolBuild as ToolBuild
49
51
  from localmodels.npm_transport import install_bifrost
50
- from localmodels.remote_ops import fetch
52
+ from localmodels.remote_ops import Archive, fetch
53
+ from localmodels.remote_ops_download import npm_copies
51
54
  from localmodels.runtime_io import error_cause
55
+ from localmodels.stack_events import CombinedEvents as _CombinedEvents
52
56
  from localmodels.stack_events import ToolEvents
53
57
  from localmodels.tool_archive import (
54
58
  ArchiveError,
@@ -97,9 +101,22 @@ class NpmArtifact(TypedDict):
97
101
  integrity: str
98
102
 
99
103
 
104
+ class _PiModuleOptional(NpmArtifact, total=False):
105
+ install_script: str # "skipped": npm would run one; scripts/pin_pi.py says why it is not
106
+
107
+
108
+ class PiModule(_PiModuleOptional):
109
+ path: (
110
+ str # its place under the package root, npm's lockfile key: node_modules/a[/node_modules/b]
111
+ )
112
+
113
+
100
114
  class PiLock(NpmArtifact):
115
+ """pi and its whole production dependency tree, written by scripts/pin_pi.py."""
116
+
101
117
  entry: str
102
- modules: list[NpmArtifact]
118
+ modules: list[PiModule]
119
+ longest_path: int # characters of the deepest file below the package root
103
120
 
104
121
 
105
122
  class MagpieLock(TypedDict):
@@ -275,7 +292,7 @@ def tool_build(builds: list[ToolBuild], platform: str, arch: str, tool: str) ->
275
292
  return match
276
293
 
277
294
 
278
- def tool_artifact(item: ToolBuild | NpmArtifact) -> Artifact:
295
+ def tool_artifact(item: ToolBuild | NpmArtifact | PiModule) -> Artifact:
279
296
  artifact: Artifact = {
280
297
  "name": item["name"],
281
298
  "url": item["url"],
@@ -284,6 +301,10 @@ def tool_artifact(item: ToolBuild | NpmArtifact) -> Artifact:
284
301
  }
285
302
  if "npm" in item:
286
303
  artifact["npm"] = cast(ToolBuild, item)["npm"]
304
+ if "npm_copy" in item:
305
+ artifact["npm_copy"] = cast(ToolBuild, item)["npm_copy"]
306
+ if "path" in item:
307
+ artifact["path"] = cast(PiModule, item)["path"]
287
308
  return artifact
288
309
 
289
310
 
@@ -339,8 +360,8 @@ def plan_tools(
339
360
  and not _owned_wrapper(wrapper)
340
361
  ):
341
362
  raise HarnessError(
342
- f"{wrapper} exists but does not run and localmodels did not create it;"
343
- " 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"
344
365
  )
345
366
  if not state["bin_on_path"]:
346
367
  warnings.append(
@@ -497,12 +518,48 @@ def _fetch(tools_dir: Path, artifact: Artifact, log: Callable[[str], None]) -> P
497
518
  staged.replace(path)
498
519
  return path
499
520
  with contextlib.redirect_stdout(_Events(log)):
500
- fetch(
501
- artifact["url"], str(path), artifact["sha256"], artifact["size_bytes"], artifact["name"]
502
- )
521
+ _download(path, artifact)
503
522
  return path
504
523
 
505
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
+
506
563
  def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], marker: str) -> Path:
507
564
  """Unpack into tools_dir/name once; a matching .complete marker means it is already there."""
508
565
  final = tools_dir / name
@@ -522,6 +579,43 @@ def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], ma
522
579
  return final
523
580
 
524
581
 
582
+ def _install_pi(
583
+ tools_dir: Path,
584
+ bin_dir: Path,
585
+ action: ToolAction,
586
+ pi: PiLock,
587
+ node: str,
588
+ log: Callable[[str], None],
589
+ ) -> list[str]:
590
+ """pi's package with its dependency tree, each module at the plan's path, and the wrapper
591
+ in ``bin_dir``; returns the tree and the wrapper."""
592
+ modules = action["artifacts"][1:]
593
+ if any("path" not in m for m in modules): # plans saved before 2026-11-18
594
+ raise HarnessError("this plan installs pi without its dependency tree; plan again")
595
+ archives = _fetch_many(tools_dir, action["artifacts"], log)
596
+
597
+ def unpack_pi(dest: Path) -> None:
598
+ _safe_extract(archives[0], dest)
599
+ for module, archive in zip(modules, archives[1:], strict=True):
600
+ target = dest.joinpath(*module["path"].split("/"))
601
+ target.mkdir(parents=True)
602
+ _safe_extract(archive, target)
603
+
604
+ marker = hashlib.sha256(",".join(a["sha256"] for a in action["artifacts"]).encode())
605
+ tree = _install_tree(tools_dir, f"pi-{pi['version']}", unpack_pi, marker.hexdigest())
606
+ wrapper = bin_dir / launcher_name()
607
+ bin_dir.mkdir(parents=True, exist_ok=True)
608
+ if wrapper.exists() and not _owned_wrapper(str(wrapper)):
609
+ raise HarnessError(f"{wrapper} exists and localmodels did not create it; not overwritten")
610
+ about = f"{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; remove this file and {tree}"
611
+ write_launcher(wrapper, [node, str(tree / pi["entry"])], about)
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")
615
+ log(f"pi {pi['version']} installed: {wrapper}")
616
+ return [str(tree), str(wrapper)]
617
+
618
+
525
619
  def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: None) -> list[str]:
526
620
  """Install the tools the plan marks ``install``; returns the paths created (owned)."""
527
621
  lock = load_lock()
@@ -543,34 +637,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
543
637
  owned.append(str(tree))
544
638
  log(f"Node.js {lock['node']['version']} installed to {tree}")
545
639
  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}")
640
+ owned += _install_pi(tools_dir, bin_dir, actions["pi"], lock["pi"], node, log)
574
641
  if "bifrost" in actions and actions["bifrost"]["action"] == "install":
575
642
  from localmodels import gateway_bifrost
576
643
 
@@ -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"
@@ -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: