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