okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2503b206b
main
1"""Shared terminal command grammar and stable exit codes.""" 2 3from __future__import annotations 4 5import argparse 6import contextlib 7import io 8import json 9import math 10import os 11import re 12import subprocess 13import sys 14import time 15from pathlib import Path 16 17from strata_control import profiles 18 19ROOT = Path (__file__ ).resolve ().parents [1 ] 20 21#: Backend families, as the engine package manifest records them. Kept here so the argument parsers 22#: stay declarative without importing the tuning module on every CLI start. 23BACKENDS = ("metal" ,"cuda" ,"hip" ,"sycl" ,"cpu" ) 24from strata_control .doctor import inspect as inspect_components 25from strata_control .profiles import ProfileError 26from strata_cli .client import ClientError ,Endpoint 27from strata_cli import monitor_commands ,tune_commands 28 29 30class _VersionAction (argparse .Action ): 31"""--version on one line: argparse's own version action wraps the text at the terminal width, and a path to the 32interpreter is the thing a user (and the packaging smoke test) wants to read back whole.""" 33 34def __call__ (self ,parser ,namespace ,values ,option_string = None ): 35import strata_cli 36sys .stdout .write (f"strata { strata_cli . PRODUCT_VERSION } (build { strata_cli . version () } ; python { sys . version . split ()[ 0 ] } at { sys . executable } )\n" ) 37parser .exit () 38 39 40def parser ()-> argparse .ArgumentParser : 41ap = argparse .ArgumentParser (prog = "strata" ,description = "Strata serving and terminal clients" ) 42ap .add_argument ("--version" ,action = _VersionAction ,nargs = 0 , 43help = "print the version and the interpreter this terminal runs on" ) 44sp = ap .add_subparsers (dest = "command" ,required = True ) 45serve = sp .add_parser ("serve" ,help = "start the existing Strata inference server in the foreground" ) 46serve .add_argument ("--profile" ,"--config" ,dest = "config" ,required = True ,metavar = "CONFIG.json" ) 47serve .add_argument ("--engine" ,choices = ("strata" ,"mock" ),default = "strata" , 48help = "strata: the engine in the run config (default); mock: a scripted engine for client tests, " 49"no GPU and no model" ) 50serve .add_argument ("--host" ) 51serve .add_argument ("--port" ,type = int ) 52serve .add_argument ("--parallel" ,type = int ,help = "requested concurrent engine slots" ) 53serve .add_argument ("--batch-groups" ,help = "requested pipeline groups (auto or positive integer)" ) 54serve .add_argument ("--max-queue" ,type = int ,help = "maximum pending inference calls beyond effective slots" ) 55serve .add_argument ("--queue-timeout" ,type = float ,help = "seconds to wait for the first engine turn (0.1..600)" ) 56serve .add_argument ("--batch-telemetry" ,action = argparse .BooleanOptionalAction ,default = None , 57help = "sample actual engine decode-window rows for the monitor (opt-in)" ) 58serve .add_argument ("--offline" ,action = "store_true" ,help = "disable remote image fetches and MCP/tool subprocesses" ) 59serve .add_argument ("--ready-file" ,help = "absolute path for a new instance record (use a private directory)" ) 60serve .add_argument ("--shutdown-timeout" ,type = float ,default = 30 , 61help = "seconds to drain owned inference calls on stop (0..300)" ) 62serve .add_argument ("--plan" ,action = "store_true" ,help = "validate and print the effective launch without starting" ) 63serve .add_argument ("--output" ,choices = ("human" ,"json" ,"jsonl" ),default = "human" , 64help = "human output, JSON plan, or JSONL foreground lifecycle" ) 65serve .add_argument ("--json" ,action = "store_true" ,help = "alias for --plan --output json" ) 66serve .add_argument ("--quiet" ,action = "store_true" ,help = "suppress human informational output" ) 67 68profile = sp .add_parser ("profile" ,help = "edit saved serving overrides outside setup's run config" ) 69profile_sp = profile .add_subparsers (dest = "profile_command" ,required = True ) 70profile_create = profile_sp .add_parser ("create" ,help = "save a named profile from an installed run config" ) 71profile_create .add_argument ("name" ) 72profile_create .add_argument ("--from-config" ,required = True ,metavar = "CONFIG.json" ) 73profile_create .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 74profile_list = profile_sp .add_parser ("list" ,help = "list saved profiles" ) 75profile_list .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 76profile_show = profile_sp .add_parser ("show" ,help = "show a profile and optional effective settings" ) 77profile_show .add_argument ("name" ) 78profile_show .add_argument ("--effective" ,action = "store_true" ) 79profile_show .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 80profile_validate = profile_sp .add_parser ("validate" ,help = "check the profile and referenced run config" ) 81profile_validate .add_argument ("name" ) 82profile_validate .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 83profile_set = profile_sp .add_parser ("set" ,help = "set typed serving overrides, e.g. parallel=8" ) 84profile_set .add_argument ("name" ) 85profile_set .add_argument ("assignments" ,nargs = "+" ) 86profile_set .add_argument ("--plan" ,action = "store_true" ,help = "show changes without saving" ) 87profile_set .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 88profile_source = profile_sp .add_parser ("use-config" ,help = "point a saved profile at another run config file" ) 89profile_source .add_argument ("name" ) 90profile_source .add_argument ("--from-config" ,required = True ,metavar = "CONFIG.json" ) 91profile_source .add_argument ("--plan" ,action = "store_true" ,help = "show the source change without saving" ) 92profile_source .add_argument ("--if-revision" ,metavar = "REVISION" , 93help = "fail if the saved profile changed since preview" ) 94profile_source .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 95profile_edit = profile_sp .add_parser ("edit" ,help = "edit a temporary JSON copy in VISUAL or EDITOR" ) 96profile_edit .add_argument ("name" ) 97profile_edit .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 98profile_history = profile_sp .add_parser ("history" ,help = "list saved profile revisions" ) 99profile_history .add_argument ("name" ) 100profile_history .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 101profile_rollback = profile_sp .add_parser ("rollback" ,help = "restore a saved profile revision" ) 102profile_rollback .add_argument ("name" ) 103profile_rollback .add_argument ("--to" ,required = True ,metavar = "REVISION" ) 104profile_rollback .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 105 106repair = sp .add_parser ("repair-access" ,help = "give you back Strata files that a run as administrator locked (Windows)" ) 107repair .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 108doctor = sp .add_parser ("doctor" ,help = "read-only check of installed engine components" ) 109doctor .add_argument ("--profile" ,help = "saved profile name or run config JSON path" ) 110doctor .add_argument ("--components" ,action = "store_true" ,help = "include component inventory (default)" ) 111doctor .add_argument ("--live" ,action = "store_true" ,help = "query host GPUs and compare selected device indices" ) 112doctor .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 113components = sp .add_parser ("components" ,help = "read-only installed component inventory" ) 114components_sp = components .add_subparsers (dest = "components_command" ,required = True ) 115components_verify = components_sp .add_parser ("verify" ,help = "check required files for an installed profile" ) 116components_verify .add_argument ("--profile" ,required = True ) 117components_verify .add_argument ("--live" ,action = "store_true" ,help = "query host GPUs and compare selected device indices" ) 118components_verify .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 119components_plan = components_sp .add_parser ( 120"plan" ,help = "read a component-package manifest and say whether it may be used here" ) 121components_plan .add_argument ("manifest" ,help = "path to the component manifest (JSON)" ) 122components_plan .add_argument ("--backend" ,default = None , 123help = "the backend family to check the component against" ) 124components_plan .add_argument ("--target" ,default = None , 125help = "override the platform key, for checking another machine's " 126"manifest on this one" ) 127components_plan .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 128components_backend = components_sp .add_parser ( 129"backends" ,help = "the OS and backend combinations that are committed to, and what is not" ) 130components_backend .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 131components_engine = components_sp .add_parser ( 132"engine" ,help = "which engine package in the local component folder this PC would start (never downloads)" ) 133components_engine .add_argument ("--backend" ,default = None ,help = "ask for one backend family instead of detecting it" ) 134components_engine .add_argument ("--components-dir" ,default = None , 135help = "the component folder (default: STRATA_COMPONENTS_DIR or the per-user folder)" ) 136components_engine .add_argument ("--full" ,action = "store_true" ,help = "hash every file, not only the entrypoint" ) 137components_engine .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 138from strata_cli import update_cmd 139update_parsers = update_cmd .add_parsers (sp ,components_sp ) 140models = sp .add_parser ("models" ,help = "inspect setup-written local model run configs" ) 141models_sp = models .add_subparsers (dest = "models_command" ,required = True ) 142models_list = models_sp .add_parser ("list" ,help = "list local installed-model config candidates" ) 143models_scope = models_list .add_mutually_exclusive_group () 144models_scope .add_argument ("--installed" ,action = "store_true" ,help = "limit discovery to local setup run configs" ) 145models_scope .add_argument ("--served" ,action = "store_true" ,help = "inspect the currently served model" ) 146models_list .add_argument ("--install-dir" ,help = "absolute path to a Strata installation" ) 147models_list .add_argument ("--url" ,help = "Strata server root; remote connections require HTTPS" ) 148models_list .add_argument ("--connection" ,help = "saved read-only connection" ) 149models_list .add_argument ("--credential-env" ,help = "environment variable containing the server credential" ) 150models_list .add_argument ("--timeout" ,type = float ,help = "bounded request timeout in seconds" ) 151models_list .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 152models_inspect = models_sp .add_parser ("inspect" ,help = "inspect a local model run config and its components" ) 153models_inspect .add_argument ("model_id" ) 154models_inspect .add_argument ("--install-dir" ,help = "absolute path to a Strata installation" ) 155models_inspect .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 156models_import = models_sp .add_parser ("import" ,help = "preview an existing GGUF file set without adopting it" ) 157models_import .add_argument ("path" ,metavar = "PATH" ) 158models_import .add_argument ("--plan" ,action = "store_true" ,required = True , 159help = "inspect only; adoption requires a qualified model workflow" ) 160models_import .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 161models_move = models_sp .add_parser ("move" ,help = "move the model files (models, packs, mtp) to another folder: copied, checked, then the old copies removed" ) 162models_move .add_argument ("to" ,metavar = "NEW_FOLDER" ,nargs = "?" ,help = "not needed with --resume, --leave or --status" ) 163models_move .add_argument ("--resume" ,action = "store_true" ,help = "finish a move that was interrupted" ) 164models_move .add_argument ("--leave" ,action = "store_true" ,help = "give up an interrupted move: keep the old folder and remove the partial copies" ) 165models_move .add_argument ("--status" ,action = "store_true" ,help = "say whether a move was interrupted (changes nothing)" ) 166models_move .add_argument ("--from" ,dest = "source" ,metavar = "OLD_FOLDER" ,help = "the folder the models are in now (default: the data folder in use)" ) 167models_move .add_argument ("--install-dir" ,help = "absolute path to a Strata installation whose run configs should follow the files" ) 168models_move .add_argument ("--plan" ,action = "store_true" ,help = "say what would happen and change nothing" ) 169models_move .add_argument ("--cancel-file" ,metavar = "PATH" ,help = "stop (safely) when this file appears" ) 170models_move .add_argument ("--output" ,choices = ("human" ,"json" ,"jsonl" ),default = "human" ) 171from strata_cli import drafting_cmd 172drafting_cmd .add_parser (sp ) 173from strata_cli import split_cmd 174split_cmd .add_parser (sp ) 175engine = sp .add_parser ("engine" ,help = "engine tuning and component actions" ) 176engine_sp = engine .add_subparsers (dest = "engine_command" ,required = True ) 177calibrate = engine_sp .add_parser ("calibrate" ,help = "measure, review and apply engine tuning" ) 178calibrate .add_argument ("--profile" ,required = True ) 179calibrate_actions = calibrate .add_mutually_exclusive_group (required = True ) 180calibrate_actions .add_argument ("--plan" ,action = "store_true" ,help = "read-only calibration preflight" ) 181calibrate_actions .add_argument ("--measure" ,action = "store_true" ,help = "run decode sweep and save a report" ) 182calibrate_actions .add_argument ("--review-result" ,metavar = "REPORT.json" ,help = "show a candidate and its freshness" ) 183calibrate_actions .add_argument ("--apply-result" ,metavar = "REPORT.json" ,help = "smoke-test and apply a fresh report" ) 184calibrate_actions .add_argument ("--review-rollback" ,metavar = "REPORT.json" , 185help = "check whether an applied result can be restored" ) 186calibrate_actions .add_argument ("--rollback-result" ,metavar = "REPORT.json" , 187help = "smoke-test and restore the configuration before an application" ) 188calibrate .add_argument ("--out" ,metavar = "REPORT.json" ,help = "new report path for --measure" ) 189calibrate .add_argument ("--exclusive" ,action = "store_true" ,help = "assert all model instances using these devices are stopped" ) 190calibrate .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 191install = sp .add_parser ( 192"install" , 193help = "the explicit installer: engine, models, Python packages (starting and serving never do this)" ) 194install .add_argument ("--update" ,action = "store_true" , 195help = "update an existing install (what UPDATE.bat / update.sh run) instead of setting one up" ) 196install .add_argument ("setup_args" ,nargs = argparse .REMAINDER , 197help = "options passed to setup.py, e.g. --family qwen --model Q2_0 --yes" ) 198runtime = sp .add_parser ( 199"runtime" ,help = "manage an owned local Strata server instance" , 200description = "`runtime start` starts a background service: the engine keeps serving after this terminal " 201"closes and until `runtime stop` (or the process named by --die-with-pid ends). " 202"`strata serve` is the foreground form: it ends with this terminal." ) 203runtime_sp = runtime .add_subparsers (dest = "runtime_command" ,required = True ) 204runtime_start = runtime_sp .add_parser ( 205"start" ,help = "start a saved profile as a background service under the local owner host (it keeps " 206"serving after this terminal closes; stop it with `runtime stop`)" ) 207runtime_start .add_argument ("--profile" ,required = True ) 208runtime_start .add_argument ("--die-with-pid" ,type = int ,metavar = "PID" , 209help = "stop the instance (drained) when this process ends; for an app that owns it" ) 210runtime_start .add_argument ("--plan" ,action = "store_true" ) 211runtime_start .add_argument ("--wait" ,type = float ,default = 300 ) 212runtime_start .add_argument ("--shutdown-timeout" ,type = float ,default = 30 ) 213runtime_start .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 214runtime_status = runtime_sp .add_parser ("status" ,help = "inspect an owned local instance" ) 215runtime_status .add_argument ("--profile" ,required = True ) 216runtime_status .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 217runtime_verify = runtime_sp .add_parser ("verify" ,help = "recheck the owned API and one-token generation" ) 218runtime_verify .add_argument ("--profile" ,required = True ) 219runtime_verify .add_argument ("--wait" ,type = float ,default = 300 ) 220runtime_verify .add_argument ("--load" ,action = "store_true" ,help = "load an unloaded model for the generation check" ) 221runtime_verify .add_argument ("--plan" ,action = "store_true" ,help = "preview the owned instance and verification effect" ) 222runtime_verify .add_argument ("--if-owner-id" ,metavar = "OWNER_ID" , 223help = "require the owner shown by verify --plan" ) 224runtime_verify .add_argument ("--if-instance-id" ,metavar = "INSTANCE_ID" , 225help = "require the instance shown by verify --plan" ) 226runtime_verify .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 227runtime_stop = runtime_sp .add_parser ("stop" ,help = "drain and stop an owned local instance" ) 228runtime_stop .add_argument ("--profile" ,required = True ) 229runtime_stop .add_argument ("--plan" ,action = "store_true" ,help = "review the current owner and instance" ) 230runtime_stop .add_argument ("--wait" ,type = float ,default = 330 ) 231runtime_stop .add_argument ("--if-owner-id" ,help = "require the owner ID from --plan" ) 232runtime_stop .add_argument ("--if-instance-id" ,help = "require the instance ID from --plan" ) 233runtime_stop .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 234runtime_cleanup = runtime_sp .add_parser ( 235"cleanup" ,help = "end servers and engines Strata started whose owner is gone (each is checked by PID, " 236"start time and command line first; a running instance is never touched)" ) 237runtime_cleanup .add_argument ("--profile" ,help = "only this profile's leftovers" ) 238runtime_cleanup .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 239runtime_restart = runtime_sp .add_parser ("restart" ,help = "drain and rerun an owned saved profile" ) 240runtime_restart .add_argument ("--profile" ,required = True ) 241runtime_restart .add_argument ("--plan" ,action = "store_true" ,help = "compare current and saved launch without draining" ) 242runtime_restart .add_argument ("--allow-source-switch" ,action = "store_true" , 243help = "permit a new source config file when the old file remains available for rollback" ) 244runtime_restart .add_argument ("--allow-source-migration" ,action = "store_true" , 245help = "permit edited run config bytes using a private rollback snapshot" ) 246runtime_restart .add_argument ("--wait" ,type = float ,default = 1000 ) 247runtime_restart .add_argument ("--startup-wait" ,type = float ,default = 300 ) 248runtime_restart .add_argument ("--if-profile-revision" ,metavar = "REVISION" ) 249runtime_restart .add_argument ("--if-owner-id" ,metavar = "OWNER_ID" , 250help = "require the owner ID shown in --plan" ) 251runtime_restart .add_argument ("--if-instance-id" ,metavar = "INSTANCE_ID" , 252help = "require the instance ID shown in --plan" ) 253runtime_restart .add_argument ("--if-source-sha256" ,metavar = "SHA256" , 254help = "require the candidate source bytes shown in --plan" ) 255runtime_restart .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 256ops = sp .add_parser ("ops" ,help = "edit and run typed local operator recipes" ) 257ops_sp = ops .add_subparsers (dest = "ops_command" ,required = True ) 258ops_items = [] 259for action in ("init" ,"list" ,"create" ,"show" ,"edit" ,"set" ,"history" ,"rollback" , 260"plan" ,"run" ,"runs" ,"result" ): 261item = ops_sp .add_parser (action ) 262ops_items .append (item ) 263if action == "result" : 264item .add_argument ("operation_id" ) 265elif action not in ("init" ,"list" ,"runs" ): 266item .add_argument ("name" ) 267item .add_argument ("--profile" ,required = True ) 268item .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 269if action == "runs" : 270item .add_argument ("--limit" ,type = int ,default = 20 ) 271if action == "create" : 272item .add_argument ("--kind" ,choices = ("runtime.restart" ,"engine.calibrate.measure" , 273"components.verify" ),required = True ) 274if action == "set" : 275item .add_argument ("assignment" ,metavar = "KEY=VALUE" ) 276item .add_argument ("--plan" ,action = "store_true" ) 277if action == "rollback" : 278item .add_argument ("--to" ,required = True ,metavar = "REVISION" ) 279if action == "run" : 280item .add_argument ("--exclusive" ,action = "store_true" , 281help = "assert exclusive device access for a calibration measurement" ) 282item .add_argument ("--if-revision" ,metavar = "REVISION" , 283help = "fail if the saved recipe changed since preview" ) 284item .add_argument ("--if-profile-revision" ,metavar = "REVISION" , 285help = "fail if the saved serving profile changed since preview" ) 286item .add_argument ("--if-owner-id" ,metavar = "OWNER_ID" , 287help = "require the runtime owner shown in a restart recipe plan" ) 288item .add_argument ("--if-instance-id" ,metavar = "INSTANCE_ID" , 289help = "require the runtime instance shown in a restart recipe plan" ) 290item .add_argument ("--if-source-sha256" ,metavar = "SHA256" , 291help = "require the candidate run-config bytes shown in a restart recipe plan" ) 292bench = sp .add_parser ("bench" ,help = "explicit serving benchmark with local JSON evidence" ) 293bench_sp = bench .add_subparsers (dest = "bench_command" ,required = True ) 294bench_run = bench_sp .add_parser ("run" ,help = "the standard benchmark (docs/BENCHMARK_PROTOCOL.md), or a serving suite" ) 295bench_source = bench_run .add_mutually_exclusive_group (required = True ) 296bench_source .add_argument ("--profile" ,help = "saved serving profile or installed run config" ) 297bench_source .add_argument ("--url" ,help = "server root; remote connections require HTTPS" ) 298bench_run .add_argument ("--suite" ,choices = ("standard-v1" ,"serving-smoke" ,"parallel-mixed-v1" ,"parallel-overload-v1" , 299"parallel-cancel-v1" ,"parallel-prefill-cancel-v1" ), 300default = "standard-v1" , 301help = "standard-v1 (default) follows docs/BENCHMARK_PROTOCOL.md; the others are serving suites for your own comparisons" ) 302bench_run .add_argument ("--concurrency" ,type = int ,default = None , 303help = "serving suites: simultaneous requests (1..16, or 1..64 for parallel-overload-v1; default 4)" ) 304bench_run .add_argument ("--repeat" ,type = int ,default = None ,help = "serving suites: repeat measured phases (1..5; default 1)" ) 305bench_run .add_argument ("--condition" ,help = "serving suites: operator label for this run, e.g. baseline or monitor-default" ) 306bench_run .add_argument ("--require-managed-match" ,action = "store_true" , 307help = "serving suites: require the local owner host and current profile to match the serving instance" ) 308bench_run .add_argument ("--request-timeout" ,type = float ,default = None , 309help = "serving suites: seconds per request (1..600; default 120). The standard suite fixes it at 1800" ) 310bench_run .add_argument ("--out" ,metavar = "NEW_DIRECTORY" , 311help = "new output directory (required for serving suites). Standard suite: a new folder " 312"<date>-standard-<gpu>-<run id> under ./bench/results or ./bench-results" ) 313bench_run .add_argument ("--credential-env" ,default = "STRATA_API_KEY" ) 314bench_run .add_argument ("--telemetry-credential-env" ,default = None ) 315bench_run .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 316standard = bench_run .add_argument_group ("standard suite (docs/BENCHMARK_PROTOCOL.md)" ) 317standard .add_argument ("--optional-concurrency" ,action = "store_true" , 318help = "also run the optional stage: four short requests released together, three rounds" ) 319standard .add_argument ("--no-start" ,action = "store_true" , 320help = "with --profile: never start the engine; use only a server that is already running" ) 321standard .add_argument ("--load-timeout" ,type = float ,default = 1800 ,metavar = "SECONDS" , 322help = "with --profile: how long to wait for the engine to load the model (default 1800)" ) 323standard .add_argument ("--track" ,choices = ("default" ,"custom" ),default = "custom" , 324help = "default: an unmodified release's setup-generated settings; custom (the default here): anything else" ) 325standard .add_argument ("--track-notes" ,default = None ,metavar = "TEXT" , 326help = "the release and setup choices (default track) or the changes made (custom track)" ) 327standard .add_argument ("--model-revision" ,metavar = "REV" ,help = "immutable revision of the quantization repository" ) 328standard .add_argument ("--source-revision" ,metavar = "REV" ,help = "revision of the original Qwen/Qwen3.8-Flash-Next weights" ) 329standard .add_argument ("--tokenizer-revision" ,metavar = "REV" ) 330standard .add_argument ("--quantization" ,metavar = "NAME" ,help = "when it cannot be read from the model file names" ) 331standard .add_argument ("--custom-pack" ,metavar = "TEXT" ,help = "describe a prepared pack or custom expert profile" ) 332standard .add_argument ("--background" ,action = "append" ,metavar = "TEXT" ,help = "a program that ran during the benchmark (repeatable)" ) 333standard .add_argument ("--build-options" ,metavar = "LIST" ,help = "comma-separated build options of a source build" ) 334standard .add_argument ("--skip-model-hash" ,action = "store_true" , 335help = "do not hash the model files (the run is then marked nonconforming)" ) 336bench_cancel = bench_sp .add_parser ("cancel" ,help = "stop the exact active saved-profile benchmark" ) 337bench_cancel .add_argument ("--profile" ,required = True ,help = "saved serving profile" ) 338bench_cancel .add_argument ("--path" ,required = True ,help = "absolute run directory or results.json" ) 339bench_cancel .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 340bench_report = bench_sp .add_parser ("report" ,help = "summarize an existing benchmark report" ) 341bench_report .add_argument ("path" ) 342bench_report .add_argument ("--output" ,choices = ("human" ,"json" ,"markdown" ),default = "human" ) 343bench_report .add_argument ("--out" ,metavar = "NEW_FILE" ,help = "write Markdown to a new file" ) 344bench_compare = bench_sp .add_parser ("compare" ,help = "compare two saved runs with workload checks" ) 345bench_compare .add_argument ("baseline" ) 346bench_compare .add_argument ("candidate" ) 347bench_compare .add_argument ("--output" ,choices = ("human" ,"json" ,"markdown" ),default = "human" ) 348bench_compare .add_argument ("--out" ,metavar = "NEW_FILE" ,help = "write Markdown to a new file" ) 349timeskip = sp .add_parser ( 350"timeskip" ,help = "retain a good result, try a bounded improvement, check it and decide" ) 351timeskip_sp = timeskip .add_subparsers (dest = "timeskip_command" ,required = True ) 352 353ts_run = timeskip_sp .add_parser ("run" ,help = "checkpoint, attempt a revision, check it and decide" ) 354ts_run .add_argument ("--workspace" ,required = True , 355help = "the directory holding the work (and, optionally, .strata/checks.json)" ) 356ts_run .add_argument ("--prompt" ,required = True ,help = "what the revision should achieve" ) 357ts_run .add_argument ("--attempts" ,type = int ,default = 2 , 358help = "bounded revision attempts (0 = checkpoint and check the baseline only); " 359"the specification's default is two" ) 360ts_run .add_argument ("--revise-command" ,default = None , 361help = "the command that performs ONE revision attempt. It runs with the " 362"candidate directory as its working directory, receives the prompt in " 363"STRATA_TIMESKIP_PROMPT and the attempt number in " 364"STRATA_TIMESKIP_ATTEMPT, and must not touch the workspace. Without it " 365"no revision is attempted, which yields an inconclusive run rather than " 366"a fabricated improvement." ) 367ts_run .add_argument ("--state-dir" ,default = None , 368help = "where runs are recorded (default: $STRATA_TIMESKIP_DIR or " 369"$XDG_STATE_HOME/strata/time-skip, %%LOCALAPPDATA%%\\Strata\\time-skip on Windows)" ) 370ts_run .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 371 372ts_status = timeskip_sp .add_parser ("status" ,help = "read a run's durable state and evidence" ) 373ts_status .add_argument ("run_id" ) 374ts_status .add_argument ("--state-dir" ,default = None ) 375ts_status .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 376 377ts_list = timeskip_sp .add_parser ("list" ,help = "list recorded runs" ) 378ts_list .add_argument ("--state-dir" ,default = None ) 379ts_list .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 380 381ts_apply = timeskip_sp .add_parser ( 382"apply" ,help = "apply the retained result, refusing if the destination changed" ) 383ts_apply .add_argument ("run_id" ) 384ts_apply .add_argument ("--workspace" ,default = None , 385help = "destination (default: the workspace the run recorded)" ) 386ts_apply .add_argument ("--attempt" ,type = int ,default = None , 387help = "apply this revision attempt (chosen by the person after review) " 388"instead of the retained checkpoint" ) 389ts_apply .add_argument ("--dry-run" ,action = "store_true" , 390help = "report what would change without writing anything" ) 391ts_apply .add_argument ("--restore" ,action = "store_true" , 392help = "put the original back instead of applying the result" ) 393ts_apply .add_argument ("--state-dir" ,default = None ) 394ts_apply .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 395 396tune = sp .add_parser ("tune" ,help = "bounded engine-configuration search with retained evidence" ) 397tune_sp = tune .add_subparsers (dest = "tune_command" ,required = True ) 398 399tune_plan = tune_sp .add_parser ("plan" ,help = "show exactly what a sweep would search, and why not" ) 400tune_plan .add_argument ("--engine" ,required = True ,help = "the engine binary to interrogate and measure" ) 401tune_plan .add_argument ("--backend" ,required = True ,choices = list (BACKENDS ), 402help = "the backend family the engine package claims" ) 403tune_plan .add_argument ("--model" ,required = True ,help = "the model identifier the measurements belong to" ) 404tune_plan .add_argument ("--objective" ,choices = ("generation" ,"prefill" ,"latency" ), 405default = "generation" ) 406tune_plan .add_argument ("--trials" ,type = int ,default = 16 ,help = "the bounded short sweep (default 16)" ) 407tune_plan .add_argument ("--time" ,dest = "total_time" ,type = float ,default = 1800.0 , 408help = "displayed total-time bound in seconds" ) 409tune_plan .add_argument ("--repeats" ,type = int ,default = 3 , 410help = "paired repeats per candidate (default 3, the specification's floor)" ) 411tune_plan .add_argument ("--hold" ,action = "append" ,default = [], 412help = "hold a dimension constant instead of searching it (repeatable)" ) 413tune_plan .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 414 415tune_run = tune_sp .add_parser ( 416"run" ,help = "run a bounded sweep: measure the baseline and candidates, then report" ) 417tune_run .add_argument ("--engine" ,required = True ,help = "the engine binary to measure" ) 418tune_run .add_argument ("--backend" ,required = True ,choices = list (BACKENDS )) 419tune_run .add_argument ("--model" ,required = True ,help = "the model the measurements belong to" ) 420tune_run .add_argument ("--objective" ,choices = ("generation" ,"prefill" ,"latency" ), 421default = "generation" ) 422tune_run .add_argument ("--trials" ,type = int ,default = 16 , 423help = "bounded number of candidate configurations (default 16)" ) 424tune_run .add_argument ("--time" ,dest = "total_time" ,type = float ,default = 1800.0 , 425help = "displayed total-time bound in seconds" ) 426tune_run .add_argument ("--repeats" ,type = int ,default = 3 , 427help = "paired repeats per candidate (default 3, the specification's floor)" ) 428tune_run .add_argument ("--prompt-tokens" ,type = int ,default = 512 , 429help = "the workload's prompt length; fixed for the whole sweep" ) 430tune_run .add_argument ("--max-new" ,type = int ,default = 128 , 431help = "the workload's output length; fixed for the whole sweep" ) 432tune_run .add_argument ("--mode" ,choices = ("protocol" ,"api" ),default = "protocol" , 433help = "protocol measures the engine's own serve protocol (cheap, for every " 434"candidate); api drives the real HTTP API the agent uses (the " 435"confirmation, and the only mode that reflects a user's wait)" ) 436tune_run .add_argument ("--api-prompt" ,default = "In one short sentence, what is a hash table?" , 437help = "the prompt the api mode sends" ) 438tune_run .add_argument ("--api-expect" ,default = None , 439help = "a regular expression the answer must match for the run to count as " 440"correct; without it correctness is not checked" ) 441tune_run .add_argument ("--api-port" ,type = int ,default = 8123 ) 442tune_run .add_argument ("--config" ,default = None , 443help = "the run configuration the api mode starts the worker with" ) 444tune_run .add_argument ("--boot-timeout" ,type = float ,default = 600.0 , 445help = "how long one candidate may take to become ready" ) 446tune_run .add_argument ("--request-timeout" ,type = float ,default = 600.0 , 447help = "how long one measured request may take" ) 448tune_run .add_argument ("--model-path" ,default = None , 449help = "the model's file, so the sweep's identity is a content digest rather " 450"than a name. Without it the record is incomparable to everything, " 451"which is safer than being falsely comparable." ) 452tune_run .add_argument ("--context" ,type = int ,default = None , 453help = "the context the measurements were taken at" ) 454tune_run .add_argument ("--full-digests" ,action = "store_true" , 455help = "hash the model and engine completely instead of sampling; slower but " 456"the strongest identity" ) 457tune_run .add_argument ("--hold" ,action = "append" ,default = [], 458help = "hold a dimension constant instead of searching it (repeatable)" ) 459tune_run .add_argument ("--state-dir" ,default = None ) 460tune_run .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 461 462tune_apply = tune_sp .add_parser ( 463"apply" ,help = "apply a reviewed recommendation, after verifying the candidate runs" ) 464tune_apply .add_argument ("job_id" ,help = "the completed sweep whose recommendation to apply" ) 465tune_apply .add_argument ("--config" ,default = None , 466help = "the run configuration to change (strata-<model>.json)" ) 467tune_apply .add_argument ("--model-path" ,default = None , 468help = "the model file, to re-check the identity before writing" ) 469tune_apply .add_argument ("--context" ,type = int ,default = None ) 470tune_apply .add_argument ("--state-dir" ,default = None ) 471tune_apply .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 472 473tune_rollback = tune_sp .add_parser ("rollback" ,help = "restore the configuration before an apply" ) 474tune_rollback .add_argument ("application_id" ) 475tune_rollback .add_argument ("--state-dir" ,default = None ) 476tune_rollback .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 477 478tune_status = tune_sp .add_parser ("status" ,help = "read a job's durable state and report" ) 479tune_status .add_argument ("job_id" ) 480tune_status .add_argument ("--state-dir" ,default = None ) 481tune_status .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 482 483tune_list = tune_sp .add_parser ("list" ,help = "list recorded jobs" ) 484tune_list .add_argument ("--state-dir" ,default = None ) 485tune_list .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 486 487tune_commands .add_tune_auto (tune_sp ) 488tune_commands .add_presets (sp ) 489from strata_cli .launch import cmd as launch_cmd 490launch_cmd .add_parsers (sp ) 491monitor_commands .add_status (sp ) 492monitor_commands .add_monitor (sp ) 493monitor_commands .add_logs (sp ) 494monitor_commands .add_connections (sp ) 495code = sp .add_parser ("code" ,help = "coding client for the shared Desktop harness" ) 496code .add_argument ("--workspace" ) 497code .add_argument ("--resume" ) 498code .add_argument ("--quiet" ,action = "store_true" ,help = "suppress human informational output" ) 499code_sp = code .add_subparsers (dest = "code_command" ) 500code_run = code_sp .add_parser ("run" ,help = "scripted harness turn (requires the shared harness component)" ) 501code_run .add_argument ("--prompt-file" ,required = True ) 502code_run .add_argument ("--policy" ,required = True ) 503code_run .add_argument ("--output" ,choices = ("jsonl" ,),default = "jsonl" ) 504code_run .add_argument ("--quiet" ,action = "store_true" ,default = argparse .SUPPRESS , 505help = "suppress human informational output" ) 506code_sessions = code_sp .add_parser ("sessions" ,help = "shared harness sessions" ) 507code_sessions .add_argument ("action" ,choices = ("list" ,)) 508code_sessions .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 509for one_shot in (profile_create ,profile_list ,profile_show ,profile_validate ,profile_set , 510profile_source ,profile_edit ,profile_history ,profile_rollback ,doctor , 511components_verify ,models_list ,models_inspect ,models_import ,models_move ,calibrate , 512runtime_start ,runtime_status ,runtime_verify ,runtime_stop ,runtime_cleanup ,runtime_restart , 513* ops_items ,bench_run ,bench_report ,bench_compare ,code_sessions ,* update_parsers ): 514one_shot .add_argument ("--json" ,action = "store_true" ,help = "alias for --output json" ) 515one_shot .add_argument ("--quiet" ,action = "store_true" ,default = argparse .SUPPRESS , 516help = "suppress human informational output" ) 517return ap 518 519 520def _file_words (exc :BaseException )-> str : 521try : 522from strata_control import longpath 523except ImportError : 524return f"local file operation failed ( { type ( exc ). __name__ } )" 525return longpath .file_words (exc ) 526 527 528def _error (message :str ,code :int ,machine :bool = False )-> int : 529if machine : 530json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :code ,"message" :message }})) 531else : 532f"strata: { message } " ,file = sys .stderr ) 533return code 534 535 536def _success (payload :dict ,* ,machine :bool ,human :str | None = None )-> int : 537if machine : 538json .dumps ({"schema_version" :1 ,"ok" :True ,** payload },ensure_ascii = False ,allow_nan = False )) 539elif human is not None : 540human ) 541else : 542json .dumps (payload ,indent = 2 ,ensure_ascii = False )) 543return 0 544 545 546def _source (ref :str )-> tuple [Path ,dict | None ,str | None ,dict ]: 547path ,saved ,revision = profiles .resolve (ref ) 548return path ,saved ,revision ,profiles .read_run_config (path ) 549 550 551def _models (a :argparse .Namespace )-> int : 552from strata_control import models 553if a .models_command == "import" : 554result = models .plan_import (a .path ) 555if result ["issues" ]: 556if a .output == "json" : 557json .dumps ({"schema_version" :1 ,"ok" :False ,"plan" :result }, 558ensure_ascii = False ,allow_nan = False )) 559else : 560_import_problem (result ),file = sys .stderr ) 561return 5 562return _success ({"plan" :result },machine = a .output == "json" ,human = _import_words (result )) 563if a .models_command == "move" : 564return _models_move (a ) 565if a .models_command == "list" : 566if a .served : 567if a .install_dir : 568return _error ("--install-dir applies only to local installed models" ,2 ,a .output == "json" ) 569from strata_cli import connections 570resolved = connections .resolve (url = a .url ,connection = a .connection , 571credential_env = a .credential_env ,timeout = a .timeout ) 572endpoint = Endpoint (resolved ["url" ],_usable_key (os .environ .get (resolved ["credential_env" ])), 573resolved ["timeout_s" ],resolved ["prefix" ]) 574snapshot = endpoint .snapshot () 575model = snapshot ["model" ] 576rows = ([{"id" :model ["id" ],"loaded" :model ["loaded" ], 577"instance_id" :snapshot ["instance" ]["id" ],"execution_compatibility" :"unverified" }] 578if model ["id" ]else []) 579result = {"scope" :"served_current_instance" ,"server" :endpoint .base_url , 580"models" :rows ,"model_count" :len (rows ), 581"note" :"current instance only; not an installed-model inventory" } 582return _success (result ,machine = a .output == "json" , 583human = "\n" .join (f" { row [ 'id' ] } " + 584 ("loaded" if row ["loaded" ]is True else 585"unloaded" if row ["loaded" ]is False else "load state unknown" ) 586for row in rows )or "No model ID reported by this server" ) 587if a .url or a .connection or a .credential_env or a .timeout is not None : 588return _error ("connection options require --served" ,2 ,a .output == "json" ) 589result = models .list_installed (a .install_dir ) 590lines = [f" { item [ 'id' ] } { item [ 'component_status' ] } " 591f" { item . get ( 'name' , item . get ( 'error' , '' )) } " for item in result ["models" ]] 592if not lines : 593where = ", " .join (result .get ("install_dirs" )or [result ["install_dir" ]]) 594lines = [f"No installed models found. Looked in: { where } . " 595"If your models are somewhere else, add --install-dir FOLDER (the folder with the strata-*.json files), " 596"or run `strata launch` to set one up." ] 597return _success (result ,machine = a .output == "json" ,human = "\n" .join (lines )) 598result = models .inspect (a .model_id ,a .install_dir ) 599item = result ["model" ] 600return _success (result ,machine = a .output == "json" , 601human = f" { item [ 'id' ] } : { item [ 'component_status' ] } ; engine compatibility unverified\n" 602f"Config: { item [ 'source_config' ] } \n" 603f"Components: { len ( result [ 'components' ][ 'components' ]) } , " 604f"issues: { len ( result [ 'components' ][ 'issues' ]) } " ) 605 606 607def _import_problem (plan :dict )-> str : 608"""Why `models import --plan` refused, in plain words (the codes stay in --output json).""" 609from strata_control import models as own_models 610words = own_models .problem_words (plan .get ("issues" )or [],missing = plan .get ("missing_shards" )) 611text = f"These files cannot be used as they are: { words } ." 612holds = next ((m for m in plan .get ("messages" )or []if "holds" in m ),"" ) 613if holds : 614text += " " + holds 615return text 616 617 618def _models_move (a :argparse .Namespace )-> int : 619from strata_control import discovery ,models ,models_move as mm 620machine = a .output in ("json" ,"jsonl" ) 621old = Path (a .source )if a .source else discovery .data_dir (Path .home ()/ "Strata" )[0 ] 622if a .status or a .resume or a .leave : 623return _models_move_unfinished (a ,old ) 624if not a .to : 625"strata: name the new folder, or use --resume / --leave / --status for an interrupted move." ,file = sys .stderr ) 626return 2 627new = Path (a .to ).expanduser () 628if a .plan : 629result = mm .plan (old ,new ) 630if machine : 631json .dumps ({"schema_version" :1 ,"ok" :result ["ok" ],"plan" :result },ensure_ascii = False ,allow_nan = False )) 632else : 633result ["issue" ]["message" ]if result ["issue" ]else 634f" { len ( result [ 'models' ]) } model(s), { result [ 'models_bytes' ] / 1e9 :.1f } GB; { result [ 'free_bytes' ] / 1e9 :.1f } GB free in { new } ." ) 635return 0 if result ["ok" ]else 5 636try : 637installs = [models .resolve_install (a .install_dir )[0 ]]if a .install_dir else [p for p ,_s in models .all_installs ()] 638except Exception : 639installs = [] 640configs = [c for i in installs for c in mm .config_files (i )] 641cancel = Path (a .cancel_file )if a .cancel_file else None 642 643def show (event :dict )-> None : 644if a .output == "jsonl" : 645json .dumps (event ,ensure_ascii = False ,allow_nan = False ),flush = True ) 646elif not machine : 647f"\r { event [ 'done' ] / 1e9 :.1f } of { event [ 'total' ] / 1e9 :.1f } GB { event [ 'file' ] } " ,end = "" ,flush = True ) 648try : 649summary = mm .move (old ,new ,on_progress = show ,cancelled = (lambda :cancel .exists ())if cancel else None ,configs = configs ) 650except mm .MoveError as e : 651extra = getattr (e ,"summary" , {}) 652if machine : 653json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :e .code ,"message" :str (e ),"details" :e .details },** extra },ensure_ascii = False )) 654else : 655f"\nstrata: { e } { e . details } " .rstrip (),file = sys .stderr ) 656return 5 657if machine : 658json .dumps ({"schema_version" :1 ,"ok" :True ,"event" :"result" ,** summary },ensure_ascii = False )) 659else : 660"\n" + ("Your models are moved." if summary ["done" ]else "Moving stopped. Nothing was lost." )) 661return 0 if summary ["done" ]else 6 662 663 664def _interrupted_words (st :dict )-> str : 665return (f"A move of your models was interrupted. They are in { st [ 'from' ] } and { st [ 'to' ] } . " 666"Finish it: strata models move --resume. Leave it (keep the models in the first folder): strata models move --leave." ) 667 668 669def _models_move_unfinished (a :argparse .Namespace ,old :Path )-> int : 670"""`strata models move --status | --resume | --leave`: the move the last run left unfinished (A move was interrupted. Finish it or leave it).""" 671from strata_control import models ,models_move as mm 672machine = a .output in ("json" ,"jsonl" ) 673st = mm .interrupted (old ) 674if a .status : 675if machine : 676json .dumps ({"schema_version" :1 ,"ok" :True ,"interrupted" :st },ensure_ascii = False ,allow_nan = False )) 677else : 678_interrupted_words (st )if st else "No move was interrupted." ) 679return 0 680if not st : 681if machine : 682json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :"nothing" ,"message" :"No move was interrupted." ,"details" :"" }})) 683else : 684"strata: no move was interrupted." ,file = sys .stderr ) 685return 5 686try : 687installs = [models .resolve_install (a .install_dir )[0 ]]if a .install_dir else [p for p ,_s in models .all_installs ()] 688except Exception : 689installs = [] 690configs = [c for i in installs for c in mm .config_files (i )] 691if a .leave : 692try : 693result = mm .leave (Path (st ["from" ]),Path (st ["to" ]),configs = configs ) 694except mm .MoveError as e : 695if machine : 696json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :e .code ,"message" :str (e ),"details" :e .details }},ensure_ascii = False )) 697else : 698f"strata: { e } { e . details } " .rstrip (),file = sys .stderr ) 699return 5 700if machine : 701json .dumps ({"schema_version" :1 ,"ok" :True ,"event" :"result" ,"left" :True ,** result },ensure_ascii = False )) 702else : 703f"Done. Your models stay in { st [ 'from' ] } ; the partial copies in { st [ 'to' ] } were removed." ) 704return 0 705a .to ,a .source ,a .resume ,a .status ,a .leave = st ["to" ],st ["from" ],False ,False ,False 706return _models_move (a ) 707 708 709def _import_words (plan :dict )-> str : 710"""The plain-words result of `strata models import --plan`: what the files are, what is already set up, what changes (nothing).""" 711cand = plan .get ("candidate_selection" )or {} 712lines = [f" { plan [ 'file_count' ] } GGUF file(s): { plan [ 'file_set_status' ] } " ] 713if cand .get ("family" ): 714lines .append (f"These files are Strata's { cand [ 'family' ] } { cand [ 'model' ] } ." ) 715done = plan .get ("already_set_up" ) 716if done : 717have = [name for key ,name in (("pack" ,"prepared model data" ), ("mtp" ,"draft layer" ), ("mmproj" ,"picture reader" ))if done .get (key )] 718if done .get ("config" ): 719lines .append (f"Already set up: { done [ 'config' ] } " + (f" (with the { ', ' . join ( have ) } )" if have else "" )) 720elif have : 721lines .append (f"Prepared files found beside it: { ', ' . join ( have ) } ." ) 722lines .append (f"Adoption: { plan [ 'adoption_status' ] } " ) 723lines .append ("No files changed" ) 724return "\n" .join (lines ) 725 726 727def _redact_argv (args :list [str ])-> list [str ]: 728out = [] 729conceal_next = False 730for item in args : 731if conceal_next : 732out .append ("<redacted>" ) 733conceal_next = False 734continue 735if item .startswith ("-" )and any (word in item .lower ()for word in ("key" ,"token" ,"secret" ,"password" ,"credential" )): 736if "=" in item : 737out .append (item .partition ("=" )[0 ]+ "=<redacted>" ) 738else : 739out .append (item ) 740conceal_next = True 741else : 742out .append (item ) 743return out 744 745 746def _effective (cfg :dict ,saved :dict | None ,cli :argparse .Namespace | None = None )-> tuple [dict ,dict ]: 747overrides = saved ["overrides" ]if saved else {} 748values = {} 749origins = {} 750for key ,default in (("host" ,"127.0.0.1" ), ("port" ,8095 ), ("parallel" ,None ), 751 ("batch_groups" ,None ), ("max_queue" ,None ), ("queue_timeout" ,None ), 752 ("offline" ,False ), ("batch_telemetry" ,False )): 753explicit = getattr (cli ,key ,None )if cli is not None else None 754if key == "offline" and explicit is False : 755explicit = None 756if explicit is not None : 757value ,origin = explicit ,"command" 758elif key in overrides : 759value ,origin = overrides [key ],"saved_profile" 760elif key in cfg : 761value ,origin = cfg [key ],"run_config" 762elif key == "batch_telemetry" and "STRATA_BATCH_TELEMETRY" in os .environ : 763value ,origin = os .environ ["STRATA_BATCH_TELEMETRY" ]== "1" ,"environment" 764else : 765value ,origin = default ,"default" 766values [key ],origins [key ]= value ,origin 767profiles .validate_overrides ({key :value for key ,value in values .items ()if key in 768 ("host" ,"port" ,"parallel" ,"batch_groups" ,"max_queue" ,"queue_timeout" , 769"offline" ,"batch_telemetry" ) 770and value is not None }) 771if values ["queue_timeout" ]is not None and values ["max_queue" ]is None : 772raise ProfileError ("queue_timeout requires max_queue to bound pending calls" ) 773if values ["parallel" ]is not None and any (flag in cfg ["args" ]for flag in ("--batch" ,"--slots" )): 774# (the all-cards split engine's run config, split_config's "split_engine_note", always carries --batch; the server turns "parallel" into its lane count) 775if origins ["parallel" ]!= "run_config" and not cfg .get ("split_engine_note" ): 776raise ProfileError ("parallel override conflicts with --batch/--slots in run config args" ) 777if values ["batch_groups" ]is not None and "--batch-groups" in cfg ["args" ]: 778raise ProfileError ("batch_groups override conflicts with --batch-groups in run config args" ) 779if values ["offline" ]and (cfg .get ("mcp_servers" )or cfg .get ("before_load" )): 780raise ProfileError ("offline serving requires MCP servers and before_load to be absent" ) 781return values ,origins 782 783 784def _launch_plan (ref :str ,cli :argparse .Namespace | None = None )-> tuple [dict ,list [str ]]: 785path ,saved ,revision ,cfg = _source (ref ) 786values ,origins = _effective (cfg ,saved ,cli ) 787host = values ["host" ] 788from serve .server import api_key_of ,explicit_no_key ,key_list 789raw_key = os .environ .get ("STRATA_API_KEY" )or cfg .get ("api_key" ,"" ) 790if not explicit_no_key (raw_key ): 791try : 792key_list (api_key_of (raw_key )) 793except ValueError : 794raise ProfileError ("the inference API key is invalid" ,5 )from None 795# A key is recommended on a network, never required: the server warns once at start (owner decision 2026-10-20). 796server_args = ["--engine" ,getattr (cli ,"engine" ,"strata" ),"--config" ,str (path ),"--host" ,str (host ), 797"--port" ,str (values ["port" ])] 798if cli is not None : 799server_args += ["--shutdown-timeout" ,str (cli .shutdown_timeout )] 800for key ,flag in (("parallel" ,"--parallel" ), ("batch_groups" ,"--batch-groups" ), 801 ("max_queue" ,"--max-queue" ), ("queue_timeout" ,"--queue-timeout" )): 802if values [key ]is not None and origins [key ]!= "run_config" : 803server_args += [flag ,str (values [key ])] 804if values ["offline" ]: 805server_args .append ("--offline" ) 806if origins ["batch_telemetry" ]not in ("run_config" ,"default" ): 807server_args .append ("--batch-telemetry" if values ["batch_telemetry" ]else "--no-batch-telemetry" ) 808ready_path = None 809if cli is not None and cli .ready_file : 810from serve .ready import preflight as ready_preflight 811ready_path = str (ready_preflight (cli .ready_file )) 812server_args += ["--ready-file" ,ready_path ] 813effective_cfg = {** cfg ,"args" :list (cfg ["args" ])} 814if values ["parallel" ]is not None : 815effective_cfg ["parallel" ]= values ["parallel" ] 816if values ["batch_groups" ]is not None : 817effective_cfg ["args" ]+= ["--batch-groups" ,str (values ["batch_groups" ])] 818from serve .server import engine_args 819notes = io .StringIO () 820with contextlib .redirect_stdout (notes ): 821engine_argv = engine_args (effective_cfg ) 822plan = {"profile" :saved ["id" ]if saved else None ,"profile_revision" :revision , 823"source_config" :str (path ),"model_name" :cfg .get ("model_name" ), 824"effective" :values ,"origin" :origins ,"server_argv" :server_args , 825"ready_file" :ready_path , 826"engine_exe" :cfg ["exe" ],"engine_argv" :_redact_argv (engine_argv ), 827"notes" : [line for line in notes .getvalue ().splitlines ()if line ]} 828return plan ,server_args 829 830 831def _serve_error (a :argparse .Namespace ,message :str ,code :int = 2 )-> int : 832if a .output == "jsonl" : 833json .dumps ({"schema_version" :1 ,"event" :"failed" ,"at" :time .time (), 834"exit_code" :code ,"error" : {"message" :message }}, 835ensure_ascii = False ,allow_nan = False )) 836return code 837return _error (message ,code ,a .output == "json" ) 838 839 840def _serve_jsonl (server_main ,args :list [str ],plan :dict ,* ,quiet :bool = False )-> int : 841output = sys .stdout 842output_open = True 843ready = False 844stopped = False 845fields = {"starting" : ("profile" ,"model_id" ,"pid" ), 846"ready" : ("instance_id" ,"pid" ,"api_url" ,"bound_host" ,"bound_port" , 847"model_id" ,"model_state" ,"api_state" ), 848"stopping" : ("instance_id" ,"reason" ), 849"draining" : ("instance_id" ,"pending_requests" ,"deadline_s" ), 850"stopped" : ("instance_id" ,"reason" ,"drained" ,"cancelled_requests" ,"exit_code" ), 851"failed" : ("phase" ,"exit_code" )} 852 853def emit (kind :str ,values :dict )-> None : 854nonlocal output_open ,ready ,stopped 855if kind not in fields : 856return 857ready |= kind == "ready" 858stopped |= kind == "stopped" 859if not output_open : 860return 861record = {"schema_version" :1 ,"event" :kind ,"at" :time .time (), 862** {key :values [key ]for key in fields [kind ]if key in values }} 863try : 864output .write (json .dumps (record ,ensure_ascii = False ,allow_nan = False )+ "\n" ) 865output .flush () 866except BrokenPipeError : 867# Losing a log consumer must not kill an owned inference service. 868output_open = False 869 870emit ("starting" , {"profile" :plan ["profile" ],"model_id" :plan ["model_name" ],"pid" :os .getpid ()}) 871try : 872with (open (os .devnull ,"w" ,encoding = "utf-8" )if quiet else 873contextlib .nullcontext (sys .stderr ))as human_output : 874with contextlib .redirect_stdout (human_output ): 875result = server_main (args ,lifecycle_event = emit ,interrupt_exit_code = 130 ) 876except SystemExit as exc : 877result = exc .code if type (exc .code )is int else 6 878if result == 0 and not ready : 879result = 6 880if not isinstance (exc .code ,int ): 881"strata: foreground service startup failed; inspect the profile and component checks" , 882file = sys .stderr ) 883emit ("failed" , {"phase" :"startup" if not ready else "running" ,"exit_code" :result }) 884return result 885except KeyboardInterrupt : 886emit ("failed" , {"phase" :"startup" if not ready else "running" ,"exit_code" :130 }) 887return 130 888except Exception as exc : 889f"strata: foreground service failed ( { type ( exc ). __name__ } )" ,file = sys .stderr ) 890emit ("failed" , {"phase" :"startup" if not ready else "running" ,"exit_code" :6 }) 891return 6 892if not ready : 893emit ("failed" , {"phase" :"startup" ,"exit_code" :result or 6 }) 894return result or 6 895if not stopped : 896emit ("failed" if result else "stopped" , 897 {"phase" :"running" ,"exit_code" :result , 898"reason" :"normal" ,"drained" :result == 0 }) 899return result 900 901 902def _serve_foreground (server_main ,args :list [str ],plan :dict ,* ,output :str ,quiet :bool )-> int : 903if output == "jsonl" : 904return _serve_jsonl (server_main ,args ,plan ,quiet = quiet ) 905if quiet : 906with open (os .devnull ,"w" ,encoding = "utf-8" )as human_output : 907with contextlib .redirect_stdout (human_output ): 908result = server_main (args ,interrupt_exit_code = 130 ) 909if result == 8 : 910"strata: shutdown drain deadline expired; owned requests were cancelled" ,file = sys .stderr ) 911elif result : 912f"strata: foreground service exited with code { result } " ,file = sys .stderr ) 913return result 914return server_main (args ,interrupt_exit_code = 130 ) 915 916 917def _serve (a :argparse .Namespace )-> int : 918if a .output == "json" and not a .plan : 919return _serve_error (a ,"--output json requires --plan; use --output jsonl for foreground events" ) 920if a .output == "jsonl" and a .plan : 921return _serve_error (a ,"--plan uses --output human or json; jsonl is for foreground events" ) 922if a .port is not None and not 0 <= a .port <= 65535 : 923return _serve_error (a ,"--port must be in 0..65535" ) 924if a .parallel is not None and not 1 <= a .parallel <= 1024 : 925return _serve_error (a ,"--parallel must be in 1..1024" ) 926if a .max_queue is not None and not 0 <= a .max_queue <= 4096 : 927return _serve_error (a ,"--max-queue must be in 0..4096" ) 928if a .queue_timeout is not None and (not math .isfinite (a .queue_timeout ) 929or not 0.1 <= a .queue_timeout <= 600 ): 930return _serve_error (a ,"--queue-timeout must be finite seconds in 0.1..600" ) 931if not 0 <= a .shutdown_timeout <= 300 : 932return _serve_error (a ,"--shutdown-timeout must be in 0..300 seconds" ) 933try : 934if a .batch_groups is not None : 935profiles .validate_overrides ({"batch_groups" :a .batch_groups if a .batch_groups == "auto" 936else int (a .batch_groups )if a .batch_groups .isdecimal ()else a .batch_groups }) 937plan ,args = _launch_plan (a .config ,a ) 938except ValueError as exc : 939if a .output == "jsonl" : 940return _serve_error (a ,str (exc ),getattr (exc ,"exit_code" ,2 )) 941raise 942if a .plan : 943return _success ({"plan" :plan },machine = a .output == "json" ) 944from serve .server import main as server_main 945if os .name not in ("posix" ,"nt" ): 946return _serve_foreground (server_main ,args ,plan ,output = a .output ,quiet = a .quiet ) 947from strata_control import runtime 948try : 949lease = runtime .acquire_activity_lease (shared = True ) 950except ValueError as exc : 951if a .output == "jsonl" : 952return _serve_error (a ,str (exc ),getattr (exc ,"exit_code" ,6 )) 953raise 954try : 955return _serve_foreground (server_main ,args ,plan ,output = a .output ,quiet = a .quiet ) 956finally : 957os .close (lease ) 958 959 960def _profile_command (a :argparse .Namespace )-> int : 961machine = a .output == "json" 962if a .profile_command == "create" : 963saved ,revision = profiles .create (a .name ,a .from_config ) 964return _success ({"profile" :saved ,"revision" :revision },machine = machine , 965human = f"Saved profile { a . name } at revision { revision } " ) 966if a .profile_command == "list" : 967items = profiles .list_profiles () 968human = "\n" .join (f" { item [ 'id' ] } { item . get ( 'revision' , item . get ( 'error' )) } " for item in items )or "No saved profiles" 969return _success ({"profiles" :items },machine = machine ,human = human ) 970saved ,revision = profiles .load (a .name ) 971if a .profile_command == "use-config" : 972proposed ,previous = profiles .propose_source (a .name ,a .from_config ) 973if previous != revision : 974raise ProfileError ("profile changed during source preview; plan it again" ,6 ) 975if a .if_revision is not None and a .if_revision != previous : 976raise ProfileError ("profile changed after preview; plan it again before selecting a config" ,6 ) 977change = {"before" :saved ["source_config" ],"after" :proposed ["source_config" ]} 978if a .plan : 979return _success ({"profile" :a .name ,"revision" :previous ,"source_config" :change , 980"model_name" :profiles .read_run_config (Path (proposed ["source_config" ])).get ("model_name" ), 981"would_save" :change ["before" ]!= change ["after" ]},machine = machine , 982human = f"Config: { change [ 'before' ] } -> { change [ 'after' ] } " ) 983saved ,revision = profiles .save (a .name ,proposed ,expected_revision = previous ) 984return _success ({"profile" :saved ,"previous_revision" :previous ,"revision" :revision , 985"source_config" :change },machine = machine , 986human = f"Saved source config for { a . name } : { change [ 'before' ] } -> { change [ 'after' ] } ; " 987"running instance unchanged" ) 988if a .profile_command == "set" : 989proposed ,previous = profiles .propose_values (a .name ,a .assignments ) 990changes = {key : {"before" :saved ["overrides" ].get (key ),"after" :value } 991for key ,value in proposed ["overrides" ].items ()if saved ["overrides" ].get (key )!= value } 992if a .plan : 993return _success ({"profile" :a .name ,"revision" :previous ,"changes" :changes , 994"would_save" :bool (changes )},machine = machine ) 995saved ,revision = profiles .save (a .name ,proposed ,expected_revision = previous ) 996return _success ({"profile" :saved ,"previous_revision" :previous ,"revision" :revision , 997"changes" :changes },machine = machine , 998human = f"Saved profile { a . name } : { previous } -> { revision } \n" + 999"\n" .join (f" { key } : { value [ 'before' ]!r } -> { value [ 'after' ]!r } " for key ,value in changes .items ())) 1000if a .profile_command == "edit" : 1001previous_value = saved 1002saved ,previous ,revision = profiles .edit (a .name ) 1003changes = {key : {"before" :previous_value .get (key ),"after" :saved .get (key )} 1004for key in saved if previous_value .get (key )!= saved .get (key )} 1005return _success ({"profile" :saved ,"previous_revision" :previous ,"revision" :revision , 1006"changes" :changes },machine = machine , 1007human = f"Saved profile { a . name } : { previous } -> { revision } " ) 1008if a .profile_command == "history" : 1009entries = profiles .history (a .name ) 1010return _success ({"profile" :a .name ,"history" :entries },machine = machine , 1011human = "\n" .join (f" { item [ 'revision' ] } { 'current' if item . get ( 'current' ) else 'saved' } " 1012for item in entries )) 1013if a .profile_command == "rollback" : 1014saved ,previous ,revision = profiles .rollback (a .name ,a .to ) 1015return _success ({"profile" :saved ,"previous_revision" :previous ,"revision" :revision },machine = machine , 1016human = f"Restored profile { a . name } : { previous } -> { revision } ; running instances are unchanged" ) 1017result = {"profile" :saved ,"revision" :revision } 1018if a .profile_command == "validate" or a .effective : 1019plan ,_ = _launch_plan (a .name ) 1020result ["plan" ]= plan 1021return _success (result ,machine = machine ,human = (f"Profile { a . name } is valid at revision { revision } " 1022if a .profile_command == "validate" else None )) 1023 1024 1025def _doctor (a :argparse .Namespace )-> int : 1026machine = a .output == "json" 1027ref = getattr (a ,"profile" ,None ) 1028path ,saved ,_ = profiles .resolve (ref )if ref else (None ,None ,None ) 1029report = inspect_components (path ,profile_id = saved ["id" ]if saved else None , 1030live = getattr (a ,"live" ,False )) 1031if machine : 1032json .dumps ({"schema_version" :1 ,"ok" :report ["ok" ],"report" :report }, 1033ensure_ascii = False ,allow_nan = False )) 1034else : 1035for item in report ["components" ]: 1036detail = item .get ("path" )or item .get ("reason" )or \ 1037 (f"version { item [ 'version' ] } " if item .get ("version" )else "" ) 1038f" { item [ 'status' ]:>16 } { item [ 'name' ] } { detail } " ) 1039for issue in report ["issues" ]: 1040f" { issue [ 'severity' ] } : { issue [ 'code' ] } : { issue [ 'message' ] } " ) 1041live_probe = report ["live_gpu_probe" ] 1042if live_probe is not None : 1043f"Live GPU probe: { live_probe [ 'status' ] } " ) 1044for card in live_probe ["cards" ]: 1045f" GPU { card [ 'index' ] } : { card [ 'name' ] } | { str ( card [ 'memory_mib' ]) + ' MiB' if card [ 'memory_mib' ] is not None else 'unified memory' } | " 1046f"driver { card [ 'driver_version' ] } | { card [ 'uuid' ] } " ) 1047return 0 if report ["ok" ]else 5 1048 1049 1050def _direct_calibration (ref :str ,kind :str ,report_path :Path ,action )-> tuple [str | None ,dict ]: 1051"""Saved profiles share the local journal; explicit run-config paths keep legacy behavior.""" 1052_ ,saved ,revision = profiles .resolve (ref ) 1053if saved is None : 1054return None ,action () 1055from strata_control import journal 1056return journal .run_direct (saved ["id" ],kind ,revision , 1057 {"report_path" :str (report_path .expanduser ().resolve ()),"exclusive_ack" :True }, 1058action ) 1059 1060 1061def _calibration (a :argparse .Namespace )-> int : 1062from strata_control import calibration 1063machine = a .output == "json" 1064if (a .out and not a .measure )or (a .exclusive and not (a .measure or a .apply_result or a .rollback_result )): 1065return _error ("--out is only for --measure; --exclusive is only for --measure, --apply-result " 1066"or --rollback-result" ,2 ,machine ) 1067if a .measure : 1068if not a .exclusive or not a .out : 1069return _error ("--measure requires --exclusive and --out REPORT.json" ,2 ,machine ) 1070with contextlib .redirect_stdout (sys .stderr ): 1071operation_id ,result = _direct_calibration (a .profile ,"engine.calibrate.measure" ,Path (a .out ), 1072lambda : {"ok" :True ,"report_path" :str (Path (a .out ).resolve ()), 1073"report" :calibration .measure (a .profile ,Path (a .out ),exclusive_ack = True , 1074say = lambda message :message ,file = sys .stderr ))}) 1075return _success ({"report" :result ["report" ],"path" :str (Path (a .out ).resolve ()), 1076** ({"operation_id" :operation_id }if operation_id else {})},machine = machine , 1077human = f"Calibration measured; review { Path ( a . out ). resolve () } before applying" ) 1078if a .review_result : 1079result = calibration .review (a .profile ,Path (a .review_result )) 1080result ["before_args" ]= _redact_argv (result ["before_args" ]) 1081result ["after_args" ]= _redact_argv (result ["after_args" ]) 1082if machine : 1083json .dumps ({"schema_version" :1 ,"ok" :result ["applicable" ],"review" :result }, 1084ensure_ascii = False ,allow_nan = False )) 1085else : 1086json .dumps (result ,indent = 2 ,ensure_ascii = False )) 1087return 0 if result ["applicable" ]else 6 1088if a .apply_result : 1089if not a .exclusive : 1090return _error ("--apply-result requires --exclusive" ,2 ,machine ) 1091with contextlib .redirect_stdout (sys .stderr ): 1092operation_id ,result = _direct_calibration (a .profile ,"engine.calibrate.apply" ,Path (a .apply_result ), 1093lambda : {"ok" :True ,"application" :calibration .apply_result ( 1094a .profile ,Path (a .apply_result ),exclusive_ack = True )}) 1095return _success ({"application" :result ["application" ], 1096** ({"operation_id" :operation_id }if operation_id else {})},machine = machine , 1097human = f"Calibration applied; rollback evidence: { result [ 'application' ][ 'application_record' ] } " ) 1098if a .review_rollback : 1099result = calibration .review_rollback (a .profile ,Path (a .review_rollback )) 1100if machine : 1101json .dumps ({"schema_version" :1 ,"ok" :result ["applicable" ],"rollback_review" :result }, 1102ensure_ascii = False ,allow_nan = False )) 1103else : 1104json .dumps (result ,indent = 2 ,ensure_ascii = False )) 1105return 0 if result ["applicable" ]else 6 1106if a .rollback_result : 1107if not a .exclusive : 1108return _error ("--rollback-result requires --exclusive" ,2 ,machine ) 1109with contextlib .redirect_stdout (sys .stderr ): 1110operation_id ,result = _direct_calibration (a .profile ,"engine.calibrate.rollback" , 1111Path (a .rollback_result ),lambda : {"ok" :True ,"rollback" :calibration .rollback_result ( 1112a .profile ,Path (a .rollback_result ),exclusive_ack = True )}) 1113return _success ({"rollback" :result ["rollback" ], 1114** ({"operation_id" :operation_id }if operation_id else {})},machine = machine , 1115human = "Previous calibration configuration restored; restart the model to use it" ) 1116plan = calibration .preview (a .profile ) 1117components = plan ["component_preflight" ] 1118if machine : 1119json .dumps ({"schema_version" :1 ,"ok" :components ["ok" ],"plan" :plan }, 1120ensure_ascii = False ,allow_nan = False )) 1121else : 1122f"Calibration plan for { plan [ 'model_name' ] or Path ( plan [ 'source_config' ]). name } " ) 1123f"Run config: { plan [ 'source_config' ] } " ) 1124"Measure engine settings for roughly 15–30 minutes with exclusive GPU access." ) 1125"This preview did not start the engine or change configuration." ) 1126if not components ["ok" ]: 1127"Required components are missing; run strata doctor --profile first." ) 1128return 0 if components ["ok" ]else 5 1129 1130 1131def _bench (a :argparse .Namespace )-> int : 1132from strata_cli import bench 1133machine = a .output == "json" 1134if a .bench_command in ("report" ,"compare" )and a .out and a .output != "markdown" : 1135return _error ("--out requires --output markdown" ,2 ,machine ) 1136if a .bench_command == "report" : 1137from strata_cli import bench_standard 1138standard_report = bench_standard .load_if_standard (Path (a .path )) 1139if standard_report is not None : 1140if a .output == "markdown" : 1141rendered = bench_standard .report_markdown (standard_report ) 1142if a .out : 1143bench .write_markdown (Path (a .out ),rendered ) 1144f"Markdown report: { Path ( a . out ). resolve () } " ) 1145else : 1146rendered ,end = "" ) 1147return 0 1148return _success ({"summary" : {"format" :standard_report ["format" ],"run_id" :standard_report ["run" ]["id" ], 1149"status" :standard_report ["run" ]["status" ], 1150"quality" :standard_report ["quality" ], 1151"summaries" :standard_report ["summaries" ]}},machine = machine , 1152human = bench_standard .format_plain (standard_report )) 1153report = bench .load (Path (a .path )) 1154result = bench .summary (report ) 1155if a .output == "markdown" : 1156rendered = bench .markdown_report (report ) 1157if a .out : 1158bench .write_markdown (Path (a .out ),rendered ) 1159f"Markdown report: { Path ( a . out ). resolve () } " ) 1160else : 1161rendered ,end = "" ) 1162return 0 1163return _success ({"summary" :result },machine = machine , 1164human = bench .format_summary (result )) 1165if a .bench_command == "compare" : 1166result = bench .compare (bench .load (Path (a .baseline )),bench .load (Path (a .candidate ))) 1167if a .output == "markdown" : 1168rendered = bench .markdown_comparison (result ) 1169if a .out : 1170bench .write_markdown (Path (a .out ),rendered ) 1171f"Markdown comparison: { Path ( a . out ). resolve () } " ) 1172else : 1173rendered ,end = "" ) 1174return 0 1175return _success ({"comparison" :result },machine = machine , 1176human = bench .format_comparison (result )) 1177if a .bench_command == "cancel" : 1178from strata_control import benchmarking ,profiles 1179if not Path (a .path ).is_absolute (): 1180return _error ("benchmark cancel path must be absolute" ,2 ,machine ) 1181profiles .load (a .profile ) 1182result = benchmarking .request_cancel (a .profile ,Path (a .path )) 1183return _success (result ,machine = machine , 1184human = "Cancellation requested; check the saved report for the final outcome." ) 1185if not a .credential_env .isidentifier ()or (a .telemetry_credential_env and 1186not a .telemetry_credential_env .isidentifier ()): 1187return _error ("credential options must name environment variables" ,2 ,machine ) 1188if a .suite == "standard-v1" : 1189return _bench_standard (a ,machine ) 1190if a .out is None : 1191return _error ("--out is required for the serving suites" ,2 ,machine ) 1192a .concurrency = 4 if a .concurrency is None else a .concurrency 1193a .repeat = 1 if a .repeat is None else a .repeat 1194a .request_timeout = 120 if a .request_timeout is None else a .request_timeout 1195maximum = 64 if a .suite == "parallel-overload-v1" else 16 1196if not 1 <= a .concurrency <= maximum or not 1 <= a .repeat <= 5 or not 1 <= a .request_timeout <= 600 : 1197return _error (f"concurrency must be 1.. { maximum } , repeat 1..5 and request timeout 1..600 seconds" ,2 , 1198machine ) 1199if a .require_managed_match and not a .profile : 1200return _error ("--require-managed-match needs a saved --profile" ,2 ,machine ) 1201profile_identity = None 1202if a .profile : 1203path ,saved ,revision ,cfg = _source (a .profile ) 1204if a .require_managed_match and saved is None : 1205return _error ("--require-managed-match needs a saved profile name" ,2 ,machine ) 1206plan ,_ = _launch_plan (a .profile ) 1207host = plan ["effective" ]["host" ] 1208host = "127.0.0.1" if host in ("0.0.0.0" ,"::" )else host 1209authority = f"[ { host } ]" if ":" in host and not host .startswith ("[" )else host 1210url = f"http:// { authority } : { plan [ 'effective' ][ 'port' ] } " 1211import hashlib 1212profile_identity = {"profile" :saved ["id" ]if saved else None ,"revision" :revision , 1213"source_config" :str (path ),"source_sha256" :hashlib .sha256 (path .read_bytes ()).hexdigest (), 1214"model_name" :cfg .get ("model_name" ),"gpu" :cfg .get ("gpu" )} 1215else : 1216url = a .url 1217key = _usable_key (os .environ .get (a .credential_env )) 1218endpoint = Endpoint (url ,key ,timeout = 10 ) 1219telemetry = Endpoint (url ,_usable_key (os .environ .get (a .telemetry_credential_env ))if a .telemetry_credential_env else key , 1220timeout = 3 ) 1221from strata_control .benchmarking import benchmark_lease 1222lease = benchmark_lease (saved ["id" ],Path (a .out ))if a .profile and saved else contextlib .nullcontext () 1223with lease ,contextlib .redirect_stdout (sys .stderr ): 1224report = bench .run (endpoint ,telemetry ,Path (a .out ),suite = a .suite , 1225concurrency = a .concurrency ,repeat = a .repeat , 1226request_timeout = a .request_timeout ,profile_identity = profile_identity , 1227condition = a .condition ,require_managed_match = a .require_managed_match ) 1228compact = bench .summary (report ) 1229if machine : 1230json .dumps ({"schema_version" :1 ,"ok" :report ["successful" ], 1231"path" :str ((Path (a .out )/ "results.json" ).resolve ()),"summary" :compact }, 1232ensure_ascii = False ,allow_nan = False )) 1233else : 1234bench .format_summary (compact )) 1235f"Evidence: { Path ( a . out ). resolve () / 'results.json' } " ) 1236return 0 if report ["successful" ]else 6 1237 1238 1239def _usable_key (value ): 1240"""An API key from the environment: "none" (any case) is the server's word for no key, so it is no key (#4483).""" 1241from strata_cli .bench_facts import usable_key 1242return usable_key (value ) 1243 1244 1245def _bench_standard (a :argparse .Namespace ,machine :bool )-> int : 1246"""`strata bench run` for docs/BENCHMARK_PROTOCOL.md: against a running server (--url, or a profile that is already serving), 1247or by starting the profile's engine for the run and stopping it afterwards.""" 1248from strata_cli import bench_facts ,bench_standard 1249fixed = [name for name ,value in (("--concurrency" ,a .concurrency ), ("--repeat" ,a .repeat ), 1250 ("--request-timeout" ,a .request_timeout ), ("--condition" ,a .condition ), 1251 ("--require-managed-match" ,a .require_managed_match or None ), 1252 ("--telemetry-credential-env" ,a .telemetry_credential_env )) 1253if value is not None ] 1254if fixed : 1255return _error (f" { ', ' . join ( fixed ) } do not apply to the standard suite: the protocol fixes the workload " 1256"(use --suite serving-smoke for a serving benchmark)" ,2 ,machine ) 1257if not a .credential_env .isidentifier (): 1258return _error ("credential options must name environment variables" ,2 ,machine ) 1259if not 1 <= a .load_timeout <= 86400 : 1260return _error ("--load-timeout must be 1..86400 seconds" ,2 ,machine ) 1261plan = None 1262saved = None 1263key = _usable_key (os .environ .get (a .credential_env )) 1264if a .profile : 1265_ ,saved ,_ ,cfg = _source (a .profile ) 1266plan ,_ = _launch_plan (a .profile ) 1267plan = {** plan ,"config" :cfg } 1268host = plan ["effective" ]["host" ] 1269host = "127.0.0.1" if host in ("0.0.0.0" ,"::" )else host 1270authority = f"[ { host } ]" if ":" in host and not host .startswith ("[" )else host 1271url = f"http:// { authority } : { plan [ 'effective' ][ 'port' ] } " 1272if not key and cfg .get ("api_key" )and str (cfg ["api_key" ]).strip ().lower ()!= "none" : 1273from serve .server import api_key_of ,key_list 1274keys = key_list (api_key_of (cfg ["api_key" ])) 1275key = keys [0 ]if keys else None 1276else : 1277url = a .url 1278from strata_cli .client import server_url 1279target = bench_standard .Target (server_url (url ),key ) 1280redact = bench_facts .redactor (key or "" ) 1281command = redact ("strata " + " " .join (str (part )for part in (a .raw_argv or ["bench" ,"run" ,"--suite" ,"standard-v1" ]))) 1282declared = {"track" :a .track ,"track_notes" :a .track_notes or "no notes given by the operator" , 1283"model_revision" :a .model_revision ,"source_revision" :a .source_revision , 1284"tokenizer_revision" :a .tokenizer_revision ,"quantization" :a .quantization , 1285"custom_pack" :a .custom_pack ,"background" :a .background or [], 1286"build_options" : [x .strip ()for x in a .build_options .split ("," )if x .strip ()]if a .build_options else None } 1287out = Path (a .out )if a .out else None 1288out_root = None if out else (Path .cwd ()/ "bench" / "results" if (Path .cwd ()/ "bench" / "results" ).is_dir () 1289else Path .cwd ()/ "bench-results" ) 1290from strata_control .benchmarking import benchmark_lease 1291import shutil 1292import tempfile 1293lease = benchmark_lease (saved ["id" ],out )if saved else contextlib .nullcontext () 1294proc ,scratch ,engine_log ,run_log ,log_start = None ,None ,None ,None ,0 1295stop_problem = None 1296try : 1297with lease ,bench_standard .term_is_interrupt (),contextlib .redirect_stdout (sys .stderr ): 1298def log (message :str )-> None : 1299message ,file = sys .stderr ,flush = True ) 1300if a .profile and target .get ("/health" ,timeout = 5 )is None : 1301if a .no_start : 1302raise ProfileError ("no server is answering at the profile's address and --no-start was given" ,5 ) 1303scratch = Path (tempfile .mkdtemp (prefix = "strata-bench-" )) 1304engine_log = scratch / "engine.log" 1305run_log = Path (str (plan ["config" ]["log" ])).expanduser ()if isinstance (plan ["config" ].get ("log" ),str )else None 1306log_start = run_log .stat ().st_size if run_log is not None and run_log .is_file ()else 0 1307proc = bench_standard .start_engine (a .profile ,target ,engine_log ,log ,a .load_timeout ) 1308elif a .profile : 1309log ("using the server that is already running at this profile's address; it will not be stopped" ) 1310doc ,out_dir = bench_standard .run (target ,out ,out_root = out_root ,optional_concurrency = a .optional_concurrency , 1311declared = declared ,plan = plan ,engine_log = engine_log ,command = command ,log = log , 1312engine_run_log = (run_log ,log_start )if proc is not None else None , 1313started_engine = proc is not None ,hash_model =not a .skip_model_hash ) 1314finally : 1315stop_problem = bench_standard .stop_engine (proc ) 1316if not isinstance (stop_problem ,str ): 1317stop_problem = None 1318if scratch is not None : 1319shutil .rmtree (scratch ,ignore_errors = True ) 1320ok = doc ["run" ]["status" ]== "complete" 1321if stop_problem :# #3438: a stop that failed is not a normal finish: the engine may still hold the port and the GPU 1322ok = False 1323f"\nERROR: the engine this run started could not be stopped: { stop_problem } . It may still hold the server port " 1324"and the GPU: stop it by hand before the next run. This run is marked FAILED." ,file = sys .stderr ,flush = True ) 1325try : 1326 (out_dir / "ENGINE-NOT-STOPPED.txt" ).write_text (stop_problem + "\n" ,encoding = "utf-8" ) 1327except OSError : 1328pass 1329path = out_dir / "results.json" 1330if machine : 1331json .dumps ({"schema_version" :1 ,"ok" :ok ,"path" :str (path .resolve ()),"status" :"failed" if stop_problem else doc ["run" ]["status" ],"engine_stop_error" :stop_problem , 1332"quality" :doc ["quality" ],"summaries" :doc ["summaries" ]},ensure_ascii = False ,allow_nan = False )) 1333else : 1334bench_standard .format_plain (doc )) 1335f"\nReport: { out_dir . resolve () / 'README.md' } \nResult: { path . resolve () } " ) 1336return 0 if ok else 6 1337 1338 1339def _runtime (a :argparse .Namespace )-> int : 1340from strata_control import management 1341machine = a .output == "json" 1342if a .runtime_command == "cleanup" : 1343from strata_control import runtime 1344result = runtime .cleanup (a .profile ) 1345if machine : 1346json .dumps ({"schema_version" :1 ,** result },ensure_ascii = False ,allow_nan = False )) 1347else : 1348f"ended { len ( result [ 'ended' ]) } leftover process(es)" + 1349 (f"; { len ( result [ 'stuck' ]) } would not end" if result ["stuck" ]else "" )+ 1350 (f"; { len ( result [ 'unverifiable' ]) } could not be identified here and were left alone" 1351if result ["unverifiable" ]else "" )) 1352return 0 if result ["ok" ]else result ["exit_code" ] 1353result = management .runtime_action ( 1354a .runtime_command ,a .profile ,plan = getattr (a ,"plan" ,False ), 1355die_with_pid = getattr (a ,"die_with_pid" ,None ), 1356wait = getattr (a ,"wait" ,300 ), 1357shutdown_timeout = getattr (a ,"shutdown_timeout" ,30 ), 1358startup_wait = getattr (a ,"startup_wait" ,300 ),load = getattr (a ,"load" ,False ), 1359if_profile_revision = getattr (a ,"if_profile_revision" ,None ), 1360if_owner_id = getattr (a ,"if_owner_id" ,None ), 1361if_instance_id = getattr (a ,"if_instance_id" ,None ), 1362allow_source_switch = getattr (a ,"allow_source_switch" ,False ), 1363allow_source_migration = getattr (a ,"allow_source_migration" ,False ), 1364if_source_sha256 = getattr (a ,"if_source_sha256" ,None )) 1365if a .runtime_command in ("start" ,"stop" ,"verify" )and a .plan and result .get ("ok" ): 1366return _success ({"plan" :result ["plan" ]},machine = machine ) 1367if machine : 1368json .dumps ({"schema_version" :1 ,** result },ensure_ascii = False ,allow_nan = False )) 1369else : 1370readiness_label = {"generation_ready" :"generation checked" , 1371"unloaded" :"API verified; model unloaded" }.get (result .get ("readiness_state" )) 1372f" { a . profile } : { result . get ( 'state' , 'unknown' ) } " + 1373 (f" instance { result [ 'instance_id' ] } " if result .get ("instance_id" )else "" )+ 1374 (f" { result [ 'api_url' ] } " if result .get ("api_url" )else "" )+ 1375 (" config/launch verified" if result .get ("launch_attested" )else "" )+ 1376 (f" { readiness_label } " if readiness_label else "" )+ 1377 (f" { result [ 'error' ] } " if result .get ("error" )else "" )) 1378if not result ["ok" ]and a .runtime_command in ("start" ,"restart" ,"verify" ): 1379for line in _engine_log_hint (a .profile ): 1380line ,file = sys .stderr ) 1381return 0 if result ["ok" ]else result .get ("exit_code" ,6 ) 1382 1383 1384def _engine_log_hint (profile :str )-> list [str ]: 1385"""Where the engine wrote why it stopped, and its last lines: "server_exited" alone names nothing to read.""" 1386try : 1387path ,_saved ,_revision = profiles .resolve (profile ) 1388log = profiles .read_run_config (path ).get ("log" ) 1389if not isinstance (log ,str )or not log : 1390return [] 1391text = Path (log ).expanduser ().read_text (encoding = "utf-8" ,errors = "replace" ) 1392except (ProfileError ,OSError ,ValueError ,KeyError ): 1393return [] 1394lines = [line .strip ()for line in text .splitlines ()if line .strip ()] 1395tail = lines [- 3 :] 1396return [f"engine log: { log } " ]+ [f" { line [: 300 ] } " for line in tail ] 1397 1398 1399def _ops (a :argparse .Namespace )-> int : 1400from strata_control import journal ,recipes 1401machine = a .output == "json" 1402action = a .ops_command 1403if action == "init" : 1404created = recipes .initialize (a .profile ) 1405return _success ({"profile" :a .profile ,"created" :created },machine = machine , 1406human = ("Created: " + ", " .join (created )if created else "Recipes already initialized" )) 1407if action == "list" : 1408items = recipes .list_recipes (a .profile ) 1409return _success ({"profile" :a .profile ,"recipes" :items },machine = machine , 1410human = "\n" .join (f" { item [ 'id' ] } { item . get ( 'kind' , item . get ( 'error' )) } " for item in items ) 1411or "No recipes; use strata ops init --profile NAME" ) 1412if action == "runs" : 1413runs = journal .list_runs (a .profile ,limit = a .limit ) 1414return _success ({"profile" :a .profile ,"runs" :runs },machine = machine , 1415human = "\n" .join (f" { item [ 'operation_id' ] } { item . get ( 'state' , item . get ( 'error' )) } " 1416for item in runs )or "No operation runs recorded" ) 1417if action == "result" : 1418record = journal .load (a .profile ,a .operation_id ) 1419return _success ({"record" :record },machine = machine ) 1420if action == "create" : 1421recipe ,revision = recipes .create (a .profile ,a .name ,a .kind ) 1422return _success ({"recipe" :recipe ,"revision" :revision },machine = machine , 1423human = f"Created recipe { a . name } ( { a . kind } ) at { revision } " ) 1424if action == "show" : 1425recipe ,revision = recipes .load (a .profile ,a .name ) 1426return _success ({"recipe" :recipe ,"revision" :revision },machine = machine ) 1427if action == "edit" : 1428recipe ,previous ,revision = recipes .edit (a .profile ,a .name ) 1429return _success ({"recipe" :recipe ,"previous_revision" :previous ,"revision" :revision }, 1430machine = machine ,human = f"Saved recipe { a . name } : { previous } -> { revision } " ) 1431if action == "set" : 1432recipe ,revision = recipes .propose_value (a .profile ,a .name ,a .assignment ) 1433if a .plan : 1434current ,_ = recipes .load (a .profile ,a .name ) 1435return _success ({"recipe" :recipe ,"revision" :revision ,"would_save" :recipe != current },machine = machine ) 1436saved ,new_revision = recipes .save (a .profile ,a .name ,recipe ,revision ) 1437return _success ({"recipe" :saved ,"previous_revision" :revision ,"revision" :new_revision }, 1438machine = machine ,human = f"Saved recipe { a . name } : { revision } -> { new_revision } " ) 1439if action == "history" : 1440entries = recipes .history (a .profile ,a .name ) 1441return _success ({"profile" :a .profile ,"recipe" :a .name ,"history" :entries },machine = machine , 1442human = "\n" .join (f" { item [ 'revision' ] } { 'current' if item . get ( 'current' ) else 'saved' } " 1443for item in entries )) 1444if action == "rollback" : 1445recipe ,previous ,revision = recipes .rollback (a .profile ,a .name ,a .to ) 1446return _success ({"recipe" :recipe ,"previous_revision" :previous ,"revision" :revision }, 1447machine = machine ,human = f"Restored recipe { a . name } : { previous } -> { revision } " ) 1448if action == "plan" : 1449plan = recipes .plan (a .profile ,a .name ) 1450ok = plan ["operation" ]["ok" ] 1451if machine : 1452json .dumps ({"schema_version" :1 ,"ok" :ok ,"plan" :plan },ensure_ascii = False ,allow_nan = False )) 1453else : 1454json .dumps (plan ,indent = 2 ,ensure_ascii = False )) 1455return 0 if ok else plan ["operation" ].get ("exit_code" ,5 ) 1456recipe ,_ = recipes .load (a .profile ,a .name ) 1457if a .exclusive and recipe ["kind" ]!= "engine.calibrate.measure" : 1458return _error ("--exclusive applies only to calibration recipes" ,2 ,machine ) 1459with contextlib .redirect_stdout (sys .stderr ): 1460operation = recipes .run (a .profile ,a .name ,exclusive_ack = a .exclusive , 1461expected_revision = a .if_revision , 1462expected_profile_revision = a .if_profile_revision , 1463expected_owner_id = a .if_owner_id , 1464expected_instance_id = a .if_instance_id , 1465expected_source_sha256 = a .if_source_sha256 ) 1466ok = operation ["result" ]["ok" ] 1467if machine : 1468json .dumps ({"schema_version" :1 ,"ok" :ok ,"operation" :operation }, 1469ensure_ascii = False ,allow_nan = False )) 1470else : 1471json .dumps (operation ,indent = 2 ,ensure_ascii = False )) 1472return 0 if ok else operation ["result" ].get ("exit_code" ,5 ) 1473 1474 1475def _timeskip (a :argparse .Namespace )-> int : 1476"""Real Time-skip: retain, revise, check, decide. 1477 1478The decision is evidence-driven and the terminal states are honest: a run whose checks are 1479missing, unevaluable or unchanged ends inconclusive and asks the user to review, and cancelling 1480or crashing leaves the last complete checkpoint selected. No timer decides anything here. 1481""" 1482from strata_control import time_skip 1483 1484def state_root ()-> Path : 1485if getattr (a ,"state_dir" ,None ): 1486return Path (a .state_dir ) 1487env = os .environ .get ("STRATA_TIMESKIP_DIR" ) 1488if env : 1489return Path (env ) 1490from strata_control .paths import state_base 1491return state_base ()/ "time-skip" 1492 1493store = time_skip .TimeSkipStore (state_root ()) 1494 1495if a .timeskip_command == "list" : 1496runs = store .list () 1497if a .output == "json" : 1498return _success ({"runs" :runs },machine = True ) 1499if not runs : 1500"no Time-skip runs recorded" ) 1501return 0 1502for r in runs : 1503decision = (r .get ("decision" )or {}).get ("outcome" )or "-" 1504f" { r [ 'id' ][: 12 ] } { str ( r . get ( 'state' , '?' )):<18 } { decision :<12 } " 1505f" { ( r . get ( 'prompt' ) or '' )[: 48 ] } " ) 1506return 0 1507 1508if a .timeskip_command == "status" : 1509try : 1510data = store .get (a .run_id ) 1511except time_skip .TimeSkipError as e : 1512return _error (str (e ),2 ,a .output == "json" ) 1513if a .output == "json" : 1514return _success ({"run" :data },machine = True ) 1515f"run { data [ 'id' ] } " ) 1516f"state { data [ 'state' ] } " ) 1517f"workspace { data [ 'workspace' ] } " ) 1518f"prompt { data [ 'prompt' ] } " ) 1519for cp in data .get ("checkpoints" , []): 1520outcomes = ", " .join (f" { c [ 'id' ] } = { c [ 'outcome' ] } " for c in cp .get ("checks" , []))or "no checks" 1521f" { cp [ 'id' ]:<16 } { cp [ 'digest' ][: 12 ] } { outcomes } " ) 1522for att in data .get ("attempts" , []): 1523f" attempt { att [ 'index' ] } : { att . get ( 'decision' ) } - { att . get ( 'reason' , '' ) } " ) 1524dec = data .get ("decision" )or {} 1525if dec : 1526f"decision { dec . get ( 'outcome' ) } ( { dec . get ( 'reason' ) } )" ) 1527f"retained { dec . get ( 'retained' ) } " ) 1528if dec .get ("needs_user_review" ): 1529" needs user review: the evidence does not justify an automatic choice" ) 1530return 0 1531 1532if a .timeskip_command == "apply" : 1533try : 1534data = store .get (a .run_id ) 1535except time_skip .TimeSkipError as e : 1536return _error (str (e ),2 ,a .output == "json" ) 1537run = _reopen_run (store ,data ) 1538destination = Path (a .workspace )if a .workspace else None 1539try : 1540if a .restore : 1541outcome = run .restore_original (destination ) 1542if a .output == "json" : 1543return _success ({"restore" :outcome },machine = True ) 1544f"restored { outcome [ 'checkpoint' ] } to { destination or data [ 'workspace' ] } " ) 1545return 0 1546outcome = run .apply (destination ,dry_run = a .dry_run ,attempt = a .attempt ) 1547except time_skip .TimeSkipError as e : 1548return _error (str (e ),2 ,a .output == "json" ) 1549if outcome .get ("conflict" ): 1550# A concurrent user edit is a conflict to report, never something to overwrite. 1551return _error (outcome ["reason" ],6 ,a .output == "json" ) 1552if not outcome .get ("applied" )and not outcome .get ("dry_run" ): 1553return _error (outcome .get ("reason" ,"apply did not complete" ),6 ,a .output == "json" ) 1554if a .output == "json" : 1555return _success ({"apply" :outcome },machine = True ) 1556if outcome .get ("dry_run" ): 1557"would write: " + (", " .join (outcome .get ("would_write" )or [])or "(nothing)" )) 1558if outcome .get ("would_remove" ): 1559"would remove: " + ", " .join (outcome ["would_remove" ])) 1560return 0 1561"applied " + (", " .join (outcome .get ("wrote" )or [])or "(no changes)" )) 1562f"rollback copy: { outcome . get ( 'rollback' ) } " ) 1563return 0 1564 1565# run 1566workspace = Path (a .workspace ) 1567if not workspace .is_dir (): 1568return _error (f"workspace is not a directory: { workspace } " ,2 ,a .output == "json" ) 1569try : 1570checks = store .load_checks (workspace ) 1571except (time_skip .TimeSkipError ,ValueError ,OSError )as e : 1572return _error (f"could not read .strata/checks.json: { e } " ,2 ,a .output == "json" ) 1573if not checks : 1574"strata: no checks are declared for this workspace (.strata/checks.json); the run " 1575"will checkpoint and report inconclusive rather than claim an improvement" , 1576file = sys .stderr ) 1577 1578run = time_skip .TimeSkipRun (state_root (),workspace ,a .prompt ,checks ,max_attempts = a .attempts ) 1579 1580def revise (candidate :Path ,prompt :str ,attempt :int ): 1581if not a .revise_command : 1582return None 1583env = {** os .environ ,"STRATA_TIMESKIP_PROMPT" :prompt , 1584"STRATA_TIMESKIP_ATTEMPT" :str (attempt )} 1585proc = subprocess .run (a .revise_command ,shell = True ,cwd = str (candidate ),env = env , 1586capture_output = True ,text = True ,errors = "replace" ) 1587if proc .returncode != 0 : 1588raise time_skip .TimeSkipError ( 1589f"the revision command failed (exit { proc . returncode } ): " 1590f" { ( proc . stderr or proc . stdout or '' )[ - 300 :] } " ) 1591return (proc .stdout or "" ).strip ()[- 500 :]or None 1592 1593result = run .run (revise ) 1594if a .output == "json" : 1595if result ["state" ]in ("failed" ,"interrupted" ): 1596return _error (result .get ("error" )or result ["state" ],6 ,True ) 1597return _success ({"run" :result },machine = True ) 1598f"run { result [ 'id' ] } -> { result [ 'state' ] } " ) 1599for att in result .get ("attempts" , []): 1600f" attempt { att [ 'index' ] } : { att . get ( 'decision' ) } - { att . get ( 'reason' , '' ) } " ) 1601dec = result .get ("decision" )or {} 1602if dec : 1603f" decision: { dec . get ( 'outcome' ) } ( { dec . get ( 'reason' ) } )" ) 1604if dec .get ("needs_user_review" ): 1605" the evidence does not justify an automatic choice; compare and select" ) 1606f" inspect: strata timeskip status { result [ 'id' ] } " ) 1607f" preview: strata timeskip apply { result [ 'id' ] } --dry-run" ) 1608if result ["state" ]in ("failed" ,"interrupted" ): 1609return _error (result .get ("error" )or result ["state" ],6 ,False ) 1610return 0 1611 1612 1613def _reopen_run (store ,data :dict ): 1614"""Rebuild a run object from its durable record so apply/restore survive a restart.""" 1615from strata_control import time_skip 1616run = time_skip .TimeSkipRun (store .root ,Path (data ["workspace" ]),data ["prompt" ], [], 1617run_id = data ["id" ]) 1618run .state = data .get ("state" ,run .state ) 1619run .checkpoints = [time_skip .Checkpoint (** cp )for cp in data .get ("checkpoints" , [])] 1620run .attempts = [time_skip .Attempt (** att )for att in data .get ("attempts" , [])] 1621run .selected_checkpoint = data .get ("selected_checkpoint" ) 1622run .decision = data .get ("decision" ) 1623run .events = data .get ("events" , []) 1624run .started_at = data .get ("started_at" ,run .started_at ) 1625run .finished_at = data .get ("finished_at" ) 1626return run 1627 1628 1629def _engine_arg (value :str ,backend :str )-> Path : 1630"""`--engine` is a path, or `component:strata-engine` for the engine package installed for this PC.""" 1631from strata_control import engine_component 1632if engine_component .is_reference (value ): 1633try : 1634return Path (engine_component .expand (value , {"backend" :backend })) 1635except engine_component .EngineMissing as exc : 1636raise ProfileError (str (exc ),5 )from None 1637return Path (value ) 1638 1639 1640def _tune (a :argparse .Namespace )-> int : 1641"""Engine tuning: a bounded search that returns a recommendation, never an automatic change. 1642 1643`plan` is the review surface. It reports which dimensions the selected backend may search and 1644*why* the rest were excluded, so a sweep can never measure a configuration the engine would 1645refuse. Running a sweep is a separate, longer step and is deliberately not exposed here yet: it 1646needs a measurement harness for the selected engine, and this Mac has no workload to measure. 1647""" 1648from strata_control import tuning 1649machine = a .output == "json" 1650 1651def state_root ()-> Path : 1652if getattr (a ,"state_dir" ,None ): 1653return Path (a .state_dir ) 1654env = os .environ .get ("STRATA_TUNE_DIR" ) 1655if env : 1656return Path (env ) 1657from strata_control .paths import state_base 1658return state_base ()/ "tuning" 1659 1660if a .tune_command == "auto" : 1661return tune_commands .auto (a ) 1662 1663if a .tune_command == "list" : 1664root = state_root () 1665jobs = [] 1666if root .is_dir (): 1667for d in sorted (root .iterdir ()): 1668f = d / "job.json" 1669if f .is_file (): 1670try : 1671data = json .loads (f .read_text (encoding = "utf-8" )) 1672except (OSError ,ValueError ): 1673continue 1674jobs .append ({"id" :data .get ("id" ),"state" :data .get ("state" ), 1675"backend" : (data .get ("plan" )or {}).get ("backend" ), 1676"objective" : (data .get ("plan" )or {}).get ("objective" )}) 1677if machine : 1678return _success ({"jobs" :jobs },machine = True ) 1679if not jobs : 1680"no tuning jobs recorded" ) 1681return 0 1682for j in jobs : 1683f" { str ( j [ 'id' ])[: 12 ] } { str ( j [ 'state' ]):<10 } { str ( j [ 'backend' ]):<8 } { j [ 'objective' ] } " ) 1684return 0 1685 1686if a .tune_command == "status" : 1687root = state_root () 1688f = root / a .job_id / "job.json" 1689if not f .is_file (): 1690return _error (f"no tuning job { a . job_id } " ,2 ,machine ) 1691data = json .loads (f .read_text (encoding = "utf-8" )) 1692if machine : 1693return _success ({"job" :data },machine = True ) 1694f"job { data [ 'id' ] } " ) 1695f"state { data [ 'state' ] } " ) 1696plan = data .get ("plan" )or {} 1697f"backend { plan . get ( 'backend' ) } objective { plan . get ( 'objective' ) } " ) 1698rep = data .get ("report" )or {} 1699if rep : 1700f"metric { rep . get ( 'metric' ) } (higher is better: { rep . get ( 'higher_is_better' ) } )" ) 1701f"trials { rep . get ( 'trials_run' ) } of { plan . get ( 'max_trials' ) } " ) 1702base = rep .get ("baseline" )or {} 1703if base : 1704f"baseline median { base . get ( 'median' ) } over { base . get ( 'measured' ) } runs" ) 1705if rep .get ("recommendation_available" ): 1706rec = rep ["recommendation" ] 1707f"recommend index { rec [ 'candidate_index' ] } median { rec [ 'median' ] } " 1708f"(baseline { rec [ 'baseline_median' ] } )" ) 1709f" args: { ' ' . join ( f' { k } { v } ' for k , v in rec [ 'args' ]. items ()) } " ) 1710else : 1711f"recommend none - { rep . get ( 'reason' ) } " ) 1712for f_ in rep .get ("failures" )or []: 1713f" failed # { f_ [ 'index' ] } { f_ [ 'status' ] } : { f_ [ 'reason' ][: 90 ] } " ) 1714return 0 1715 1716if a .tune_command == "run" : 1717return _tune_run (a ,store_root = state_root ()) 1718if a .tune_command == "apply" : 1719return _tune_apply (a ,store_root = state_root ()) 1720if a .tune_command == "rollback" : 1721return _tune_rollback (a ,store_root = state_root ()) 1722 1723# plan 1724engine = _engine_arg (a .engine ,a .backend ) 1725plan = tuning .plan_tuning (engine ,a .backend ,a .model ,a .objective , 1726 {"note" :"the workload is supplied by the measurement harness" }, 1727hold = a .hold ,max_trials = a .trials ,total_time_s = a .total_time , 1728repeats = a .repeats ,devices = [], 1729model_path = getattr (a ,"model_path" ,None )) 1730if machine : 1731return _success ({"plan" :plan .to_dict ()},machine = True ) 1732f"engine { plan . engine } " ) 1733f"flags { 'read from the binary' if plan . engine_flags_known else 'could not be read; the static table was used and this is recorded' } " ) 1734f"backend { plan . backend } objective { plan . objective } repeats { plan . repeats } " ) 1735f"bounds at most { plan . max_trials } trials, { plan . total_time_s :.0f } s total" ) 1736"searches:" ) 1737for d in plan .dimensions : 1738mark = " (benchmark only: never exported)" if d ["benchmark_only" ]else "" 1739f" { d [ 'id' ]:<18 } { ', ' . join ( d [ 'flags' ]) } values { d [ 'values' ] } { mark } " ) 1740if not plan .dimensions : 1741" (none: this backend offers no searchable dimension)" ) 1742"excluded:" ) 1743for e in plan .excluded : 1744f" { e [ 'id' ]:<18 } { e [ 'reason' ] } " ) 1745"Applying a result is a separate step; a sweep never writes the active profile." ) 1747return 0 1748 1749 1750def _tune_run (a :argparse .Namespace ,* ,store_root :Path )-> int : 1751"""Run a bounded sweep and write its report. 1752 1753The measurement is `tune_engine.EngineHarness`: it boots the engine with one candidate's flags, 1754sends the fixed workload and reads the engine's own protocol output. Nothing here invents a 1755number — a candidate that cannot be measured is recorded with the engine's reason and excluded 1756from selection. 1757 1758Two honest limitations are printed with the result rather than buried: 1759 1760* the winner is measured through the engine's own serve protocol, **not** through the full 1761HTTP API the Harness uses, so the recommendation still needs the exported-configuration 1762retest the qualification kit describes before it is trusted; 1763* no profile is written. Applying is a separate, reversible step. 1764""" 1765from strata_control import tune_engine ,tuning 1766 1767engine = _engine_arg (a .engine ,a .backend ) 1768if not engine .exists (): 1769return _error (f"no engine binary at { engine } " ,2 ,a .output == "json" ) 1770 1771plan = tuning .plan_tuning ( 1772engine ,a .backend ,a .model ,a .objective , 1773 {"prompt_tokens" :a .prompt_tokens ,"max_new" :a .max_new ,"seed" :1 ,"temperature" :0.0 }, 1774hold = a .hold ,max_trials = a .trials ,total_time_s = a .total_time ,repeats = a .repeats ,devices = [], 1775model_path = Path (a .model_path )if a .model_path else None ,context = a .context , 1776full_digests = a .full_digests ) 1777 1778workload = {"prompt_tokens" :a .prompt_tokens ,"max_new" :a .max_new ,"seed" :1 ,"temperature" :0.0 } 1779if a .mode == "api" : 1780from strata_control import tune_api 1781if not a .config : 1782return _error ("--mode api needs --config: the worker is started from a run " 1783"configuration so the candidate's flags are the ones it boots with" , 17842 ,a .output == "json" ) 1785if not a .api_expect : 1786return _error ("--mode api needs --api-expect: without an expectation a fast wrong answer " 1787"cannot be told from a fast right one" ,2 ,a .output == "json" ) 1788measure = tune_api .make_api_measure ( 1789python = sys .executable ,serve_dir = Path (__file__ ).resolve ().parents [1 ], 1790config_path = Path (a .config ),prompt = a .api_prompt ,max_new = a .max_new , 1791expect = a .api_expect ,port = a .api_port ,boot_timeout_s = a .boot_timeout , 1792request_timeout_s = a .request_timeout ) 1793else : 1794measure = tune_engine .make_measure (engine ,workload = workload ) 1795 1796if a .output != "json" : 1797searched = ", " .join (d ["id" ]for d in plan .dimensions )or "(nothing)" 1798f"sweeping { searched } " ) 1799if a .mode == "api" : 1800f"measuring through the HTTP API at port { a . api_port } , " 1801f"checking the answer against { a . api_expect !r } " ) 1802else : 1803"measuring the engine's own serve protocol" ) 1804f"backend { plan . backend } · objective { plan . objective } · repeats { plan . repeats } · " 1805f"at most { plan . max_trials } trials / { plan . total_time_s :.0f } s" ) 1806if not plan .dimensions : 1807"strata: this backend offers no searchable dimension for this engine, so the " 1808"sweep will measure the baseline and stop" ,file = sys .stderr ) 1809 1810job = tuning .Tuner (store_root ,plan ,measure ) 1811result = job .run () 1812 1813if a .output == "json" : 1814return _success ({"job" :result },machine = True ) 1815 1816rep = result .get ("report" )or {} 1817f"job { result [ 'id' ] } -> { result [ 'state' ] } " ) 1818base = rep .get ("baseline" )or {} 1819if base : 1820f" baseline median { base . get ( 'median' ) } over { base . get ( 'measured' ) } runs" ) 1821total = rep .get ("combinations_total" )or 0 1822ran = rep .get ("trials_run" ,0 ) 1823if rep .get ("trials_are_a_prefix" )and total : 1824# Say plainly that this was a prefix of the space. Otherwise "4 trials" reads as "4 was all 1825# there was", and a partial search gets mistaken for a complete one. 1826f" trials { ran } of { plan . max_trials } allowed, from { total } possible combinations " 1827f"(a prefix of the enumeration)" ) 1828else : 1829f" trials { ran } of { plan . max_trials } " ) 1830for f in rep .get ("failures" )or []: 1831f" failed # { f [ 'index' ] } { f [ 'status' ] } : { f [ 'reason' ][: 90 ] } " ) 1832if rep .get ("drift" )and rep .get ("drift_material" ): 1833d = rep ["drift" ] 1834f" drift baseline { d [ 'first' ]:.1f } -> { d [ 'last' ]:.1f } " 1835f"( { d [ 'relative' ] * 100 :+.1f } %) — the comparison is weaker than the repeat count suggests" ) 1836elif rep .get ("drift" ): 1837d = rep ["drift" ] 1838f" drift baseline { d [ 'first' ]:.1f } -> { d [ 'last' ]:.1f } " 1839f"( { d [ 'relative' ] * 100 :+.1f } %) — within noise" ) 1840if rep .get ("recommendation_available" ): 1841rec = rep ["recommendation" ] 1842args = " " .join (f" { k } { v } " for k ,v in rec ["args" ].items ())or "(no flags)" 1843f" recommend index { rec [ 'candidate_index' ] } : { args } " ) 1844f" median { rec [ 'median' ]:.1f } against a baseline of { rec [ 'baseline_median' ]:.1f } " ) 1845else : 1846f" recommend none — { rep . get ( 'reason' ) } " ) 1847if a .mode == "api" : 1849" measured through the worker's HTTP API, which is what a user waits for." ) 1850else : 1851" measured through the engine's own serve protocol, which is not what a user waits" ) 1852" for. Confirm any recommendation with --mode api before trusting it." ) 1853" Apply it as a separate reviewed step: strata tune apply <job>. No profile has changed." ) 1854f" report: strata tune status { result [ 'id' ] } " ) 1855return 0 1856 1857 1858def _tune_apply (a :argparse .Namespace ,* ,store_root :Path )-> int : 1859"""Apply a recommendation to a run configuration, after verifying the candidate runs. 1860 1861The verification is a real start: the candidate configuration is booted and required to produce at 1862least one token before the file is touched. A sweep cannot see that failure, because a sweep 1863measures generation on a configuration it never writes. 1864""" 1865from strata_control import tune_apply ,tune_history 1866 1867job = _load_job (store_root ,a .job_id ) 1868if job is None : 1869return _error (f"no tuning job { a . job_id } in { store_root } " ,2 ,a .output == "json" ) 1870 1871config = Path (a .config )if a .config else _find_config_for (job ) 1872if config is None or not config .exists (): 1873return _error ("no run configuration found; pass --config strata-<model>.json" , 18742 ,a .output == "json" ) 1875 1876identity = None 1877if a .model_path or (job .get ("plan" )or {}).get ("identity" ): 1878try : 1879engine_path = Path ((job .get ("plan" )or {}).get ("engine" )or "" ) 1880identity = tune_history .comparison_key ( 1881engine = tune_history .file_identity (engine_path ), 1882model = tune_history .file_identity (Path (a .model_path ))if a .model_path 1883else {"path" :None ,"exists" :False ,"method" :None ,"digest" :None ,"bytes" :None }, 1884backend = (job .get ("plan" )or {}).get ("backend" )or "" , 1885workload = ((job .get ("report" )or {}).get ("metric" )and 1886_workload_of (job ))or {}, 1887context = (job .get ("plan" )or {}).get ("context" )) 1888except Exception :# noqa: BLE001 - an unavailable identity means "cannot verify", below 1889identity = None 1890 1891# The recorded sweep has to carry a model digest before anything is written. A sweep planned 1892# without `--model-path` records `model_digest: null`, and `null` does not equal any real digest, 1893# so such a recommendation can never be matched to what is installed -- which means it cannot be 1894# applied, however plausible its numbers look. This is a refusal, not a warning. 1895recorded = ((job .get ("report" )or {}).get ("identity" )or {}) 1896if not recorded .get ("model_digest" ): 1897return _error ( 1898"the sweep recorded no model digest, so its recommendation cannot be matched to the " 1899"installed weights; re-run the sweep with --model-path and apply that result instead" , 19002 ,a .output == "json" ) 1901if a .model_path and identity is not None and not identity .get ("model_digest" ): 1902return _error (f"no model file at { a . model_path } " ,2 ,a .output == "json" ) 1903if identity is None : 1904return _error ("the sweep's identity could not be re-derived; refusing to apply a " 1905"configuration that may have been measured against different bytes" , 19062 ,a .output == "json" ) 1907 1908try : 1909result = tune_apply .apply_recommendation ( 1910job = job ,config_path = config ,current_identity = identity ,state_dir = store_root , 1911verify = None )# a real verification needs a model; the plan is still checked 1912except tune_apply .ApplyError as e : 1913return _error (str (e ),e .code ,a .output == "json" ) 1914 1915if a .output == "json" : 1916return _success (result ,machine = True ) 1917plan = result ["plan" ] 1918f"applied to { plan [ 'config_path' ] } " ) 1919for item in plan ["added" ]: 1920f" + { item } " ) 1921for item in plan ["removed" ]: 1922f" - { item } " ) 1923f" before { plan [ 'before_sha256' ][: 16 ] } after { plan [ 'after_sha256' ][: 16 ] } " ) 1924f" rollback: strata tune rollback { result [ 'application' ][ 'application_id' ] } " ) 1925" The candidate was NOT verified against a running model: no supported model fits this" ) 1927" machine. The configuration was checked for staleness, identity and diff, and the" ) 1928" previous bytes were retained. Verify generation before relying on this configuration." ) 1929return 0 1930 1931 1932def _find_config_for (job :dict )-> Path | None : 1933"""The run configuration for the sweep's model, found next to the repository.""" 1934from strata_control import tune_apply 1935model = (job .get ("plan" )or {}).get ("model" )or "" 1936candidates = tune_apply .find_config_files (Path .cwd ()) 1937if not candidates : 1938return None 1939for path in candidates : 1940if model and model .lower ()in path .stem .lower (): 1941return path 1942return candidates [0 ]if len (candidates )== 1 else None 1943 1944 1945def _workload_of (job :dict )-> dict : 1946return dict (((job .get ("plan" )or {}).get ("identity" )or {}).get ("workload" )or {}) 1947 1948 1949def _load_job (store_root :Path ,job_id :str )-> dict | None : 1950if not re .fullmatch (r"[0-9a-f]{8,64}" ,str (job_id or "" )): 1951return None 1952path = Path (store_root )/ job_id / "job.json" 1953if not path .exists (): 1954return None 1955try : 1956return json .loads (path .read_text (encoding = "utf-8" )) 1957except (OSError ,json .JSONDecodeError ): 1958return None 1959 1960 1961def _tune_rollback (a :argparse .Namespace ,* ,store_root :Path )-> int : 1962from strata_control import tune_apply 1963try : 1964result = tune_apply .rollback (application_id = a .application_id ,state_dir = store_root ) 1965except tune_apply .ApplyError as e : 1966return _error (str (e ),e .code ,a .output == "json" ) 1967if a .output == "json" : 1968return _success (result ,machine = True ) 1969f"restored { result [ 'restored' ] } " ) 1970f" application { result [ 'application' ][ 'application_id' ] } marked rolled back" ) 1971return 0 1972 1973 1974def _components_plan (a :argparse .Namespace )-> int : 1975"""Read a component manifest and report whether it may be used on this machine. 1976 1977This is the input that decides what gets downloaded and unpacked, so it is read strictly and the 1978platform and backend gates are applied before anything is fetched. An unsupported combination is 1979reported as unsupported rather than attempted. 1980""" 1981from strata_control import components 1982path = Path (a .manifest ) 1983if not path .exists (): 1984return _error (f"no component manifest at { path } " ,2 ,a .output == "json" ) 1985try : 1986component = components .parse_manifest (path .read_text (encoding = "utf-8" )) 1987except components .ComponentError as e : 1988return _error (str (e ),e .code ,a .output == "json" ) 1989 1990target = a .target or components .host_platform () 1991reasons = components .check_compatible (component ,target = target ,backend = a .backend ) 1992payload = { 1993"id" :component .id ,"version" :component .version ,"kind" :component .kind , 1994"backend" :component .backend ,"target" :target , 1995"platforms" :list (component .platforms ),"cache_key" :component .cache_key , 1996"usable" :not reasons ,"reasons" :reasons , 1997"artifacts" : [{"name" :art .name ,"bytes" :art .bytes ,"sha256" :art .sha256 , 1998"format" :art .format }for art in component .artifacts ], 1999"total_bytes" :sum (art .bytes for art in component .artifacts ), 2000"requires" :list (component .requires ),"entrypoint" :component .entrypoint , 2001 } 2002if a .output == "json" : 2003return _success (payload ,machine = True ) 2004f" { component . id } { component . version } ( { component . kind } " 2005+ (f", { component . backend } " if component .backend else "" )+ ")" ) 2006f" platforms { ', ' . join ( component . platforms ) } " ) 2007f" target { target } " ) 2008f" payload { payload [ 'total_bytes' ] / ( 1 << 20 ):.1f } MiB in " 2009f" { len ( component . artifacts ) } artifact(s)" ) 2010f" cache key { component . cache_key [: 16 ] } (the bytes, not the version label)" ) 2011if a .backend : 2012f" backend { a . backend } " ) 2013f" usable { 'yes' if payload [ 'usable' ] else 'NO' } " ) 2014for reason in reasons : 2015f" - { reason } " ) 2016if component .requires : 2017f" requires { ', ' . join ( component . requires ) } " ) 2018" nothing was downloaded, unpacked or changed" ) 2019return 0 2020 2021 2022def _components_engine (a :argparse .Namespace )-> int : 2023"""Which engine package the local component folder offers this PC. Read-only; a missing engine is a notice with a 2024non-zero exit (5), never a fetch.""" 2025from strata_control import engine_component 2026root = Path (a .components_dir )if a .components_dir else None 2027try : 2028report = engine_component .status (root ,backend = a .backend ,full = a .full ) 2029except engine_component .ComponentProblem as exc : 2030return _error (str (exc ),2 ,a .output == "json" ) 2031code = 0 if report ["usable" ]else 5 2032if a .output == "json" : 2033json .dumps ({"schema_version" :1 ,"ok" :report ["usable" ],** report },ensure_ascii = False )) 2034return code 2035f"component folder { report [ 'components_dir' ] } " ) 2036f"this PC { report [ 'platform' ] } , { report [ 'backend' ] or 'no GPU found' } ( { report [ 'backend_source' ] } )" ) 2037for item in report ["installed" ]: 2038f" installed { item [ 'version' ] } { item [ 'platform' ] } - { item [ 'backend' ] } { item [ 'root' ] } " ) 2039for item in report ["problems" ]: 2040f" unusable { item [ 'folder' ] } : { item [ 'problem' ] } " ) 2041if report ["usable" ]: 2042f"engine { report [ 'engine' ][ 'exe' ] } (version { report [ 'engine' ][ 'version' ] } )" ) 2043else : 2044report ["notice" ],file = sys .stderr ) 2045for row in report .get ("shapes" )or []:# the engines of model shapes, only on a PC that has one (strata_control/shape_engine.py) 2046f"engine for { row [ 'shape' ] } " + (f" { row [ 'engine' ][ 'exe' ] } (version { row [ 'engine' ][ 'version' ] } )" if row ["usable" ]else str (row .get ("notice" )))) 2047notice = engine_component .cached_notice (root ) 2048if notice : 2049notice ) 2050"nothing was downloaded or changed" ) 2051return code 2052 2053 2054def _components_backends (a :argparse .Namespace )-> int : 2055"""The committed OS and backend matrix, so an unsupported combination is visible up front.""" 2056from strata_control import components 2057here = components .host_platform () 2058rows = [] 2059for backend ,platforms in sorted (components .BACKEND_MATRIX .items ()): 2060rows .append ({"backend" :backend ,"platforms" :list (platforms ),"here" :here in platforms }) 2061if a .output == "json" : 2062return _success ({"host" :here ,"matrix" :rows },machine = True ) 2063f"this machine is { here } " ) 2064for row in rows : 2066mark = "supported here" if row ["here" ]else "not supported here" 2067f" { row [ 'backend' ]:<6 } { ', ' . join ( row [ 'platforms' ]):<45 } { mark } " ) 2068" Unsupported combinations are not attempted. A combination that is listed but has not" ) 2070" been qualified on real hardware is prepared, not claimed: see packaging/README.md." ) 2071return 0 2072 2073 2074def _install (a :argparse .Namespace )-> int : 2075"""The one place the terminal acquires anything: it hands over to the installer (setup.py) of a full Strata 2076folder, which is where pip, the engine and the models are fetched. A folder without it (the terminal archive) 2077says so and names what to do instead.""" 2078installer = Path (os .environ .get ("STRATA_INSTALL_DIR" )or ROOT )/ "setup.py" 2079if not installer .is_file (): 2080return _error ("this folder has no installer (setup.py). Engines, models and updates are installed from a " 2081"full Strata folder with SETUP.bat / ./setup.sh and UPDATE.bat / ./update.sh; " 2082"set STRATA_INSTALL_DIR to that folder to run it from here. To update the engine and Control " 2083"from the signed update feed, run `strata update`" ,5 ) 2084extra = [x for x in a .setup_args if x != "--" ] 2085env = dict (os .environ ) 2086if (ROOT / "python" ).is_dir ()and (ROOT / "VERSION" ).is_file (): 2087# the Terminal bundle: its installer only downloads and prepares the model (no pip, no engine fetch, no compiler) 2088env ["STRATA_CONTROL_INSTALL" ]= "1" 2089from strata_cli .launch .catalog import install_root 2090env .setdefault ("STRATA_INSTALL_DIR" ,str (install_root ())) 2091return subprocess .call ([sys .executable ,str (installer ),"--update" if a .update else "--setup" ,* extra ], 2092cwd = str (installer .parent ),env = env ) 2093 2094 2095def _access_retry (a :argparse .Namespace ,error :BaseException )-> int | None : 2096"""A file in Strata's own per-user folders that this user cannot open (a run as administrator made it) is repaired once 2097and the command runs again; if that does not help the person gets one plain sentence, with the technical text after it.""" 2098try : 2099from strata_control import private_files 2100except ImportError : 2101return None 2102if not (isinstance (error ,PermissionError )or "PermissionError" in str (error )): 2103return None 2104as_json = bool (getattr (a ,"json" ,False )or getattr (a ,"output" ,None )in ("json" ,"jsonl" )) 2105in_use = private_files .is_sharing_violation (error ) 2106if getattr (a ,"_access_retried" ,False ): 2107message = private_files .IN_USE_MESSAGE if in_use else private_files .ACCESS_MESSAGE 2108return _error (f" { message } (details: { error } )" ,5 ,as_json ) 2109a ._access_retried = True 2110if in_use : 2111time .sleep (1.5 )# a scanner or a sync tool lets go of the file in a moment; repairing would not help 2112else : 2113private_files .repair_known_roots () 2114return _run (a ) 2115 2116 2117def _repair_access (a :argparse .Namespace )-> int : 2118from strata_control import private_files 2119report = private_files .repair_known_roots () 2120if getattr (a ,"output" ,"human" )== "json" : 2121json .dumps ({"ok" :not report ["failed" ],** report })) 2122else : 2123f"checked { report [ 'checked' ] } entries, repaired { report [ 'repaired' ] } , could not repair { report [ 'failed' ] } " ) 2124if report ["failed" ]: 2125private_files .ACCESS_MESSAGE ) 2126return 0 if not report ["failed" ]else 5 2127 2128 2129def _run (a :argparse .Namespace )-> int : 2130try : 2131if a .command == "serve" : 2132return _serve (a ) 2133if a .command == "install" : 2134return _install (a ) 2135if a .command == "repair-access" : 2136return _repair_access (a ) 2137if a .command == "profile" : 2138return _profile_command (a ) 2139if a .command == "components" and a .components_command == "plan" : 2140return _components_plan (a ) 2141if a .command == "components" and a .components_command == "backends" : 2142return _components_backends (a ) 2143if a .command == "components" and a .components_command == "engine" : 2144return _components_engine (a ) 2145if a .command == "update" or (a .command == "components" and a .components_command in ("update" ,"rollback" ,"install-file" ,"engines" ,"use" ,"remove" )): 2146from strata_cli import update_cmd 2147return update_cmd .run (a ) 2148if a .command in ("doctor" ,"components" ): 2149return _doctor (a ) 2150if a .command == "models" : 2151return _models (a ) 2152if a .command == "engine" : 2153return _calibration (a ) 2154if a .command == "drafting" : 2155from strata_cli import drafting_cmd as _drafting_cmd 2156return _drafting_cmd .run (a ) 2157if a .command == "split-engine" : 2158from strata_cli import split_cmd as _split_cmd 2159return _split_cmd .run (a ) 2160if a .command == "bench" : 2161return _bench (a ) 2162if a .command == "timeskip" : 2163return _timeskip (a ) 2164if a .command == "presets" : 2165return tune_commands .presets_command (a ) 2166if a .command in ("launch" ,"connect" ): 2167from strata_cli .launch import cmd as launch_cmd 2168return launch_cmd .run_launch (a )if a .command == "launch" else launch_cmd .run_connect (a ) 2169if a .command == "tune" : 2170return _tune (a ) 2171if a .command == "runtime" : 2172return _runtime (a ) 2173if a .command == "ops" : 2174return _ops (a ) 2175if a .command == "code" : 2176return _error ("the shared Desktop harness component is not installed; coding sessions are unavailable" ,5 , 2177getattr (a ,"output" ,None )in ("json" ,"jsonl" )) 2178return monitor_commands .run (a ) 2179except ValueError as e : 2180retried = _access_retry (a ,e ) 2181if retried is not None : 2182return retried 2183if a .command == "serve" and a .output == "jsonl" : 2184return _serve_error (a ,str (e ),getattr (e ,"exit_code" ,2 )) 2185return _error (str (e ),getattr (e ,"exit_code" ,2 ), 2186bool (getattr (a ,"json" ,False )or getattr (a ,"output" ,None )in ("json" ,"jsonl" ))) 2187except BrokenPipeError : 2188return 0 2189except OSError as e : 2190retried = _access_retry (a ,e ) 2191if retried is not None : 2192return retried 2193if a .command == "serve" and a .output == "jsonl" : 2194return _serve_error (a ,_file_words (e ),6 ) 2195return _error (_file_words (e ),6 , 2196bool (getattr (a ,"output" ,None )in ("json" ,"jsonl" ))) 2197except ClientError as e : 2198if a .command == "serve" and a .output == "jsonl" : 2199return _serve_error (a ,str (e ),e .exit_code ) 2200return _error (str (e ),e .exit_code , 2201bool (getattr (a ,"json" ,False )or getattr (a ,"output" ,None )in ("json" ,"jsonl" ))) 2202except KeyboardInterrupt : 2203if a .command == "serve" and a .output == "jsonl" : 2204return _serve_error (a ,"interrupted; operation completion may be unknown" ,130 ) 2205return _error ("interrupted; operation completion may be unknown" ,130 , 2206bool (getattr (a ,"json" ,False )or getattr (a ,"output" ,None )in ("json" ,"jsonl" ))) 2207 2208 2209class _QuietCapture : 2210"""Keep the last human output to show only when an operation fails.""" 2211 2212def __init__ (self ,limit :int = 64 * 1024 ): 2213self .limit = limit 2214self .text = "" 2215self .truncated = False 2216 2217def write (self ,value :str )-> int : 2218if len (self .text )+ len (value )> self .limit : 2219self .truncated = True 2220self .text = (self .text + value )[- self .limit :] 2221return len (value ) 2222 2223def flush (self )-> None : 2224pass 2225 2226def getvalue (self )-> str : 2227return self .text 2228 2229 2230def _install_argv (argv :list [str ])-> list [str ]: 2231"""`strata install` hands everything after it to setup.py (`strata install --family qwen --model IQ3_XXS --yes`). argparse cannot do that 2232by itself: an option it does not know ahead of the first plain word (--source, --family) was refused as "unrecognized arguments", or 2233split from its value (#4188). So the options of setup.py go behind a `--`, and only `--update` and --help stay strata's own.""" 2234if not argv or argv [0 ]!= "install" : 2235return argv 2236rest = list (argv [1 :]) 2237if rest and rest [0 ]in ("-h" ,"--help" ): 2238return argv 2239update = "--update" in rest 2240if update : 2241rest .remove ("--update" ) 2242return ["install" ,* (["--update" ]if update else []),"--" ,* rest ] 2243 2244 2245def main (argv :list [str ]| None = None )-> int : 2246try : 2247from strata_control .childenv import quiet_crash_env 2248quiet_crash_env ()# every program Strata starts inherits it: ggml never starts gdb on a user's machine 2249except ImportError :# a thin bundle ships without strata_control 2250pass 2251try : 2252from strata_control import private_files 2253private_files .adopt_user_defaults ()# what this process creates belongs to the user even when it runs as administrator 2254except ImportError :# a thin bundle ships without strata_control 2255pass 2256ap = parser () 2257raw = list (sys .argv [1 :]if argv is None else argv ) 2258a ,extras = ap .parse_known_args (_install_argv (raw )) 2259a .raw_argv = raw 2260if extras : 2261if getattr (a ,"command" ,None )in ("launch" ,"connect" ): 2262from strata_cli .launch import cmd as launch_cmd 2263"strata: " + launch_cmd .unknown_option_message (a .command ,extras ,ap ),file = sys .stderr ) 2264return 2 2265ap .error ("unrecognized arguments: " + " " .join (extras )) 2266if getattr (a ,"json" ,False )and a .command not in ("status" ,"monitor" ,"logs" ,"connection" ,"config" ): 2267if a .output == "jsonl" : 2268return _serve_error (a ,"--json is one-shot only; use --output jsonl for foreground events" ) 2269a .output = "json" 2270if not getattr (a ,"quiet" ,False )or getattr (a ,"output" ,"human" )in ("json" ,"jsonl" ): 2271return _run (a ) 2272if a .command in ("status" ,"monitor" ,"logs" ,"connection" ,"config" )or \ 2273 (a .command == "serve" and not a .plan ): 2274return _run (a ) 2275captured = _QuietCapture () 2276with contextlib .redirect_stdout (captured ): 2277code = _run (a ) 2278if code and captured .getvalue (): 2279if captured .truncated : 2280sys .stderr .write ("strata: earlier human output omitted in quiet mode\n" ) 2281sys .stderr .write (captured .getvalue ()) 2282return code