okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-028-app-p13b8dc8fa3

main
35.2 KiB619 linesraw
1"""Owner-local, typed runtime operations shared by CLI and future Desktop adapters.
2
3The one-shot JSON entry point is for a trusted local host process. It is not an
4HTTP API and must not be forwarded from a browser or an inference credential.
5All mutations still pass through the existing owner host and operation journal.
6"""
7
8from __future__ import annotations
9
10import contextlib
11import hashlib
12import json
13import math
14import re
15import sys
16from pathlib import Path
17from typing import Any
18
19from strata_control import doctor, journal, models, profiles, runtime
20from strata_control.profiles import ProfileError
21
22
23MAX_REQUEST_BYTES = 64 * 1024
24_ACTIONS = {
25    "bench.run.plan": {"path", "suite", "concurrency", "repeat", "request_timeout", "condition"},
26    "bench.run": {"path", "suite", "concurrency", "repeat", "request_timeout", "condition",
27                  "if_profile_revision", "if_source_sha256", "if_owner_id", "if_instance_id"},
28    "bench.job.create": {"job_id", "path", "suite", "concurrency", "repeat", "request_timeout",
29                         "condition", "if_profile_revision", "if_source_sha256",
30                         "if_owner_id", "if_instance_id"},
31    "bench.job": {"job_id"},
32    "bench.progress": {"path"},
33    "bench.cancel": {"path"},
34    "bench.report": {"path"},
35    "bench.compare": {"baseline", "candidate"},
36    "calibration.plan": set(),
37    "calibration.job.create": {"job_id", "action", "path", "exclusive_ack",
38                               "if_profile_revision", "if_source_sha256", "if_report_sha256"},
39    "calibration.job": {"job_id"},
40    "calibration.cancel": {"job_id"},
41    "calibration.measure": {"path", "exclusive_ack", "if_profile_revision", "if_source_sha256"},
42    "calibration.apply.plan": {"path"},
43    "calibration.apply": {"path", "exclusive_ack", "if_profile_revision", "if_source_sha256",
44                          "if_report_sha256"},
45    "calibration.rollback.plan": {"path"},
46    "calibration.rollback": {"path", "exclusive_ack", "if_profile_revision", "if_source_sha256",
47                             "if_report_sha256"},
48    "components.inspect": {"live"},
49    "models.installed": set(),
50    "models.inspect": {"model_id"},
51    "models.import.plan": {"path"},
52    "profile.inspect": set(),
53    "profile.change.plan": {"overrides", "source_config", "if_revision"},
54    "profile.change": {"overrides", "source_config", "if_revision", "if_source_sha256"},
55    "runtime.start.plan": {"shutdown_timeout_s"},
56    "runtime.start": {"wait_s", "shutdown_timeout_s", "if_profile_revision", "if_source_sha256"},
57    "runtime.status": set(),
58    "runtime.verify.plan": {"load"},
59    "runtime.verify": {"wait_s", "load", "if_owner_id", "if_instance_id"},
60    "runtime.stop.plan": set(),
61    "runtime.stop": {"wait_s", "if_owner_id", "if_instance_id"},
62    "runtime.restart.plan": {"allow_source_switch", "allow_source_migration"},
63    "runtime.restart": {"wait_s", "startup_wait_s", "if_profile_revision",
64                        "if_owner_id", "if_instance_id", "allow_source_switch",
65                        "allow_source_migration", "if_source_sha256"},
66}
67
68
69def _profile_change_plan(profile: str, overrides: object, source_config: object) -> tuple[dict, dict]:
70    """Validate an editable candidate without changing the saved profile."""
71    current, revision = profiles.load(profile)
72    if not isinstance(overrides, dict):
73        raise ProfileError("profile overrides must be an object")
74    profiles.validate_overrides(overrides)
75    if not isinstance(source_config, str) or not Path(source_config).is_absolute():
76        raise ProfileError("source_config must be an absolute path")
77    if source_config == current["source_config"]:
78        source = source_config
79    else:
80        proposed_source, source_revision = profiles.propose_source(profile, source_config)
81        if source_revision != revision:
82            raise ProfileError("profile changed during source preview; retry", 6)
83        source = proposed_source["source_config"]
84    proposed = {**current, "source_config": source, "overrides": dict(overrides)}
85    profiles.validate_profile(proposed, expected_name=profile)
86    path = Path(source)
87    try:
88        raw = path.read_bytes()
89        if len(raw) > 1024 * 1024:
90            raise ProfileError("run config is larger than 1 MiB", 5)
91        cfg = profiles.read_run_config(path)
92        if path.read_bytes() != raw:
93            raise ProfileError("run config changed during profile preview; retry", 6)
94    except OSError as exc:
95        raise ProfileError(f"cannot read run config ({type(exc).__name__})", 5) from None
96    from strata_cli.cli import _effective
97    effective, origins = _effective(cfg, proposed)
98    changes = {key: {"before": current["overrides"].get(key), "after": overrides.get(key)}
99               for key in sorted(profiles.OVERRIDE_KEYS)
100               if current["overrides"].get(key) != overrides.get(key)}
101    plan = {"profile": profile, "revision": revision,
102            "source_config_before": current["source_config"],
103            "source_config_after": source,
104            "source_sha256": hashlib.sha256(raw).hexdigest(),
105            "overrides_before": current["overrides"],
106            "overrides_after": proposed["overrides"],
107            "changes": changes, "effective": effective, "origin": origins,
108            "would_save": bool(changes or current["source_config"] != source),
109            "running_unchanged": True}
110    return plan, proposed
111
112
113def _seconds(value: object, low: float, high: float, label: str) -> float:
114    if (type(value) not in (int, float) or not math.isfinite(value) or
115            not low <= value <= high):
116        raise ProfileError(f"{label} must be finite seconds in {low:g}..{high:g}")
117    return float(value)
118
119
120def _boolean(value: object, label: str) -> bool:
121    if type(value) is not bool:
122        raise ProfileError(f"{label} must be true or false")
123    return value
124
125
126def _optional_revision(value: object, label: str) -> str | None:
127    if value is None:
128        return None
129    if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
130        raise ProfileError(f"{label} must be a 64-character lowercase SHA-256")
131    return value
132
133
134def _profile_revision(value: object) -> str | None:
135    if value is None:
136        return None
137    if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{16}", value):
138        raise ProfileError("if_profile_revision must be a 16-character lowercase revision")
139    return value
140
141
142def _optional_identity(value: object, label: str) -> str | None:
143    if value is None:
144        return None
145    if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{32}", value):
146        raise ProfileError(f"{label} must be a 32-character lowercase ID")
147    return value
148
149
150def _local_report_path(value: object, label: str) -> Path:
151    if not isinstance(value, str) or len(value) > 1024 or not Path(value).is_absolute() or \
152            any(ord(char) < 32 or ord(char) == 127 or
153                0x202a <= ord(char) <= 0x202e or 0x2066 <= ord(char) <= 0x2069 for char in value):
154        raise ProfileError(f"{label} must be an absolute local report path under 1024 characters")
155    return Path(value)
156
157
158def _calibration_source(profile: str) -> tuple[str, str]:
159    source, saved, revision = profiles.resolve(profile)
160    if saved is None or revision is None:
161        raise ProfileError("calibration requires a saved profile", 2)
162    try:
163        raw = source.read_bytes()
164    except OSError:
165        raise ProfileError("calibration source config is unavailable", 5) from None
166    if len(raw) > 1024 * 1024:
167        raise ProfileError("calibration source config exceeds 1 MiB", 5)
168    return revision, hashlib.sha256(raw).hexdigest()
169
170
171def _calibration_expected_source(profile: str, params: dict) -> tuple[str, str]:
172    revision = _profile_revision(params["if_profile_revision"])
173    digest = _optional_revision(params["if_source_sha256"], "if_source_sha256")
174    if revision is None or digest is None:
175        raise ProfileError("calibration needs the reviewed profile revision and source digest")
176    if (revision, digest) != _calibration_source(profile):
177        raise ProfileError("calibration source changed after review; review again", 6)
178    return revision, digest
179
180
181def _calibration_report(profile: str, value: object, label: str) -> tuple[Path, dict]:
182    from strata_control import calibration
183    path = _local_report_path(value, label)
184    report = calibration.load_report(path)
185    return path, report
186
187
188def runtime_action(action: str, profile: str, *, plan: bool = False,
189                   wait: float = 300, shutdown_timeout: float = 30,
190                   startup_wait: float = 300, load: bool = False,
191                   if_profile_revision: str | None = None,
192                   if_owner_id: str | None = None,
193                   if_instance_id: str | None = None,
194                   allow_source_switch: bool = False,
195                   allow_source_migration: bool = False,
196                   if_source_sha256: str | None = None,
197                   die_with_pid: int | None = None) -> dict:
198    """Execute one validated owner operation and return its CLI/host result."""
199    runtime._name(profile)
200    if type(plan) is not bool:
201        raise ProfileError("plan must be true or false")
202    if action == "start":
203        # The same ceiling the owner runtime itself enforces, read from it rather than repeated here: a start
204        # may wait for a big model longer than ten minutes (#3949). The CLI used to stop at 600 s while
205        # runtime.start took 1800 s, so a caller that asked what the runtime allows was refused here first.
206        wait = _seconds(wait, 0, runtime.MAX_START_WAIT, "start wait")
207        shutdown_timeout = _seconds(shutdown_timeout, 0, 300, "shutdown timeout")
208        if_profile_revision = _profile_revision(if_profile_revision)
209        if_source_sha256 = _optional_revision(if_source_sha256, "if_source_sha256")
210        if plan:
211            if if_profile_revision is not None or if_source_sha256 is not None:
212                raise ProfileError("start plan cannot include execution preconditions")
213            runtime._supported()
214            profiles.load(profile)
215            launch, source_sha256 = runtime._start_candidate(profile)
216            repeated_launch, repeated_digest = runtime._start_candidate(profile)
217            if launch != repeated_launch or source_sha256 != repeated_digest:
218                raise ProfileError("start candidate changed during preview; retry", 6)
219            return {"ok": True, "plan": {"profile": profile, "launch": launch,
220                                          "source_sha256": source_sha256,
221                                          "shutdown_timeout": shutdown_timeout,
222                                          "would_start": False}}
223        revision = profiles.load(profile)[1]
224        if if_profile_revision is not None or if_source_sha256 is not None:
225            runtime._check_start_candidate(profile, if_profile_revision, if_source_sha256)
226        operation_id, result = journal.run_direct(profile, "runtime.start", revision,
227            {"wait_s": wait, "shutdown_timeout_s": shutdown_timeout,
228             "expected_profile_revision": if_profile_revision,
229             "expected_source_sha256": if_source_sha256},
230            lambda: runtime.start(profile, wait=wait, shutdown_timeout=shutdown_timeout,
231                                  expected_profile_revision=if_profile_revision,
232                                  expected_source_sha256=if_source_sha256,
233                                  die_with_pid=die_with_pid))
234    elif action == "status":
235        if plan:
236            raise ProfileError("status has no plan")
237        return runtime.status(profile)
238    elif action == "verify":
239        load = _boolean(load, "load")
240        if_owner_id = _optional_identity(if_owner_id, "if_owner_id")
241        if_instance_id = _optional_identity(if_instance_id, "if_instance_id")
242        if plan:
243            if if_owner_id is not None or if_instance_id is not None:
244                raise ProfileError("verify plan cannot include execution preconditions")
245            current = runtime.status(profile)
246            if not current.get("ok") or current.get("state") != "ready":
247                return {"ok": False, "state": current.get("state", "unavailable"),
248                        "error": "runtime_not_ready", "exit_code": 6}
249            owner, instance = current.get("owner_id"), current.get("instance_id")
250            if _optional_identity(owner, "owner_id") is None or \
251                    _optional_identity(instance, "instance_id") is None:
252                raise ProfileError("runtime verification needs an owned ready instance", 6)
253            return {"ok": True, "plan": {"profile": profile, "state": "ready",
254                    "owner_id": owner, "instance_id": instance,
255                    "model_state": current.get("model_state"),
256                    "load": load, "would_load": load and current.get("model_state") == "unloaded",
257                    "would_verify": False, "probe": "one_token_generation"}}
258        wait = _seconds(wait, 1, 600, "verify wait")
259        if (if_owner_id is None) != (if_instance_id is None):
260            raise ProfileError("verify requires both reviewed owner and instance IDs")
261        if if_owner_id is not None:
262            current = runtime.status(profile)
263            if current.get("owner_id") != if_owner_id:
264                raise ProfileError("owner_changed_after_verify_plan", 6)
265            if current.get("instance_id") != if_instance_id:
266                raise ProfileError("instance_changed_after_verify_plan", 6)
267        revision = profiles.load(profile)[1]
268        operation_id, result = journal.run_direct(profile, "runtime.verify", revision,
269            {"wait_s": wait, "load": load,
270             "expected_owner_id": if_owner_id, "expected_instance_id": if_instance_id},
271            lambda: runtime.verify(profile, timeout=wait, load=load,
272                                   expected_owner_id=if_owner_id,
273                                   expected_instance_id=if_instance_id))
274    elif action == "stop":
275        wait = _seconds(wait, 1, 600, "stop wait")
276        if_owner_id = _optional_identity(if_owner_id, "if_owner_id")
277        if_instance_id = _optional_identity(if_instance_id, "if_instance_id")
278        if plan:
279            if if_owner_id is not None or if_instance_id is not None:
280                raise ProfileError("stop plan cannot include execution preconditions")
281            return runtime.plan_stop(profile)
282        if if_owner_id is not None:
283            current = runtime.status(profile)
284            if current.get("owner_id") != if_owner_id:
285                raise ProfileError("owner_changed_after_stop_plan", 6)
286            if current.get("instance_id") != if_instance_id:
287                raise ProfileError("instance_changed_after_stop_plan", 6)
288        revision = profiles.load(profile)[1]
289        operation_id, result = journal.run_direct(profile, "runtime.stop", revision,
290            {"wait_s": wait, "expected_owner_id": if_owner_id,
291             "expected_instance_id": if_instance_id},
292            lambda: runtime.stop(profile, timeout=wait,
293                                 expected_owner_id=if_owner_id,
294                                 expected_instance_id=if_instance_id))
295    elif action == "restart":
296        allow_source_switch = _boolean(allow_source_switch, "allow_source_switch")
297        allow_source_migration = _boolean(allow_source_migration, "allow_source_migration")
298        if_source_sha256 = _optional_revision(if_source_sha256, "if_source_sha256")
299        if_profile_revision = _profile_revision(if_profile_revision)
300        if_owner_id = _optional_identity(if_owner_id, "if_owner_id")
301        if_instance_id = _optional_identity(if_instance_id, "if_instance_id")
302        if plan:
303            if any(value is not None for value in (if_profile_revision, if_source_sha256,
304                                                   if_owner_id, if_instance_id)):
305                raise ProfileError("restart plan cannot include execution preconditions")
306            return runtime.plan_restart(profile, allow_source_switch=allow_source_switch,
307                                        allow_source_migration=allow_source_migration)
308        wait = _seconds(wait, 1, 1800, "restart wait")
309        # Same ceiling as the restart itself takes below (#3949): a restart waits out the same big-model load a start does.
310        startup_wait = _seconds(startup_wait, 1, runtime.MAX_START_WAIT, "startup wait")
311        if (if_owner_id is None) != (if_instance_id is None):
312            raise ProfileError("restart requires both reviewed owner and instance IDs")
313        if (allow_source_switch or allow_source_migration) and not if_source_sha256:
314            raise ProfileError("source change needs --if-source-sha256 from --plan")
315        if if_owner_id is not None:
316            current = runtime.status(profile)
317            if current.get("owner_id") != if_owner_id:
318                raise ProfileError("owner_changed_after_restart_plan", 6)
319            if current.get("instance_id") != if_instance_id:
320                raise ProfileError("instance_changed_after_restart_plan", 6)
321        revision = profiles.load(profile)[1]
322        expected = if_profile_revision or revision
323        operation_id, result = journal.run_direct(profile, "runtime.restart", revision,
324            {"wait_s": wait, "startup_wait_s": startup_wait,
325             "expected_profile_revision": expected,
326             "expected_owner_id": if_owner_id,
327             "expected_instance_id": if_instance_id,
328             "allow_source_switch": allow_source_switch,
329             "allow_source_migration": allow_source_migration,
330             "expected_source_sha256": if_source_sha256},
331            lambda: runtime.restart(profile, timeout=wait, startup_wait=startup_wait,
332                                    expected_profile_revision=expected,
333                                    expected_owner_id=if_owner_id,
334                                    expected_instance_id=if_instance_id,
335                                    allow_source_switch=allow_source_switch,
336                                    allow_source_migration=allow_source_migration,
337                                    expected_source_sha256=if_source_sha256))
338    else:
339        raise ProfileError("unsupported runtime action")
340    return {**result, "operation_id": operation_id}
341
342
343def dispatch(request: object) -> dict:
344    """Validate one versioned local-host request; reject unknown fields/actions."""
345    if (not isinstance(request, dict) or set(request) !=
346            {"schema_version", "action", "profile", "params"} or
347            type(request.get("schema_version")) is not int or request["schema_version"] != 1):
348        raise ProfileError("management request needs schema_version 1, action, profile and params")
349    action, profile, params = request["action"], request["profile"], request["params"]
350    if not isinstance(action, str) or action not in _ACTIONS:
351        raise ProfileError("management action is unsupported")
352    if not isinstance(profile, str) or not profiles.PROFILE_ID.fullmatch(profile):
353        raise ProfileError("management profile name is invalid")
354    if not isinstance(params, dict) or (set(params) != _ACTIONS[action] and
355            not (action == "bench.run" and set(params) == _ACTIONS[action] | {"job_id"}) and
356            not (action in ("calibration.measure", "calibration.apply", "calibration.rollback") and
357                 set(params) == _ACTIONS[action] | {"job_id"})):
358        raise ProfileError("management action parameters are invalid")
359    if action in ("calibration.measure", "calibration.apply", "calibration.rollback") and "job_id" in params:
360        from strata_control import calibration_jobs
361        result = calibration_jobs.execute(profile, action.removeprefix("calibration."), params)
362    elif action in ("bench.run.plan", "bench.run"):
363        from strata_control import benchmarking
364        checked = {**params, "path": str(_local_report_path(params["path"], "benchmark output path"))}
365        if action == "bench.run":
366            identities = (_profile_revision(checked["if_profile_revision"]),
367                          _optional_revision(checked["if_source_sha256"], "if_source_sha256"),
368                          _optional_identity(checked["if_owner_id"], "if_owner_id"),
369                          _optional_identity(checked["if_instance_id"], "if_instance_id"))
370            if any(identity is None for identity in identities):
371                raise ProfileError("benchmark execution needs reviewed profile, source, owner and instance IDs")
372            result = benchmarking.run(profile, checked)
373        else:
374            result = {"ok": True, "plan": benchmarking.plan(profile, checked)}
375    elif action == "bench.job.create":
376        from strata_control import benchmarking
377        checked = {**params, "path": str(_local_report_path(params["path"], "benchmark output path"))}
378        result = benchmarking.create_job(profile, checked)
379    elif action == "bench.job":
380        from strata_control import benchmarking
381        result = benchmarking.job_status(profile, params["job_id"])
382    elif action == "bench.progress":
383        from strata_cli import bench
384        from strata_control import benchmarking
385        profiles.load(profile)
386        target = _local_report_path(params["path"], "benchmark progress path")
387        progress = bench.progress(target)
388        directory = target.parent if target.name in ("results.json", "progress.json") else target
389        result = {"ok": True, "progress": progress,
390                  "activity": benchmarking.benchmark_activity(profile, directory),
391                  "cancel_requested": benchmarking.cancel_requested(directory)}
392    elif action == "bench.cancel":
393        from strata_control import benchmarking
394        profiles.load(profile)
395        result = benchmarking.request_cancel(
396            profile, _local_report_path(params["path"], "benchmark cancel path"))
397    elif action == "bench.report":
398        from strata_cli import bench
399        profiles.load(profile)
400        report = bench.load(_local_report_path(params["path"], "benchmark report path"))
401        result = {"ok": True, "summary": bench.summary(report),
402                  "markdown": bench.markdown_report(report)}
403    elif action == "bench.compare":
404        from strata_cli import bench
405        profiles.load(profile)
406        baseline = bench.load(_local_report_path(params["baseline"], "baseline report path"))
407        candidate = bench.load(_local_report_path(params["candidate"], "candidate report path"))
408        comparison = bench.compare(baseline, candidate)
409        result = {"ok": True, "comparison": comparison,
410                  "markdown": bench.markdown_comparison(comparison)}
411    elif action == "calibration.plan":
412        from strata_control import calibration
413        result = {"ok": True, "plan": calibration.preview(profile)}
414    elif action == "calibration.job.create":
415        from strata_control import calibration_jobs
416        if params["action"] not in calibration_jobs.KINDS:
417            raise ProfileError("calibration job action is invalid", 2)
418        _calibration_expected_source(profile, params)
419        if _boolean(params["exclusive_ack"], "exclusive_ack") is not True:
420            raise ProfileError("calibration requires exclusive-access acknowledgement")
421        path = _local_report_path(params["path"], "calibration report path")
422        report_sha = params["if_report_sha256"]
423        if params["action"] == "measure":
424            if report_sha is not None or path.exists() or path.is_symlink() or not path.parent.is_dir():
425                raise ProfileError("calibration output must be a new file in an existing directory", 2)
426        else:
427            _, report = _calibration_report(profile, str(path), "calibration report path")
428            expected = _optional_revision(report_sha, "if_report_sha256")
429            if expected is None or expected != report["body_sha256"]:
430                raise ProfileError("calibration report changed after review; review again", 6)
431        result = calibration_jobs.create(profile, params["action"], {**params, "path": str(path)})
432    elif action == "calibration.job":
433        from strata_control import calibration_jobs
434        result = calibration_jobs.status(profile, params["job_id"])
435    elif action == "calibration.cancel":
436        from strata_control import calibration_jobs
437        result = calibration_jobs.cancel(profile, params["job_id"])
438    elif action == "calibration.measure":
439        from strata_control import calibration
440        revision, digest = _calibration_expected_source(profile, params)
441        if _boolean(params["exclusive_ack"], "exclusive_ack") is not True:
442            raise ProfileError("calibration requires exclusive-access acknowledgement")
443        path = _local_report_path(params["path"], "calibration report path")
444        operation_id, measured = journal.run_direct(profile, "engine.calibrate.measure", revision,
445            {"report_path": str(path), "exclusive_ack": True},
446            lambda: {"ok": True, "report_path": str(path), "report": calibration.measure(
447                profile, path, exclusive_ack=True, say=lambda _: None,
448                expected_profile_revision=revision, expected_source_sha256=digest)})
449        report = measured["report"]
450        result = {"ok": True, "operation_id": operation_id, "path": str(path),
451                  "report_id": report["report_id"], "applicable": report["applicable"],
452                  "settings": report["settings"]}
453    elif action in ("calibration.apply.plan", "calibration.rollback.plan"):
454        from strata_control import calibration
455        revision, digest = _calibration_source(profile)
456        path, report = _calibration_report(profile, params["path"], "calibration report path")
457        review = (calibration.review(profile, path) if action == "calibration.apply.plan" else
458                  calibration.review_rollback(profile, path))
459        result = {"ok": True, "plan": review, "path": str(path),
460                  "profile_revision": revision, "source_sha256": digest,
461                  "report_sha256": report["body_sha256"]}
462    elif action in ("calibration.apply", "calibration.rollback"):
463        from strata_control import calibration
464        revision, _ = _calibration_expected_source(profile, params)
465        if _boolean(params["exclusive_ack"], "exclusive_ack") is not True:
466            raise ProfileError("calibration requires exclusive-access acknowledgement")
467        path, report = _calibration_report(profile, params["path"], "calibration report path")
468        expected_report = _optional_revision(params["if_report_sha256"], "if_report_sha256")
469        if expected_report is None or report["body_sha256"] != expected_report:
470            raise ProfileError("calibration report changed after review; review again", 6)
471        kind = "engine.calibrate.apply" if action == "calibration.apply" else "engine.calibrate.rollback"
472        operation_id, outcome = journal.run_direct(profile, kind, revision,
473            {"report_path": str(path), "exclusive_ack": True},
474            lambda: {"ok": True, ("application" if action == "calibration.apply" else "rollback"):
475                calibration.apply_result(profile, path, exclusive_ack=True,
476                    expected_report_sha256=expected_report) if action == "calibration.apply" else
477                calibration.rollback_result(profile, path, exclusive_ack=True,
478                    expected_report_sha256=expected_report)})
479        result = {"ok": True, "operation_id": operation_id,
480                  "application" if action == "calibration.apply" else "rollback":
481                  outcome["application" if action == "calibration.apply" else "rollback"]}
482    elif action == "components.inspect":
483        live = _boolean(params["live"], "live")
484        source, _, _ = profiles.resolve(profile)
485        result = {"ok": True, "report": doctor.inspect(source, profile_id=profile, live=live)}
486    elif action == "models.installed":
487        profiles.load(profile)
488        result = {"ok": True, "inventory": models.list_installed()}
489    elif action == "models.inspect":
490        profiles.load(profile)
491        result = {"ok": True, "inspection": models.inspect(params["model_id"])}
492    elif action == "models.import.plan":
493        profiles.load(profile)
494        source = params["path"]
495        if not isinstance(source, str) or len(source) > 1024 or not Path(source).is_absolute() or \
496                any(ord(char) < 32 or ord(char) == 127 for char in source):
497            raise ProfileError("model import path must be an absolute path under 1024 characters")
498        result = {"ok": True, "plan": models.plan_import(source)}
499    elif action == "profile.inspect":
500        saved, revision = profiles.load(profile)
501        plan, _ = _profile_change_plan(profile, saved["overrides"], saved["source_config"])
502        if plan["revision"] != revision or plan["overrides_before"] != saved["overrides"] or \
503                plan["source_config_before"] != saved["source_config"]:
504            raise ProfileError("profile changed during inspection; reload it", 6)
505        result = {"ok": True, "profile": saved, "revision": revision,
506                  "source_sha256": plan["source_sha256"],
507                  "effective": plan["effective"], "origin": plan["origin"]}
508    elif action == "profile.change.plan":
509        expected_revision = _profile_revision(params["if_revision"])
510        if expected_revision is None:
511            raise ProfileError("profile preview needs its loaded revision")
512        plan, _ = _profile_change_plan(profile, params["overrides"], params["source_config"])
513        if plan["revision"] != expected_revision:
514            raise ProfileError("profile changed since it was loaded; reload before review", 6)
515        result = {"ok": True, "plan": plan}
516    elif action == "profile.change":
517        expected_revision = _profile_revision(params["if_revision"])
518        expected_source = _optional_revision(params["if_source_sha256"], "if_source_sha256")
519        if expected_revision is None or expected_source is None:
520            raise ProfileError("profile save needs its reviewed revision and source digest")
521        plan, proposed = _profile_change_plan(profile, params["overrides"], params["source_config"])
522        if plan["revision"] != expected_revision or plan["source_sha256"] != expected_source:
523            raise ProfileError("profile or source config changed after review; review again", 6)
524        saved, revision = profiles.save(profile, proposed, expected_revision=expected_revision,
525                                        expected_source_sha256=expected_source)
526        result = {"ok": True, "profile": saved, "previous_revision": expected_revision,
527                  "revision": revision, "source_sha256": expected_source,
528                  "saved": plan["would_save"], "running_unchanged": True}
529    elif action == "runtime.start.plan":
530        result = runtime_action("start", profile, plan=True,
531                                shutdown_timeout=params["shutdown_timeout_s"])
532    elif action == "runtime.start":
533        if params["if_profile_revision"] is None or params["if_source_sha256"] is None:
534            raise ProfileError("Desktop start needs the profile revision and source digest from its plan")
535        result = runtime_action("start", profile, wait=params["wait_s"],
536                                shutdown_timeout=params["shutdown_timeout_s"],
537                                if_profile_revision=params["if_profile_revision"],
538                                if_source_sha256=params["if_source_sha256"])
539    elif action == "runtime.status":
540        result = runtime_action("status", profile)
541    elif action == "runtime.verify.plan":
542        result = runtime_action("verify", profile, plan=True, load=params["load"])
543    elif action == "runtime.verify":
544        if params["if_owner_id"] is None or params["if_instance_id"] is None:
545            raise ProfileError("Desktop verify needs the owner and instance IDs from its plan")
546        result = runtime_action("verify", profile, wait=params["wait_s"], load=params["load"],
547                                if_owner_id=params["if_owner_id"],
548                                if_instance_id=params["if_instance_id"])
549    elif action == "runtime.stop.plan":
550        result = runtime_action("stop", profile, plan=True)
551    elif action == "runtime.stop":
552        if params["if_owner_id"] is None:
553            raise ProfileError("Desktop stop needs the owner ID from its plan")
554        result = runtime_action("stop", profile, wait=params["wait_s"],
555                                if_owner_id=params["if_owner_id"],
556                                if_instance_id=params["if_instance_id"])
557    elif action == "runtime.restart.plan":
558        result = runtime_action("restart", profile, plan=True,
559                                allow_source_switch=params["allow_source_switch"],
560                                allow_source_migration=params["allow_source_migration"])
561    else:
562        if any(params[key] is None for key in ("if_profile_revision", "if_source_sha256",
563                                              "if_owner_id", "if_instance_id")):
564            raise ProfileError("Desktop restart needs profile, source, owner and instance IDs from its plan")
565        result = runtime_action("restart", profile, wait=params["wait_s"],
566                                startup_wait=params["startup_wait_s"],
567                                if_profile_revision=params["if_profile_revision"],
568                                if_owner_id=params["if_owner_id"],
569                                if_instance_id=params["if_instance_id"],
570                                allow_source_switch=params["allow_source_switch"],
571                                allow_source_migration=params["allow_source_migration"],
572                                if_source_sha256=params["if_source_sha256"])
573    return {"schema_version": 1, **result}
574
575
576def _unique_pairs(pairs: list[tuple[str, Any]]) -> dict:
577    result = {}
578    for key, value in pairs:
579        if key in result:
580            raise ProfileError("management request has a duplicate field")
581        result[key] = value
582    return result
583
584
585def _reject_constant(_: str) -> None:
586    raise ProfileError("management request has a nonfinite number")
587
588
589def main() -> int:
590    """Handle one owner-local JSON request on stdin and one JSON response on stdout."""
591    try:
592        payload = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
593        if not payload or len(payload) > MAX_REQUEST_BYTES:
594            raise ProfileError("management request must be 1..65536 bytes")
595        request = json.loads(payload.decode("utf-8"), object_pairs_hook=_unique_pairs,
596                             parse_constant=_reject_constant)
597        with contextlib.redirect_stdout(sys.stderr):
598            response = dispatch(request)
599        code = 0 if response.get("ok") else response.get("exit_code", 6)
600        if code != 0 and "exit_code" not in response:
601            response = {**response, "exit_code": code}
602    except (ProfileError, ValueError, UnicodeError) as exc:
603        code = getattr(exc, "exit_code", 2)
604        response = {"schema_version": 1, "ok": False, "error": str(exc), "exit_code": code}
605    except OSError as exc:
606        code = 6
607        response = {"schema_version": 1, "ok": False,
608                    "error": f"local operation failed ({type(exc).__name__})", "exit_code": code}
609    except KeyboardInterrupt:
610        code = 130
611        response = {"schema_version": 1, "ok": False,
612                    "error": "operation interrupted; completion must be checked in the journal",
613                    "exit_code": code}
614    print(json.dumps(response, ensure_ascii=False, allow_nan=False))
615    return code
616
617
618if __name__ == "__main__":
619    raise SystemExit(main())