@simplexai/localmodels-linux-arm64 0.1.0-dev.62 → 0.1.0-dev.63

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 (57) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +56 -54
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_checks.py +19 -13
  5. package/modules/localmodels/bifrost_clients.py +38 -36
  6. package/modules/localmodels/bifrost_config.py +19 -6
  7. package/modules/localmodels/bifrost_log.py +3 -3
  8. package/modules/localmodels/bifrost_models.py +9 -8
  9. package/modules/localmodels/bifrost_pi.py +27 -72
  10. package/modules/localmodels/catalog.json +51 -58
  11. package/modules/localmodels/custom_hub.py +10 -1
  12. package/modules/localmodels/custom_hub_http.py +14 -3
  13. package/modules/localmodels/debug_mode.py +3 -3
  14. package/modules/localmodels/gateway.py +56 -55
  15. package/modules/localmodels/gateway_bifrost.py +70 -83
  16. package/modules/localmodels/gateway_clients.py +33 -116
  17. package/modules/localmodels/gateway_home.py +5 -5
  18. package/modules/localmodels/gateway_keys.py +8 -6
  19. package/modules/localmodels/gateway_probe.py +4 -4
  20. package/modules/localmodels/gateway_server.py +4 -4
  21. package/modules/localmodels/gateway_speed.py +2 -2
  22. package/modules/localmodels/harness.py +185 -401
  23. package/modules/localmodels/harness_core.py +409 -0
  24. package/modules/localmodels/harness_gateway.py +75 -73
  25. package/modules/localmodels/harness_probe.py +19 -216
  26. package/modules/localmodels/library_custom.py +51 -16
  27. package/modules/localmodels/library_elastic.py +1 -1
  28. package/modules/localmodels/library_gateway.py +59 -176
  29. package/modules/localmodels/library_model.py +23 -0
  30. package/modules/localmodels/library_pricing.py +2 -2
  31. package/modules/localmodels/library_serve.py +5 -3
  32. package/modules/localmodels/library_smoke.py +33 -21
  33. package/modules/localmodels/library_status.py +330 -2
  34. package/modules/localmodels/llm_rank.py +14 -5
  35. package/modules/localmodels/magpie_setup.py +5 -4
  36. package/modules/localmodels/magpie_windows.py +1 -1
  37. package/modules/localmodels/pi_profile.py +384 -0
  38. package/modules/localmodels/process_identity.py +3 -3
  39. package/modules/localmodels/runtime_cli.py +32 -46
  40. package/modules/localmodels/runtime_pi.py +1 -1
  41. package/modules/localmodels/source_byok.py +9 -16
  42. package/modules/localmodels/stack_binding.py +9 -7
  43. package/modules/localmodels/stack_clients.py +137 -21
  44. package/modules/localmodels/stack_doctor.py +6 -3
  45. package/modules/localmodels/stack_hardware.py +18 -0
  46. package/modules/localmodels/stack_lifecycle.py +3 -2
  47. package/modules/localmodels/stack_remove.py +2 -1
  48. package/modules/localmodels/stack_verify.py +2 -2
  49. package/modules/localmodels/stack_view_events.py +2 -2
  50. package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/METADATA +1 -1
  51. package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/RECORD +53 -51
  52. package/package.json +1 -1
  53. package/tool.json +1 -1
  54. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/WHEEL +0 -0
  55. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/entry_points.txt +0 -0
  56. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/NOTICE +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,384 @@
1
+ """Unified runtime profile resolution and Pi ``models.json``/``settings.json``/``auth.json`` store.
2
+
3
+ Lower-layer seam below ``runtime_cli``, ``bifrost_pi``, ``stack_clients``, ``gateway_bifrost``,
4
+ ``library_gateway``, and ``source_byok``. Owns shared profile-directory conventions, private
5
+ gateway client contexts, and atomic JSON/ownership-marker updates for Pi configuration files.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import os
13
+ import tempfile
14
+ from collections.abc import Mapping
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from localmodels import hosts, runtime_auth, runtime_discovery, runtime_io
19
+
20
+ RUNTIMES = ("codex", "claude", "pi")
21
+ PROFILE_KEYS = {
22
+ "codex": "CODEX_HOME",
23
+ "claude": "CLAUDE_CONFIG_DIR",
24
+ "pi": "PI_CODING_AGENT_DIR",
25
+ }
26
+ PROFILE_DIRS = {
27
+ "codex": ".codex",
28
+ "claude": ".claude",
29
+ "pi": ".pi/agent",
30
+ }
31
+
32
+
33
+ class PiProfileError(ValueError):
34
+ """Unreadable, malformed, or foreign Pi profile configuration."""
35
+
36
+
37
+ def gateway_home(tools_dir: str | Path) -> Path:
38
+ """The private gateway client context under ``tools_dir``. Existing parent links such as a
39
+ relocated ``~/.local`` resolve first; ``gateway-home`` itself is never resolved."""
40
+ return Path(hosts.tools_dir(tools_dir)).expanduser().resolve() / "gateway-home"
41
+
42
+
43
+ def client_environment(tools_dir: str) -> dict[str, str]:
44
+ """Settings written by an automatic stack stay in its private gateway context."""
45
+ home = gateway_home(tools_dir)
46
+ return {
47
+ "PI_CODING_AGENT_DIR": str(home / ".pi/agent"),
48
+ "CODEX_HOME": str(home / ".codex"),
49
+ "CLAUDE_CONFIG_DIR": str(home / ".claude"),
50
+ }
51
+
52
+
53
+ def owned_profile(directory: Path) -> bool:
54
+ """Whether ``directory`` has a valid private localmodels auth ownership manifest."""
55
+ files = (
56
+ runtime_auth.owned_files(directory)
57
+ if runtime_discovery.private_file(directory / "localmodels-auth.json")
58
+ else {}
59
+ )
60
+ return bool(files) and all(runtime_discovery.private_file(directory / name) for name in files)
61
+
62
+
63
+ def active_profile(runtime: str, env: Mapping[str, str] | None = None) -> Path:
64
+ """Resolve the active profile directory for a native runtime (codex, claude, or pi)."""
65
+ resolved = os.environ if env is None else env
66
+ return Path(resolved.get(PROFILE_KEYS[runtime], str(Path.home() / PROFILE_DIRS[runtime])))
67
+
68
+
69
+ def pi_dir(env: Mapping[str, str] | None = None) -> Path:
70
+ """Resolve pi's agent directory from ``PI_CODING_AGENT_DIR`` or ``~/.pi/agent``."""
71
+ resolved = os.environ if env is None else env
72
+ return Path(
73
+ resolved.get("PI_CODING_AGENT_DIR", str(Path.home() / ".pi" / "agent"))
74
+ ).expanduser()
75
+
76
+
77
+ def library_pi_dir(tools_dir: str | None = None, env: Mapping[str, str] | None = None) -> Path:
78
+ """pi's directory for library registrations: explicit ``PI_CODING_AGENT_DIR``, else the
79
+ stack's private client context that ``setup binding`` hands to Linger."""
80
+ resolved = os.environ if env is None else env
81
+ given = resolved.get("PI_CODING_AGENT_DIR")
82
+ if given:
83
+ return Path(given).expanduser()
84
+ root = hosts.tools_dir() if tools_dir is None else hosts.tools_dir(tools_dir)
85
+ return Path(client_environment(root)["PI_CODING_AGENT_DIR"])
86
+
87
+
88
+ def read_json(path: Path) -> dict[str, Any]:
89
+ """Read a JSON object from ``path``, returning ``{}`` when absent."""
90
+ try:
91
+ value = json.loads(path.read_text(encoding="utf-8"))
92
+ except FileNotFoundError:
93
+ return {}
94
+ except (OSError, ValueError) as exc:
95
+ raise PiProfileError(f"{path} cannot be read as JSON; left as is") from exc
96
+ if not isinstance(value, dict):
97
+ raise PiProfileError(f"{path} is not a JSON object; left as is")
98
+ return value
99
+
100
+
101
+ def write_json(path: Path, value: dict[str, Any]) -> None:
102
+ """Atomically write ``value`` to ``path``, preserving existing mode or defaulting to 0600."""
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ mode = path.stat().st_mode & 0o777 if path.is_file() else 0o600
105
+ fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
106
+ try:
107
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
108
+ handle.write(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
109
+ os.chmod(tmp, mode)
110
+ os.replace(tmp, path)
111
+ except BaseException:
112
+ with contextlib.suppress(OSError):
113
+ os.unlink(tmp)
114
+ raise
115
+
116
+
117
+ def default_model_from_settings(doc: Mapping[str, Any]) -> str | None:
118
+ """Format ``defaultProvider``/``defaultModel`` from a parsed pi ``settings.json``."""
119
+ if not doc.get("defaultModel"):
120
+ return None
121
+ provider = doc.get("defaultProvider")
122
+ return f"{provider}/{doc['defaultModel']}" if provider else str(doc["defaultModel"])
123
+
124
+
125
+ def provider_doc(base: str, api_key: str, models: list[dict[str, Any]]) -> dict[str, Any]:
126
+ """Build one OpenAI-compatible provider entry for pi's ``models.json``."""
127
+ return {
128
+ "baseUrl": f"{base}/v1",
129
+ "api": "openai-completions",
130
+ "apiKey": api_key,
131
+ "models": models,
132
+ }
133
+
134
+
135
+ def marker_for_other_file(marker: Path, path: Path) -> bool:
136
+ """Whether ``marker`` records ownership of a different existing ``models.json``."""
137
+ try:
138
+ recorded = marker.read_text(encoding="utf-8").strip()
139
+ except OSError:
140
+ return False
141
+ if not recorded:
142
+ return False
143
+ other = Path(recorded)
144
+ try:
145
+ return other.resolve() != path.resolve() and other.is_file()
146
+ except OSError:
147
+ return False
148
+
149
+
150
+ class PiProfileStore:
151
+ """Cohesive store over one Pi agent directory's ``models.json``, ``settings.json``, and
152
+ ``auth.json`` files, enforcing ownership markers and atomic updates."""
153
+
154
+ def __init__(self, directory: Path) -> None:
155
+ self.directory = directory
156
+
157
+ @property
158
+ def models_path(self) -> Path:
159
+ return self.directory / "models.json"
160
+
161
+ @property
162
+ def settings_path(self) -> Path:
163
+ return self.directory / "settings.json"
164
+
165
+ @property
166
+ def auth_path(self) -> Path:
167
+ return self.directory / "auth.json"
168
+
169
+ def read_models(self) -> dict[str, Any]:
170
+ return read_json(self.models_path)
171
+
172
+ def write_models(self, doc: dict[str, Any]) -> None:
173
+ write_json(self.models_path, doc)
174
+
175
+ def read_settings(self) -> dict[str, Any]:
176
+ return read_json(self.settings_path)
177
+
178
+ def write_settings(self, doc: dict[str, Any]) -> None:
179
+ write_json(self.settings_path, doc)
180
+
181
+ def read_regular_settings(self) -> dict[str, Any] | None:
182
+ """Read ``settings.json`` only when it is a regular, non-symlink file."""
183
+ path = self.settings_path
184
+ if not path.is_file() or path.is_symlink():
185
+ return None
186
+ loaded = json.loads(path.read_text(encoding="utf-8"))
187
+ return loaded if isinstance(loaded, dict) else None
188
+
189
+ def read_owned_auth(self, *, owned: bool | None = None) -> dict[str, Any]:
190
+ """Read ``auth.json`` when the profile is owned by localmodels and the file exists."""
191
+ is_owned = owned_profile(self.directory) if owned is None else owned
192
+ if not is_owned or not self.auth_path.is_file():
193
+ return {}
194
+ loaded = json.loads(self.auth_path.read_text(encoding="utf-8"))
195
+ return loaded if isinstance(loaded, dict) else {}
196
+
197
+ def default_model(self) -> str | None:
198
+ """pi's default model as ``settings.json`` names it (``provider/model``), or None."""
199
+ try:
200
+ doc = self.read_settings()
201
+ except PiProfileError:
202
+ return None
203
+ return default_model_from_settings(doc)
204
+
205
+ def set_default(self, provider: str, model: str) -> None:
206
+ settings = self.read_settings()
207
+ settings["defaultProvider"], settings["defaultModel"] = provider, model
208
+ self.write_settings(settings)
209
+
210
+ def restore_default(self, previous: str | None) -> None:
211
+ settings = self.read_settings()
212
+ if previous and "/" in previous:
213
+ provider, _, model = previous.partition("/")
214
+ settings["defaultProvider"], settings["defaultModel"] = provider, model
215
+ else:
216
+ settings.pop("defaultProvider", None)
217
+ settings.pop("defaultModel", None)
218
+ self.write_settings(settings)
219
+
220
+ def ensure_provider_free(self, provider: str, *, marker: Path) -> None:
221
+ """Refuse, before anything changes, a pi provider of ``provider`` this tool did not add."""
222
+ current = self.read_models().get("providers")
223
+ if isinstance(current, dict) and provider in current and not marker.is_file():
224
+ raise PiProfileError(f"pi already has a provider {provider} this tool did not add")
225
+
226
+ def upsert_provider_model(
227
+ self,
228
+ provider: str,
229
+ entry: dict[str, Any],
230
+ base: str,
231
+ api_key: str,
232
+ *,
233
+ marker: Path,
234
+ ) -> None:
235
+ """Add or update ``entry`` under an owned ``provider`` in ``models.json``."""
236
+ models = self.read_models()
237
+ providers = models.setdefault("providers", {})
238
+ if not isinstance(providers, dict):
239
+ raise PiProfileError("providers in pi's models.json is not an object; left as is")
240
+ current = providers.get(provider)
241
+ if current is not None and not marker.is_file():
242
+ raise PiProfileError(f"pi already has a provider {provider} this tool did not add")
243
+ marker.parent.mkdir(parents=True, exist_ok=True)
244
+ marker.write_text(str(self.models_path) + "\n", encoding="utf-8")
245
+ kept = [m for m in (current or {}).get("models", []) if m.get("id") != entry["id"]]
246
+ providers[provider] = provider_doc(base, api_key, [*kept, entry])
247
+ self.write_models(models)
248
+
249
+ def drop_provider_model(self, provider: str, model_id: str, *, marker: Path) -> None:
250
+ """Remove ``model_id`` from an owned ``provider``, deleting the marker only after write."""
251
+ if not marker.is_file():
252
+ return
253
+ models = self.read_models()
254
+ providers = models.get("providers")
255
+ current = providers.get(provider) if isinstance(providers, dict) else None
256
+ if not isinstance(providers, dict) or not isinstance(current, dict):
257
+ if not marker_for_other_file(marker, self.models_path):
258
+ marker.unlink(missing_ok=True)
259
+ return
260
+ kept = [m for m in current.get("models", []) if m.get("id") != model_id]
261
+ if kept:
262
+ current["models"] = kept
263
+ else:
264
+ del providers[provider]
265
+ self.write_models(models) # committed first: a failed write keeps ownership proof
266
+ if not kept:
267
+ marker.unlink(missing_ok=True)
268
+
269
+ def sync_shared_model(
270
+ self,
271
+ provider: str,
272
+ model_id: str,
273
+ context: int,
274
+ base: str,
275
+ api_key: str,
276
+ *,
277
+ entry: dict[str, Any] | None = None,
278
+ ) -> None:
279
+ """Sync ``contextWindow``/``maxTokens`` on an owned pi provider entry without changing
280
+ stack ownership or clobbering a user-defined provider (different ``baseUrl``)."""
281
+ if context <= 0:
282
+ return
283
+ try:
284
+ models = self.read_models()
285
+ except PiProfileError:
286
+ if entry is not None:
287
+ raise
288
+ return
289
+ providers = models.setdefault("providers", {})
290
+ if not isinstance(providers, dict):
291
+ if entry is not None:
292
+ raise PiProfileError("providers in pi's models.json is not an object; left as is")
293
+ return
294
+ current = providers.get(provider)
295
+ if current is None:
296
+ if entry is not None:
297
+ providers[provider] = provider_doc(base, api_key, [entry])
298
+ self.write_models(models)
299
+ return
300
+ if not isinstance(current, dict) or not str(current.get("baseUrl", "")).startswith(
301
+ f"{base}/"
302
+ ):
303
+ return
304
+ items = current.get("models")
305
+ if not isinstance(items, list):
306
+ return
307
+ max_tokens = min(32768, max(4096, context // 4))
308
+ matched = [m for m in items if isinstance(m, dict) and m.get("id") == model_id]
309
+ changed = False
310
+ for item in matched:
311
+ if item.get("contextWindow") != context or item.get("maxTokens") != max_tokens:
312
+ item["contextWindow"], item["maxTokens"] = context, max_tokens
313
+ changed = True
314
+ if not matched and entry is not None:
315
+ items.append(entry)
316
+ changed = True
317
+ if changed:
318
+ self.write_models(models)
319
+
320
+ def drop_provider_if_base_matches(self, provider: str, addr: str) -> bool:
321
+ """Delete ``provider`` from ``models.json`` only if its ``baseUrl`` targets ``addr``."""
322
+ models = self.read_models()
323
+ providers = models.get("providers")
324
+ entry = providers.get(provider) if isinstance(providers, dict) else None
325
+ ours = isinstance(entry, dict) and str(entry.get("baseUrl", "")).startswith(
326
+ f"http://{addr}/"
327
+ )
328
+ if ours and isinstance(providers, dict):
329
+ del providers[provider]
330
+ self.write_models(models)
331
+ return ours
332
+
333
+ def drop_provider(self, provider: str) -> bool:
334
+ """Remove a legacy provider entry (such as ``magpie``) from ``models.json`` if present."""
335
+ try:
336
+ models = self.read_models()
337
+ except PiProfileError:
338
+ return False
339
+ providers = models.get("providers")
340
+ if isinstance(providers, dict) and provider in providers:
341
+ del providers[provider]
342
+ self.write_models(models)
343
+ return True
344
+ return False
345
+
346
+ def sync_default_off_magpie(
347
+ self,
348
+ pi_provider: str,
349
+ gateway_model: str,
350
+ *,
351
+ stack_provider: str | None,
352
+ retired_magpie: bool = False,
353
+ ) -> None:
354
+ """Keep pi's ``settings.json`` off a dead legacy ``magpie`` default (and restore the
355
+ Quick Install default when an adopted stack LLM is reloaded after ``unpoint_pi``).
356
+ Never overwrites a user-chosen non-magpie default."""
357
+ try:
358
+ settings = self.read_settings()
359
+ except PiProfileError:
360
+ return
361
+ current_provider = settings.get("defaultProvider")
362
+ current_model = settings.get("defaultModel")
363
+ was_magpie = current_provider == "magpie" or (
364
+ not current_provider
365
+ and isinstance(current_model, str)
366
+ and current_model.startswith("magpie/")
367
+ )
368
+ if was_magpie or (stack_provider is not None and not current_model):
369
+ settings["defaultProvider"] = pi_provider
370
+ settings["defaultModel"] = gateway_model
371
+ self.write_settings(settings)
372
+ if was_magpie or retired_magpie:
373
+ self.drop_provider("magpie")
374
+
375
+ def write_isolated_profile(
376
+ self, provider: str, provider_entry: dict[str, Any], default_model: str
377
+ ) -> Path:
378
+ """Write an isolated private Pi profile (used for BYOK) with owner-only permissions."""
379
+ runtime_io.private_directory(self.directory)
380
+ models_doc = {"providers": {provider: provider_entry}}
381
+ settings_doc = {"defaultProvider": provider, "defaultModel": default_model}
382
+ runtime_io.write_private_json(self.models_path, models_doc)
383
+ runtime_io.write_private_json(self.settings_path, settings_doc)
384
+ return self.directory
@@ -213,7 +213,7 @@ def adopt_successor(pid_file: str | Path, program: str) -> bool:
213
213
  return False
214
214
  path = Path(pid_file)
215
215
  try:
216
- saved = _recorded(path)
216
+ saved = recorded(path)
217
217
  if saved is None or _windows_inspect(saved["pid"]) is not None:
218
218
  return False # still running, or its PID was reused: nothing provable to adopt
219
219
  successors = [
@@ -604,7 +604,7 @@ def _forget(pid_file: Path) -> None:
604
604
  path.unlink()
605
605
 
606
606
 
607
- def _recorded(pid_file: Path) -> Identity | None:
607
+ def recorded(pid_file: Path) -> Identity | None:
608
608
  """Receipt identity, or None for an exited legacy bare PID file; raises ValueError if untrusted."""
609
609
  try:
610
610
  saved = json.loads(_private(Path(str(pid_file) + ".identity.json")))
@@ -638,7 +638,7 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
638
638
  if not os.path.lexists(path):
639
639
  return "none"
640
640
  try:
641
- saved = _recorded(path)
641
+ saved = recorded(path)
642
642
  current = None if saved is None else inspect(saved["pid"])
643
643
  if (
644
644
  saved is None
@@ -15,13 +15,17 @@ from typing import Any
15
15
 
16
16
  from localmodels import (
17
17
  http_local,
18
+ pi_profile,
18
19
  runtime_auth,
19
20
  runtime_discovery,
20
21
  runtime_install,
21
22
  runtime_pi,
22
23
  runtime_process,
23
24
  )
24
- from localmodels.harness import load_lock
25
+ from localmodels.harness_core import load_lock
26
+ from localmodels.pi_profile import PROFILE_DIRS as PROFILE_DIRS
27
+ from localmodels.pi_profile import PROFILE_KEYS as PROFILE_KEYS
28
+ from localmodels.pi_profile import RUNTIMES as RUNTIMES
25
29
  from localmodels.runtime_auth import check_config, owned_files, provider_accepted, save_config
26
30
  from localmodels.runtime_auth import save_api_key as save_api_key
27
31
  from localmodels.runtime_discovery import compatible_version as _compatible_version
@@ -43,27 +47,16 @@ from localmodels.runtime_releases import codex_release as _codex_release
43
47
  from localmodels.runtime_releases import resolve as _external_release
44
48
  from localmodels.runtime_releases import version_key as _stable_version
45
49
 
46
- RUNTIMES = ("codex", "claude", "pi")
47
50
  LOCK = Path(__file__).with_name("runtime-lock.json")
48
- PROFILE_KEYS = {"codex": "CODEX_HOME", "claude": "CLAUDE_CONFIG_DIR", "pi": "PI_CODING_AGENT_DIR"}
49
- PROFILE_DIRS = {"codex": ".codex", "claude": ".claude", "pi": ".pi/agent"}
50
51
  platform = runtime_discovery.platform_tag
51
- _platform = platform
52
52
 
53
53
 
54
54
  def owned_profile(directory: Path) -> bool:
55
- files = owned_files(directory) if _private_file(directory / "localmodels-auth.json") else {}
56
- return bool(files) and all(_private_file(directory / name) for name in files)
57
-
58
-
59
- _owned_profile = owned_profile
55
+ return pi_profile.owned_profile(directory)
60
56
 
61
57
 
62
58
  def active_profile(runtime: str, env: dict[str, str]) -> Path:
63
- return Path(env.get(PROFILE_KEYS[runtime], str(Path.home() / PROFILE_DIRS[runtime])))
64
-
65
-
66
- _active_profile = active_profile
59
+ return pi_profile.active_profile(runtime, env)
67
60
 
68
61
 
69
62
  def _probe(
@@ -142,7 +135,7 @@ def _managed_command(root: Path, runtime: str, node: str | None = None) -> list[
142
135
  target = _target(root, runtime)
143
136
  if runtime == "pi":
144
137
  return [str(target / ("pi.exe" if os.name == "nt" else "pi"))]
145
- artifacts = _lock()["artifacts"].get(f"{runtime}/{_platform()}", [])
138
+ artifacts = _lock()["artifacts"].get(f"{runtime}/{platform()}", [])
146
139
  return [str(target / artifacts[0]["executable"])] if artifacts else []
147
140
 
148
141
 
@@ -155,9 +148,6 @@ def runtime_env(root: Path, runtime: str) -> dict[str, str]:
155
148
  return env
156
149
 
157
150
 
158
- _runtime_env = runtime_env
159
-
160
-
161
151
  def _credential_ambiguous(
162
152
  runtime: str, profile: Path, owned: dict[str, str], env: dict[str, str]
163
153
  ) -> bool:
@@ -201,16 +191,16 @@ def _auth(runtime: str, argv: list[str], env: dict[str, str]) -> tuple[bool, str
201
191
  except (ValueError, AttributeError):
202
192
  return False, mode
203
193
  # Pi auth check is credential resolvability; provider acceptance is a separate descriptor.
204
- directory = Path(env.get("PI_CODING_AGENT_DIR", str(Path.home() / ".pi/agent")))
205
- settings_path = directory / "settings.json"
194
+ store = pi_profile.PiProfileStore(active_profile("pi", env))
195
+ settings = store.read_regular_settings()
206
196
  model: str | None = None
207
- if settings_path.is_file() and not settings_path.is_symlink():
208
- settings = json.loads(settings_path.read_text())
209
- if settings.get("defaultProvider") == "localmodels" and isinstance(
210
- settings.get("defaultModel"), str
211
- ):
212
- model = "localmodels/" + settings["defaultModel"]
213
- mode = "api-key"
197
+ if (
198
+ settings is not None
199
+ and settings.get("defaultProvider") == "localmodels"
200
+ and isinstance(settings.get("defaultModel"), str)
201
+ ):
202
+ model = "localmodels/" + settings["defaultModel"]
203
+ mode = "api-key"
214
204
  return _pi_native_auth(argv, env, model, mode)
215
205
 
216
206
 
@@ -218,12 +208,8 @@ def _pi_native_auth(
218
208
  argv: list[str], env: dict[str, str], model: str | None, mode: str | None
219
209
  ) -> tuple[bool, str | None]:
220
210
  selections: list[list[str]] = []
221
- directory = _active_profile("pi", env)
222
- stored = (
223
- json.loads((directory / "auth.json").read_text())
224
- if _owned_profile(directory) and (directory / "auth.json").is_file()
225
- else {}
226
- )
211
+ directory = active_profile("pi", env)
212
+ stored = pi_profile.PiProfileStore(directory).read_owned_auth(owned=owned_profile(directory))
227
213
  provider = next(
228
214
  (name for name in ("openai", "anthropic") if stored.get(name, {}).get("type") == "api_key"),
229
215
  None,
@@ -279,12 +265,12 @@ def inspect_runtimes(
279
265
  hosts = (
280
266
  [explicit]
281
267
  if explicit is not None
282
- else runtime_discovery.host_commands(runtime, _platform())
268
+ else runtime_discovery.host_commands(runtime, platform())
283
269
  )
284
270
  commands: list[tuple[str, list[str], str]] = [(host, [], "host") for host in hosts if host]
285
271
  if explicit is None:
286
272
  managed = _managed_command(root, runtime, node)
287
- managed_commands = runtime_discovery.managed_commands(root, runtime, _platform())
273
+ managed_commands = runtime_discovery.managed_commands(root, runtime, platform())
288
274
  if managed and managed not in managed_commands:
289
275
  managed_commands.append(managed)
290
276
  commands.extend((entry[0], entry[1:], "managed") for entry in managed_commands)
@@ -322,9 +308,9 @@ def inspect_runtimes(
322
308
  )
323
309
  break
324
310
  continue
325
- env = _runtime_env(root, runtime)
326
- profile = _active_profile(runtime, env)
327
- managed_profile = profile == root / "runtime" / runtime and _owned_profile(profile)
311
+ env = runtime_env(root, runtime)
312
+ profile = active_profile(runtime, env)
313
+ managed_profile = profile == root / "runtime" / runtime and owned_profile(profile)
328
314
  owned = owned_files(profile) if managed_profile else {}
329
315
  row["providerVerified"] = (
330
316
  managed_profile
@@ -422,7 +408,7 @@ def build_plan(
422
408
  plan = native_plan(
423
409
  runtime,
424
410
  root,
425
- _platform(),
411
+ platform(),
426
412
  command=[status["executable"], *status["argvPrefix"]] if status["installed"] else [],
427
413
  version=status["version"],
428
414
  )
@@ -434,7 +420,7 @@ def build_plan(
434
420
  plan["artifactSource"] = "codex-stable-npm"
435
421
  if runtime == "pi" and plan["action"] == "install":
436
422
  runtime_pi.plan_install(
437
- plan, lock, node, launcher, before_version, platform=_platform(), probe=_probe
423
+ plan, lock, node, launcher, before_version, platform=platform(), probe=_probe
438
424
  )
439
425
  if runtime == "claude" and plan["action"] == "install" and before_version is not None:
440
426
  plan["version"], plan["artifacts"] = _external_release(
@@ -505,7 +491,7 @@ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
505
491
  lock = _lock()
506
492
  if (
507
493
  plan["schema"] != "localmodels.harness-plan/v1"
508
- or plan["platform"] != _platform()
494
+ or plan["platform"] != platform()
509
495
  or plan["lockDigest"] != _lock_digest()
510
496
  ):
511
497
  raise ValueError("Runtime platform or artifact lock changed; create a new plan")
@@ -525,26 +511,26 @@ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
525
511
  or not isinstance(plan["version"], str)
526
512
  ):
527
513
  raise ValueError("Invalid Codex registry plan")
528
- expected_version, expected_artifacts = _codex_release(_platform(), plan["version"])
514
+ expected_version, expected_artifacts = _codex_release(platform(), plan["version"])
529
515
  elif runtime == "claude" and plan.get("artifactSource") == "claude-stable":
530
516
  if plan["action"] != "install" or not isinstance(plan["version"], str):
531
517
  raise ValueError("Invalid stable runtime plan")
532
518
  expected_version, expected_artifacts = _external_release(
533
- runtime, _platform(), plan["version"]
519
+ runtime, platform(), plan["version"]
534
520
  )
535
521
  elif "artifactSource" not in plan:
536
522
  expected_version = lock["versions"].get(runtime)
537
- expected_artifacts = lock["artifacts"].get(f"{runtime}/{_platform()}")
523
+ expected_artifacts = lock["artifacts"].get(f"{runtime}/{platform()}")
538
524
  else:
539
525
  raise ValueError("Unknown runtime artifact source")
540
526
  if (plan["version"], plan["artifacts"]) != (expected_version, expected_artifacts):
541
527
  raise ValueError("Runtime artifact changed; create a new plan")
542
528
  if (
543
529
  plan.get("nodeArtifact") is not None
544
- and plan["nodeArtifact"] != lock["node"]["artifacts"].get(_platform())
530
+ and plan["nodeArtifact"] != lock["node"]["artifacts"].get(platform())
545
531
  ) or (
546
532
  plan.get("launcherArtifact") is not None
547
- and plan["launcherArtifact"] != lock["launchers"].get(_platform())
533
+ and plan["launcherArtifact"] != lock["launchers"].get(platform())
548
534
  ):
549
535
  raise ValueError("Runtime bootstrap lock changed")
550
536
 
@@ -15,7 +15,7 @@ from pathlib import Path
15
15
  from typing import Any
16
16
 
17
17
  from localmodels import runtime_process
18
- from localmodels.harness import load_lock
18
+ from localmodels.harness_core import load_lock
19
19
  from localmodels.runtime_discovery import owned_marker as owned_marker
20
20
  from localmodels.runtime_install import bootstrap
21
21
  from localmodels.runtime_io import rename_with_retry
@@ -19,6 +19,7 @@ from localmodels import (
19
19
  harness,
20
20
  hosts,
21
21
  library_gateway,
22
+ pi_profile,
22
23
  runtime_io,
23
24
  )
24
25
  from localmodels.probe import HostFacts
@@ -443,22 +444,14 @@ def _write_claude_profile(root: Path, addr: str, context: int) -> str:
443
444
 
444
445
 
445
446
  def _write_pi_profile(root: Path, addr: str, facts: bifrost_models.LlmFacts) -> str:
446
- pi_dir = root / ".pi" / "agent"
447
- runtime_io.private_directory(pi_dir)
448
- models_doc = {
449
- "providers": {
450
- gateway_bifrost.PI_PROVIDER: bifrost_models.pi_provider(
451
- facts, BYOK_MODEL, f"http://{addr}"
452
- )
453
- }
454
- }
455
- settings_doc = {
456
- "defaultProvider": gateway_bifrost.PI_PROVIDER,
457
- "defaultModel": BYOK_MODEL,
458
- }
459
- runtime_io.write_private_json(pi_dir / "models.json", models_doc)
460
- runtime_io.write_private_json(pi_dir / "settings.json", settings_doc)
461
- return str(pi_dir)
447
+ store = pi_profile.PiProfileStore(root / ".pi" / "agent")
448
+ return str(
449
+ store.write_isolated_profile(
450
+ gateway_bifrost.PI_PROVIDER,
451
+ bifrost_models.pi_provider(facts, BYOK_MODEL, f"http://{addr}"),
452
+ BYOK_MODEL,
453
+ )
454
+ )
462
455
 
463
456
 
464
457
  def write_byok_profiles(addr: str, creds: ByokCredentials) -> dict[str, str]: